-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractGrid.java
More file actions
88 lines (81 loc) · 2.72 KB
/
Copy pathAbstractGrid.java
File metadata and controls
88 lines (81 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
* AP(r) Computer Science GridWorld Case Study:
* Copyright(c) 2005-2006 Cay S. Horstmann (http://horstmann.com)
*
* This code is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Cay Horstmann
*/
import java.util.ArrayList;
/**
* <code>AbstractGrid</code> contains the methods that are common to grid
* implementations. <br />
* The implementation of this class is testable on the AP CS AB exam.
*/
public abstract class AbstractGrid<E> implements Grid<E>
{
public ArrayList<E> getNeighbors(Location loc)
{
ArrayList<E> neighbors = new ArrayList<E>();
for (Location neighborLoc : getOccupiedAdjacentLocations(loc))
neighbors.add(get(neighborLoc));
return neighbors;
}
public ArrayList<Location> getValidAdjacentLocations(Location loc)
{
ArrayList<Location> locs = new ArrayList<Location>();
int d = Location.NORTH;
for (int i = 0; i < Location.FULL_CIRCLE / Location.HALF_RIGHT; i++)
{
Location neighborLoc = loc.getAdjacentLocation(d);
if (isValid(neighborLoc))
locs.add(neighborLoc);
d = d + Location.HALF_RIGHT;
}
return locs;
}
public ArrayList<Location> getEmptyAdjacentLocations(Location loc)
{
ArrayList<Location> locs = new ArrayList<Location>();
for (Location neighborLoc : getValidAdjacentLocations(loc))
{
if (get(neighborLoc) == null)
locs.add(neighborLoc);
}
return locs;
}
public ArrayList<Location> getOccupiedAdjacentLocations(Location loc)
{
ArrayList<Location> locs = new ArrayList<Location>();
for (Location neighborLoc : getValidAdjacentLocations(loc))
{
if (get(neighborLoc) != null)
locs.add(neighborLoc);
}
return locs;
}
/**
* Creates a string that describes this grid.
* @return a string with descriptions of all objects in this grid (not
* necessarily in any particular order), in the format {loc=obj, loc=obj,
* ...}
*/
public String toString()
{
String s = "{";
for (Location loc : getOccupiedLocations())
{
if (s.length() > 1)
s += ", ";
s += loc + "=" + get(loc);
}
return s + "}";
}
}