So I am making a game of 2048. The Game class (extends World) contains a 2D boolean array to indicate which cells are clear and which aren't. Here's some of the code of the Game class:
And here's some of the code from the Tile class
When one of the IsClear methods of the Tile class is called (precisely game.getCells()), a NullPointerException is thrown. This doesn't happen however when getCells() is called directly from the Game object. So what is wrong here?
Thank you!
public class Game extends World
{
private ArrayList<Tile> tiles = new ArrayList();
private boolean[][] cells = new boolean[4][4];
private int time = 0;
public Game()
{
super(4, 4, 122);
int newX = Greenfoot.getRandomNumber(4);
int newY = Greenfoot.getRandomNumber(4);
int newValue = Greenfoot.getRandomNumber(10)==0? 4:2;
tiles.add(new Tile(newValue, newX, newY));
addObject(tiles.get(0), newX, newY);
cells[newY][newX] = true;
while(cells[newY][newX])
{
newX = Greenfoot.getRandomNumber(4);
newY = Greenfoot.getRandomNumber(4);
}
newValue = Greenfoot.getRandomNumber(10)==0? 4:2;
tiles.add(new Tile(newValue, newX, newY));
addObject(tiles.get(1), newX, newY);
cells[newY][newX] = true;
}
public boolean[][] getCells()
{
return cells;
}
}
private Game game;
private int value;
public Tile(int value, int x, int y)
{
game = (Game)getWorld();
this.value = value;
setLocation(x, y);
}
public boolean topIsClear()
{
if(getY() == 0)
return false;
return !game.getCells()[getY()-1][getX()];
}
public boolean rightIsClear()
{
if(getX() == 3)
return false;
return !game.getCells()[getY()][getX()+1];
}
public boolean downIsClear()
{
if(getY() == 3)
return false;
return !game.getCells()[getY()+1][getX()];
}
public boolean leftIsClear()
{
if(getX() == 0)
return false;
return !game.getCells()[getY()][getX()-1];
}
}
