Build a HTML5 game like “A Life of Logic” with Phaser framework

Read all posts about "" game

Are you playing “A Life Of Logic“, by Latte Games?

It’s an elegant logic puzzle where the objective is to fill a board with two different tiles while satisfying three simple rules:

No three same tiles next to each other

Each row and column must have the same amount of both tile types

No identical rows or columns

It was also featured as “Game of the Day” in Apple app store, and we are going to build a prototype using Phaser, look at the result which replicates the first level of the original game:

Click or tap on empty tiles to change their value from empty to zero, from zero to one or from one to empty again.

On the right side of the canvas, messages saying if you completed the level or which rules you are breaking.

The source code is quite simple, most of the script is checking for all rules ti be satisfied.

Still uncommented because I want to optimize it a bit and add some more levels:

let game;
let gameOptions = {
    rows: 6,
    columns: 6,
    tileSize: 100
}
let level = [
    [2, 0, 2, 0, 1, 2],
    [0, 2, 0, 2, 2, 0],
    [2, 0, 2, 1, 0, 1],
    [0, 1, 2, 0, 1, 2],
    [2, 2, 0, 2, 1, 0],
    [1, 0, 1, 1, 0, 2]
]
window.onload = function() {
    let gameConfig = {
        type: Phaser.AUTO,
        backgroundColor: 0x444444,
        scale: {
            mode: Phaser.Scale.FIT,
            autoCenter: Phaser.Scale.CENTER_BOTH,
            parent: "thegame",
            width: 1200,
            height: 600
        },
       scene: playGame
    }
    game = new Phaser.Game(gameConfig);
}
class playGame extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }
    preload(){
        this.load.spritesheet("tiles", "tiles.png", {
            frameWidth: gameOptions.tileSize,
            frameHeight: gameOptions.tileSize
        });
    }
    create(){
        this.gameArray = [];
        for(let i = 0; i < gameOptions.rows; i ++){
            this.gameArray[i] = [];
            for(let j = 0; j < gameOptions.columns; j ++){
                let tile = this.add.sprite(j * gameOptions.tileSize, i * gameOptions.tileSize, "tiles", level[i][j]);
                tile.setOrigin(0);
                this.gameArray[i][j] = {
                    value: level[i][j],
                    isFixed: level[i][j] != 0,
                    sprite: tile
                }
            }
        }
        this.input.on("pointerdown", this.changeTile, this);
        this.gameText = this.add.text(620, 20, "", {
            fontFamily: "Arial",
            fontSize: 24
        });
    }
    changeTile(pointer){
        let row = Math.floor(pointer.y / gameOptions.tileSize);
        let col = Math.floor(pointer.x / gameOptions.tileSize);
        if(this.gameArray[row] != undefined &amp;&amp; this.gameArray[row][col] != undefined &amp;&amp; !this.gameArray[row][col].isFixed){
            this.gameArray[row][col].value = Phaser.Math.Wrap(this.gameArray[row][col].value + 1, 0, 3);
            this.gameArray[row][col].sprite.setFrame(2 * this.gameArray[row][col].value + this.gameArray[row][col].value % 2);
            this.checkRules();
        }
    }
    checkRules(){
        let rowsContent = [];
        let colsContent = [];
        let messageString = "";
        for(let i = 0; i < gameOptions.rows; i ++){
            if(this.threeConsecutiveInRow(i)){
                messageString += "3 or more consecutive symbols at row " + i + "\n";
            }
            if(this.unbalancedRow(i)){
                messageString += "different amount of symbols at row " + i + "\n";
            }
            if(this.duplicatedRow(i)){
                messageString += "identical row at row " + i + "\n";
            }
        }
        for(let i = 0; i < gameOptions.columns; i ++){
            if(this.threeConsecutiveInColumn(i)){
                messageString += "3 or more consecutive symbols at column " + i + "\n";
            }
            if(this.unbalancedColumn(i)){
                messageString += "different amount of symbols at column " + i + "\n";
            }
            if(this.duplicatedColumn(i)){
                messageString += "identical column at column " + i + "\n";
            }
        }
        if(messageString == "" &amp;&amp; this.boardCompleted()){
            messageString = "LEVEL COMPLETED";
        }
        this.gameText.setText(messageString);
    }
    threeConsecutiveInColumn(column){
        for(let i = 2; i < gameOptions.rows; i ++){
            let element = this.gameArray[i][column].value;
            if(element == this.gameArray[i - 1][column].value &amp;&amp; element == this.gameArray[i - 2][column].value){
                return true;
            }
        }
        return false;
    }
    threeConsecutiveInRow(row){
        for(let i = 2; i < gameOptions.columns; i ++){
            let element = this.gameArray[row][i].value;
            if(element == this.gameArray[row][i - 1].value &amp;&amp; element == this.gameArray[row][i - 2].value){
                return true;
            }
        }
        return false;
    }
    unbalancedColumn(column){
        let values = [0, 0];
        for(let i = 0; i < gameOptions.rows; i ++){
            values[0] += (this.gameArray[i][column].value == 1) ? 1 : 0;
            values[1] += (this.gameArray[i][column].value == 2) ? 1 : 0;
        }
        return (values[0] + values[1] == gameOptions.rows) &amp;&amp; (values[0] != gameOptions.rows / 2 || values[1] != gameOptions.rows / 2);
    }
    unbalancedRow(row){
        let values = [0, 0];
        for(let i = 0; i < gameOptions.columns; i ++){
            values[0] += (this.gameArray[row][i].value == 1) ? 1 : 0;
            values[1] += (this.gameArray[row][i].value == 2) ? 1 : 0;
        }
        return  (values[0] + values[1] == gameOptions.columns) &amp;&amp; (values[0] != gameOptions.columns / 2 || values[1] != gameOptions.columns / 2);
    }
    duplicatedColumn(column){
        for(let i = 0; i < gameOptions.columns; i ++){
            if(i != column &amp;&amp; this.columnValue(column) != 0 &amp;&amp; this.columnValue(i) != 0 &amp;&amp; this.columnValue(i) == this.columnValue(column)){
                return true
            }
        }
        return false;
    }
    duplicatedRow(row){
        for(let i = 0; i < gameOptions.rows; i ++){
            if(i != row &amp;&amp; this.rowValue(row) != 0 &amp;&amp; this.rowValue(i) != 0 &amp;&amp; this.rowValue(i) == this.rowValue(row)){
                return true
            }
        }
        return false;
    }
    columnValue(column){
        let value = 0;
        for(let i = 0; i < gameOptions.rows; i++){
            if(this.gameArray[i][column].value == 0){
                return 0;
            }
            if(this.gameArray[i][column].value == 2){
                value +=  Math.pow(2, i);
            }
        }
        return value;
    }
    rowValue(row){
        let value = 0;
        for(let i = 0; i < gameOptions.columns; i++){
            if(this.gameArray[row][i].value == 0){
                return 0;
            }
            if(this.gameArray[row][i].value == 2){
                value +=  Math.pow(2, i);
            }
        }
        return value;
    }
    boardCompleted(){
        for(let i = 0; i < gameOptions.rows; i ++){
            for(let j = 0; j < gameOptions.columns; j ++){
                if(this.gameArray[i][j].value == 0){
                    return false;
                }
            }
        }
        return true;
    }
}

And as you can see, any simple original idea like this one, which has been awarded with “Game of the Day”, can be built with the power of Phaser. 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