Hi, im new to this and i tried to make a runnable snake game. When i try to run my code i get this:
Exception in thread "main" java.lang.NullPointerException at Game.Move(Game.java:85) at Game.run(Game.java:244) at Game.main(Game.java:38)
The game runs, but the snake doesn't move, and apples are spawned everywhere.
I can't post all the code, so here are Move, run and main code:
public static void main(String[] args) { JFrame frame = new JFrame("Snake"); Game game = new Game(); frame.add(game); frame.setSize(406, 430); frame.setVisible(true); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); game.run(); }public void run() { while (true) { Move(); Draw(globalGraphics); repaint(); try { Thread.currentThread(); Thread.sleep(100); } catch(Exception e) { e.printStackTrace(); } } }public void Move() { Point head = snake.peekFirst(); Point newPoint = head; switch (direction) { case Direction.NORTH: newPoint = new Point(head.x, head.y - 1); break; case Direction.SOUTH: newPoint = new Point(head.x, head.y + 1); break; case Direction.WEST: newPoint = new Point(head.x - 1, head.y); break; case Direction.EAST: newPoint = new Point(head.x + 1, head.y); break; } snake.remove(snake.peekLast()); if (newPoint.equals(fruit)) { score+=10; Point addPoint = (Point) newPoint.clone(); switch (direction) { case Direction.NORTH: newPoint = new Point(head.x, head.y - 1); break; case Direction.SOUTH: newPoint = new Point(head.x, head.y + 1); break; case Direction.WEST: newPoint = new Point(head.x - 1, head.y); break; case Direction.EAST: newPoint = new Point(head.x + 1, head.y); break; } snake.push(addPoint); PlaceFruit(); } else if (newPoint.x < 0 || newPoint.x > (GRID_WIDTH - 1)) { GenerateDefaultSnake(); return; } else if (newPoint.y < 0 || newPoint.y > (GRID_HEIGHT - 1)) { GenerateDefaultSnake(); return; } else if (snake.contains(newPoint)) { GenerateDefaultSnake(); return; } snake.push(newPoint); }