Cover by Raffaele Cecco

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

The Game Code

This section examines the entire code for the game, deconstructing all the game elements and covering them in detail.

Game-Wide Variables

Here, the various game variables are defined; for clarity and convenience, the unchanging constants appear in all uppercase. $drawTarget refers to the play area, which is defined as a div element within the page:

var PLAYER = 1,
    LASER = 2,
    ALIEN = 4,
    ALIEN_BOMB = 8,
    SHIELD = 16,
    SAUCER = 32,
    TOP_OF_SCREEN = 64,
    TANK_Y = 352 - 16,
    SHIELD_Y = TANK_Y - 56,
    SCREEN_WIDTH = 480,
    SCREEN_HEIGHT = 384,
    ALIEN_COLUMNS = 11,
    ALIEN_ROWS = 5,
    SYS_process,
    SYS_collisionManager,
    SYS_timeInfo,
    SYS_spriteParams = {
        width: 32,
        height: 32,
        imagesWidth: 256,
        images: '/images/invaders.png',
        $drawTarget: $('#draw-target')
    };

Reading Keys

jQuery makes reading keyboard input in JavaScript relatively easy. By listening for keydown and keyup events bound to the page (document), and reading the which property of the passed event{} object after the keyboard event is triggered, we can determine which keys have been pressed or released. Orbit Assault requires checking for three keys—left, right, and fire:

var keys = function () {

The keyMap{} object maps event key codes to the name of the game button we are interested in. In this case, key Z is the left button, key X is the right button, and key M is the fire button. We can change these to any other desired keys (see Table 5-1):

    var keyMap = {
        '90': 'left',
        '88': 'right',
        '77': 'fire'
    },

Table 5-1. JavaScript key codes ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required