Match 3 Bejeweled HTML5 prototype made with Phaser – suggesting moves

Read all posts about "" game
When you create a Match 3 game, a very important feature to help unskilled players or to introduce some kind of tutorial is to suggest a possible move. If you played Drawsum, my latest HTML5 game, you probably noticed the game always suggests the first move. This way the player knows what to do. I developed a little routine and added it to my match 3 Bejeweled HTML5 prototype made with Phaser to suggest a move using tweens, let’s have a look at it:
The game is completely playable so you can enjoy it. Anyway it shows the first valid move and not the best move, but I’ll be working on it. This is the source code, with the suggestion routine highlighted.
var game;
var fieldSize = 7;
var orbColors = 6;
var orbSize = 100;
//
var swapSpeed = 200;
var fallSpeed = 1000;
var destroySpeed = 500;
var fastFall = true;
//
var gameArray = [];
var removeMap = [];
var orbGroup;
var selectedOrb;
var canPick = true;
//
var hand;
var handTween;

window.onload = function() {	        
	game = new Phaser.Game(700, 700);
	game.state.add("PlayGame", playGame)
	game.state.start("PlayGame");
}

var playGame = function(game){}
playGame.prototype = {
	preload: function(){
          game.load.spritesheet("orbs", "assets/sprites/orbs.png", orbSize, orbSize);
          game.load.image("hand", "assets/sprites/hand.png");	
	},
	create: function(){
          drawField();
          showSuggestion();
          canPick = true;
          game.input.onDown.add(orbSelect);
          game.input.onUp.add(orbDeselect);
	}
}	

function drawField(){
     orbGroup = game.add.group();
     for(var i = 0; i < fieldSize; i ++){
          gameArray[i] = [];
          for(var j = 0; j < fieldSize; j ++){
               var orb = game.add.sprite(orbSize * j + orbSize / 2, orbSize * i + orbSize / 2, "orbs");
               orb.anchor.set(0.5);
               orbGroup.add(orb);
               do{
                    var randomColor = game.rnd.between(0, orbColors - 1);  
                    orb.frame = randomColor;
                    gameArray[i][j] = {
                         orbColor: randomColor,
                         orbSprite: orb
                    }
               } while(isMatch(i, j));   
          }
     }
     selectedOrb = null;
     hand = game.add.sprite(0, 0, "hand");
     hand.anchor.set(0.5);
     hand.visible = false;
}

function showSuggestion(){
     var matchFound = false;
     for(var i = 0; i < fieldSize - 1; i ++){          
          for(var j = 0; j < fieldSize - 1; j ++){
               tmpSwap(i, j, i + 1, j);
               if(matchInBoard()){
                    hand.visible = true;
                    hand.x = gameArray[i + 1][j].orbSprite.x + 16;
                    hand.y = gameArray[i + 1][j].orbSprite.y + 70;
                    handTween = game.add.tween(hand).to({
                         y: hand.y + 100
                    }, 500, Phaser.Easing.Linear.None, true, 0, -1, true);
                    matchFound = true;
               }
               tmpSwap(i, j, i + 1, j);
               if(matchFound){
                    return;
               }   
               tmpSwap(i, j, i, j + 1);
               if(matchInBoard()){
                    hand.visible = true;
                    hand.x = gameArray[i][j + 1].orbSprite.x + 16;
                    hand.y = gameArray[i][j + 1].orbSprite.y + 70;
                    handTween = game.add.tween(hand).to({
                         x: hand.x + 100
                    }, 500, Phaser.Easing.Linear.None, true, 0, -1, true);
                    matchFound = true;
               }
               tmpSwap(i, j, i, j + 1);
               if(matchFound){
                    return;
               }     
          }
     } 
     console.log("no match");    
}

function tmpSwap(row1, col1, row2, col2){
     var tmp = gameArray[row1][col1];
     gameArray[row1][col1] = gameArray[row2][col2];
     gameArray[row2][col2] = tmp;     
}

