Building a Complete Game in 500 Lines

To drive home the point of how easy it is to build games in HTML5, the final game you build in the first three chapters contains fewer than 500 lines of code, all without using any libraries.

Understanding the Game

Alien Invasion is a top-down 2-D shooter game built in the spirit of the game 1942 (but in space) or a simplified version of Galaga. The player controls a ship, shown at the bottom of the screen, flying the ship vertically through an endless space field while defending Earth against an incoming hoard of aliens.

When played on a mobile device, control is via left and right arrows shown on the bottom left of the screen, and a Fire button on the right. When played on the desktop, the user can use the keyboard’s arrow keys to fly and the spacebar to fire.

To compensate for all the different screen sizes of mobile devices, the game resizes the play area to always play at the size of the device. On the desktop it plays in a rectangular area in the middle of the browser page.

Structuring the Game

Nearly every game of this type consists of a few of the same pieces: some asset loading, a title screen, sprites, user input, collision detection, and a game loop to tie it all together.

The game uses as few formal structures as possible. Instead of building explicit classes, you take advantage of JavaScript’s dynamic typing (more on this in the section “Building Object-Oriented JavaScript”). Languages such as C, C++, and Java are called “strongly ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.