How to Procedurally Generate a Dungeon in Phaser – Part 1

Some games have a fixed number of levels created by a level designer. This way, the designer can create the levels so as to provide the desired gameplay experience to the player. However, it reduces the replay value of the game, since the levels will always be the same every time they are played.
Another alternative is to procedurally generate levels using an algorithm instead of a level designer. This results in a virtually infinite number of levels, and the player will never play the same level twice. However, since the game designers have no full control on the levels, they probably won’t be so good as if they were generated by a experienced level designer.
Each kind of game level (manual or procedural) has advantages and disadvantages, and can be applied in different kinds of games (both strategies could even be used in the same game). In this tutorial, we will procedurally create a dungeon with multiple rooms, using a simple algorithm. Notice that there are several ways of doing so (as you can check here), and each one can be recommended for a specific kind of game. So, if you’re building a game and need procedurally generated content (not just levels), take a look in different approaches to see which one better fits your game.
First, I will explain the algorithm we are going to use to generate our dungeon. Then, we will build a demo that creates a dungeon with multiple rooms and load them using Tiled maps.
To read this tutorial, it is important that you’re familiar with the following concepts:

  • Javascript and object-oriented concepts.
  • Basic Phaser concepts, such as: states, sprites, groups and arcade physics
  • Creating maps using Tiled

Learn Phaser by building 15 games

If you want to master Phaser and learn how to publish Phaser games as native games for iOS and Android feel free to check Zenva‘s online course The Complete Mobile Game Development Course – Build 15 Games.

Source code files

You can download the tutorial source code files here.

Creating the Tiled maps

We will start by creating room templates using Tiled for each possible room in our game. Then, our game will load the correct room map according to the current room configuration. For example, if the player is currently in a room with a single door in the north direction, it should load the “room_N.json” map.

The figure below shows an example of room created using Tiled. If you’re not familiar with Tiled, you can check one of my previous tutorials, where I cover it with more details. Even if you’re familiar with it, I highly suggest using the maps provided by the source code, since it is necessary to create one for each room configuration (resulting in a total of 15 maps). If you still wish to create your own maps, the only required things to follow is that you must create a layer called collision with a collision property set to true, and you must set the object properties as shown below, as this will be required for our demo.

maplayer_properties object_properties

The Dungeon Generation Algorithm

We’re going to procedurally generate a dungeon with multiple rooms in a grid structure. We will do that by creating a given number of rooms by traveling a grid, and then connecting the neighbor rooms.
Given a grid and a desired number of rooms “n”, we generate the dungeon with the following steps:

  1. Add the cordinate of the middle of the grid in a list called “rooms_to_create”
  2. While the number of created rooms is less than “n”, repeat:
    1. Get the first coordinate in “rooms_to_create”
    2. Create a room with this coordinate
    3. Add this room in a “created_rooms” list
    4. Add a random number of neighbor coordinates of the current room to “rooms_to_create”
  3. After all rooms are created, connect all neighbor rooms

Notice that, for this algorithm to work we must guarantee that each iteration of the while loop in step two adds at least one new room to “rooms_to_create”, so the algorithm may continue until all rooms are created. We guarantee that by making the grid big enough so the dungeon can always be expanded to any direction (this is possible if the width and height of the grid is twice the number of rooms, for example) and by forcing the last step of the while loop to always add at least one neighbor coordinate to “rooms_to_create”.
The code below shows the implementation of this algorithm. The algorithm is implemented in the “generate_dungeon” method. First, it initialize the grid with its dimensions equals twice the number of rooms, and add the middle coordinate to the “rooms_to_create” list. Then, the while loop repeats the process described by the algorithm, creating a new room and adding a random number of neighbors to “rooms_to_create”. After creating all rooms, it iterates through all of them connecting them.

