This is the third post in a series of blog posts about creating modular worlds with tilemaps in the Phaser 3 game engine. In this edition, we’ll create an endless, procedurally-generated dungeon:

Tileset and Character by Michele “Buch” Bucelli

If you haven’t checked out the previous posts in the series, here are the links:

In the next post in the series, we’ll investigate using Matter.js with tilemaps.

Before we dive in, all the source code and assets that go along with this post can be found in this repository. These tutorials use the latest version of Phaser (v3.16.2) and Tiled (v1.2.2) as of 02/26/19. Some pairings of older versions of Phaser and Tiled don’t get along well, so I recommend using these two version.

Intended Audience

This post will make the most sense if you have some experience with JavaScript (classes, arrow functions & modules), Phaser and the Tiled map editor. If you don’t, you might want to start at the beginning of the series, or continue reading and keep Google, the Phaser tutorial and the Phaser examples & documentation handy.

Alright, Let’s get into it!

Overview

This post builds on the idea of static vs dynamic tilemap layers that we talked about last time. The code we’re going to build in this post is based on one of my contributions to Phaser Labs. It was definitely the example I had the most fun making, and it conveniently covers a lot of additional parts of the dynamic tilemap layer API that we haven’t covered yet — from randomizing tiles to using per-tile transparency to create shadows.

We’ll start by getting comfortable with a dungeon generator library using vanilla HTML & JS. From there, we’ll start bringing in Phaser and progressively building out our endless dungeon world.

A Dungeon

We’re going to get a head start on generating worlds by using a dungeon generator library, mikewesthad/dungeon. It’s my updated fork of nickgravelyn/dungeon that has a few new features, along with being published on npm. It’s a pretty simple, brute force dungeon generator. You give it some configuration info, and it randomly builds a dungeon room-by-room starting at the center of the map.

You can load the library via a CDN, by downloading the script, or through npm (install instructions). Once you’ve got the library loaded, you’ll have a Dungeon class that you can use to construct a dungeon instance like this:

And we can visualize the random dungeon by generating some HTML via dungeon.drawToHtml which converts the dungeon to a <pre><table> ... </table></pre> HTML element. We just need to specify which characters we want to use for each type of "tile" in the dungeon:

And voilà, emoji-goodness: