Was trying to implement a counter for the asteroid tutorial but keep getting a java.lang.NullPointerException when running the scenario, as soon as the shot hits the asteroid it throws an error, below is the code for Space, Counter and Shot.
public class Space extends World
{
private Counter theCounter;
/**
* Constructor for objects of class Space.
*/
public Space()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(600, 400, 1);
addObject(new Rocket(), 300, 200);
Counter theCounter = new Counter();
addObject(theCounter, 5, 5);
}
public Counter getCounter()
{
return theCounter;
}
/**
* Prepare the world for the start of the program. That is: create the initial
* objects and add them to the world.
*/
private void prepare()
{
}
public void act()
{
if (Greenfoot.getRandomNumber(1000) < 3) {
addObject(new Asteroid(), 0, 20);
}
}
}
public class Counter extends Actor
{
private int totalCount = 0;
public Counter()
{
setImage(new GreenfootImage("0", 20, Color.WHITE, Color.BLACK));
}
/**
* Increase the total amount displayed on the counter, by a given amount.
*/
public void bumpCount(int amount)
{
totalCount += amount;
setImage(new GreenfootImage("" + totalCount, 20, Color.WHITE, Color.BLACK));
}
}
public class Shot extends Actor
{
private Rocket myShip;
/**
* Constructor for a Shot. You must specify the ship the shot comes from.
*/
public Shot(Rocket myShip)
{
this.myShip = myShip;
}
/**
* Act - do whatever the Shot wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
int ypos = getY();
if (ypos > 0) {
ypos = ypos - 5;
setLocation(getX(), ypos);
Actor rock = getOneIntersectingObject(Asteroid.class);
if (rock != null) {
// We've hit an asteroid!
hitAnAsteroid();
getWorld().removeObject(rock);
getWorld().removeObject(this);
}
}
else {
// I reached the top of the screen
getWorld().removeObject(this);
}
}
/**
* This method gets called (from the act method, above) when the shot hits an
* asteroid. It needs to do only one thing: increase the score counter.
* (Everything else, such as removing the asteroid which was hit, is dealt
* with in the act method).
*/
private void hitAnAsteroid()
{
Space spaceWorld = (Space) getWorld();
Counter counter = spaceWorld.getCounter();
counter.bumpCount(5);
//What goes here????
// We want to call the "bumpCount" method from the Counter class -
// but how??!!
}
}


