I created a rectangle array to store my snake body. In the grow method, I create a local ArrayList and initialize it, adding the content of the rectangle array. Then I try to add new rectangle to the ArrayList, however at this point, I receive NullPointerException, and I'm not sure why and how to fix it. I've tried searching it up on google and on this website, however I did not find a topic with this problem.
public class Snake extends GameObject
{
private Rectangle[] snake;
private int speed;
public Snake(int locX, int locY, int width, int height, int speed, ID id)
{
super(locX, locY, width, height, id);
snake = new Rectangle[3];
snake[0] = new Rectangle(locX, locY, width, height);
this.speed = speed;
grow();
}
public void render(Graphics g)
{
g.setColor(Color.GREEN);
drawSnake(g);
}
public Rectangle getBounds()
{
return new Rectangle(locX, locY, width, height);
}
private void drawSnake(Graphics g)
{
for(int i = 0; i < snake.length - 1; i++)
{
g.fillRect(locX, locY, width, height);
}
}
private void grow()
{
ArrayList<Rectangle> tempBody = new ArrayList<Rectangle>(Arrays.asList(snake));
tempBody.add(new Rectangle(snake[snake.length - 1].x, snake[snake.length - 1].y, width, height));
snake = tempBody.toArray(snake);
}
}