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:

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:

var grid = [

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:

Did you like this challenge?

Click on a star to rate it!

Average rating 4 / 5. Vote count: 4

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: