“Mike Dangers” HTML5 game engine made with Phaser and ARCADE physics – optimizing the code and making the game fair

Read all posts about "" game
In this new chapter of the Mike Dangers series we are going to optimize the code and make the game fair. Making a game fair is the top priority when you randomly generate levels. Players have to have the feeling they lost the game because they weren’t skilled enough – and they will retry – and not because the level was in some way impossible to solve. In previous step, spikes are randomly placed on the floor, and sometimes – quite often actually – they are placed right at the end of a ladder, making the player crashing into them with no way to avoid them. To prevent this, each time I place a ladder I create some kind of “safe area”, which means each ladder has a “spike-free” radius. Sme thing goes for the spikes, each spike has its own “spike-free” radius because we do not want two spikes being too close to each other. Another important change is I do not longer use arrays to store floors, ladders and stuff. I only use arrays for the object pooling while in-game objects are only organized in groups. This won’t affect performance because we only have a few objects on the canvas, but will make the code more understandable and easier to port in other languages. Last but not least, floors below the player won’t fall down anymore. It just does not feel realistic. Now they simple scroll down, fading away into some kind of fog. Well, have a look at the game:
Just tap or click to make the player jump. Try to climb the ladders and collect diamonds while avoding spikes. If you have a mobile device, you can play directly at this link. Now, the source code, not that big for a complete prototype:
var game;
var gameOptions = {
    gameWidth: 800,
    floorStart: 1 / 8 * 5,
    floorGap: 250,
    playerGravity: 10000,
    playerSpeed: 450,
    climbSpeed: 450,
    playerJump: 1800,
    diamondRatio: 2,
    doubleSpikeRatio: 1,
    skyColor: 0xaaeaff,
    safeRadius: 120
}
window.onload = function() {
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;
    if(windowWidth > windowHeight){
        windowHeight = windowWidth * 1.8
    }
    game = new Phaser.Game(gameOptions.gameWidth, windowHeight * gameOptions.gameWidth / windowWidth);
    game.state.add("PreloadGame", preloadGame);
    game.state.add("PlayGame", playGame);
    game.state.start("PreloadGame");
}
var preloadGame = function(game){}
preloadGame.prototype = {
    preload: function(){
        game.stage.backgroundColor = gameOptions.skyColor;
        game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
        game.scale.pageAlignHorizontally = true;
        game.scale.pageAlignVertically = true;
        game.stage.disableVisibilityChange = true;
        game.load.image("floor", "floor.png");
        game.load.image("hero", "hero.png");
        game.load.image("ladder", "ladder.png");
        game.load.image("diamond", "diamond.png");
        game.load.image("spike", "spike.png");
        game.load.image("cloud", "cloud.png");
    },
    create: function(){
        game.state.start("PlayGame");
    }
}
var playGame = function(game){}
playGame.prototype = {
    create: function(){
        this.gameOver = false;
        this.reachedFloor = 0;
        game.physics.startSystem(Phaser.Physics.ARCADE);
        this.canJump = true;
        this.isClimbing = false;
        this.defineGroups();
        var cloud = game.add.sprite(0, game.height, "cloud");
        cloud.anchor.set(0, 1);
        cloud.tint = gameOptions.skyColor;
        this.drawLevel();
        this.defineTweens();
        game.input.onTap.add(this.handleTap, this);
    },
    drawLevel: function(){
        this.currentFloor = 0;
        this.highestFloorY = game.height * gameOptions.floorStart;
        this.floorsBeforeDisappear = Math.ceil((game.height - game.height * (gameOptions.floorStart)) / gameOptions.floorGap) + 1;
        this.floorPool = [];
        this.ladderPool = [];
        this.diamondPool = [];
        this.spikePool = [];
        while(this.highestFloorY > - 2 * gameOptions.floorGap){
                this.addFloor();
                if(this.currentFloor > 0){
                    this.addLadder();
                    this.addDiamond();
                    this.addSpike();
                }

                this.highestFloorY -= gameOptions.floorGap;
                this.currentFloor ++;
        }
        this.highestFloorY += gameOptions.floorGap;
        this.currentFloor = 0;
        this.addHero();
    },
    addFloor: function(){
        if(this.floorPool.length > 0){
            var floor = this.floorPool.pop();
            floor.y = this.highestFloorY;
            floor.revive();
        }
        else{
            var floor = game.add.sprite(0, this.highestFloorY, "floor");
            this.floorGroup.add(floor);
            game.physics.enable(floor, Phaser.Physics.ARCADE);
            floor.body.immovable = true;
            floor.body.checkCollision.down = false;
        }
    },
    addLadder: function(){
        var ladderXPosition = game.rnd.integerInRange(50, game.width - 50);
        if(this.ladderPool.length > 0){
            var ladder = this.ladderPool.pop();
            ladder.x = ladderXPosition;
            ladder.y = this.highestFloorY;
            ladder.revive();
        }
        else{
            var ladder = game.add.sprite(ladderXPosition, this.highestFloorY, "ladder");
            this.ladderGroup.add(ladder);
            ladder.anchor.set(0.5, 0);
            game.physics.enable(ladder, Phaser.Physics.ARCADE);
            ladder.body.immovable = true;
        }
        this.safeZone = [];
        this.safeZone.length = 0;
        this.safeZone .push({
            start: ladderXPosition - gameOptions.safeRadius,
            end: ladderXPosition + gameOptions.safeRadius
        });
    },
    addDiamond: function(){
        if(game.rnd.integerInRange(0, gameOptions.diamondRatio) != 0){
            var diamondX = game.rnd.integerInRange(50, game.width - 50);
            if(this.diamondPool.length > 0){
                var diamond = this.diamondPool.pop();
                diamond.x = diamondX;
                diamond.y = this.highestFloorY - gameOptions.floorGap / 2;
                diamond.revive();
            }
            else{
                var diamond = game.add.sprite(diamondX, this.highestFloorY - gameOptions.floorGap / 2, "diamond");
                diamond.anchor.set(0.5, 0);
                game.physics.enable(diamond, Phaser.Physics.ARCADE);
                diamond.body.immovable = true;
                this.diamondGroup.add(diamond);
            }
        }
    },
    addSpike: function(){
        var spikes = 1;
        if(game.rnd.integerInRange(0, gameOptions.doubleSpikeRatio) == 0){
            spikes = 2;
        }
        for(var i = 1; i <= spikes; i++){
            var spikeXPosition = this.findSpikePosition();
            if(this.spikePool.length > 0){
                var spike = this.spikePool.pop();
                spike.x = spikeXPosition;
                spike.y = this.highestFloorY - 20;
                spike.revive();
            }
            else{
                var spike = game.add.sprite(spikeXPosition, this.highestFloorY - 20, "spike");
                spike.anchor.set(0.5, 0);
                game.physics.enable(spike, Phaser.Physics.ARCADE);
                spike.body.immovable = true;
                this.spikeGroup.add(spike);
            }
        }
    },
    findSpikePosition: function(){
        do{
            var posX = game.rnd.integerInRange(150, game.width - 150)
        } while(!this.isSafe(posX));
        this.safeZone.push({
            start: posX - gameOptions.safeRadius,
            end: posX + gameOptions.safeRadius
        })
        return posX;
    },
    isSafe: function(n){
        for(var i = 0; i < this.safeZone.length; i++){
            if(n > this.safeZone[i].start && n < this.safeZone[i].end){
                return false;
            }
        }
        return true;
    },
    addHero: function(){
        this.hero = game.add.sprite(game.width / 2, game.height * gameOptions.floorStart - 40, "hero");
        this.gameGroup.add(this.hero)
        this.hero.anchor.set(0.5, 0);
        game.physics.enable(this.hero, Phaser.Physics.ARCADE);
        this.hero.body.collideWorldBounds = true;
        this.hero.body.gravity.y = gameOptions.playerGravity;
        this.hero.body.velocity.x = gameOptions.playerSpeed;
        this.hero.body.onWorldBounds = new Phaser.Signal();
        this.hero.body.onWorldBounds.add(function(sprite, up, down, left, right){
            if(left){
                this.hero.body.velocity.x = gameOptions.playerSpeed;
                this.hero.scale.x = 1;
            }
            if(right){
                this.hero.body.velocity.x = -gameOptions.playerSpeed;
                this.hero.scale.x = -1;
            }
            if(down){
                game.state.start("PlayGame");
            }
        }, this)
    },
    defineTweens: function(){
        this.tweensToGo = 0;
        this.scrollTween = game.add.tween(this.gameGroup);
        this.scrollTween.to({
            y: gameOptions.floorGap
        }, 500, Phaser.Easing.Cubic.Out);
        this.scrollTween.onComplete.add(function(){
            this.gameGroup.y = 0;
            this.gameGroup.forEach(function(item){
                if(item.length > 0){
                    item.forEach(function(subItem) {
                        subItem.y += gameOptions.floorGap;
                        if(subItem.y > game.height){
                            switch(subItem.key){
                                case "floor":
                                    this.killFloor(subItem);
                                    break;
                                case "ladder":
                                    this.killLadder(subItem);
                                    break;
                                case "diamond":
                                    this.killDiamond(subItem);
                                    break;
                                case "spike":
                                    this.killSpike(subItem);
                                    break;
                            }
                        }
                    }, this);
                }
                else{
                    item.y += gameOptions.floorGap;
                }
            }, this);
            this.addFloor();
            this.addLadder();
            this.addDiamond();
            this.addSpike();
            if(this.tweensToGo > 0){
                this.tweensToGo --;
                this.scrollTween.start();
            }
        }, this);
    },
    defineGroups: function(){
        this.gameGroup = game.add.group();
        this.floorGroup = game.add.group();
        this.ladderGroup = game.add.group();
        this.diamondGroup = game.add.group();
        this.spikeGroup = game.add.group();
        this.gameGroup.add(this.floorGroup);
        this.gameGroup.add(this.ladderGroup);
        this.gameGroup.add(this.diamondGroup);
        this.gameGroup.add(this.spikeGroup);
    },
    handleTap: function(pointer, doubleTap){
        if(this.canJump && !this.isClimbing && !this.gameOver){
            this.hero.body.velocity.y = -gameOptions.playerJump;
            this.canJump = false;
        }
    },
    update: function(){
        if(!this.gameOver){
            this.checkFloorCollision();
            this.checkLadderCollision();
            this.checkDiamondCollision();
            this.checkSpikeCollision();
        }
    },
    checkFloorCollision: function(){
        game.physics.arcade.collide(this.hero, this.floorGroup, function(){
            this.canJump = true;
        }, null, this);
    },
    checkLadderCollision: function(){
        if(!this.isClimbing){
            game.physics.arcade.overlap(this.hero, this.ladderGroup, function(player, ladder){
                if(Math.abs(player.x - ladder.x) < 10){
                    this.ladderToClimb = ladder;
                    this.hero.body.velocity.x = 0;
                    this.hero.body.velocity.y = - gameOptions.climbSpeed;
                    this.hero.body.gravity.y = 0;
                    this.isClimbing = true;
                    this.reachedFloor ++;
                    if(this.scrollTween.isRunning){
                        this.tweensToGo ++;
                    }
                    else{
                        this.scrollTween.start();
                    }
                }
            }, null, this);
        }
        else{
            if(this.hero.y < this.ladderToClimb.y - 40){
                this.hero.body.gravity.y = gameOptions.playerGravity;
                this.hero.body.velocity.x = gameOptions.playerSpeed * this.hero.scale.x;
                this.hero.body.velocity.y = 0;
                this.isClimbing = false;
            }
        }
    },
    checkDiamondCollision: function(){
        game.physics.arcade.overlap(this.hero, this.diamondGroup, function(player, diamond){
            this.killDiamond(diamond);
        }, null, this);
    },
    checkSpikeCollision: function(){
        game.physics.arcade.overlap(this.hero, this.spikeGroup, function(){
            this.gameOver = true;
            this.hero.body.velocity.x =  game.rnd.integerInRange(-20, 20);
            this.hero.body.velocity.y = -gameOptions.playerJump;
            this.hero.body.gravity.y = gameOptions.playerGravity;
        }, null, this);
    },
    killFloor: function(floor){
        floor.kill();
        this.floorPool.push(floor);
    },
    killLadder: function(ladder){
        ladder.kill();
        this.ladderPool.push(ladder);
    },
    killDiamond: function(diamond){
        diamond.kill();
        this.diamondPool.push(diamond);
    },
    killSpike: function(spike){
        spike.kill();
        this.spikePool.push(spike);
    }
}

Less than 350 lines. I’ll try to add score management and a splash screen keeping the code below 350 lines, then will start commenting it line by line. 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

215 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
// Stairs
// 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