public void setDirection(Direction direcnew){
if ( (direction==Direction.RIGHT || direction==Direction.LEFT) && (snakeParts.get(0).x == snakeParts.get(1).x) ) {
return;
}
if ( (direction==Direction.DOWN || direction==Direction.UP) && (snakeParts.get(0).y == snakeParts.get(1).y) ) {
return;
}
if ( (direcnew == Direction.LEFT && direction==Direction.RIGHT) || (direcnew==Direction.RIGHT && direction==Direction.LEFT) ){
return;
}
if ( (direcnew==Direction.DOWN && direction==Direction.UP) || (direcnew==Direction.UP && direction==Direction.DOWN) ){
return;
}
this.direction = direcnew;
}
package com.javarush.games.snake;
import com.javarush.engine.cell.*;
import java.util.*;
import java.io.*;
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 = 28;
@Override
public void initialize (){
setScreenSize(WIDTH,HEIGHT);
createGame();
}
private void drawScene(){
for (int x=0; x<WIDTH; x++){
for (int y=0; y<HEIGHT; y++){
//setCellColor(x,y,Color.DARKSEAGREEN);
//setCellValueEx(i, j, Color.AQUA, "");
setCellValueEx(x, y, Color.DARKSEAGREEN, "");
}
}
snake.draw(this);
apple.draw(this);
}
private void createGame(){
turnDelay = 300;
setTurnTimer(turnDelay);
snake = new Snake (WIDTH/2,HEIGHT/2);
//apple = new Apple (5,5);
createNewApple();
isGameStopped = false;
drawScene();
//Apple apple = new Apple(7,7);
//apple.draw(this);
}
@Override
public void onTurn(int step){
snake.move(apple);
if (this.apple.isAlive==false){
createNewApple();
}
if (this.snake.isAlive==false){
gameOver();
}
if (this.snake.getLength() > this.GOAL) {
win();
}
drawScene();
}
@Override
public void onKeyPress(Key key){
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;
default:
}
}
private void createNewApple(){
this.apple = new Apple(getRandomNumber(WIDTH), getRandomNumber(HEIGHT));
if(this.snake.checkCollision(this.apple)){
createNewApple();
}
}
private void gameOver(){
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.BLUE,"Game Over",Color.RED,50);
}
private void win(){
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.BLUE,"YOU WIN",Color.RED,50);
}
}