
[ad_1]
A Tutorial for Re-creating Space Invaders with HTML and Javascript
Want to add a simple 2D game to your website? Or do you want to learn the basics of making 2D games? This article explains how to recreate the classic Space Invaders game for most modern browsers with only HTML and JavaScript.
Before starting development it might be a good idea to specify the basic features of the game to give an overview of the work that needs to be done.
The specifications of the game can be defined as follows:
- The game requires an object that can be moved, drawn on the surface of the canvas, and provides collision checks.
- Enemy and player objects must be able to fire bullets towards each other.
- A bullet object should only be able to move in one direction.
- The player object should only be able to move left and right on the x-axis within the bounds of the canvas.
- An asteroid object must have many destructive parts.
- If all enemies are destroyed, or if one of the enemies reaches the player’s position on the y-axis, the game must start over.
sporting goods
The class diagram in Figure 1 shows an overview of the different classes of play and their relationships. For example it can be seen that all scene objects are created by the base class GameObject, or that the player class inherits properties and behavior from both the Spaceship and the GameObject class.

The first step is to set up the HTML document with the canvas element (see Figure 2). An HTML canvas provides the ability to draw various 2D graphics (Mozilla, 2022a).
For example it is possible to draw simple shapes or images inside a canvas (Mozilla, 2022b) (Mozilla, 2022c). In Figure 2, line 9, the canvas element is defined with id
, width
And height
Property.
id
The property is used to refer to the canvas element in JavaScript, and width
And height
Attributes only specify the dimensions of the canvas.
The next step is to set up a JavaScript object that can be used to hold different properties and behaviors (Mozilla, 2022d). Figure 3, line 12, shows the implementation of a Javascript object called game
,
The idea behind using JavaScript objects to hold properties and behavior in this tutorial is to avoid the logic of the game being available in the form of too many global variables and functions.
general properties
Three properties are added to game
Object on line 15-19, in figure 3 canvas
The property refers to the HTML canvas element, ctx
refers to the interface, which can be used to draw on the surface of the canvas (Mozilla, 2022e), and backgroundColor
Refers to the background color of the canvas.
normal behavior
There are five methods added to this game
Object on lines 22-43, figure 3. update()
Defines the persistent behavior of the game, such as drawing elements, dynamic elements, etc. the first two lines within update()
Method (lines 24-25, Figure 3) Set the background of the canvas to the value of backgroundColor
Property.
recreating the background every time update()
Is called ensures that objects that are moving will be drawn to the new position rather than both the new and old position.keydown()
Defines what should happen if a key was pressed on the keyboard. init()
Defines the start of the game that starts the game loop. stop()
defines how to stop the game loop, and restart()
Defines how to restart the game.
A class called GameObject is added to define the general behavior of objects used within the game. A typical game object has five properties. x
And y
Defines the position of the game object. width
And height
defines the shape of the game object’s rectangle, and color
Defines the color of the rectangle.
The GameObject class also has three methods. draw()
Used to draw game objects within the canvas. update(dx, dy)
moves the game object in any direction, and collidesWith(obj)
Returns true if the given game object overlaps with the game object.
After adding the GameObject class, a simple Bullet class can be added that inherits properties and behavior from the GameObject class.
Bullet class has an additional property called dy
Which is used to define the direction in which the bullet should move on the y axis. update(dx, dy)
A method inherited from the GameObject class that is overridden in the Bullet class (see lines 22-25, Figure 5) is defined to always move towards the given start direction.
A class called Spaceship is added to define the general properties and behavior of player and enemy objects. The Spaceship class is also a subclass of the GameObject class.
The Spaceship class has five additional attributes. canvasHeight
Used to specify the boundaries of bullets fired by a spaceship. bulletWidth
And bulletHeight
Defines the dimensions of the bullets. bulletColor
defines the color of the bullets, and bullets
is an array used to specify bullets generated by spaceships.
The Spaceship class is designed to override draw(ctx)
Method inherited from the GameObject class to implement a check that removes bullets out of the screen, and loops drawing and moving bullets.
The SpaceShip class also includes an additional method called shoot(dy)
Which is used to disperse bullets moving towards a given direction on the y axis.
A Player class is added as a subclass of the SpaceShip class to implement properties and behavior specific to the Player object.
The Player class has an additional property called canvasWidth
Defining the width of the game’s canvas.

