HTML5 Drag and Match engine made with Phaser

Read all posts about "" game

I like a lot the drag and match engine seen in 10000000 game, and I already developed this working prototype three times:

1) Creation of a Flash AS3 match 3 engine by dragging rows and columns rather than swapping items, made in AS3 with an 8 steps detailed tutorial.

2) Drag and Match engine like the one used in 10000000 made with Stencyl made with Stencyl.

3) Drag and Match engine like the one used in 10000000 game made with Construct2 made with the popular HTML5 game creation Construct2.

Today I am showing you the same prototype made with the awesome Phaser framework.

Here you can see the prototype, originally made at 320×320, upscaled to 500×500

To test in your mobile browser, you can also use this QRCode

The creation of this prototype was basically a porting of the AS3 version, with the only exception I used a sprite sheet to store images:

Here you can see the commented source code, but I recommend to read the post with the step by step creation first:

<!doctype html>
<html>
	<head>
    		<script src="phaser.min.js"></script>
    		<style>
    			body{margin:0}
    		</style>
    		<script type="text/javascript">
			window.onload = function() {
				var game = new Phaser.Game(300,300,Phaser.CANVAS,"",{preload:onPreload, create:onCreate, update:onUpdate});				
				// tile size, in pixels
				var tileSize = 50;
				// number of tiles per row/column
				var fieldSize = 6;
				// different kind of tiles allowed
				var tileTypes = 6
				// are we dragging?
				var dragging = false;
				// row to move
				var movingRow;
				// column to move
				var movingCol;
				// array with all game tiles
				var tileArray = [];
				// x coordinate saved when the player starts dragging
				var startX;
				// y coordinate saved when the player starts dragging
				var startY;
				// horizontal distance travelled during dragging
				var distX;
				// vertical distance travelled during dragging
				var distY;
				// dragging direction
				var dragDirection = "";
				// temporary tile
				var tempTile;
				
				// THE GAME IS PRELOADING
				function onPreload() {
					// loading the spritesheet with all tiles
					game.load.spritesheet("tiles","tiles.png",tileSize,tileSize);
				}
				
				// THE GAME HAS BEEN CREATED
				function onCreate() {
					// showing the game in full screen
					game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
                    	game.scale.setScreenSize();
                    	// generating the game field
					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,i*tileSize,"tiles");
							// "frame" and "value" are custom attributes
							theTile.frame = randomTile;
							theTile.value = randomTile;
							tileArray[i][j]=theTile;	
						}
					}
					// at this time we also create temporary tiles
					tempTile = game.add.sprite(0,0,"tiles");
					tempTile.visible = false;
					// listener for input down
					game.input.onDown.add(pickTile, this);
				}
				
				// A TILE HAS BEEN PICKED
				function pickTile(){
					// Saving input coordinates
					startX = game.input.worldX;
					startY = game.input.worldY;
					// Saving row and column numbers
					movingRow = Math.floor(startY/tileSize);
					movingCol = Math.floor(startX/tileSize);
					// now dragging is allowed
					dragging = true
					// updating listeners
					game.input.onDown.remove(pickTile, this);
					game.input.onUp.add(releaseTile, this);
				}
				
				// A TILE HAS BEEN RELEASE3D
				function releaseTile(){
					// did we drag horizontally or vertically?
					switch(dragDirection){
						case "horizontal":
								// determining how many tiles we shifted and adjusting game array
								// and tiles accordingly
								var shiftAmount = Math.floor(distX/(tileSize/2));
								shiftAmount = Math.ceil(shiftAmount/2)%fieldSize;
								var tempArray = [];
								if(shiftAmount>0){
									for(i=0;i<fieldSize;i++){
										tempArray[(shiftAmount+i)%fieldSize] = tileArray[movingRow][i].value;
									}
								}
								else{
									shiftAmount *= -1;
									for(i=0;i<fieldSize;i++){
										tempArray[i]=tileArray[movingRow][(shiftAmount+i)%fieldSize].value;
									}
								}
								for(i=0;i<fieldSize;i++){
									tileArray[movingRow][i].value = tempArray[i];
									tileArray[movingRow][i].frame = tempArray[i];
									tileArray[movingRow][i].x=i*tileSize;
								}
						break;
						case "vertical":
								// determining how many tiles we shifted and adjusting game array
								// and tiles accordingly
								var shiftAmount = Math.floor(distY/ (tileSize/2));
								shiftAmount = Math.ceil(shiftAmount/2)%fieldSize;
								var tempArray = [];
								if(shiftAmount>0){
									for(i=0;i<fieldSize;i++){
										tempArray[(shiftAmount+i)%fieldSize] = tileArray[i][movingCol].value;
									}
								}
								else{
									shiftAmount *= -1;
									for(i=0;i<fieldSize;i++){
										tempArray[i]=tileArray[(shiftAmount+i)%fieldSize][movingCol].value;
									}
								}
								for(i=0;i<fieldSize;i++){
									tileArray[i][movingCol].value = tempArray[i];
									tileArray[i][movingCol].frame = tempArray[i];
									tileArray[i][movingCol].y=i*tileSize;
							}
						break;	
					}
					// let the player be able to pick and drag again
					dragDirection = "";
					dragging = false;
					tempTile.visible=false;
					game.input.onUp.remove(releaseTile, this);
					game.input.onDown.add(pickTile, this);
				}
				
				// THE GAME IS GOING TO BE UPDATED
				function onUpdate() {
					if(dragging){
						distX = game.input.worldX-startX;
                    		distY = game.input.worldY-startY;
					     switch(dragDirection){
					     	// dragging, but still looking for a direction
							case "":
                    				var dist = distX*distX+distY*distY;
                    				if (dist>25) {
                        					var dragAngle=Math.abs(Math.atan2(distY,distX));
                        					if ((dragAngle>Math.PI/4 && dragAngle<3*Math.PI/4)) {
                            					dragDirection="vertical";
                        					}
                        					else {
                            					dragDirection="horizontal";
                        					}
                    				}
							break;
							// horizontal drag
							case "horizontal":
								tempTile.visible = false;
								tempTile.y=movingRow*tileSize;
								var deltaX = (Math.floor(distX/tileSize)%fieldSize);
								if (deltaX>=0) {									
                        					tempTile.frame = tileArray[movingRow][fieldSize-1-deltaX].value;
                    				}
                    				else{
									deltaX=deltaX*-1-1;
									tempTile.frame = tileArray[movingRow][deltaX].value;		
								}
								for(i=0;i<fieldSize;i++){
                        					tileArray[movingRow][i].x=(i*tileSize+distX)%(tileSize*fieldSize);
                        					if (tileArray[movingRow][i].x<0) {
                            					tileArray[movingRow][i].x+=tileSize*fieldSize;
                        					}
                                             if(distX%tileSize>0){
                                             	tempTile.visible = true;
                                                  tempTile.x=distX%tileSize-tileSize;
                                             }
                                             if(distX%tileSize<0){
                                             	tempTile.visible = true;
                                                  tempTile.x=distX%tileSize;
                                             } 
                    				}
							break;
							// vertical drag
							case "vertical":
								tempTile.visible = false;
								tempTile.x=movingCol*tileSize;
								var deltaY = (Math.floor(distY/tileSize)%fieldSize);
								if (deltaY>=0) {									
                        					tempTile.frame = tileArray[fieldSize-1-deltaY][movingCol].value;
                    				}
                    				else{
									deltaY=deltaY*-1-1;
									tempTile.frame = tileArray[deltaY][movingCol].value;		
								}
								for(i=0;i<fieldSize;i++){
                        					tileArray[i][movingCol].y=(i*tileSize+distY)%(tileSize*fieldSize);
                        					if (tileArray[i][movingCol].y<0) {
                            					tileArray[i][movingCol].y+=tileSize*fieldSize;
                        					}
                                             if(distY%tileSize>0){
                                             	tempTile.visible = true;
                                                  tempTile.y=distY%tileSize-tileSize;
                                             }
                                             if(distY%tileSize<0){
                                             	tempTile.visible = true;
                                                  tempTile.y=distY%tileSize;
                                             }   
                    				}
							break;
						}
					}
	    			}
	    		};
		</script>
    </head>
    <body>
    </body>
</html>

There are a lot of games you can create out of this prototype, if you have a nice idea, let me know it and I will be happy do show it on the blog. Meanwhile, you can download the entire 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