You have initialized your board as a six element array (where each element is itself an array of seven elements):
new BoundedGrid<Piece>(6,7)
(Internally, this is a two-dimensional array.)
The indexes in a six-element array are 0 through 5. Yet you are trying to access it with
grid.get(new Location(r+2,col))
Where r
ranges from 0
through 4
, as specified in your for loop:
for (int r = 0; r<grid.getNumRows()-1; r++) {
Because grid.getNumRows()-1
is 5
.
So when you attempt these lines, here are the resulting values of r
. As you can see, it goes out of bounds in many cases.
// When r is
// 0 1 2 3 4
// ---------------
Piece y =grid.get(new Location(r,col)); // 0 1 2 3 4
Piece y2 =grid.get(new Location(r+1,col)); // 1 2 3 4 5
Piece y3 =grid.get(new Location(r+2,col)); // 2 3 4 5 6
Piece y4 =grid.get(new Location(r+3,col)); // 3 4 5 6 7
There is a similar problem with these:
Piece z =grid.get(new Location(r,col));
Piece z2 =grid.get(new Location(r-1,col+1));
Piece z3 =grid.get(new Location(r-2,col+2));
Piece z4 =grid.get(new Location(r-3,col+3));
(You may also want to double check the col
indexes.)
This all assumes that Location
is accessing the elements in the BoundedGrid
object. Without knowing gridworld
, this is the best I can guess.
(I'd recommend putting comments like the above permanently in your code. Confusing code is always made a little clearer with detailed comments.)