Got a new task in School to code the Snake Game from scratch and need to use a array to add a new Snake bodypart when the Snakehead eats food and at the beginning the Snake need to have 1 head and 2 bodyparts..and I have no idea how to do this..can someone out there help me on right direction..how to start? Here is my code so far:
The world:
public class WorldofSnake extends World
{
/**
* Constructor for objects of class WorldofSnake.
*
*/
public WorldofSnake()
{
super(600, 400, 1);
addObject ( new Snake(),70 , 50);
addObject ( new Food(), Greenfoot.getRandomNumber(600), Greenfoot.getRandomNumber(400));
}
}
The class Snake:
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
{
private int foodEaten;
public Snake()
{
foodEaten = 0;
}
public void act()
{
checkKeypress();
lookForFood();
}
public void checkKeypress()
{ if(Greenfoot.isKeyDown("left")){
setLocation(getX() - 2,(getY()));
}
if(Greenfoot.isKeyDown("right")){
setLocation(getX() + 2,(getY()));
}
if(Greenfoot.isKeyDown("up")){
setLocation(getX() ,(getY() - 2));
}
if(Greenfoot.isKeyDown("down")){
setLocation(getX() ,(getY() + 2));
}
}
public void lookForFood()
{
Actor a = getOneIntersectingObject(Food.class);
if (a !=null)
{
getWorld().removeObject(a);
getWorld().addObject ( new Food(), Greenfoot.getRandomNumber(600), Greenfoot.getRandomNumber(400));
foodEaten = foodEaten + 1;
}
}
}