Наведите на мысль, не пишите правильный ответ. Благодарю.
П.С. рекурсию тоже не приняло:
apple = new Apple(getRandomNumber(WIDTH), getRandomNumber(HEIGHT));
while (snake.checkCollision(apple)) {
createNewApple();
}
c checkCollision вроде тоже все ок. Но пишет про бесконечный цикл. Почему?!package com.javarush.games.snake;
import com.javarush.engine.cell.*;
import java.util.stream.IntStream;
public class SnakeGame extends Game{
public static final int WIDTH = 15;
public static final int HEIGHT = 15;
private Snake snake;
private int turnDelay;
private Apple apple;
private boolean isGameStopped;
private static final int GOAL = 10;
@Override
public void initialize() {
setScreenSize(WIDTH, HEIGHT);
createGame();
}
private void drawScene() {
IntStream.range(0, WIDTH).forEach(x -> IntStream.range(0, HEIGHT).forEach(y -> setCellValueEx(x, y, Color.DARKSEAGREEN, "")));
snake.draw(this);
apple.draw(this);
}
private void createGame() {
snake = new Snake(WIDTH/2,HEIGHT/2);
createNewApple();
isGameStopped = false;
drawScene();
turnDelay = 300;
setTurnTimer(turnDelay);
}
public void onTurn(int time) {
snake.move(apple);
if (apple.isAlive == false) {
createNewApple();
}
if (snake.isAlive == false) {
gameOver();
}
if (snake.getLength() > GOAL) {
win();
}
drawScene();
}
public void onKeyPress(Key key) {
switch (key) {
case LEFT:
snake.setDirection(Direction.LEFT);
break;
case RIGHT:
snake.setDirection(Direction.RIGHT);
break;
case UP:
snake.setDirection(Direction.UP);
break;
case DOWN:
snake.setDirection(Direction.DOWN);
break;
case SPACE:
if (isGameStopped) {
createGame();
}
}
}
private void createNewApple() {
Apple newApple;
do {
newApple = new Apple(getRandomNumber(WIDTH), getRandomNumber(HEIGHT));
} while (snake.checkCollision(newApple));
this.apple = newApple;
}
private void gameOver() {
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.RED, "GAME OVER", Color.BLACK, 75);
}
private void win() {
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.GREEN, "YOU WIN", Color.BLACK, 75);
}
}