I am trying to make pacman eat the pellets. I am quite new to greenfoot and keep getting java.lang.NullPointerException
at Pacman.eat(Pacman.java:77)
at Pacman.act(Pacman.java:37) as an error.
Here is my Pacman code
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Pacman here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Pacman extends Actor
{
/**
* Act - do whatever the Pacman wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public Pacman()
{
GreenfootImage image = getImage();
image.scale(35, 35);
setImage(image);
}
public void act()
{
controls();
move(-3);
eat();
}
private void controls()
{
if ( Greenfoot.isKeyDown("right") || Greenfoot.isKeyDown("D") ) {
setRotation(-180);
}
if ( Greenfoot.isKeyDown("left") || Greenfoot.isKeyDown("A") ) {
setRotation(-0);
}
if ( Greenfoot.isKeyDown("up") || Greenfoot.isKeyDown("W") ) {
setRotation(-270);
}
if ( Greenfoot.isKeyDown("down") || Greenfoot.isKeyDown("S") ) {
setRotation(-90);
}
}
private boolean checkForWall(int x, int y)
{
int origX = getX();
int origY = getY();
// Finds a wall object at the offset to the player.
setLocation(x , y);
Actor wall = getOneIntersectingObject( Wall.class );
setLocation(origX, origY);
return (wall != null);
}
public void eat()
{
Actor Pellet = getOneObjectAtOffset(0, 0,Pellet.class);
if(Pellet != null)
{
World world = getWorld();
world.removeObject(Pellet);
((MyWorld)world).counter.add(1);
}
}
}
Pellet code:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Pellet here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Pellet extends Actor
{
/**
* Act - do whatever the Pellet wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
eat();
}
public Pellet()
{
GreenfootImage image = getImage();
image.scale(45, 35);
setImage(image);
}
public void eat()
{
Actor Pacman = getOneObjectAtOffset(0, 0,Pellet.class);
if(Pacman != null)
{
World world = getWorld();
world.removeObject(this);
((MyWorld)world).counter.add(1);
}
}
}
My world code is pretty much empty.

