Pure JavaScript A* maze solving – with a bit of magic thanks to Phaser and EasyStar.js updated to Phaser 3.8.0 and EasyStar.js 0.4.3

Read all posts about "" game
During these days I am working on a project which requires A* algorithm for path finding, so I grabbed my 3 years old post “Pure JavaScript A* maze solving – with a bit of magic thanks to Phaser and EasyStar.js” and updated to the latest Phaser and EasyStar versions. Here is a maze, solved by A* algorithm, going from the top left cell to the bottom right cell. Once a maze is solved, a new random maze is generated and solved again, and so on.
I am using the awesome EasyStar.js to solve the maze. If you want more information about maze generation, refer to the post “Pure JavaScript perfect tile maze generation – with a bit of magic thanks to Phaser“. If you are interested in the source code, here it is:
var game;

var gameOptions = {
    mazeWidth: 81,
    mazeHeight: 61,
    tileSize: 10
}

window.onload = function() {
    var gameConfig = {
       type: Phaser.CANVAS,
       width: gameOptions.mazeWidth * gameOptions.tileSize,
       height: gameOptions.mazeHeight * gameOptions.tileSize,
       backgroundColor: 0xaaaaaa,
       scene: [playGame]
    };
    game = new Phaser.Game(gameConfig);
    window.focus()
    resize();
    window.addEventListener("resize", resize, false);
}

class playGame extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }
    create(){
        this.mazeGraphics = this.add.graphics();
        var moves = [];
        this.maze = [];
        for(var i = 0; i < gameOptions.mazeHeight; i ++){
            this.maze[i] = [];
            for(var j = 0; j < gameOptions.mazeWidth; j ++){
                this.maze[i][j] = 1;
            }
        }
        var posX = 1;
        var posY = 1;
        this.maze[posX][posY] = 0;
        moves.push(posY + posY * gameOptions.mazeWidth);
        while(moves.length){
            var possibleDirections = "";
            if(posX+2 &gt; 0 &amp;&amp; posX + 2 < gameOptions.mazeHeight - 1 &amp;&amp; this.maze[posX + 2][posY] == 1){
                possibleDirections += "S";
            }
            if(posX-2 &gt; 0 &amp;&amp; posX - 2 < gameOptions.mazeHeight - 1 &amp;&amp; this.maze[posX - 2][posY] == 1){
                possibleDirections += "N";
            }
            if(posY-2 &gt; 0 &amp;&amp; posY - 2 < gameOptions.mazeWidth - 1 &amp;&amp; this.maze[posX][posY - 2] == 1){
                possibleDirections += "W";
            }
            if(posY+2 &gt; 0 &amp;&amp; posY + 2 < gameOptions.mazeWidth - 1 &amp;&amp; this.maze[posX][posY + 2] == 1){
                possibleDirections += "E";
            }
            if(possibleDirections){
                var move = Phaser.Math.Between(0, possibleDirections.length - 1);
                switch (possibleDirections[move]){
                    case "N":
                        this.maze[posX - 2][posY] = 0;
                        this.maze[posX - 1][posY] = 0;
                        posX -= 2;
                        break;
                    case "S":
                        this.maze[posX + 2][posY] = 0;
                        this.maze[posX + 1][posY] = 0;
                        posX += 2;
                        break;
                    case "W":
                        this.maze[posX][posY - 2] = 0;
                        this.maze[posX][posY - 1] = 0;
                        posY -= 2;
                        break;
                    case "E":
                        this.maze[posX][posY + 2] = 0;
                        this.maze[posX][posY + 1] = 0;
                        posY += 2;
                        break;
                }
                moves.push(posY + posX * gameOptions.mazeWidth);
            }
            else{
                var back = moves.pop();
                posX = Math.floor(back / gameOptions.mazeWidth);
                posY = back % gameOptions.mazeWidth;
            }
        }
        this.drawMaze(posX, posY);
        var easystar = new EasyStar.js();
        easystar.setGrid(this.maze);
        easystar.setAcceptableTiles([0]);
        easystar.findPath(1, 1, gameOptions.mazeWidth - 2, gameOptions.mazeHeight - 2, function(path){
            this.drawPath(path);
        }.bind(this));
        easystar.calculate();
    }
    drawMaze(posX, posY){
        this.mazeGraphics.fillStyle(0x000000);
        for(var i = 0; i < gameOptions.mazeHeight; i ++){
            for(var j = 0; j < gameOptions.mazeWidth; j ++){
                if(this.maze[i][j] == 1){
                    this.mazeGraphics.fillRect(j * gameOptions.tileSize, i * gameOptions.tileSize, gameOptions.tileSize, gameOptions.tileSize);
                }
            }
        }
    }
    drawPath(path){
        var i = 0;
        this.time.addEvent({
            delay: 5,
            callback: function(){
                if(i < path.length){
                    this.mazeGraphics.fillStyle(0x660000);
                    this.mazeGraphics.fillRect(path[i].x * gameOptions.tileSize + 1, path[i].y * gameOptions.tileSize + 1, gameOptions.tileSize - 2, gameOptions.tileSize - 2);
                    i++;
                }
                else{
                    this.scene.start("PlayGame");
                }
            },
            callbackScope: this,
            loop: true
        });
    }
}
function resize() {
    var canvas = document.querySelector("canvas");
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;
    var windowRatio = windowWidth / windowHeight;
    var gameRatio = game.config.width / game.config.height;
    if(windowRatio < gameRatio){
        canvas.style.width = windowWidth + "px";
        canvas.style.height = (windowWidth / gameRatio) + "px";
    }
    else{
        canvas.style.width = (windowHeight * gameRatio) + "px";
        canvas.style.height = windowHeight + "px";
    }
}
Next time I’ll show you a little RPG engine using A* algorithm, meanwhile download the source code.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers