“String Avoider” HTML5 game reinvented with mobile phones in mind

Read all posts about "" game
If you liked the post “String Avoider” HTML5 game updated to Phaser 2.6.2 and want to continue in the creation of your own string avoider game, there is something more to keep in mind if you want your game to work well on mobile devices. First, we have to fix a graphic glitch due to Phaser (and PIXI) lineTo method, which causes a graphic error when the angle between two segments drawn with lineTo method is too close to 180 degrees. This is what I mean: There is really no way to avoid this while you use a series of lineTo methods because Phaser (and PIXI) does not feature caps and joints management in lineStyle like good old AS3 did. To fix this glitch, we’ll have to reposition the graphic pen each time we use a lineTo method, you will find this fix at line 201 of the source code. Then we added a start and an end where the string starts and must stop, but above all there was an important change in the way the string is moved. If you play the game on mobile, with your string running under your finger, you won’t be able to see the position of your string head because it’s covered by your finger. This would affect gameplay in a very negative way, so I changed the way it works: if you touch the canvas in any position and move your mouse/finger, the string will move the same way following your input movement, but you will be able to see your string head because if you are a smart player you won’t be covering it with your finger. Look at the game:
Touch the canvas, and “start” circle will disappear revealing the string, drag your finger anywhere and see how the string follows your finger movements. Touch an obstacle or reach the end and the game will restart in two seconds. This is way better, isn’t it? You can also play directly on your mobile device from this link. And obviously the graphic glitch disappeared. Here is the full commented source code:
// the game itself
var game

var gameOptions = {

     // game width
     gameWidth: 640,
     
     // game height
     gameHeight: 960,
     
     // number of segments which build the tail
     tailSegments: 300,
     
     // lenght of each segment
     segmentLength: 2     
}

// when the window loads
window.onload = function() {
    
     // game creation	
	game = new Phaser.Game(gameOptions.gameWidth, gameOptions.gameHeight);
     
     // adding game state
     game.state.add("TheGame", TheGame);
     
     // starting game state
     game.state.start("TheGame");
}

var TheGame = function(){};

