Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Space Invaders Game Written in TypeScript

4.67/5 (4 votes)
8 Dec 2014CPOL2 min read 30.6K   572  
This is a browser-based game similar to the old Space Invaders video game written in TypeScript.

Introduction

The code is written entirely in TypeScript. It provides examples of object orientation in TypeScript such as classes, constructors, and public/private/static object attributes and methods. It is also a good example of how to create a 2D game with a viewport, event handlers (listeners) and the use of JavaScript setInterval and setTimeout functions.

Using the Code

The code consists entirely of four separate classes encased in a TypeScript module. The four classes are named Game, Ship, Rocket and Alien. The Game class is the primary class used to control the game itself and is the one instantiated outside of the Games module as follows where 'viewPort' is the id of a <div> element where the game is displayed.

C#
var game = new Games.Game('viewPort');

The setInterval JavaScript function is used to keep the game itself running. You provide a function and a time interval (in milliseconds) to setInterval and the function provided is continually invoked until the window is closed. Here is an example of using setInterval to keep the aliens moving:

C#
setInterval(() =>
{ 
    for (var index = 0; index < this.aliens.length; index++)
        if (this.aliens[index].active)
            this.aliens[index].Move();
}, 1);

The aliens attribute is an array that stores all of the aliens and each member of the array is an object of class type Alien.

A standard 'keydown' event listener is used for handling keyboard input. You will notice that this uses a static JSON object from the Game class that acts as a kind-of enum that provides a textual description of the ASCII key codes used:

C#
public static KeyCodes = { LeftArrow: 37, RightArrow: 39, SpaceBar: 32 };

So, in the event listener, we can use the associated text description of the key in a switch statement as follows:

C#
switch (keyCode)
{
    case Game.KeyCodes.LeftArrow:
    case Game.KeyCodes.RightArrow:
        this.ship.Move(keyCode);
        break;

    case Game.KeyCodes.SpaceBar:
        if (this.rocket.active)
            this.rocket.Move();
        else
            this.rocket.Start(this.ship.posX + (this.ship.width / 2), this.ship.posY);
        break;
}

The JavaScript window function setTimout is used in the Kill function of the Alien class to control an exploding alien. Four different images are displayed in sequence to mimic an exploding alien as follows:

C#
public Kill()
{
    this.image.style.visibility = 'hidden';
    this.active = false;

    if (this.explosionImageURLs.length > 0)
    {
        this.explosionIndex = 0;
        for (var index = 0; index < this.explosionImageURLs.length; index++)
        {
            setTimeout(() =>
            {
                if (!this.explosionImage)
                {
                    this.explosionImage = <HTMLImageElement>document.createElement('img');
                    this.viewPort.appendChild(this.explosionImage);
                    this.explosionImage.style.position = 'absolute';
                    this.explosionImage.style.zIndex = '9999';
                    this.explosionImage.style.posLeft = this.posX;
                    this.explosionImage.style.posTop = this.posY;
                }

                this.explosionImage.src = this.explosionImageURLs[this.explosionIndex++];
            }, index * 200);
        }

        setTimeout(() =>
        {
            this.viewPort.removeChild(this.explosionImage);
        }, this.explosionImageURLs.length * 200);
    }
}

The rest of the code is relatively straight forward. Each of the Ship, Rocket and Alien classes encapsulates its own image and position within the viewport and provide a Move, SetXPos and SetYPos functions that control the movement of each object.

History

  • Version 1

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)