ΠΠ΅ ΠΏΡΠΎΡ
ΠΎΠ΄ΠΈΡ ΠΏΠΎΡΠ»Π΅Π΄Π½ΠΈΠΉ ΠΏΡΠ½ΠΊΡ, ΡΠΊΠ°ΠΆΠΈΡΠ΅ Π³Π΄Π΅ ΠΌΠΎΡ ΠΎΡΠΈΠ±ΠΊΠ°?
package com.javarush.games.snake;
import com.javarush.engine.cell.Color;
import com.javarush.engine.cell.*;
import com.javarush.engine.cell.Game;
public class SnakeGame extends Game {
public static final int HEIGHT = 15;
public static final int WIDTH = 15;
private Snake snake;
private int score;
private Apple apple;
private static final int GOAL = 28;
private boolean isGameStopped;
private int turnDelay=300;
//ΠΡΡ, ΡΡΠΎ Π΄ΠΎΠ»ΠΆΠ½ΠΎ ΠΏΡΠΎΠΈΡΡ
ΠΎΠ΄ΠΈΡΡ Π² ΠΈΠ³ΡΠ΅ Π½Π° ΠΏΡΠΎΡΡΠΆΠ΅Π½ΠΈΠΈ ΠΎΠ΄Π½ΠΎΠ³ΠΎ Ρ
ΠΎΠ΄Π°, ΠΎΠΏΠΈΡΡΠ²Π°Π΅ΡΡΡ Π·Π΄Π΅ΡΡ.
public void onTurn(int step) {
snake.move(apple);
if (!apple.isAlive) {
createNewApple();
score = score+5;
setScore(score);
turnDelay = turnDelay - 10;
setTurnTimer(turnDelay);
}
setTurnTimer(turnDelay);
if (!snake.isAlive) gameOver();
if (GOAL < snake.getLength()) win();
drawScene();
}
//Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ ΠΏΠΎΠ»Π΅
@Override
public void initialize() {
setScreenSize(15, 15);
createGame();
}
private void win() {
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.WHITE, "Win", Color.RED, 16);
}
private void createNewApple() {
do {
apple = new Apple (getRandomNumber(WIDTH), getRandomNumber(HEIGHT));
}while (snake.checkCollision(apple));
}
private void gameOver(){
this.stopTurnTimer();
this.showMessageDialog(Color.BLACK, "Game Over", Color.RED, 75);
isGameStopped = true;
}
/* @Override
public void onKeyPress(Key key){
if (key == Key.LEFT && snake.getDirection() != Direction.RIGHT)
snake.setDirection(Direction.LEFT);
if (key == Key.RIGHT && snake.getDirection() != Direction.LEFT)
snake.setDirection(Direction.RIGHT);
if (key == Key.UP && snake.getDirection() != Direction.DOWN)
snake.setDirection(Direction.UP);
if (key == Key.DOWN && snake.getDirection() != Direction.UP)
snake.setDirection(Direction.DOWN);
}
*/
@Override
public void onKeyPress(Key key){
if (key == Key.SPACE && isGameStopped == true) {
createGame();
}
if(key == Key.LEFT){
snake.setDirection(Direction.LEFT);
}
if(key == Key.RIGHT){
snake.setDirection(Direction.RIGHT);
}
if(key == Key.UP){
snake.setDirection(Direction.UP);
}
if(key == Key.DOWN){
snake.setDirection(Direction.DOWN);
}
}
//Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ ΠΈΠ³ΡΡ
private void createGame(){
snake = new Snake(WIDTH/2, HEIGHT/2);
//Apple app = new Apple(5,5);
createNewApple();
score = 0;
setScore(score);
isGameStopped = false;
drawScene();
turnDelay=300;
setTurnTimer(turnDelay);
//Apple app = new Apple(7,7);
//app.draw(this);
}
//ΠΡΡΠΈΡΠΎΠ²ΠΊΠ° ΠΏΠΎΠ»Ρ
private void drawScene(){
for(int x = 0; x < HEIGHT; x++){
for(int y = 0; y < WIDTH; y++){
//ΠΠΎΡΠ»Π΅ ΠΏΠ΅ΡΠ΅Π΄Π²ΠΈΠΆΠ΅Π½ΠΈΡ Π·ΠΌΠ΅ΠΉΠΊΠΈ Π½ΡΠΆΠ½ΠΎ ΠΎΡΠΈΡΠ°ΡΡ ΠΈΠ³ΡΠΎΠ²ΠΎΠ΅ ΠΏΠΎΠ»Π΅ ΠΎΡ ΡΠΆΠ΅ Π½Π΅ΡΡΡΠ΅ΡΡΠ²ΡΡΡΠΈΡ
Π΅Π΅ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ²
setCellValueEx(x, y,Color.DARKSEAGREEN, "");
}
}
snake.draw(this);
apple.draw(this);
}
}