Level generation using a 2D array

In this post we will investigate how to generate a level/stage for a platform game using a 2D array.

We will focus on the level for a 2D platform game such as Super Mario:
platform-level

By applying a grid layout to this stage, we can break down the stage in a collection of tiles. We can then store each tile using a 2D array as follows:

2d-array-level .

In this array, each tile can be associated with an integer value. For instance, in the above array/grid, a 1 represents a platform, a 2 represents a gold coin.

In javascript, the 2D array for this stage would be initialised as follows:

Using nested loops, we can then write an algorithm to scan through all the values of the array and display each tile corresponding to their integer value accordingly.

See the Pen
Level Generator
by 101 Computing (@101Computing)
on CodePen.

Please note that using a 2D array approach to store the details of a stage/level is not the only approach available. Other approaches could be used such as storing the position and dimensions of each platform in a list. The use of a 2D array in a more advanced game could quickly become too “greedy” in terms of memory use.

Adapt the code…


Using a 2D array approach can be used to create games using a top-down view such as Pacman. You can adapt the above code to recreate a maze used in a Pacman game as follows:
2d-array-pacman-maze-layout

Share Button
Tagged with: