In the setDirection() method i've done what is write to do, but it fails all the checks.
I don't know why, but when in the method i change both the 2 if statements for the UP and DOWN:
if(snakeParts.get(0).y == snakeParts.get(1).y);
into this :
if(snakeParts.get(0).y != snakeParts.get(1).y);
the machine checks the first 2 points correctly.
Thank you.package com.codegym.games.snake;
import com.codegym.engine.cell.*;
public class SnakeGame extends Game{
//VARIABILI
private static final int GOAL = 28;
private int turnDelay;
private Snake snake;
private Apple apple;
private boolean isGameStopped;
//METODI
private void createNewApple(){
do{
apple = new Apple(getRandomNumber(WIDTH),getRandomNumber(HEIGHT));
}
while(snake.checkCollision(apple));
}
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();
}
break;
default:
break;
}
}
public void onTurn(int n){
snake.move(apple);
if(!snake.isAlive){
gameOver();
}
if(!apple.isAlive){
createNewApple();
}
if(snake.getLength()>GOAL){
win();
}
drawScene();
}
private void win(){
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.NONE, "YOU WIN", Color.RED, 75);
}
private void gameOver(){
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.NONE, "GAME OVER", Color.RED, 75);
}
public static final int HEIGHT = 15;
public static final int WIDTH = 15;
public void initialize(){
setScreenSize(WIDTH, HEIGHT);
createGame();
}
private void createGame(){
isGameStopped = false;
snake = new Snake(WIDTH/2, HEIGHT/2);
createNewApple();
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);
}
}