Hi there
Just wondering if someone can help me to debug this code. I am fairly new to this and cannot spot the error in my counter. Whenever the crab eats a wombat the counter fails to update and the game freezes with a nullexceptione error. Here is the crab code:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Crab here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Crab extends Actor
{
/**
* Act - do whatever the Crab wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
move();
}
public void move()
{
if (Greenfoot.isKeyDown("right"))
{
turn(5);
}
if (Greenfoot.isKeyDown("left"))
{
turn(-5);
}
if (Greenfoot.isKeyDown("up"))
{
move(2);
}
if (Greenfoot.isKeyDown("down"))
{
move(-2);
}
checkForWombat();
}
public void checkForWombat()
{
Actor theWombat=getOneObjectAtOffset(0,0,Wombat.class);
if (theWombat != null)
{
WombatWorld eatingWorld=(WombatWorld) getWorld();
eatingWorld.removeObject(theWombat);
Greenfoot.playSound("slurp.wav");
bumpCounter();
}
}
public void bumpCounter()
{
WombatWorld counterWorld= (WombatWorld) getWorld();
Counter theCounter = counterWorld.getCounter();
theCounter.bumpCount(1);
}
}
And here is the counter code:
import greenfoot.*;
import java.awt.Color; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Counter here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Counter extends Actor
{
private int totalCount=0;
/**
* A constructor for the counter, which sets the counter's initial text image.
*/
public Counter()
{
setImage(new GreenfootImage("Wombats Eaten: " +totalCount, 20, Color.WHITE, Color.BLACK));
}
/**
* Increase the total amount displayed on the counter, by a given amount.
*/
public void bumpCount(int amount)
{
totalCount = totalCount+amount;
setImage(new GreenfootImage("Wombats Eaten: " +totalCount, 20, Color.WHITE, Color.BLACK));
}
}
Many thanks in advance!