The method “check_for_neighbors” is responsible for adding the random neighbors to “rooms_to_create”. First, it finds how many neighbor coordinates are not occupied yet, putting them in the “available_neighbors” list. Then, it selects the number of neighbors that will be created randomly, using Phaser random data generator (you can learn more of it, in Phaser documentation). Finally, for each neighbor coordinate to be created, it randomly chooses one of the available neighbors. This is done by assigning a range to each available neighbor and generating a random number between 0 and 1. The chosen neighbor is the one whose range contains the generated number. For example, if there are two available neighbors, the first one will be selected if the generated number is up to 0.5, otherwise the second neighbor is selected.
We still have to create our Room class, which is shown below. The room will have its coordinates and should be able to inform its neighbors and the name of its map file. The method “neighbor_coordinates” simply returns the neighbor coordinates in each direction. The method “connect” is used to define the neighbors that actually exist and the “template_name” method returns the name of the JSON map to be loaded for this room. This name always starts with “room_” and it’s followed by the directions that there are rooms, in clockwise order. For example, if the room has doors in the north, south and west directions, its template name is “room_NSW.json”.

Phaser states of our demo

We will save the level data of our demo in a JSON file, which will be read when it starts. The JSON file I’m going to use is shown below. This file will define the game assets and groups, which will be the same for any room. This way we can preload all the assets in a LoadingState and create all groups before loading the map. Since the map file will be different for each room, it will be passed as a parameter, instead of being defined in the JSON file.

Our demo will have four states: BootState, LoadingState, DungeonState and RoomState. The frist two states are simple and responsible for loading the game JSON file and all the necessary assets before starting any room. Their codes are shown below. You can see that BootState simply loads the JSON file in its “preload” method and starts the LoadingState in the “create” method. The LoadingState, by its turn, loads all the assets in the “preload” method, by using the asset type to call the appropriate Phaser method. When all assets are loaded, it starts the next state (in the “next_state” variable) in the “create” method.

The DungeonState will be responsible for generating the dungeon, and it is shown below. It initializes the Dungeon object in the “init” method and generate a new dungeon in the “create” method. After generating the dungeon it starts a RoomState with the initial room of the dungeon.

Finally, RoomState is where most of the game will run. In the “init” method it starts the physics engine, sets the scale and save data for other methods. In the “preload” method it loads the map file given by the room template name. Then, in the “create” method it creates the map, the map layers, the groups and the prefabs. Notice that when creating the layers we check for the collision property to make it collidable. The “create_object” method is responsible for creating the prefabs. First, it adjusts the positions, since Tiled and Phaser coordinate systems are different, then it instantiate the correct prefab using the “prefab_classes” property (initially empty). Notice that, this is possible because all prefabs have the same constructor, defined in their base class shown below.

By now you can already try running the demo to see if its correcting loading the room maps. Try running multiple times and see if the initial room is changing.


Navigating through the rooms

You may have noticed the Tiled maps provided in the source code have hero and doors prefabs, which will be used to allow our hero to navigate through the dungeon rooms. Now, we are going to implement them.
First, the Hero prefab code is shown below. The only thing it will do by now is walk, so it just needs a “walking_speed” property. In the “update” method we check for player input to move the hero, which is done with the “cursors” object. To properly control the hero, we move it to a given direction only if it is not already moving to the opposite direction. For example, the hero can move left only if it is not already moving right. Also, if the player is moving, we must play the walking animation, otherwise stop it.

Now, we implement the Door prefab as shown below. It will have a “direction” property so we can know to where the player is navigating. In the “update” method we check for collisions with the hero, and if so, call the “enter_door” method. This method gets the next room using the door direction and starts a new RoomState for the next room.

Finally, we add both the Hero and Door prefabs to the “prefab_classes” property in the RoomState. And then, you can actually run the demo navigating through the different rooms in the dungeon.

And this conclude this tutorial. In the next one we will populate the rooms with random obstacles and enemies. Then, we will add an exit, so the hero can leave the dungeon.