The Essential Guide to HTML5

(Greg DeLong) #1

MAZES


{


keyCode = event.keyCode;
event.preventDefault();
}


The preventDefault method does what it sounds like: prevents any default action, such as a special
shortcut action that is associated with the particular key in the particular browser. The only keys of
interest in this application are the arrow keys. The following switch statement moves the Token
referenced by the variable mypent; that is, the location information is changed so that the next time
everything is drawn, the token will move. (This isn't quite true. The moveit function contains a collision
check to make sure we dont hit any walls first, but that will be described later.)


switch(keyCode)
{
case 37: //left arrow
mypent.moveit(-unit,0);
break;
case 38: //up arrow
mypent.moveit(0,-unit);
break;
case 39: //right arrow
mypent.moveit(unit,0);
break;
case 40: //down arrow
mypent.moveit(0,unit);
break;
default:
window.removeEventListener('keydown',getkeyAndMove,false);
}


Tip: Do put comments in your code as demonstrated by the comments indicating the keyCode for the
different arrow keys. The examples in this book don't have comments because Ive supplied an
explanation for every line of code in the relevant tables, so this is a case of do as I say, not as I
(mostly) do. Comments are critical for team projects and for reminding you of whats going on when
you return to old work. In JavaScript, you can use the // to indicate that the rest of the line is a
comment or surround multiple lines with / and /. Comments are ignored by the JavaScript
interpreter.


How did I know that the keycode for the left arrow was 37? You can look up keycodes on the Web (for
example, http://www.w3.org/2002/09/tests/keys.html)) or you can write code that issues an alert statement:


alert(" You just pressed keycode "+keyCode);


The default action for our maze application, which occurs when the key is not one of the four arrow keys,
stops event handling on key strokes. The assumption here is that the player wants to type in a name to
save or retrieve wall information to or from local storage. In many applications, the appropriate action to
take would be a message, possibly using alert, to let the user know what the expected keys are.

Free download pdf