[Phaser 3] Maze generation + shadows render

mazesmall
Demo: https://jjcapellan.github.io/maze-generator/
Info and source: https://github.com/jjcapellan/maze-generator/

Hi all,
I was thinking of making a pacman style game, and I found it interesting to create a class to generate mazes.

The Maze class generates two types of array to represent a maze. I have tried to implement a non-recursive backtracker algorithm. Surely there are more efficient implementations, but at least I understand my code :smile: .

The Maze.tiles () method returns a 2d array of ones and zeros, which can be used directly by a Phaser Tilemap.

The Maze.cells () method returns an array of cells like this cell:

[1 /*left open*/, 0 /*up closed*/, 0 /*down closed*/, 1 /*right open*/]

This second format can be useful if for example we have an image for each type of cell.

Maze.gateway (cellX, cellY) allows us to define a gateway to the maze.

For the demo I only used two images (wall, floor) and a 2d array generated with Maze.tiles (). This is the rendering function with my way to add shadows:

renderTiles(x, y, maze, tilesize) {
    const width = tilesize * maze[0].length;
    const height = tilesize * maze.length;

    // Walls    
    let wallsMap = this.make.tilemap({ data: maze, tileWidth: 50, tileHeight: 50 });
    let wallTile = wallsMap.addTilesetImage('wall');
    let wallsLayer = wallsMap.createStaticLayer(0, wallTile, x, y);
    wallsLayer.setDisplaySize(width, height);

    // Floor 
    this.swapZeros(maze); // swaps 0 - 1
    let map = this.make.tilemap({ data: maze, tileWidth: 50, tileHeight: 50 });
    let floorTile = map.addTilesetImage('floor');
    let floorLayer = map.createStaticLayer(0, floorTile, x, y);
    floorLayer.setDisplaySize(width, height);

    // Shadows
    const offset = 0.2 * tilesize;
    let rt = this.add.renderTexture(x + offset, y + offset, width, height);
    rt.draw(wallsLayer, 0, 0);
    rt.setAlpha(0.4);
    rt.setTint(0);

    // Move walls to front
    wallsLayer.setDepth(rt.depth + 1);
  }

Greetings and merry Christmas to all !!

4 Likes

that’s really cool! great job