Game Development Reference
In-Depth Information
};
}
In the global scope, we create two instances of this player class, one representing
the hero of the game and the other the enemy that we try to defeat.
var hero = new Player("[data-name='goodGuy']");
var enemy = new Player("[data-name='badGuy']");
When the game starts, we initialize some code, which is among a few other things,
means that we determine how fast the game timer is to run, how fast the enemy play-
er is to move, what phrase the user is to type in, and most importantly, we register a
keyboard event on the body element of our HTML structure. In other words, we listen
to every key press anywhere on the page, so that we can detect what the user has
typed in after the game has begun.
This is probably the most complex function in the game because we have to handle
every key press by ourselves. This means that we need to take into account wheth-
er or not the user has pressed a key while holding the Shift key (in which case they
have entered a capital letter), or whether a special key combination was pressed. For
example, if the user presses the Backspace key, by default the browser will respond
to this event by navigating the web page back to the last page navigated. Obviously,
we don't want the browser to navigate away from our game. Instead we want the last
character typed in by the user to be deleted. Thus, small details such as this must
be taken into account.
Finally, at each letter typed in by the user, we must check whether that letter was the
same letter we were expecting (the correct letter) or whether the user has typed in
a wrong letter. Based on this decision, we output to the screen the letter just typed,
along with some HTML that allows us to render that letter differently based on wheth-
er or not it was the right key.
function handleKeyPress(event) {
var keyCodes = {
SHIFT_KEY: 16,
BACKSPACE_KEY: 8,
Search WWH ::




Custom Search