Hi, I am new to greenfoot and I am currently getting an error with this. I have created a sceanario in which you control a player and you "eat" goals to get points in a maze. If the player touches a mazewall, he or she will be spawned back at the starting point. This is where the error comes in. After spawning again, if one tries to "eat" a goal to add points the error will happen.
This is my terminal window
java.lang.NullPointerException
at Player.TrytoEat(Player.java:56)
at Player.act(Player.java:23)
at greenfoot.core.Simulation.actActor(Simulation.java:568)
at greenfoot.core.Simulation.runOneLoop(Simulation.java:526)
at greenfoot.core.Simulation.runContent(Simulation.java:215)
at greenfoot.core.Simulation.run(Simulation.java:205)
this is my player code
this is my mazewall that respawns the player if he touches the wall
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | private Counter counter; /** * Act - do whatever the Player wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { CheckKeys(); TrytoEat(); } public Player (Counter count) { counter = count; } public void CheckKeys() { if ( Greenfoot.isKeyDown( "up" )) { move(- 1 ); } if ( Greenfoot.isKeyDown( "down" )) { move( 2 ); } if ( Greenfoot.isKeyDown( "left" )) { turn(- 5 ); } if ( Greenfoot.isKeyDown( "right" )) { turn( 5 ); } } public void TrytoEat() { if (canSee(Goal. class )) { eat(Goal. class ); counter.add( 2 ); if (counter.getValue()> 8 ) { gameOver(); } } } public void gameOver() { Greenfoot.stop(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | private Counter counter; /** * Act - do whatever the MazeWall wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { TrytoEatHuman(); } public void TrytoEatHuman() { if (canSee(Player. class )) { eat(Player. class ); addPlayer(); } } public void gameOver() { Greenfoot.stop(); } public void addPlayer() { Player player = new Player(counter); World world = getWorld(); int x = 34 ; int y = 42 ; world.addObject(player, x, y); } } |