function orbSelect(e){
     if(canPick){
          hand.visible = false;
          handTween.stop();
          var row = Math.floor(e.clientY / orbSize);
          var col = Math.floor(e.clientX / orbSize);
          var pickedOrb = gemAt(row, col)
          if(pickedOrb != -1){
               if(selectedOrb == null){
                    pickedOrb.orbSprite.scale.setTo(1.2);
                    pickedOrb.orbSprite.bringToTop();
                    selectedOrb = pickedOrb;
                    game.input.addMoveCallback(orbMove);
               }
               else{
                    if(areTheSame(pickedOrb, selectedOrb)){
                         selectedOrb.orbSprite.scale.setTo(1);
                         selectedOrb = null;
                    }
                    else{     
                         if(areNext(pickedOrb, selectedOrb)){
                              selectedOrb.orbSprite.scale.setTo(1);
                              swapOrbs(selectedOrb, pickedOrb, true);                  
                         }
                         else{
                              selectedOrb.orbSprite.scale.setTo(1);
                              pickedOrb.orbSprite.scale.setTo(1.2); 
                              selectedOrb = pickedOrb;  
                              game.input.addMoveCallback(orbMove);      
                         }
                    }
               }     
          }
     }
}

function orbDeselect(e){
     game.input.deleteMoveCallback(orbMove);     
}

function orbMove(event, pX, pY){
     if(event.id == 0){
          var distX = pX - selectedOrb.orbSprite.x;
          var distY = pY - selectedOrb.orbSprite.y;
          var deltaRow = 0;
          var deltaCol = 0;
          if(Math.abs(distX) > orbSize / 2){
               if(distX > 0){
                    deltaCol = 1;
               }
               else{
                    deltaCol = -1;
               }
          }
          else{
               if(Math.abs(distY) > orbSize / 2){
                    if(distY > 0){
                        deltaRow = 1;
                    }
                    else{
                         deltaRow = -1;
                    }
               }
          }
          if(deltaRow + deltaCol != 0){
               var pickedOrb = gemAt(getOrbRow(selectedOrb) + deltaRow, getOrbCol(selectedOrb) + deltaCol); 
               if(pickedOrb != -1){
                    selectedOrb.orbSprite.scale.setTo(1);
                    swapOrbs(selectedOrb, pickedOrb, true);
                    game.input.deleteMoveCallback(orbMove);
               }    
          }
     }
}

function swapOrbs(orb1, orb2, swapBack){ 
     canPick = false;   
     var fromColor = orb1.orbColor;
     var fromSprite = orb1.orbSprite;
     var toColor = orb2.orbColor;
     var toSprite = orb2.orbSprite;
     gameArray[getOrbRow(orb1)][getOrbCol(orb1)].orbColor = toColor;
     gameArray[getOrbRow(orb1)][getOrbCol(orb1)].orbSprite = toSprite;
     gameArray[getOrbRow(orb2)][getOrbCol(orb2)].orbColor = fromColor;
     gameArray[getOrbRow(orb2)][getOrbCol(orb2)].orbSprite = fromSprite;
     var orb1Tween = game.add.tween(gameArray[getOrbRow(orb1)][getOrbCol(orb1)].orbSprite).to({
          x: getOrbCol(orb1) * orbSize + orbSize / 2,
          y: getOrbRow(orb1) * orbSize + orbSize / 2
     }, swapSpeed, Phaser.Easing.Linear.None, true);     
     var orb2Tween = game.add.tween(gameArray[getOrbRow(orb2)][getOrbCol(orb2)].orbSprite).to({
          x: getOrbCol(orb2) * orbSize + orbSize / 2,
          y: getOrbRow(orb2) * orbSize + orbSize / 2
     }, swapSpeed, Phaser.Easing.Linear.None, true); 
     orb2Tween.onComplete.add(function(){
          if(!matchInBoard() && swapBack){
               swapOrbs(orb1, orb2, false);          
          }
          else{ 
               if(matchInBoard()){
                    handleMatches();
               }
               else{        
                    canPick = true;
                    selectedOrb = null;
               }
          }    
     });
}

