HTML5 “Down the Mountain” prototype built with Phaser updated to Phaser 3

Read all posts about "" game
I usually update the Down the Mountain prototype every summer, so it’s time to release another update, porting the latest version to Phaser 3. The game features object pooling to recycle all blocks – actually hexagons – which fly off the top of the canvas. Have a look:
Tap or click on the left half of the canvas to move left, on the right half of the canvas to move right. I managed to handle player position and scrolling using pure math rather than looking for their world coordinates. This makes the code look a bit more clean. I still have some doubts about using Bezier curves on tweeens, so in this version the tweens uses a linear movement rather than a curve to properly simulate a jump, but I’ll be studying it. Containers have also been used, since there is no way to add children to sprites. Have a look at the source code:
<pre class="wp-block-syntaxhighlighter-code">var game;

var gameOptions = {
    hexagonWidth: 70,
    hexagonHeight: 80,
    gridSizeX: 5,
    gridSizeY: 14
}

window.onload = function() {
    var gameConfig = {
        thpe: Phaser.CANVAS,
        width: 600,
        height: 600,
        backgroundColor: 0xffffff,
        scene: [playGame]
    }
    game = new Phaser.Game(gameConfig);
    window.focus()
    resize();
    window.addEventListener("resize", resize, false);
}
class playGame extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }
    preload(){
        this.load.image("hexagon", "hexagon.png");
        this.load.spritesheet("marker", "marker.png",  {
            frameWidth: 56,
            frameHeight: 64
        });
    }
    create(){
        this.playerMove = true;
        this.playerCol = 2;
        this.playerRow = 0;
        this.hexagonPool = [];
        this.hexagonContainer = this.add.container();
        for(var i = 0; i < gameOptions.gridSizeY; i ++){
            this.addHexagonRow(i);
        }
        this.hexagonContainer.x = (game.config.width - gameOptions.hexagonWidth * gameOptions.gridSizeX) / 2;
        this.hexagonContainer.y = 20;
        this.marker = this.add.sprite(gameOptions.hexagonWidth * gameOptions.gridSizeX / 2, 6, "marker");
        this.hexagonContainer.add(this.marker);
        this.input.on("pointerdown", function(e){
            if(this.playerMove){
                if(e.x < (game.config.width / 2) && (this.playerCol > 0 || (this.playerRow % 2 == 1))){
                    this.placeMarker(this.playerCol - (1 - this.playerRow % 2), this.playerRow + 1);
                    this.marker.setFrame(0);
                }
                if(e.x >= (game.config.width / 2) &&  this.playerCol < gameOptions.gridSizeX - 1){
                    this.placeMarker(this.playerCol + (this.playerRow % 2), this.playerRow + 1);
                    this.marker.setFrame(1);
                }
            }
        }, this)
    }
    update(){
        var playerPosition = this.marker.y + this.hexagonContainer.y;
        if(playerPosition > 60){
            var distance = 60 - playerPosition;
            this.hexagonContainer.y += distance / 25;
        }
        for(var i = 0; i < this.hexagonContainer.list.length; i++){
            var blockPosition = this.hexagonContainer.list[i].y + this.hexagonContainer.y;
            if(blockPosition < -gameOptions.hexagonHeight){
                this.hexagonContainer.list[i].y += gameOptions.hexagonHeight * (gameOptions.gridSizeY * 3 / 4);
            }
        }
    }
    addHexagonRow(i){
        for(var j = 0; j < gameOptions.gridSizeX - i % 2; j ++){
            var singleHexagonContainer = this.add.container();
            var hexagonX = gameOptions.hexagonWidth * j + (gameOptions.hexagonWidth / 2) * (i % 2);
            var hexagonY = gameOptions.hexagonHeight * i / 4 * 3;
            singleHexagonContainer.x = hexagonX;
            singleHexagonContainer.y = hexagonY;
            var hexagon = this.add.sprite(0, 0, "hexagon");
            hexagon.setOrigin(0, 0);
            singleHexagonContainer.add(hexagon);
            var hexagonText = this.add.text(gameOptions.hexagonWidth / 3, gameOptions.hexagonHeight / 5, i + "," + j, {
                color: "#000000"
            });
            singleHexagonContainer.add(hexagonText);
            this.hexagonContainer.add(singleHexagonContainer);
        }
    }
    placeMarker(posX, posY){
        this.playerRow = posY;
        this.playerCol = posX;
        var nextX = gameOptions.hexagonWidth * (2 * posX + 1 + posY % 2) / 2;
        var nextY = gameOptions.hexagonHeight * (3 * posY + 1) / 4 - 14;
        this.playerMove = false;
        var bezierX = gameOptions.hexagonWidth;
        if(this.marker.x > nextX){
            bezierX *= -1;
        }
        this.tweens.add({
            targets: [this.marker],
            x: nextX,
            y: nextY,
            duration: 100,
            callbackScope: this,
            onComplete: function(){
                this.playerMove = true;
            }
        })
    }
}

// pure javascript to scale the game
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";
    }
}</pre>
See you soon with Bezier tweens, 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