HTML5 SameGame engine powered by Phaser

Read all posts about "" game
According to this Wikipedia page , SameGame is a tile-matching puzzle video game originally released under the name “Chain Shot!” in 1985 by Kuniaki Moribe (Morisuke). It has since been ported to numerous computer platforms and handheld devices. Its simple game mechanic is perfect to introduce tile based matching games: SameGame is played on a rectangular field, typically initially filled with four or five kinds of blocks placed at random. By selecting a group of adjoining blocks of the same color, a player may remove them from the screen. Blocks that are no longer supported will fall down, and a column without any blocks will be trimmed away by other columns always sliding to one side (often the left). The goal of the game is to remove as many blocks from the playing field as possible. You can Google for “SameGame” and play a ton of SameGame clones, and this is the plain engine, with no animations to keep the code as simple as possible:
Click on a tile to remove the group of tiles of the same color, there must be at least two tiles of the same color for you to remove them. The code is very simple and although is not commented, it’s very readable. Anyway, here is a brief information about how the game works: * Tiles are placed on stage, in this case a 8×8 board with 4 different colors * The player selects a tile * A flood fill algorithm is performed to see how may tiles of the same color are grouped with the selected tile * If there’s only one tile, the move is not valid * If there are at least two tiles, we remove them * Tiles witouth another tile under their feet fall down * Columns with an empty column on their left will slide to the left * The player can select another tile This is the source code:
var game;

var gameOptions = {
	gameWidth: 800, 
	gameHeight: 800, 
	tileSize: 100, 
	fieldSize: {
          rows: 8,
          cols: 8
     },
     colors: [0xff0000, 0x00ff00, 0x0000ff, 0xffff00]
}

window.onload = function() {	
	game = new Phaser.Game(gameOptions.gameWidth, gameOptions.gameHeight);
     game.state.add("TheGame", TheGame);
     game.state.start("TheGame");
}

var TheGame = function(){};

TheGame.prototype = {
     preload: function(){
          game.stage.backgroundColor = 0x222222;
          game.load.image("tiles", "assets/sprites/tile.png"); 
     },
  	create: function(){
          game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
		game.scale.pageAlignHorizontally = true;
		game.scale.pageAlignVertically = true;   
  		this.createLevel();
  	}, 
	createLevel: function(){
          this.tilesArray = [];
		this.tileGroup = game.add.group();
          this.tileGroup.x = (game.width - gameOptions.tileSize * gameOptions.fieldSize.cols) / 2;
          this.tileGroup.y = (game.height -  gameOptions.tileSize * gameOptions.fieldSize.rows) / 2;
  		for(var i = 0; i < gameOptions.fieldSize.rows; i++){
               this.tilesArray[i] = [];
			for(var j = 0; j < gameOptions.fieldSize.cols; j++){
				this.addTile(i, j);
			}
		}
	},
	addTile: function(row, col){
		var tileXPos = col * gameOptions.tileSize + gameOptions.tileSize / 2;
		var tileYPos = row * gameOptions.tileSize + gameOptions.tileSize / 2;
		var theTile = game.add.button(tileXPos, tileYPos, "tiles", this.pickTile, this);
		theTile.anchor.set(0.5);
          theTile.value = game.rnd.integerInRange(0, gameOptions.colors.length - 1);
          theTile.tint = gameOptions.colors[theTile.value];
          theTile.coordinate = new Phaser.Point(col, row);
          this.tilesArray[row][col] = theTile;
	     this.tileGroup.add(theTile);	
	},
     pickTile: function(e){
          this.filled = [];
          this.filled.length = 0;
          this.floodFill(e.coordinate, e.value);
          if(this.filled.length > 1){
               this.destroyTiles();
               this.fillVerticalHoles();
               this.fillHorizontalHoles();
          }
     },
     destroyTiles: function(){
          for(var i = 0; i < this.filled.length; i++){
               this.tilesArray[this.filled[i].y][this.filled[i].x].destroy();
               this.tilesArray[this.filled[i].y][this.filled[i].x] = null;
          }
     },
     fillVerticalHoles: function(){
          for(var i = gameOptions.fieldSize.rows - 2; i >= 0; i--){
               for(var j = 0; j < gameOptions.fieldSize.cols; j++){
                    if(this.tilesArray[i][j] != null){
                         var holesBelow = 0;
                         for(var z = i + 1; z < gameOptions.fieldSize.rows; z++){
                              if(this.tilesArray[z][j] == null){
                                   holesBelow ++;
                              }    
                         }
                         if(holesBelow){  
                              this.moveTile(i, j, i + holesBelow, j)                                                                   
                         }
                    }     
               }
          }
     },
     fillHorizontalHoles: function(){
          for(i = 0; i < gameOptions.fieldSize.cols - 1; i++){
               if(this.tilesInColumn(i) == 0){
                    for(j = i + 1; j < gameOptions.fieldSize.cols; j++){
                         if(this.tilesInColumn(j) != 0){
                              for(z = 0; z < gameOptions.fieldSize.rows; z++){
                                   if(this.tilesArray[z][j] != null){
                                        this.moveTile(z, j, z, i)
                                   }    
                              }
                              break;
                         }     
                    }
               }
          }
     },
     moveTile: function(fromRow, fromCol, toRow, toCol){
          this.tilesArray[toRow][toCol] = this.tilesArray[fromRow][fromCol];
          this.tilesArray[toRow][toCol].coordinate = new Phaser.Point(toCol, toRow);
          this.tilesArray[toRow][toCol].x = toCol * gameOptions.tileSize + gameOptions.tileSize / 2;
          this.tilesArray[toRow][toCol].y = toRow * gameOptions.tileSize + gameOptions.tileSize / 2;
          this.tilesArray[fromRow][fromCol] = null;
     },
     tilesInColumn: function(col){
          var result = 0;
          for(var i = 0; i < gameOptions.fieldSize.rows; i++){
               if(this.tilesArray[i][col] != null){
                    result ++;
               }
          }
          return result;
     },
     floodFill: function(p, n){
          if(p.x < 0 || p.y < 0 || p.x >= gameOptions.fieldSize.cols || p.y >= gameOptions.fieldSize.rows){
               return;
          }
          if(this.tilesArray[p.y][p.x] != null && this.tilesArray[p.y][p.x].value == n && !this.pointInArray(p)){
               this.filled.push(p);
               this.floodFill(new Phaser.Point(p.x + 1, p.y), n);
               this.floodFill(new Phaser.Point(p.x - 1, p.y), n); 
               this.floodFill(new Phaser.Point(p.x, p.y + 1), n);
               this.floodFill(new Phaser.Point(p.x, p.y - 1), n);       
          }
     },
     pointInArray: function(p){
          for(var i = 0; i < this.filled.length; i++){
               if(this.filled[i].x == p.x && this.filled[i].y == p.y){
                    return true;
               }
          }
          return false;
     }
}
Download the source code of the full project, a complete game as well as some interesting variations of SameGame will follow during next days.

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