Click here to Skip to main content
15,881,709 members
Articles / Web Development / HTML
Tip/Trick

Space Invaders Game Written in TypeScript

Rate me:
Please Sign up or sign in to vote.
4.67/5 (4 votes)
8 Dec 2014CPOL2 min read 30.1K   571   12   1
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)


Written By
Software Developer (Senior)
United States United States
For over 25 years I have worked in the Information Systems field as both a full-time employee and an independent contractor for a variety of companies.

I have extensive professional experience with numerous programming languages and technologies including C#, JavaScript, SQL, VB.NET, and ASP.NET as well as a working knowledge of a great variety of others. I also have an advanced understanding of the concepts behind these technologies including Object-Oriented Programming, Relational Data, Functional Programming, MVC and MVVM.

Some of my more recent work has been designing and building web applications primarily with JavaScript in conjunction with many of the JavaScript libraries/frameworks including jQuery, KnockoutJS and Bootstrap and consuming both JSON and REST services.

In nearly all of the work I have been involved with in the past ten years I have played a lead role in the design as well as the development of the work. More recently I have managed a team of software developers at a local mid-size company.

Comments and Discussions

 
QuestionNice, thanks Pin
Garry Lowther9-Dec-14 2:43
Garry Lowther9-Dec-14 2:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.