Согласно требованиям: Метод onKeyPress(Key) должен вызывать метод createGame(), если параметр метода — клавиша SPACE, и игра была остановлена (isGameStopped == true).
У меня в коде так и происходит, но валидатор не принимает:
@Override
public void onKeyPress(Key key) {
Direction dir = snake.direction;
switch (key) {
case UP:
snake.setDirection(Direction.UP);
break;
case RIGHT:
snake.setDirection(Direction.RIGHT);
break;
case DOWN:
snake.setDirection(Direction.DOWN);
break;
case LEFT:
snake.setDirection(Direction.LEFT);
break;
case SPACE:
if (isGameStopped) createGame();
break;
}
}
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 static final int GOAL = 28;
private static final Color BACKGROUND_COLOR = Color.DARKSEAGREEN;
private int turnDelay = 300;
private Snake snake;
private Apple apple;
private boolean isGameStopped = false;
private void drawScene() {
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
setCellValueEx(x, y, BACKGROUND_COLOR, "");
}
}
snake.draw(this);
apple.draw(this);
}
private void createGame() {
turnDelay = 300;
setTurnTimer(turnDelay);
snake = new Snake(WIDTH/2, HEIGHT/2);
createNewApple();
isGameStopped = false;
drawScene();
}
private void createNewApple() {
do {
apple = new Apple(getRandomNumber(WIDTH), getRandomNumber(HEIGHT));
} while (snake.checkCollision(apple));
}
private void gameOver() {
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.TRANSPARENT, "YOU LOSE 😂😂", Color.BLACK, 50);
}
private void win() {
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.TRANSPARENT, "YOU WIN! 😂😂", Color.BLACK, 50);
}
@Override
public void onKeyPress(Key key) {
Direction dir = snake.direction;
switch (key) {
case UP:
snake.setDirection(Direction.UP);
break;
case RIGHT:
snake.setDirection(Direction.RIGHT);
break;
case DOWN:
snake.setDirection(Direction.DOWN);
break;
case LEFT:
snake.setDirection(Direction.LEFT);
break;
case SPACE:
if (isGameStopped) createGame();
break;
}
}
@Override
public void onTurn(int s) {
snake.move(apple);
if (!apple.isAlive) createNewApple();
if (!snake.isAlive) gameOver();
if (snake.getLength() > GOAL) win();
drawScene();
}
@Override
public void initialize() {
setScreenSize(WIDTH, HEIGHT);
createGame();
}
}