So I'm trying to make a snake game and i can't get body parts to fallow each other in line. Can anyone give me any help? Here's my code:
public class Ground extends World
{
Random rand = new Random();
public Ground()
{
super(500, 500, 1);
addObject( new Snake(), 250, 250);
addObject(new Apple(), rand.nextInt(460) + 20, rand.nextInt(460) + 20);
}
public void showMap1()
{
setBackground("ground.png");
}
}
public class Apple extends Actor {
public Apple(){
GreenfootImage image = getImage();
image.scale(30, 30);
setImage(image);
}
}
public class Snake extends Actor {
public Snake(){
GreenfootImage image = getImage();
image.scale(40, 40);
setImage(image);
}
@Override
public void act() {
moveHead();
if(Greenfoot.isKeyDown("left") && getRotation() != 0 ){
setRotation(180);
}
if(Greenfoot.isKeyDown("right") && getRotation() != 180){
setRotation(0);
}
if(Greenfoot.isKeyDown("up") && getRotation() != 90 ){
setRotation(270);
}
if(Greenfoot.isKeyDown("down") && getRotation() != 270 ){
setRotation(90);
}
Random rand = new Random();
int i = 1;
Actor b = getOneIntersectingObject(Apple.class);
if(b != null)
{
getWorld().removeObject(b);
getWorld().addObject(new Apple(), rand.nextInt(460) + 20, rand.nextInt(460) + 20);
Body node = new Body(i);
getWorld().addObject(node, getX(), getY());
i++;
}
}
public void moveHead()
{
delay(10);
if(getRotation() == 180){//left
setLocation(getX() - 30, getY());
}
if(getRotation() == 0){//right
setLocation(getX() + 30, getY());
}
if(getRotation() == 270){//up
setLocation(getX(), getY() - 30);
}
if(getRotation() == 90){//down
setLocation(getX(), getY() + 30);
}
}
}
public class Body extends Snake {
private int i;
public Body(int node){
this.i = node;
GreenfootImage image = getImage();
image.scale(45, 45);
setImage(image);
}
@Override
public void act() {
moveBody(this.i);
}
public void moveBody(int i)
{
if(getRotation() == 180){//left
setLocation(getX() - (30*i), getY());
}
if(getRotation() == 0){//right
setLocation(getX() + (30*i), getY());
}
if(getRotation() == 270){//up
setLocation(getX(), getY() - (30*i));
}
if(getRotation() == 90){//down
setLocation(getX(), getY() + (30*i));
}
}
}
