unsigned long target_creation;
10
-
enum GameState {
-
INTRO, STARTING, RUNNING, DONE
-
};
-
15
GameState state;
-
In game programming you often have to manage a lot of global variables—even
in a small game like ours. First, we define a TVout instance named
tv
and a
Nunchuk instance named
nunchuk
. After that, we define Boolean variables for
all Nunchuk properties we’re interested in. They all work the same—we set
up
to
true
, for example, if the user pushes the Nunchuk’s analog stick upward.
chx
and
chy
contain the current position of the crosshairs.
chvx
and
chvy
contain
its X and Y velocity. Similarly,
target_x
and
target_y
contain the position of the
current target. Because the target is a circle, we also need a radius, which
we store in
target_r
.
target_count
contains the number of targets we’ve created already, and in
hits
you can find the number of targets the player has hit so far. Targets disappear
automatically after a short period of time, so we need a place to store the
creation time of the current target. This place is
target_creation
.
In line 12, we define an enumeration that lists our game’s potential states. If
the game is in the
INTRO
state, it displays a title screen and waits for the
player to press the Z button. If the player presses the Z button, the game
changes to the
STARTING
state. It outputs a “READY?” message and waits for
another button press to give the player some time to prepare.
The
RUNNING
state is where all the action is. In this state the game loop creates
new targets, checks the player’s moves, and so on. After all targets have
appeared, the game state changes to
DONE
. The player will see a game-over
screen and the number of targets that he or she has hit.
We need to initialize all of these global variables whenever a new game starts.
The following functions will do that:
Tinkering/Pragduino/Pragduino.ino
void init_game() {
up = down = left = right = c_button = z_button = false;
chx = WIDTH / 2;
chy = HEIGHT / 2;
chvx = 1;
chvy = 1;
state = INTRO;
target_count = 0;
Chapter 9. Tinkering with the Wii Nunchuk • 156
report erratum • discuss
www.it-ebooks.info