-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathSnakeGame.java
More file actions
131 lines (107 loc) · 2.38 KB
/
SnakeGame.java
File metadata and controls
131 lines (107 loc) · 2.38 KB
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
// To represent a cell of display board.
public class Cell {
private final int row, col;
private CellType cellType;
public Cell(int row, int col)
{
this.row = row;
this.col = col;
}
public CellType getCellType()
{
return cellType;
}
public void setCellType(CellType cellType)
{
this.cellType = cellType;
}
public int getRow()
{
return row;
}
public int getCol()
{
return col;
}
}
// To represent a snake
import java.util.LinkedList;
public class Snake {
private LinkedList<Cell> snakePartList
= new LinkedList<>();
private Cell head;
public Snake(Cell initPos)
{
head = initPos;
snakePartList.add(head);
head.setCellType(CellType.SNAKE_NODE);
}
public void grow() { snakePartList.add(head); }
public void move(Cell nextCell)
{
System.out.println("Snake is moving to "
+ nextCell.getRow() + " "
+ nextCell.getCol());
Cell tail = snakePartList.removeLast();
tail.setCellType(CellType.EMPTY);
head = nextCell;
head.setCellType(CellType.SNAKE_NODE);
snakePartList.addFirst(head);
}
public boolean checkCrash(Cell nextCell)
{
System.out.println("Going to check for Crash");
for (Cell cell : snakePartList) {
if (cell == nextCell) {
return true;
}
}
return false;
}
public LinkedList<Cell> getSnakePartList()
{
return snakePartList;
}
public void
setSnakePartList(LinkedList<Cell> snakePartList)
{
this.snakePartList = snakePartList;
}
public Cell getHead() { return head; }
public void setHead(Cell head) { this.head = head; }
}
public class Board {
final int ROW_COUNT, COL_COUNT;
private Cell[][] cells;
public Board(int rowCount, int columnCount)
{
ROW_COUNT = rowCount;
COL_COUNT = columnCount;
cells = new Cell[ROW_COUNT][COL_COUNT];
for (int row = 0; row < ROW_COUNT; row++) {
for (int column = 0; column < COL_COUNT; column++) {
cells[row][column] = new Cell(row, column);
}
}
}
public Cell[][] getCells()
{
return cells;
}
public void setCells(Cell[][] cells)
{
this.cells = cells;
}
public void generateFood()
{
System.out.println("Going to generate food");
while(true){
int row = (int)(Math.random() * ROW_COUNT);
int column = (int)(Math.random() * COL_COUNT);
if(cells[row][column].getCellType()!=CellType.SNAKE_NODE)
break;
}
cells[row][column].setCellType(CellType.FOOD);
System.out.println("Food is generated at: " + row + " " + column);
}
}