0

To make the snake game, I need to position the snake at the beginning at (0,0), (1.0). I'm working with a coordinate class and a snake class. In the constructor of the coordinate class I set all x and y values to 0. I created an array with coordinates and I want to set the first 2 coordinates manually (method startPositionSnake) because it's the starting position. This is when I get a nullpointerexception. I don't get why this happens because all coordinates are (0,0) by default. (under the screenshots is the used code) enter image description here enter image description here

code:

package Snake;

import java.util.Random;
import java.util.Locale;
import java.util.Scanner;
import ui.Event;
import ui.SnakeUserInterface;
import ui.UserInterfaceFactory;

public class Coordinate {

    public static final int WIDTH = 26;
    public static final int HEIGHT = 26;
    int x;
    int y;

    Coordinate() {
        x = 0;
        y = 0;
    }

    void locateApple() {
        Random random = new Random();
        x = random.nextInt(WIDTH);
        y = random.nextInt(HEIGHT);
    }
}
package Snake;

import java.util.Random;
import java.util.Locale;
import java.util.Scanner;
import ui.Event;
import ui.SnakeUserInterface;
import ui.UserInterfaceFactory;

public class Snake {

    int lengthOfSnake;
    Coordinate headOfSnake = new Coordinate();
    Coordinate[] snakePosition = new Coordinate[20];
    
    Snake() {
        lengthOfSnake = 2;
    }
    
    void startPositionSnake() {
        snakePosition[0].x = 1;
        snakePosition[0].y = 0;
        snakePosition[1].x = 0;
        snakePosition[1].y = 0;
    }
    

1 Answers1

0

Object arrays are filled with null values by default. To fill them with the coordinates you have to loop through the array and fill them (see NullPointerException when Creating an Array of objects)