HTML and CSS Reference
In-Depth Information
The player controls a spaceship by moving the mouse, and fires missiles using the left
mouse button. We need to play a “shoot” sound every time the player fires a missile.
When the missiles hit the enemy space raiders, we need to remove them from the screen,
and then play an “explosion” sound. We are not limiting the number of shots the player
can fire, which means that there could be any number of shoot and explode sounds
playing simultaneously. Our goal is to manage all these dynamic sounds.
State machine
This game runs using a very simple state machine. A state machine is a construct that
allows an application to exist in only one state at a time, which means it is only doing
one thing. This kind of construct is great for single-player games because it removes
the need to hold a bunch of Booleans describing what is going on at any one moment.
Space Raiders has four states plus a variable named appState that holds the value of the
current state. Those states include:
STATE_INIT
A state to set up the loading of assets:
const STATE_INIT = 10;
STATE_LOADING
A wait state that has the application sleep until all assets have been loaded:
const STATE_LOADING = 20;
STATE_RESET
A state to set up the initial game values:
const STATE_RESET = 30;
STATE_PLAYING
A state that handles all game-play logic:
const STATE_PLAYING = 40;
A final game of this type might have a few more states, such as
STATE_END_GAME and STATE_NEXT_LEVEL , but our case study does not re-
quire them.
The heart of our state machine is the run() function, which is called on an interval every
33 milliseconds. The appState variable determines what function to call at any given
time using a switch() statement. appState is updated to a different state any time the
program is ready to move on and do something else. The process of calling a function
such as run() on an interval and switching states is commonly known as a game loop :
function run() {
switch(appState) {
Search WWH ::




Custom Search