Hi,
I am making a snake/worm game but I have no idea how to keep on adding Tails to the worm so it gets larger after it eats a Food object. My code for the Worm class is shown below (I have added a tail every time the worm eats the food). What do I need to put in the Tail class to make this work?
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class Worm extends Actor
{
private static final int EAST = 0;
private static final int SOUTH = 90;
private static final int WEST = 180;
private static final int NORTH = 270;
private int counter = 0;
public Worm()
{
GreenfootImage img = new GreenfootImage(Ground.CELL_SIZE,Ground.CELL_SIZE);
img.drawRect(0,0,Ground.CELL_SIZE,Ground.CELL_SIZE);
img.fillRect(0,0,Ground.CELL_SIZE,Ground.CELL_SIZE);
setImage(img);
}
public void act()
{
checkKeys();
moveForward();
if( atEdgeOfWorld() ) {
getWorld().removeObject(this);
Greenfoot.stop();
}else{
Actor food = getOneIntersectingObject(Food.class);
if(food!=null) {
getWorld().addObject(new Tail(),getX(),getY());
getWorld().addObject(new Food(),Greenfoot.getRandomNumber(40),Greenfoot.getRandomNumber(30));
getWorld().removeObject(food);
}
}
}
public void moveForward()
{
counter++;
if( counter == 3 ) {
move(1);
counter = 0;
}
}
public void checkKeys()
{
if( Greenfoot.isKeyDown("right") ) {
setRotation(EAST);
}
if( Greenfoot.isKeyDown("down") ) {
setRotation(SOUTH);
}
if( Greenfoot.isKeyDown("left") ) {
setRotation(WEST);
}
if( Greenfoot.isKeyDown("up") ) {
setRotation(NORTH);
}
}
private boolean atEdgeOfWorld()
{
return getX()<=-1 || getY()<=-1 || getX()>=getWorld().getWidth()+0|| getY()>=getWorld().getHeight()+0;
}
}
