Game Development Reference
In-Depth Information
Next, we define a list called
parts
that holds all the parts of Mr. Nom. The first item in that list is
the head, and the other items are the tail parts. The second member of the
Snake
class holds the
direction in which Mr. Nom is currently heading.
public
Snake() {
direction =
UP
;
parts.add(
new
SnakePart(5, 6));
parts.add(
new
SnakePart(5, 7));
parts.add(
new
SnakePart(5, 8));
}
In the constructor, we set up Mr. Nom to be composed of his head and two additional tail parts,
positioned more or less in the middle of the world, as shown previously in Figure
6-6
. We also
set the direction to
Snake.UP
, so that Mr. Nom will advance upward by one cell the next time he's
asked to advance.
public void
turnLeft() {
direction += 1;
if
if(direction >
RIGHT
)
direction =
UP
;
}
public void
turnRight() {
direction - = 1;
if
if(direction <
UP
)
direction =
RIGHT
;
}
The methods
turnLeft()
and
turnRight()
just modify the direction member of the
Snake
class.
For a turn left, we increment it by one, and for a turn right, we decrement it by one. We also have
to make sure that we wrap Mr. Nom around if the
direction
value gets outside the range of the
constants we defined earlier.
public void
eat() {
SnakePart end = parts.get(parts.size()-1);
parts.add(
new
SnakePart(end.x, end.y));
}
Next up is the
eat()
method. All it does is add a new
SnakePart
to the end of the list. This new
part will have the same position as the current end part. The next time Mr. Nom advances, those
two overlapping parts will move apart, as discussed earlier.
public void
advance() {
SnakePart head = parts.get(0);
int
len = parts.size() - 1;
for
(
int
i = len; i > 0; i--) {
SnakePart before = parts.get(i-1);
SnakePart part = parts.get(i);
part.x = before.x;
part.y = before.y;
}