“Mike Dangers” HTML5 game engine made with Phaser and ARCADE physics – optimizing the code and making the game fair

Talking about Mike Dangers game, Game development, HTML5, Javascript and Phaser.

In this new chapter of the Mike Dangers series we are going to optimize the code and make the game fair. Making a game fair is the top priority when you randomly generate levels. Players have to have the feeling they lost the game because they weren’t skilled enough – and they will retry – and not because the level was in some way impossible to solve. In previous step, spikes are randomly placed on the floor, and sometimes – quite often actually – they are placed right at the end of a ladder, making the player crashing into them with no way to avoid them. To prevent this, each time I place a ladder I create some kind of “safe area”, which means each ladder has a “spike-free” radius. Sme thing goes for the spikes, each spike has its own “spike-free” radius because we do not want two spikes being too close to each other. Another important change is I do not longer use arrays to store floors, ladders and stuff. I only use arrays for the object pooling while in-game objects are only organized in groups. This won’t affect performance because we only have a few objects on the canvas, but will make the code more understandable and easier to port in other languages. Last but not least, floors below the player won’t fall down anymore. It just does not feel realistic. Now they simple scroll down, fading away into some kind of fog. Well, have a look at the game:
Just tap or click to make the player jump. Try to climb the ladders and collect diamonds while avoding spikes. If you have a mobile device, you can play directly at this link. Now, the source code, not that big for a complete prototype:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
var game;
var gameOptions = {
    gameWidth: 800,
    floorStart: 1 / 8 * 5,
    floorGap: 250,
    playerGravity: 10000,
    playerSpeed: 450,
    climbSpeed: 450,
    playerJump: 1800,
    diamondRatio: 2,
    doubleSpikeRatio: 1,
    skyColor: 0xaaeaff,
    safeRadius: 120
}
window.onload = function() {
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;
    if(windowWidth > windowHeight){
        windowHeight = windowWidth * 1.8
    }
    game = new Phaser.Game(gameOptions.gameWidth, windowHeight * gameOptions.gameWidth / windowWidth);
    game.state.add("PreloadGame", preloadGame);
    game.state.add("PlayGame", playGame);
    game.state.start("PreloadGame");
}
var preloadGame = function(game){}
preloadGame.prototype = {
    preload: function(){
        game.stage.backgroundColor = gameOptions.skyColor;
        game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
        game.scale.pageAlignHorizontally = true;
        game.scale.pageAlignVertically = true;
        game.stage.disableVisibilityChange = true;
        game.load.image("floor", "floor.png");
        game.load.image("hero", "hero.png");
        game.load.image("ladder", "ladder.png");
        game.load.image("diamond", "diamond.png");
        game.load.image("spike", "spike.png");
        game.load.image("cloud", "cloud.png");
    },
    create: function(){
        game.state.start("PlayGame");
    }
}
var playGame = function(game){}
playGame.prototype = {
    create: function(){
        this.gameOver = false;
        this.reachedFloor = 0;
        game.physics.startSystem(Phaser.Physics.ARCADE);
        this.canJump = true;
        this.isClimbing = false;
        this.defineGroups();
        var cloud = game.add.sprite(0, game.height, "cloud");
        cloud.anchor.set(0, 1);
        cloud.tint = gameOptions.skyColor;
        this.drawLevel();
        this.defineTweens();
        game.input.onTap.add(this.handleTap, this);
    },
    drawLevel: function(){
        this.currentFloor = 0;
        this.highestFloorY = game.height * gameOptions.floorStart;
        this.floorsBeforeDisappear = Math.ceil((game.height - game.height * (gameOptions.floorStart)) / gameOptions.floorGap) + 1;
        this.floorPool = [];
        this.ladderPool = [];
        this.diamondPool = [];
        this.spikePool = [];
        while(this.highestFloorY > - 2 * gameOptions.floorGap){
                this.addFloor();
                if(this.currentFloor > 0){
                    this.addLadder();
                    this.addDiamond();
                    this.addSpike();
                }
 
                this.highestFloorY -= gameOptions.floorGap;
                this.currentFloor ++;
        }
        this.highestFloorY += gameOptions.floorGap;
        this.currentFloor = 0;
        this.addHero();
    },
    addFloor: function(){
        if(this.floorPool.length > 0){
            var floor = this.floorPool.pop();
            floor.y = this.highestFloorY;
            floor.revive();
        }
        else{
            var floor = game.add.sprite(0, this.highestFloorY, "floor");
            this.floorGroup.add(floor);
            game.physics.enable(floor, Phaser.Physics.ARCADE);
            floor.body.immovable = true;
            floor.body.checkCollision.down = false;
        }
    },
    addLadder: function(){
        var ladderXPosition = game.rnd.integerInRange(50, game.width - 50);
        if(this.ladderPool.length > 0){
            var ladder = this.ladderPool.pop();
            ladder.x = ladderXPosition;
            ladder.y = this.highestFloorY;
            ladder.revive();
        }
        else{
            var ladder = game.add.sprite(ladderXPosition, this.highestFloorY, "ladder");
            this.ladderGroup.add(ladder);
            ladder.anchor.set(0.5, 0);
            game.physics.enable(ladder, Phaser.Physics.ARCADE);
            ladder.body.immovable = true;
        }
        this.safeZone = [];
        this.safeZone.length = 0;
        this.safeZone .push({
            start: ladderXPosition - gameOptions.safeRadius,
            end: ladderXPosition + gameOptions.safeRadius
        });
    },
    addDiamond: function(){
        if(game.rnd.integerInRange(0, gameOptions.diamondRatio) != 0){
            var diamondX = game.rnd.integerInRange(50, game.width - 50);
            if(this.diamondPool.length > 0){
                var diamond = this.diamondPool.pop();
                diamond.x = diamondX;
                diamond.y = this.highestFloorY - gameOptions.floorGap / 2;
                diamond.revive();
            }
            else{
                var diamond = game.add.sprite(diamondX, this.highestFloorY - gameOptions.floorGap / 2, "diamond");
                diamond.anchor.set(0.5, 0);
                game.physics.enable(diamond, Phaser.Physics.ARCADE);
                diamond.body.immovable = true;
                this.diamondGroup.add(diamond);
            }
        }
    },
    addSpike: function(){
        var spikes = 1;
        if(game.rnd.integerInRange(0, gameOptions.doubleSpikeRatio) == 0){
            spikes = 2;
        }
        for(var i = 1; i <= spikes; i++){
            var spikeXPosition = this.findSpikePosition();
            if(this.spikePool.length > 0){
                var spike = this.spikePool.pop();
                spike.x = spikeXPosition;
                spike.y = this.highestFloorY - 20;
                spike.revive();
            }
            else{
                var spike = game.add.sprite(spikeXPosition, this.highestFloorY - 20, "spike");
                spike.anchor.set(0.5, 0);
                game.physics.enable(spike, Phaser.Physics.ARCADE);
                spike.body.immovable = true;
                this.spikeGroup.add(spike);
            }
        }
    },
    findSpikePosition: function(){
        do{
            var posX = game.rnd.integerInRange(150, game.width - 150)
        } while(!this.isSafe(posX));
        this.safeZone.push({
            start: posX - gameOptions.safeRadius,
            end: posX + gameOptions.safeRadius
        })
        return posX;
    },
    isSafe: function(n){
        for(var i = 0; i < this.safeZone.length; i++){
            if(n > this.safeZone[i].start && n < this.safeZone[i].end){
                return false;
            }
        }
        return true;
    },
    addHero: function(){
        this.hero = game.add.sprite(game.width / 2, game.height * gameOptions.floorStart - 40, "hero");
        this.gameGroup.add(this.hero)
        this.hero.anchor.set(0.5, 0);
        game.physics.enable(this.hero, Phaser.Physics.ARCADE);
        this.hero.body.collideWorldBounds = true;
        this.hero.body.gravity.y = gameOptions.playerGravity;
        this.hero.body.velocity.x = gameOptions.playerSpeed;
        this.hero.body.onWorldBounds = new Phaser.Signal();
        this.hero.body.onWorldBounds.add(function(sprite, up, down, left, right){
            if(left){
                this.hero.body.velocity.x = gameOptions.playerSpeed;
                this.hero.scale.x = 1;
            }
            if(right){
                this.hero.body.velocity.x = -gameOptions.playerSpeed;
                this.hero.scale.x = -1;
            }
            if(down){
                game.state.start("PlayGame");
            }
        }, this)
    },
    defineTweens: function(){
        this.tweensToGo = 0;
        this.scrollTween = game.add.tween(this.gameGroup);
        this.scrollTween.to({
            y: gameOptions.floorGap
        }, 500, Phaser.Easing.Cubic.Out);
        this.scrollTween.onComplete.add(function(){
            this.gameGroup.y = 0;
            this.gameGroup.forEach(function(item){
                if(item.length > 0){
                    item.forEach(function(subItem) {
                        subItem.y += gameOptions.floorGap;
                        if(subItem.y > game.height){
                            switch(subItem.key){
                                case "floor":
                                    this.killFloor(subItem);
                                    break;
                                case "ladder":
                                    this.killLadder(subItem);
                                    break;
                                case "diamond":
                                    this.killDiamond(subItem);
                                    break;
                                case "spike":
                                    this.killSpike(subItem);
                                    break;
                            }
                        }
                    }, this);
                }
                else{
                    item.y += gameOptions.floorGap;
                }
            }, this);
            this.addFloor();
            this.addLadder();
            this.addDiamond();
            this.addSpike();
            if(this.tweensToGo > 0){
                this.tweensToGo --;
                this.scrollTween.start();
            }
        }, this);
    },
    defineGroups: function(){
        this.gameGroup = game.add.group();
        this.floorGroup = game.add.group();
        this.ladderGroup = game.add.group();
        this.diamondGroup = game.add.group();
        this.spikeGroup = game.add.group();
        this.gameGroup.add(this.floorGroup);
        this.gameGroup.add(this.ladderGroup);
        this.gameGroup.add(this.diamondGroup);
        this.gameGroup.add(this.spikeGroup);
    },
    handleTap: function(pointer, doubleTap){
        if(this.canJump && !this.isClimbing && !this.gameOver){
            this.hero.body.velocity.y = -gameOptions.playerJump;
            this.canJump = false;
        }
    },
    update: function(){
        if(!this.gameOver){
            this.checkFloorCollision();
            this.checkLadderCollision();
            this.checkDiamondCollision();
            this.checkSpikeCollision();
        }
    },
    checkFloorCollision: function(){
        game.physics.arcade.collide(this.hero, this.floorGroup, function(){
            this.canJump = true;
        }, null, this);
    },
    checkLadderCollision: function(){
        if(!this.isClimbing){
            game.physics.arcade.overlap(this.hero, this.ladderGroup, function(player, ladder){
                if(Math.abs(player.x - ladder.x) < 10){
                    this.ladderToClimb = ladder;
                    this.hero.body.velocity.x = 0;
                    this.hero.body.velocity.y = - gameOptions.climbSpeed;
                    this.hero.body.gravity.y = 0;
                    this.isClimbing = true;
                    this.reachedFloor ++;
                    if(this.scrollTween.isRunning){
                        this.tweensToGo ++;
                    }
                    else{
                        this.scrollTween.start();
                    }
                }
            }, null, this);
        }
        else{
            if(this.hero.y < this.ladderToClimb.y - 40){
                this.hero.body.gravity.y = gameOptions.playerGravity;
                this.hero.body.velocity.x = gameOptions.playerSpeed * this.hero.scale.x;
                this.hero.body.velocity.y = 0;
                this.isClimbing = false;
            }
        }
    },
    checkDiamondCollision: function(){
        game.physics.arcade.overlap(this.hero, this.diamondGroup, function(player, diamond){
            this.killDiamond(diamond);
        }, null, this);
    },
    checkSpikeCollision: function(){
        game.physics.arcade.overlap(this.hero, this.spikeGroup, function(){
            this.gameOver = true;
            this.hero.body.velocity.x =  game.rnd.integerInRange(-20, 20);
            this.hero.body.velocity.y = -gameOptions.playerJump;
            this.hero.body.gravity.y = gameOptions.playerGravity;
        }, null, this);
    },
    killFloor: function(floor){
        floor.kill();
        this.floorPool.push(floor);
    },
    killLadder: function(ladder){
        ladder.kill();
        this.ladderPool.push(ladder);
    },
    killDiamond: function(diamond){
        diamond.kill();
        this.diamondPool.push(diamond);
    },
    killSpike: function(spike){
        spike.kill();
        this.spikePool.push(spike);
    }
}
Less than 350 lines. I’ll try to add score management and a splash screen keeping the code below 350 lines, then will start commenting it line by line. Meanwhile, download the source code.