The Playfield

The game playfield is a 15×15 grid of 32×32 tiles. This is a total of 225 tiles with a width and height of 480 pixels each. Every time we start a new game, all the objects are placed randomly on the grid. The playField[] array holds 15 row arrays each with 15 columns. This gives us 225 tiles that can be easily accessed with the simple playField[row][col] syntax.

We first place a road tile on each of the 225 playField array locations. We then randomly place all the wall tiles. (These actually replace some of the road tiles at locations in the playField array.)

Next, we randomly place all the enemy tank tiles. Unlike the wall tiles, the tank tiles do not replace road tiles in the playField array. Instead, they are placed in an array of their own called enemy. To ensure that neither the player nor the goal object occupies the same tile space as the enemy tanks, we create another array, items.

The items array is also a 15×15 two-dimensional array of rows and columns, which can be considered the second layer of playfield data. Unlike the playField array, it is used only to make sure no two objects (player, enemy, or goal) occupy the same space while building the playfield. We must do this because the player and enemy objects are not added to the playField array.

After we have placed the enemy, we randomly place the player at a spot that is not currently occupied by an enemy or a wall. Finally, we place the goal tile in a spot not taken by the player, a wall, or an enemy tank. ...

Get HTML5 Canvas, 2nd Edition 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.