I'm coding a game where a snake ( a black square) is controlled by my keys and tries to eat the food (red squares). However, when the snake touches the edge of the world, I want the game to stop and show 'Game Over'.
Can someone one please help me?
I'm pasting my code for the head class, GameOver class
Code for head:
Code for game over:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color; //import colour class to set image as black
public class Head extends MainActor
{
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++; //foodEaten + 1
MyWorld world = (MyWorld)getWorld();
world.addFood();
}
}
public boolean atWorldEdge()
{
if (atWorldEdge() == true ) {
eat(Head.class);
Greenfoot.stop();
}
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;
public class GameOver extends Actor
{
public GameOver()
{
setImage(new GreenfootImage("Game Over", 48, Color.BLACK, Color.WHITE)); //set Game Over size (48 pixels), black foreground, white background
}
}
