I have a 2D array which acts as a game board and the user can make moves into certain cells etc and each user has a specific id e.g. player 1 replaces the cells in the array with their playerId = 1.
I am trying to create a method to find out when the user's playerId gets stuck. They get stuck when they are surrounded by another a value which is not 0.
For example, if player 1 is in the cell 2,5 then P(which represents a 0) is the possible moves they can make. However, if the player was surrounded by other values then they should not be able to make a move (return false).
xxxPPPxxxx
xxxP1Pxxxx
xxxPPPxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
Method:
public boolean checkBlocked(int[][] array,List<Coordinates> track,int playerId)
{
boolean blocked = false;
int trueCount = 0;
for (Coordinates cells: track)
{
int x = cells.getX();
int y = cells.getY();
if(array[x-1][y-1] == 0 ) trueCount++; //topleft
if(array[x-1][y] == 0) trueCount++; //top
if(array[x-1][y+1] == 0) trueCount++;//topright
if(array[x][y+1] == 0) trueCount++;//right
if(array[x][y-1] == 0) trueCount++;//left
if(array[x+1][y-1] == 0) trueCount++;//bottomleft
if(array[x+1][y] == 0) trueCount++;//bottom
if(array[x+1][y+1] == 0) trueCount++; //bottomright
}
if (trueCount == 0)
{
blocked = true;
}
return blocked;
}
I tried to do this method, but then this doesn't work because the 2D array is 6x10 and then if the cell is 1,1 or 6,1 then it gives an ArrayIndexOutOfBoundsException.
Is there an easier way that I can do this check or a way around the exception?