forked from calveym/finalProject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnake.java
More file actions
89 lines (65 loc) · 2.11 KB
/
Snake.java
File metadata and controls
89 lines (65 loc) · 2.11 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
import java.util.Vector;
public class Snake {
private Vector<Coord> positions; // this vector stores all of the coordinates
// that currently contain a snake part
private int dir; // 0- up, 1- right, 2- down, 3- left
// Constructor
public Snake(Coord startCoordinate) {
dir = 0;
positions = new Vector<Coord>();
positions.add(below(below(startCoordinate)));
positions.add(below(startCoordinate));
positions.add(startCoordinate);
}
// Accessors
public Coord head() {
return positions.firstElement(); // returns first item in positions vector
}
public Coord tail() {
return positions.lastElement(); // returns last item in positions vector
}
public int direction() {
return dir;
}
// Movement
public void move() {
Coord newPos = head();
// calculate which coordinate changes
if(dir == 0) {
newPos.y = head().y -1;
} else if(dir == 1) {
newPos.x = head().x +1;
} else if(dir == 2) {
newPos.y = head().y +1;
} else if(dir == 3) {
newPos.x = head().x -1;
}
positions.add(0, newPos); // add new head coordinate
positions.remove(positions.lastElement()); // remove tail coordinate
}
// Directions
public void left() {
dir = 3;
}
public void right() {
dir = 1;
}
public void up() {
dir = 0;
}
public void down() {
dir = 2;
}
// Helpers
// ensures rotations wrap around
public void normalize() {
if(dir > 3)
dir = 0;
if(dir < 0)
dir = 3;
}
// returns coordinate below input
public Coord below(Coord input) {
return new Coord(input.x, input.y++);
}
}