-
Notifications
You must be signed in to change notification settings - Fork 304
/
snakegame.java
133 lines (111 loc) · 3.18 KB
/
snakegame.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// To represent Snake Game
public class Game {
public static final int DIRECTION_NONE = 0, DIRECTION_RIGHT = 1,
DIRECTION_LEFT = -1, DIRECTION_UP = 2, DIRECTION_DOWN = -2;
private Snake snake;
private Board board;
private int direction;
private boolean gameOver;
public Game(Snake snake, Board board)
{
this.snake = snake;
this.board = board;
}
public Snake getSnake()
{
return snake;
}
public void setSnake(Snake snake)
{
this.snake = snake;
}
public Board getBoard()
{
return board;
}
public void setBoard(Board board)
{
this.board = board;
}
public boolean isGameOver()
{
return gameOver;
}
public void setGameOver(boolean gameOver)
{
this.gameOver = gameOver;
}
public int getDirection()
{
return direction;
}
public void setDirection(int direction)
{
this.direction = direction;
}
// We need to update the game at regular intervals,
// and accept user input from the Keyboard.
public void update()
{
System.out.println("Going to update the game");
if (!gameOver) {
if (direction != DIRECTION_NONE) {
Cell nextCell = getNextCell(snake.getHead());
if (snake.checkCrash(nextCell)) {
setDirection(DIRECTION_NONE);
gameOver = true;
}
else {
snake.move(nextCell);
if (nextCell.getCellType() == CellType.FOOD) {
snake.grow();
board.generateFood();
}
}
}
}
}
private Cell getNextCell(Cell currentPosition)
{
System.out.println("Going to find next cell");
int row = currentPosition.getRow();
int col = currentPosition.getCol();
if (direction == DIRECTION_RIGHT) {
col++;
}
else if (direction == DIRECTION_LEFT) {
col--;
}
else if (direction == DIRECTION_UP) {
row--;
}
else if (direction == DIRECTION_DOWN) {
row++;
}
Cell nextCell = board.getCells()[row][col];
return nextCell;
}
public static void main(String[] args)
{
System.out.println("Going to start game");
Cell initPos = new Cell(0, 0);
Snake initSnake = new Snake(initPos);
Board board = new Board(10, 10);
Game newGame = new Game(initSnake, board);
newGame.gameOver = false;
newGame.direction = DIRECTION_RIGHT;
// We need to update the game at regular intervals,
// and accept user input from the Keyboard.
// here I have just called the different methods
// to show the functionality
for (int i = 0; i < 5; i++) {
if (i == 2)
newGame.board.generateFood();
newGame.update();
if (i == 3)
newGame.direction = DIRECTION_RIGHT;
if (newGame.gameOver == true)
break;
}
}
}