-
Notifications
You must be signed in to change notification settings - Fork 0
/
Snake.java
107 lines (92 loc) · 2.73 KB
/
Snake.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
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
//Snake class for the controllable element of the game.
public class Snake extends Entity{
private LinkedList<Point> body;
private char direction;
private boolean grow;
public Snake() {
body = new LinkedList<>(); //The Snake uses a linked list to track the growth and position of it's body.
direction = 'R';
grow = false;
}
public void initialize() {
body.clear();
body.add(new Point(2, 0));
body.add(new Point(1, 0));
body.add(new Point(0, 0));
direction = 'R';
grow = false;
}
public Point getHead() {
return body.getFirst();
}
public void move() {
Point newHead = (Point) getHead().clone();
switch (direction) {
case 'U':
newHead.translate(0, -1);
break;
case 'D':
newHead.translate(0, 1);
break;
case 'L':
newHead.translate(-1, 0);
break;
case 'R':
newHead.translate(1, 0);
break;
}
body.addFirst(newHead);
if (!grow) {
body.removeLast();
} else {
grow = false;
}
}
public boolean checkSelfCollision() {
Point head = getHead();
for (int i = 1; i < body.size(); i++) {
if (head.equals(body.get(i))) {
return true;
}
}
return false;
}
public boolean checkWallCollision() {
Point head = getHead();
int maxX = (SnakeGame.WIDTH / SnakeGame.UNIT_SIZE) - 1;
int maxY = (SnakeGame.HEIGHT / SnakeGame.UNIT_SIZE) - 1;
return head.x < 0 || head.y < 0 || head.x > maxX || head.y > maxY;
}
public void draw(Graphics g) {
g.setColor(Color.green);
for (Point point : body) {
g.fillRect(point.x * SnakeGame.UNIT_SIZE, point.y * SnakeGame.UNIT_SIZE, SnakeGame.UNIT_SIZE, SnakeGame.UNIT_SIZE);
}
}
public void changeDirection(int key) {
switch (key) {
case KeyEvent.VK_UP:
if (direction != 'D')
direction = 'U';
break;
case KeyEvent.VK_DOWN:
if (direction != 'U')
direction = 'D';
break;
case KeyEvent.VK_LEFT:
if (direction != 'R')
direction = 'L';
break;
case KeyEvent.VK_RIGHT:
if (direction != 'L')
direction = 'R';
break;
}
}
public void grow() {
grow = true;
}
}