-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
315 lines (281 loc) · 10.1 KB
/
app.js
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
(function() {
//Get canvas and context
var c = document.getElementById('canvas'),
ctx = c.getContext('2d');
//Load assets
var bgImg = loadImage('assets/background.jpg', 640, 480),
playerImg = loadImage('assets/player.png', 192, 64),
enemyUpImg = loadImage('assets/enemy_up.png', 64, 316),
enemyDownImg = loadImage('assets/enemy_down.png', 64, 316);
var pointAudio = new Audio('assets/point.mp3'),
loseAudio = new Audio('assets/lose.mp3');
//Helper methods
function loadImage(src, width, height) {
var img = new Image(width, height);
img.src = src;
return img;
}
function randomIntFromInterval(min,max) {
return Math.floor(Math.random()*(max-min+1)+min);
}
var textAlpha = (function() {
var alpha = 1,
shouldIncrease = false;
return {
fluctuate: function() {
if (alpha < 0) shouldIncrease = true;
if (alpha > 1) shouldIncrease = false;
if (shouldIncrease) alpha += 0.02;
else alpha -= 0.02;
return alpha;
},
get: function() {
return alpha;
}
};
})();
//Game constants
var PLAYER_CONTROLS_ON = false;
var GAME_PLAYING = false;
//Classes & objects
//******* Score counter object **********//
var scoreCounter = {
//state
_score: 0,
//methods
increaseScore: function() {
this._score++;
pointAudio.play();
},
getScore: function() {
return this._score;
},
reset: function() {
this._score = 0;
}
};
//******* Background Constructor **********//
function Background(x, y, speed, img) {
this.x = x || 0;
this.y = y || 0;
this.img = img || bgImg;
this.speed = speed || 1;
}
Background.prototype = {
move: function() {
this.x -= this.speed;
if (this.x <= -this.img.width) {
this.x = c.width;
}
}
};
//******* Player Object **********//
//fps locking vars
var fpsCounter = Date.now(), //custom timer to restrict fps
fps = 30;
//free falling counter
var fallingCounter = Date.now();
//Player
player = {
//private state
_currentFrame: 0,
//public properties
//physics
velocity: 2,
force: 0.15,
//positional
x: 70,
y: 20,
width: 64,
height: 64,
//methods
jump: function() {
this.velocity = -6;
},
fall: function() {
var now = Date.now();
if (now - fallingCounter > 1000 / fps) {
if (this.velocity < 8) this.velocity += this.force;
this.y += this.velocity;
}
},
hasCollided: function() {
var hasCollided = false;
var playerX = this.x + this.width,
playerTopY = this.y,
playerBottomY = this.y + this.height;
var enemyX = enemies[nextEnemyId].enemyDown.x + 40,
enemyLookingDownY = enemies[nextEnemyId].enemyDown.y + enemies[nextEnemyId].enemyDown.img.height,
enemyLookingUpY = enemies[nextEnemyId].enemyUp.y,
enemyWidth = enemies[nextEnemyId].enemyDown.img.width;
//when the enemy is inside an obstacle
if (playerX > enemyX && playerX < enemyX + enemyWidth - 40) {
//check for collision and tag player as collided if they hit an obstacle
if (playerTopY < enemyLookingDownY || playerBottomY > enemyLookingUpY)
hasCollided = true;
}
//if the player goes above/below screen tag as collided
if (playerBottomY < 0 || playerTopY > c.height) {
hasCollided = true;
}
if (hasCollided & PLAYER_CONTROLS_ON) loseAudio.play();
//return collision result
return hasCollided;
},
reset: function() {
this.velocity = 2;
this.y = 20;
},
getNextFrame: function() {
var now = Date.now();
if (now - fpsCounter > 1000 / fps) {
fpsCounter = now;
this._currentFrame++;
if (this._currentFrame > 2) this._currentFrame = 0;
}
return this._currentFrame;
}
};
//******* Enemy Constructor **********//
//constants
var ENEMY_NUMBER = 5, //how many sets of enemies
ENEMY_OFFSET = 300, //horizontal distance between obstacles
ENEMY_DISTANCE = 120, //vertical opening between obstacles
MAX_YOFFSET = 50,
MIN_YOFFSET = -150;
//Enemy IDs
var nextEnemyId, lastEnemyId; // defined in setupEnemies()
function Enemy(id, y, yOffset, imgDirectionIsUp, speed, img) {
if (typeof id === 'undefined') throw new Error('Parameter ID must be defined');
this.id = id;
this.imgDirectionIsUp = typeof imgDirectionIsUp === 'undefined' ? true : imgDirectionIsUp;
this.yOffset = yOffset || 0;
this.x = c.width + id * ENEMY_OFFSET || 0;
if
(this.imgDirectionIsUp) this.y = y + ENEMY_DISTANCE + this.yOffset || 0;
else
this.y = y - ENEMY_DISTANCE + this.yOffset || 0;
this.speed = speed || 3;
this.img = img || (this.imgDirectionIsUp ? enemyUpImg : enemyDownImg);
}
Enemy.prototype = {
move: function() {
this.x -= this.speed;
if (this.x <= -this.img.width && this.imgDirectionIsUp) {
//Set x of this enemy set to next enemy set + enemy offset
this.x = enemies[this.id].enemyDown.x = enemies[lastEnemyId].enemyUp.x + ENEMY_OFFSET;
//Set new random Y
this.yOffset = enemies[this.id].enemyDown.yOffset = randomIntFromInterval(MIN_YOFFSET, MAX_YOFFSET);
//Update last enemy ID
lastEnemyId = lastEnemyId === ENEMY_NUMBER - 1 ? 0 : lastEnemyId + 1;
}
if (this.id === nextEnemyId && this.x + this.img.width < player.x + player.width) {
//Update next enemy ID
nextEnemyId = nextEnemyId === ENEMY_NUMBER - 1 ? 0 : nextEnemyId + 1;
//Increase the score
if (PLAYER_CONTROLS_ON) scoreCounter.increaseScore();
}
}
};
//Main functions
var updateLoop;
function update() {
draw();
updateLoop = window.requestAnimationFrame(update);
}
function draw() {
//Set font style
ctx.font = '48px Raleway';
//Clean canvas
ctx.clearRect(0, 0, c.width, c.height);
//Draw next frame with props
drawBackground();
//If game hasn't started or player lost show splash screen text
if (!GAME_PLAYING) {
ctx.strokeStyle = 'rgba(0,0,0,' + textAlpha.get() + ')';
ctx.strokeText('Click to start game', c.width / 2 - 230, 80);
ctx.fillStyle = 'rgba(255,255,255,' + textAlpha.get() + ')';
ctx.fillText('Click to start game', c.width / 2 - 230, 80);
textAlpha.fluctuate();
}
//If game is playing draw everything
else {
drawEnemies();
drawPlayer();
//Draw the score
ctx.fillStyle = 'black';
ctx.strokeText(scoreCounter.getScore(), c.width / 2 - 11, 51);
ctx.fillStyle = 'white';
ctx.fillText(scoreCounter.getScore(), c.width / 2 - 10, 50);
}
}
//Instantiate, draw and animate backgrounds
var bg1 = new Background(0, 0);
var bg2 = new Background(c.width, 0);
function drawBackground() {
ctx.drawImage(bg1.img, bg1.x, bg1.y);
ctx.drawImage(bg2.img, bg2.x, bg2.y);
bg1.move();
bg2.move();
}
//Instantiate and draw player
function drawPlayer() {
//render player
ctx.drawImage(playerImg, player.getNextFrame() * player.width, 0, //crop start
player.width, player.height, //crop end
player.x, player.y, //player pos
player.width, player.height); //player sprite size
//move player
player.fall();
//collision check
if (player.hasCollided()) {
//deactivate player controls
PLAYER_CONTROLS_ON = false;
//when player falls of screen stop game
if (player.y - player.height > c.height) GAME_PLAYING = false;
}
}
//Set up initial enemy positions before rendering them
var enemies = [];
function setupEnemies() {
nextEnemyId = 0;
lastEnemyId = ENEMY_NUMBER - 1; //used to reposition enemies
for (var i = 0; i < ENEMY_NUMBER; i++) {
var yOffset = randomIntFromInterval(MIN_YOFFSET, MAX_YOFFSET);
var enemySet = {
enemyUp: new Enemy(i, c.height / 2, yOffset),
enemyDown: new Enemy(i, 0, yOffset, false)
};
enemies[i] = enemySet;
}
}
//Instantiate and draw enemies
function drawEnemies() {
for (var i = 0; i < enemies.length; i++) {
ctx.drawImage(enemies[i].enemyUp.img, enemies[i].enemyUp.x, enemies[i].enemyUp.y);
ctx.drawImage(enemies[i].enemyDown.img, enemies[i].enemyDown.x, enemies[i].enemyDown.y);
enemies[i].enemyUp.move();
enemies[i].enemyDown.move();
}
}
//Reset game function
function resetGame() {
scoreCounter.reset();
player.reset();
setupEnemies();
}
//Register event handlers & kick off the game
window.onload = function() {
c.addEventListener('click', function() {
if (PLAYER_CONTROLS_ON) {
player.jump();
}
if (!GAME_PLAYING) {
resetGame();
GAME_PLAYING = true;
PLAYER_CONTROLS_ON = true;
}
});
update();
};
})();