function areNext(orb1, orb2){
     return Math.abs(getOrbRow(orb1) - getOrbRow(orb2)) + Math.abs(getOrbCol(orb1) - getOrbCol(orb2)) == 1;
}

function areTheSame(orb1, orb2){
     return getOrbRow(orb1) == getOrbRow(orb2) && getOrbCol(orb1) == getOrbCol(orb2);
}

function gemAt(row, col){
     if(row < 0 || row >= fieldSize || col < 0 || col >= fieldSize){
          return -1;
     }
     return gameArray[row][col];
}

function getOrbRow(orb){
     return Math.floor(orb.orbSprite.y / orbSize);
}

function getOrbCol(orb){
     return Math.floor(orb.orbSprite.x / orbSize);
}

function isHorizontalMatch(row, col){
     return gemAt(row, col).orbColor == gemAt(row, col - 1).orbColor && gemAt(row, col).orbColor == gemAt(row, col - 2).orbColor; 
}

function isVerticalMatch(row, col){
     return gemAt(row, col).orbColor == gemAt(row - 1, col).orbColor && gemAt(row, col).orbColor == gemAt(row - 2, col).orbColor; 
}

function isMatch(row, col){
     return isHorizontalMatch(row, col) || isVerticalMatch(row, col);
}

function matchInBoard(){
     for(var i = 0; i < fieldSize; i++){
          for(var j = 0; j < fieldSize; j++){
               if(isMatch(i, j)){
                    return true;
               }
          }
     }
     return false;
}

function handleMatches(){   
     removeMap = []; 
     for(var i = 0; i < fieldSize; i++){
          removeMap[i] = [];
          for(var j = 0; j < fieldSize; j++){
               removeMap[i].push(0);
          }
     }
     handleHorizontalMatches();
     handleVerticalMatches();
     destroyOrbs();
}

function handleVerticalMatches(){
     for(var i = 0; i < fieldSize; i++){
          var colorStreak = 1;
          var currentColor = -1;
          var startStreak = 0;
          for(var j = 0; j < fieldSize; j++){ 
               if(gemAt(j, i).orbColor == currentColor){
                    colorStreak ++;
               }              
               if(gemAt(j, i).orbColor != currentColor || j == fieldSize - 1){
                    if(colorStreak >= 3){
                         console.log("VERTICAL :: Length = "+colorStreak + " :: Start = ("+startStreak+","+i+") :: Color = "+currentColor);
                         for(var k = 0; k < colorStreak; k++){
                              removeMap[startStreak + k][i] ++;
                         }
                    }
                    startStreak = j;
                    colorStreak = 1;
                    currentColor = gemAt(j, i).orbColor;
               }
          }
     }
}

function handleHorizontalMatches(){
     for(var i = 0; i < fieldSize; i++){
          var colorStreak = 1;
          var currentColor = -1;
          var startStreak = 0;
          for(var j = 0; j < fieldSize; j++){ 
               if(gemAt(i, j).orbColor == currentColor){
                    colorStreak ++;
               }              
               if(gemAt(i, j).orbColor != currentColor || j == fieldSize - 1){
                    if(colorStreak >= 3){
                         console.log("HORIZONTAL :: Length = "+colorStreak + " :: Start = ("+i+","+startStreak+") :: Color = "+currentColor);
                         for(var k = 0; k < colorStreak; k++){
                              removeMap[i][startStreak + k] ++;
                         }
                    }
                    startStreak = j;
                    colorStreak = 1;
                    currentColor = gemAt(i, j).orbColor;
               }
          }
     }
}

