Hi! I am coding a game to make a snake (black square) eat food. (red square) Currently it grows by one square when it eats a piece of food. How can I change that so that the snake has a constant length of 4 squares.
Code for Head:
Code for Tail:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color; //import colour class to set image as black
/**
* Write a description of class Head here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Head extends Actor
{
private final int NORTH = 270;
private final int SOUTH = 90;
private final int EAST = 0;
private final int WEST = 180;
private final int SPEED = 10;
private int counter = 0;
private int foodEaten = 0;
public Head()
{
GreenfootImage img = new GreenfootImage (20,20);
img.fill(); //no colour specified- black
setImage(img);
setRotation(Greenfoot.getRandomNumber(4)*90); //gets a random number(0,1,2,3) and multiplies by 90 to get private final int)
}
public void act()
{
moveRandom();
getKeys();
if(isTouching(Food.class)) { //checks to see if actor is touching any other object
removeTouching(Food.class); //removes object from class that the actor is touching
foodEaten++;
MyWorld world = (MyWorld)getWorld();
world.addFood();
}
if ( facingEdge() ) {
Greenfoot.stop(); //stop game if facing edge of world
}
}
private boolean facingEdge()
{
switch(getRotation()) {
case EAST: return getX()==getWorld().getWidth()-1;
case SOUTH: return getY()==getWorld().getHeight()-1;
case WEST: return getX()==0; //if x co-ordinate is o
case NORTH: return getY()==0; //if y co-ordinate is o
}
return false;
}
public void moveRandom()
{
counter ++; //counter + 1
if(counter==SPEED) { //speed = 10
getWorld().addObject(new Tail(foodEaten*SPEED), getX(), getY());
move(1); //move one cell = 20x20 pixels
counter=0;
}
}
public void getKeys()
{
if (Greenfoot.isKeyDown("right")) {
setRotation(EAST);
}
if (Greenfoot.isKeyDown("left")) {
setRotation(WEST);
}
if (Greenfoot.isKeyDown("up")) {
setRotation(NORTH);
}
if (Greenfoot.isKeyDown("down")) {
setRotation(SOUTH);
}
}
}
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color; //import colour class to set image as black
/**
* Write a description of class Tail here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Tail extends Actor
{
private int age = 0; //initial age of tail
private int lifeSpan;
public Tail(int lifeSpan)
{
GreenfootImage img = new GreenfootImage (20,20);
img.fill(); //no colour specified- black
setImage(img);
this.lifeSpan = lifeSpan; //this=tail
}
public void act()
{
if (age == lifeSpan) {
getWorld().removeObject(this);
}
age++;
}
}
