HTML5 Diamond Digger Saga prototype made with Phaser

Read all posts about "" game

Some days ago I showed you how Diamond Digger Saga is basically based upon flood fill algorithm, now it’s time to make a working HTML5 prototype made with Phaser.

First, let’s have a look at what we are going to build:

Click on a globe to remove all its adjacent globes and make new globes fall from the top.

You can also play it with your mobile devices pointing to this link.

Once the player clicks on a tile – remember you can have gems, balls, fruits, animals, but they all are tiles – flood fill algorithm is called to remove all contiguous tiles of the same color.

When a tile is removed, it leaves a hole in the game board. holesBelow function calculates how many empty tiles there are under a given tile, so we can tween it to its new position. Also, new tiles has to be placed, making them fall from the top. Another tween handles this situation.

Here is the source code:

<!doctype html>
<html>
	<head>
		<style>
          	body{
				margin:0;
				padding:0;
			}
          </style>
		<script src="phaser.min.js"></script>
		<script type="text/javascript">
		 
			var game = new Phaser.Game(315,315,Phaser.CANVAS,"",{preload:onPreload, create:onCreate});

			var tileSize = 35;                	// tile size, in pixels
			var fieldSize = 9;				// number of tiles per row/column
			var tileTypes = 3;                 // different kind of tiles allowed
			var tileArray = [];                // array with all game tiles

			// on preloading, preload the graphics and enable scale mode
               function onPreload() {
				game.load.spritesheet("tiles","assets/tiles.png",35,35);
				game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
				game.scale.setScreenSize(true);
			}
			
               // when the game is created, generate the tiles
			function onCreate(){
				for(i=0;i<fieldSize;i++){
					tileArray[i]=[];
					for(j=0;j<fieldSize;j++){
						var randomTile = Math.floor(Math.random()*tileTypes)
						theTile=game.add.sprite(j*tileSize+tileSize/2,i*tileSize+tileSize/2,"tiles");
						theTile.frame = randomTile;
						theTile.anchor.setTo(0.5,0.5);
						tileArray[i][j]=theTile;
					}
				}
				game.input.onDown.add(pickTile, this);	
			}

			// a tile has been picked
			function pickTile(){
				// save input coordinates
				startX = game.input.worldX;
				startY = game.input.worldY;
				// retrieve selected row and column 
				selectedRow = Math.floor(startY/tileSize);
				selectedCol = Math.floor(startX/tileSize);
				// delete using flood fill
				floodFill(selectedRow,selectedCol,tileArray[selectedRow][selectedCol].frame);
				// make existing gems fall down
				fallDown();
				// replenish game field from the top 
				fallFromTop();
			}
			
			// flood fill function. There is an entire post about it at http://bit.ly/1BsyiOd
               function floodFill(row,col,val){
				if(row>=0 && row<fieldSize && col>=0 && col<fieldSize){
					if(tileArray[row][col]!=null && tileArray[row][col].frame==val){
						tileArray[row][col].destroy();
						tileArray[row][col]=null;
						floodFill(row+1,col,val);
	                         floodFill(row-1,col,val);
	                         floodFill(row,col+1,val);
	                         floodFill(row,col-1,val);	
					}
				}	
			}
			
               // function to make remaining tiles fall down once you removed tiles
			function fallDown(){
				for(var i=fieldSize-1;i>=0;i--){
					for(var j=0;j<fieldSize;j++){
						if(tileArray[i][j]!=null){
		                         var delta = holesBelow(i,j);
		                         if(delta>0){
		                         	console.log(delta)
		                         	var tileTween = game.add.tween(tileArray[i][j]);
								tileTween.to({
									y: (i+delta)*tileSize+tileSize/2
								},800,Phaser.Easing.Cubic.Out,true);
		                              tileArray[i+delta][j]=tileArray[i][j];
	                              	tileArray[i][j]=null;
		                         }
						}	
					}
				}
			}
			
			// function to add new tiles falling from the top
               function fallFromTop(){
				for(i=0;i<fieldSize;i++){
					var holes = holesBelow(-1,i);
					for(j=0;j<holes;j++){
						var randomTile = Math.floor(Math.random()*tileTypes);
						var tileXPos = i*tileSize+tileSize/2;
						var tileYPos = -(holes-j)*tileSize-tileSize/2;
						var theTile = game.add.sprite(tileXPos,tileYPos,"tiles");
						theTile.frame = randomTile;
						theTile.anchor.setTo(0.5,0.5);
						tileArray[j][i]=theTile;		
	                    	tileTween = game.add.tween(tileArray[j][i]);
						tileTween.to({
							y: j*tileSize+tileSize/2
						},800,Phaser.Easing.Cubic.Out,true);	
					}
				}
			}
			
               // given a row and a column position, returns how may holes (empty places) we have under such position
			function holesBelow(row,col){
				var holes = 0;
				for(var i=row+1;i<fieldSize;i++){
					if(tileArray[i][col]==null){
						holes++;
					}		
				}
				return holes;				
			}
			           
		</script>
    </head>
    <body>
    </body>
</html>

Next time we will see how to create water like in the original game, but all in all it’s just another flood fill so you should be able to do it by yourself. If you can’t don’t worry because next step will come next week. Meanwhile you can download the source code of the entire project.

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