public class MyWorld extends World
{
Snake snake = new Snake();
private int xVel = 5;
private int yVel = 2;
private int speed = 2;
/**
* Constructor for objects of class MyWorld.
*
*/
public MyWorld() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(900, 600, 1);
snake.setImage(new GreenfootImage("smiley1.png"));
addObject(snake, 1, 0);
addBodySegment(0, 0, snake);
}
private void addBodySegment(int xLoc, int yLoc, Snake leader) {
Snake body = new Snake();
leader.setFollower(body);
addObject(body, xLoc, yLoc);
}
public void act() {
moveAndGrow();
wallCollision();
}
private void moveAndGrow() {
int atX = snake.getX();
int atY = snake.getY();
Snake body = snake;
moveSnakeHead();
while(body.getFollower() != null) {
body = body.getFollower();
int newX = body.getX();
int newY = body.getY();
body.setLocation(atX, atY);
atX = newX;
atY = newY;
}
if (Greenfoot.getRandomNumber(100) < (10))
addBodySegment(atX, atY, body);
}
private void moveSnakeHead() {
snake.setLocation(snake.getX()+(xVel+speed), snake.getY()+(yVel+speed));
}
public void wallCollision() {
if (snake.getX() < 40 || snake.getX() > 860) {
xVel = -xVel;
}
if (snake.getY() < 40 || snake.getY() > 560) {
yVel = -yVel;
}
}
}