TheGame.prototype = {

     // when the state preloads
     preload: function(){
     
          // setting the game on maximum scale mode to cover the entire screen
          game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
          game.scale.pageAlignHorizontally = true;
          game.scale.pageAlignVertically = true;
          
          // preloading maze image, a PNG image with transparency
          game.load.image("maze", "assets/sprites/maze.png");
          
          // preloading start and end icons as spritesheet
          game.load.spritesheet("startend", "assets/sprites/startend.png", 80, 80);
     },
     
     // once the state has been created
     create: function(){
          
          // creation of a bitmap data with the same size as the game
          this.bitmap = game.make.bitmapData(game.width, game.height);
          
          // drawing "maze" image on the bitmap data
          this.bitmap.draw("maze");
          
          // updating bitmap data to let it have actual image data
          this.bitmap.update();
          
          // adding the bitmap data as a sprite
          game.add.sprite(0, 0, this.bitmap);  
          
          // adding start icon
          this.startSpot = game.add.sprite(80, 80, "startend", 0);
          
          // setting start icon registration point to its centre
          this.startSpot.anchor.set(0.5);
          
          // adding end icon
          this.endSpot = game.add.sprite(game.width - 80, game.height - 80, "startend", 1);
          
          // setting start icon registration point to its centre
          this.endSpot.anchor.set(0.5);
          
          // just a flag to inform us if we already had an input, that is if the player already clicked/touched the canvas
          this.firstInput = true;
          
          // we create a graphics instance called "canvas", we'll draw the string on it
          this.canvas = game.add.graphics(0, 0);
          
          // segments is the array which will contain string segments
          this.segments = []; 
          
          // waiting for player input to call startMove method
          game.input.onDown.add(this.startMove, this); 
     },
     
     // startMove method, will be called each time the player touches/clicks the canvas
     startMove: function(e){
     
          // checking if it's the first input: player clicks/touchs the canvas for the first time
          if(this.firstInput){
          
               // not the first input anymore
               this.firstInput = false;
               
               // making start icon invisible
               this.startSpot.visible = false;
               
               // populating segments array with an amount of "gameOptions.tailSegments" Phaser Point objects
               for(var i = 0; i < gameOptions.tailSegments; i++){
               
                    // I want the string to be a circle at first, so I am using a little trigonometry to place these points accordingly
                    var radians = 12 * Math.PI * i / gameOptions.tailSegments + Math.PI / 4;
                    
                    // creating Points objects and placing them into segments array. "10" is the radius of the circle
                    this.segments[i] = new Phaser.Point(this.startSpot.x + 10 * Math.cos(radians), this.startSpot.y + 10 * Math.sin(radians));
               }  
               
               // calling moveString function. Actually this function moves and renders the string, and the two arguments represent
               // respectively the x and y movement to apply to string's head. We set them to zero because there's no movement
               this.moveString(0, 0);                            
          }
          
          // removing callback
          game.input.onDown.remove(this.startMove, this);
          
          // add a move callback to be fired when the player moves the mouse/finger and call dragString method
          game.input.addMoveCallback(this.dragString, this);   
          
          // add a up callback to be fired when the player releases the finger/mouse button and call endMove method
          game.input.onUp.add(this.endMove, this);
          
          // saving current event position, that is the position where the player is currently touching/clicking
          this.startPosition = e.position;
     },
     
     // endMove method is called when the player released the finger/the mouse button
     endMove: function(){
     
          // waiting for player input to call startMove method
          game.input.onDown.add(this.startMove, this);
          
          // removing other listeners
          game.input.onUp.remove(this.endMove, this);
          game.input.deleteMoveCallback(this.dragString, this);     
     },
     
     // dragString method is called when the player moves the finger or the mouse while keeping mouse button pressed
     dragString: function(e){
     
          // calling moveString function. Actually this function moves and renders the string, and the two arguments represent
          // respectively the x and y movement to apply to string's head.
          // We set them to represent the distance from current input position and previous input position
          this.moveString(e.position.x - this.startPosition.x, e.position.y - this.startPosition.y);
          
          // updating startPosition variable
          this.startPosition = new Phaser.Point(e.position.x, e.position.y);     
     },
     
     // moveString method updates and renders the string
     moveString: function(x, y){
     
          // it's not game over yet
          var gameOver = false;
     
          // clearing the canvas, ready to be redrawn
          this.canvas.clear();
          
          // setting line style to a 4 pixel thick line, red, 100% opaque
          this.canvas.lineStyle(8, 0x00ff00, 1);
          
          // the head of the string is current input position
          var head = new Phaser.Point(this.segments[0].x + x, this.segments[0].y + y);
          
          // placing the pen on the head
          this.canvas.moveTo(head.x, head.y);
          
          // the first segment is the head itself
          this.segments[0] = new Phaser.Point(head.x, head.y);
          
          // looping through all segments starting from the second one
          for(var i = 1; i < this.segments.length - 1; i++){
          
               // determining the angle between current segment and previous segment
               var nodeAngle = Math.atan2(this.segments[i].y - this.segments[i - 1].y, this.segments[i].x - this.segments[i - 1].x);
               
               // calculating new segment position according to previous segment position and the angle
               this.segments[i] = new Phaser.Point(this.segments[i - 1].x + gameOptions.segmentLength * Math.cos(nodeAngle), this.segments[i - 1].y + gameOptions.segmentLength * Math.sin(nodeAngle));
               
               // getting the color behind the segment
               var color = this.bitmap.getPixelRGB(Math.round(this.segments[i].x), Math.round(this.segments[i].y));
               
               // if the color alpha is different than zero, that is it's not a transparent pixel...
               if(color.a != 0){
               
                    // from now on, draw the string in red
                    this.canvas.lineStyle(4, 0xff0000, 1);
                    
                    // game over...
                    gameOver = true;                    
               } 
               
               // drawing the segment
               this.canvas.lineTo(this.segments[i].x, this.segments[i].y);
               
               // repositioning graphic pen to avoid graphic glitch
               this.canvas.moveTo(this.segments[i].x, this.segments[i].y); 
                  
          }
          
          // if it's game over or the head of the string is fairly inside the end spot...
          if(this.segments[0].distance(this.endSpot.position) < this.endSpot.width / 4 || gameOver){
               
               // removing listeners
               game.input.onUp.remove(this.endMove, this);
               game.input.deleteMoveCallback(this.dragString, this);
               
               // wait 2 seconds before restarting the game.
               game.time.events.add(Phaser.Timer.SECOND * 2, function(){
                    game.state.start("TheGame");
               }, this);                               
          }          
     }
}

Next time I will create some levels, 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

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