Game Development Reference
In-Depth Information
Next, we have some public members that hold a
Snake
instance, a
Stain
instance, a Boolean
that stores whether the game is over, and the current score.
We define another four package private members: the 2D array we'll use to place a new stain;
an instance of the
Random
class, through which we'll produce random numbers to place the stain
and generate its type; the time accumulator variable,
tickTime
, to which we'll add the frame
delta time; and the current duration of a tick, which defines how often we advance Mr. Nom.
public
World() {
snake =
new
Snake();
placeStain();
}
In the constructor, we create an instance of the
Snake
class, which will have the initial
configuration shown in Figure
6-6
. We also place the first random stain via the
placeStain()
method.
private void
placeStain() {
for
(
int
x = 0; x <
WORLD_WIDTH
; x++) {
for
(
int
y = 0; y <
WORLD_HEIGHT
; y++) {
fields[x][y] =
false
;
}
}
int
len = snake.parts.size();
for
(
int
i = 0; i < len; i++) {
SnakePart part = snake.parts.get(i);
fields[part.x][part.y] =
true
;
}
int
stainX = random.nextInt(
WORLD_WIDTH
);
int
stainY = random.nextInt(
WORLD_HEIGHT
);
while
(
true
) {
if
(fields[stainX][stainY] ==
false
)
break
;
stainX += 1;
if
(stainX >=
WORLD_WIDTH
) {
stainX = 0;
stainY += 1;
if
(stainY >=
WORLD_HEIGHT
) {
stainY = 0;
}
}
}
stain =
new
Stain(stainX, stainY, random.nextInt(3));
}
The
placeStain()
method implements the placement strategy discussed previously. We start
off by clearing the cell array. Next, we set all the cells occupied by parts of the snake to
true
.
Finally, we scan the array for a free cell starting at a random position. Once we have found a free
cell, we create a
Stain
with a random type. Note that if all cells are occupied by Mr. Nom, then
the loop will never terminate. We'll make sure that will never happen in the next method.