-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnake.java
More file actions
91 lines (76 loc) · 2.32 KB
/
Copy pathSnake.java
File metadata and controls
91 lines (76 loc) · 2.32 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
import java.awt.Point;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import core.Entity;
import core.Relation;
public class Snake extends Entity<Relation> {
private final Deque<Point> body = new ArrayDeque<>();
private Direction direction = Direction.RIGHT;
private Direction pendingDirection = Direction.RIGHT;
public Snake(int id, String label, int startX, int startY) {
super(id, label);
reset(startX, startY);
}
public void reset(int startX, int startY) {
body.clear();
body.addLast(new Point(startX, startY));
body.addLast(new Point(startX - 1, startY));
body.addLast(new Point(startX - 2, startY));
direction = Direction.RIGHT;
pendingDirection = Direction.RIGHT;
}
public void queueDirection(Direction nextDirection) {
if (nextDirection == null || nextDirection.isOpposite(direction)) {
return;
}
pendingDirection = nextDirection;
}
public Point nextHead() {
Point head = body.peekFirst();
return new Point(head.x + pendingDirection.dx(), head.y + pendingDirection.dy());
}
public void advance(Point nextHead, boolean grow) {
direction = pendingDirection;
body.addFirst(new Point(nextHead));
if (!grow) {
body.removeLast();
}
}
public boolean hitsSelf(Point candidate, boolean growing) {
int lastIndex = body.size() - 1;
int index = 0;
for (Point segment : body) {
if (!growing && index == lastIndex) {
break;
}
if (segment.equals(candidate)) {
return true;
}
index++;
}
return false;
}
public boolean occupies(Point point) {
for (Point segment : body) {
if (segment.equals(point)) {
return true;
}
}
return false;
}
public Point getHead() {
return new Point(body.peekFirst());
}
public int getLength() {
return body.size();
}
public List<Point> getSegments() {
List<Point> segments = new ArrayList<>();
for (Point point : body) {
segments.add(new Point(point));
}
return segments;
}
}