The property is used to check whether the player is outside the screen on the x-axis. The check is implemented by overriding update(dy, dx)
The method is inherited from the parent class and by adding a few extra lines of code takes the player’s position on the x-axis to zero or the width of the player by subtracting the canvas width.
The last orbit needed is the asteroid class. This class is not a subclass of the GameObject class, however, the class is closely related to the GameObject class, as it has a property called parts
Which is an array of game objects.
This design allows an asteroid to be destroyed part by part in the game (see Figure 9).

The asteroid class also has three methods. draw(ctx)
Asteroid is used to attract game objects. collidesWith(obj)
If one of the asteroid’s game objects collides with the given game object, and removeOnCollide(obj)
If one of the asteroid’s game objects collides with the given game object, removes one of the asteroid’s game objects.
Figure 11, line 24-45 shows the implementation of additional required game properties for asteroids and enemies.
Additional Asteroid Properties
asteroidsParts
The game defines the number of objects an asteroid is made of, noOfAsteroids
used to define the number of asteroids to be included in the game, and asteroidsSpace
Defines the space between each asteroid.
additional enemy properties
enemiesEachLine
Define the number of enemies to be generated on each line. enemyLines
Defines the number of lines of enemies. enemySpace
Defines the space between each enemy. enemyFireRate
defines how often enemies must fire, and enemyFireTimer
Is a variable used to keep track of the time since the last shot. enemyDirection
defines whether enemies should move left or right (left = -1, right = 1), and enemyStep
Defines how much enemies should be moved on the y-axis when they reach the left or right side of the canvas.
Now it is possible to accomplish game
of object init()
method (see lines 27-62, Figure 12). The method should include a few additional lines of code that define how to make the player, enemies, and asteroids in their initial positions.
This allows the design to be used game
of object restart()
method, to reset the game to the initial state.
game
of object keydown()
The method is called every time a user presses a key on the keyboard (see lines 23–36, figure 13). The specific key pressed can be read as a number from the argument e
reading its property keyCode
,
For example, the number 37
LEFT ARROW KEY, and defines the number 39
Defines the right arrow key. keydown()
The method is designed to test whether the user has pressed one of the arrow keys, or the A-key and D-key, which move the player left or right. It also includes an additional test to detect when the user presses the space key which triggers a bullet in the player’s position.
The last mode of the game that needs modification is game
of object update()
Method (see lines 23-154, Fig. 14).
Draw players, asteroids and enemies
Rows 29-38, Figure 14, Just Call draw(ctx)
method on different objects to ensure that they are drawn within the canvas. Line 39, figure 14, draws enemies in the same loop, moving enemies in the direction specified in enemyDirection
Property.
enemy count check
Rows 43-46, Figure 14, Check if game
of object enemies
The array is empty, and restarts the game if the check evaluates to true. This check may include additional codes that reduce a player’s life
property until it reaches zero, which will then restart the game.
enemy movement
Rows 49-91, Figure 14, Check if enemyDirection
The property is either 1 or -1. If the property is 1, the method finds the enemy closest to the right side of the screen, and if that enemy approaches the right, the method sets enemyDirection
to -1 and takes all enemies below a value of k enemyStep
, The opposite happens if . value of enemyDirection
is -1.
enemy random shot
Rows 94-99, Figure 14, Extend enemyTimer
Property unless a random enemy is chosen to fire a shot moving towards the player.
bullet collision investigation
Lines 102–154, figure 14, show four loops with almost identical behaviour. For example, the first loop, Lines 101-110, Figure 14, loops through all player bullets and checks if they hit one of the Asteroids game objects. The third loop, Lines 125–134, Figure 14, loops through all the player bullets and checks whether one of the bullets collides with the enemy.
Full code can be found here this link.
Mozilla. 2022a. Canvas API.
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API,
Accessed: 28 June 2022
Mozilla. 2022b. using images.
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images,
Accessed: 28 June 2022
Mozilla. 2022c. Drawing shapes with canvas.
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes,
Accessed: 28 June 2022
Mozilla. 2022d. working with objects.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects,
Accessed: 28 June 2022
Mozilla. 2022E. Canvas RenderingContext 2D.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D,
Accessed: 28 June 2022
[ad_2]
Source link
#Build #Classic #Space #Invaders #Game #JavaScript #HTML