I am making a Snake game. Snake increases its tail when eats food. However, the snake eats food, its tail doesn't increase.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Snake here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Snake extends Actor
{
/**
* Act - do whatever the Snake wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
private int speed = 2;
private int dx = 1;
private int dy = 0;
private int foodCounter = 0;
public Snake()
{ //Set the head of snake.
GreenfootImage img = new GreenfootImage(10,10); //Create a new image with 20x20 as the size.
img.setColor(Color.WHITE); //Set colour
img.fill(); //Fill the block.
setImage(img); //Save our changes.
}
public void act()
{
//
turnAround();
move(speed);
if(isTouching(food.class))
{
removeTouching(food.class);
SnakeWorld sw = (SnakeWorld)getWorld();
sw.addFood();
getWorld().addObject(new tail(), getX()-1, getY()-1);
}
}
public void turnAround()
{
if(Greenfoot.isKeyDown("up") && dx == 0)
{
dx = -1;
dy = 0;
setRotation(270);
}
if(Greenfoot.isKeyDown("down") && dx == 0)
{
dx = -1;
dy = 0;
setRotation(90);
}
if(Greenfoot.isKeyDown("left") && dy == 0)
{
dx = 0;
dy = 1;
setRotation(180);
}
if(Greenfoot.isKeyDown("right") && dy == 0)
{
dx = 0;
dy = 1;
setRotation(360);
}
}
}
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class tail here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class tail extends Actor
{
/**
* Act - do whatever the tail wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
int count = 0;
public tail()
{
GreenfootImage img = new GreenfootImage(10,10); //Create a new image with 20x20 as the size.
img.setColor(Color.WHITE); //Set colour
img.fill(); //Fill the block.
setImage(img);
}
public void act()
{
}
}
