Испробовал разные варианты кода, чёт никак не получается.
package com.javarush.games.snake;
import com.javarush.engine.cell.*;
public class SnakeGame extends Game {
public static final int WIDTH = 15;
public static final int HEIGHT = 15;
private Snake snake;
private Apple apple;
private boolean isGameStopped;
private int turnDelay;
private static final int GOAL = 28;
public void initialize(){
setScreenSize(WIDTH, HEIGHT);
createGame();
}
public void onTurn(int step){
snake.move(apple);
if(apple.isAlive==false){
createNewApple();
}
if(snake.isAlive==false){
gameOver();
}
int a=snake.getLength();
if(a>GOAL){
win();
}
drawScene();
}
private void createNewApple(){
int x = getRandomNumber(WIDTH);
int y = getRandomNumber(HEIGHT);
Apple apple = new Apple(x, y);
this.apple = apple;
while (snake.checkCollision(apple))
apple = new Apple(getRandomNumber(WIDTH),getRandomNumber(HEIGHT));
}
private void createGame(){
Snake snake = new Snake(WIDTH/2,HEIGHT/2);
this.snake=snake;
createNewApple();
isGameStopped = false;
drawScene();
turnDelay=300;
setTurnTimer(turnDelay);
}
private void drawScene(){
for(int x=0; x<WIDTH; x++){
for(int y=0; y<HEIGHT; y++){
setCellValueEx(x,y,Color.DARKSEAGREEN,"");
}
}
snake.draw(this);
apple.draw(this);
}
public void onKeyPress(Key key){
if (key == Key.UP){
snake.setDirection(Direction.UP);
}
if (key == Key.LEFT){
snake.setDirection(Direction.LEFT);
}
if (key == Key.RIGHT){
snake.setDirection(Direction.RIGHT);
}
if (key == Key.DOWN){
snake.setDirection(Direction.DOWN);
}
if (key == Key.SPACE && isGameStopped==true){
createGame();
}
}
private void gameOver(){
stopTurnTimer();
isGameStopped=true;
showMessageDialog(Color.BLACK, "Game Over", Color.RED, 75);
}
private void win(){
stopTurnTimer();
isGameStopped=true;
showMessageDialog(Color.YELLOW, "YOU WIN", Color.RED, 75);
}
}