function destroyOrbs(){
     var destroyed = 0;
     for(var i = 0; i < fieldSize; i++){
          for(var j = 0; j < fieldSize; j++){
               if(removeMap[i][j]>0){
                    var destroyTween = game.add.tween(gameArray[i][j].orbSprite).to({
                         alpha: 0
                    }, destroySpeed, Phaser.Easing.Linear.None, true);
                    destroyed ++;
                    destroyTween.onComplete.add(function(orb){
                         orb.destroy();
                         destroyed --;
                         if(destroyed == 0){
                              makeOrbsFall();
                              if(fastFall){
                                   replenishField();
                              }    
                         }
                    });
                    gameArray[i][j] = null;  
               }
          }
     }
}

function makeOrbsFall(){
     var fallen = 0;
     var restart = false;
     for(var i = fieldSize - 2; i >= 0; i--){
          for(var j = 0; j < fieldSize; j++){
               if(gameArray[i][j] != null){
                    var fallTiles = holesBelow(i, j);
                    if(fallTiles > 0){
                         if(!fastFall && fallTiles > 1){
                              fallTiles = 1;
                              restart = true;                             
                         }
                         var orb2Tween = game.add.tween(gameArray[i][j].orbSprite).to({
                              y: gameArray[i][j].orbSprite.y + fallTiles * orbSize
                         }, fallSpeed, Phaser.Easing.Linear.None, true); 
                         fallen ++;
                         orb2Tween.onComplete.add(function(){
                              fallen --;
                              if(fallen == 0){
                                   if(restart){
                                        makeOrbsFall();
                                   }
                                   else{
                                        if(!fastFall){
                                             replenishField();
                                        }
                                   }      
                              }
                         })
                         gameArray[i + fallTiles][j] = {
                              orbSprite: gameArray[i][j].orbSprite,
                              orbColor: gameArray[i][j].orbColor     
                         }
                         gameArray[i][j] = null;
                    }
               }
          }
     }
     if(fallen == 0){
          replenishField();     
     }
}

function replenishField(){
     var replenished = 0;
     var restart = false;
     for(var j = 0; j < fieldSize; j++){
          var emptySpots = holesInCol(j);
          if(emptySpots > 0){
               if(!fastFall && emptySpots > 1){
                    emptySpots = 1;
                    restart = true;   
               }
               for(i = 0; i < emptySpots; i++){
                    var orb = game.add.sprite(orbSize * j + orbSize / 2, - (orbSize * (emptySpots - 1 - i) + orbSize / 2), "orbs");
                    orb.anchor.set(0.5);
                    orbGroup.add(orb);
                    var randomColor = game.rnd.between(0, orbColors - 1);  
                    orb.frame = randomColor;
                    gameArray[i][j] = {
                         orbColor: randomColor,
                         orbSprite: orb
                    }
                    var orb2Tween = game.add.tween(gameArray[i][j].orbSprite).to({
                         y: orbSize * i + orbSize / 2
                    }, fallSpeed, Phaser.Easing.Linear.None, true);
                    replenished ++;  
                    orb2Tween.onComplete.add(function(){
                         replenished --;
                         if(replenished == 0){
                              if(restart){
                                   makeOrbsFall();
                              }
                              else{
                                   if(matchInBoard()){
                                        game.time.events.add(250, handleMatches);
                                   }
                                   else{
                                        canPick = true;
                                        selectedOrb = null;
                                        showSuggestion();
                                   }  
                              }
                         }
                    }) 
               }
          }
     }
}

function holesBelow(row, col){
     var result = 0;
     for(var i = row + 1; i < fieldSize; i++){
          if(gameArray[i][col] == null){
               result ++;          
          }
     }
     return result;
}

function holesInCol(col){
     var result = 0;
     for(var i = 0; i < fieldSize; i++){
          if(gameArray[i][col] == null){
               result ++;          
          }
     }
     return result;     
}
You know what? I would like to make a fun Match 3 game which does not feature free to play model. Hope I will manage to create a stable engine, 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