Hi,
I am creating a space shooter game. I want add a score counter in my project but not able to do so. I am using the latest version.
Following are the codes:-
For the World:-
import greenfoot.*;
/**
* Write a description of class Space here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Space extends World
{
Counter counter = new Counter();
/**
* Constructor for objects of class Space.
*
*/
public Space()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(600, 600, 1);
prepare();
}
public Counter getCounter()
{
return counter;
}
public void act()
{
addEnemy1();
addEnemy2();
}
public void addEnemy1()
{
if(Greenfoot.getRandomNumber(120)<1)
{
addObject(new Enemy1(),Greenfoot.getRandomNumber(600), 0);
}
}
public void addEnemy2()
{
if(Greenfoot.getRandomNumber(200)<1)
{
addObject(new Enemy2(),Greenfoot.getRandomNumber(600), 0);
}
}
/**
* Prepare the world for the start of the program. That is: create the initial
* objects and add them to the world.
*/
private void prepare()
{
Player player = new Player();
addObject(player, 311, 533);
Counter counter = new Counter();
addObject(counter, 50, 50);
counter.setLocation(80, 29);
}
}
For the enemy:-
import greenfoot.*;
/**
* Write a description of class Enemy1 here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Enemy1 extends Enemy
{
/**
* Act - do whatever the Enemy1 wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public Enemy1()
{
setRotation(90);
}
public void act()
{
moveEnemy();
removeEnemy();
hitByProjectile();
}
public void hitByProjectile()
{
Actor projectile = getOneIntersectingObject(Projectile.class);
if (projectile != null)
{
Space space = (Space)getWorld();
space .removeObject(projectile);
Counter counter = space.getCounter();
counter.addScore();
getWorld() .removeObject(this);
}
}
}
For the counter:-
import greenfoot.*;
/**
* Write a description of class counter here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Counter extends Actor
{
int Score = 0;
/**
* Act - do whatever the counter wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public Counter()
{
setImage(new GreenfootImage("Score:" + Score , 50, Color.GREEN, Color.BLACK));
}
public void act()
{
setImage(new GreenfootImage("Score:" + Score , 50, Color.GREEN, Color.BLACK));
}
public void addScore()
{
Score++;
}
}