-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
451 lines (377 loc) · 12 KB
/
main.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/* Author: Wolz Aurélien
* Based on: http://codepen.io/anon/pen/JsHok
*/
/*********************************
* VARIABLES
********************************/
var stage, w, h, loader, pipe1height, pipe2height, pipe3height, startX, startY, wiggleDelta;
var background, penguin, ground, pipe, bottomPipe, pipes, rotationDelta, counter, counterOutline;
var double = false;
var started = false;
var startJump = false;
var jumpAmount = 120;
var jumpTime = 266;
var dead = false;
var KEYCODE_SPACE = 32;
var gap = 250;
var masterPipeDelay = 78;
var pipeDelay = masterPipeDelay;
var counterShow = false;
var btnLoadRemoved = false;
var btnSaveDisplayed = false;
document.onkeydown = handleKeyDown;
/*********************************
* INITIALIZE
********************************/
function init() {
// Create and add stage
stage = new createjs.Stage("game");
createjs.Touch.enable(stage);
// Define variables
w = stage.canvas.width;
h = stage.canvas.height;
assets = [
// Pictures
{ src:"img/penguin.png", id:"penguin" },
{ src:"img/background.png", id:"background" },
{ src:"img/ground.png", id:"ground" },
{ src:"img/pipe.png", id:"pipe" },
{ src:"img/restart.png", id:"btnRestart" },
{ src:"img/share.png", id:"btnShare" },
{ src:"img/load.png", id:"btnLoad" },
{ src:"img/save.png", id:"btnSave" }
];
// Loading
loader = new createjs.LoadQueue(false);
loader.addEventListener("complete", handleComplete);
loader.loadManifest(assets);
}
/*********************************
* LOADING COMPLETED
********************************/
function handleComplete() {
// Display the background
background = new createjs.Shape();
background.graphics.beginBitmapFill(loader.getResult("background")).drawRect(0,0,w,h);
stage.addChild(background);
// Display and move the ground
var groundImg = loader.getResult("ground");
ground = new createjs.Shape();
ground.graphics.beginBitmapFill(groundImg).drawRect(0, 0, w+groundImg.width, groundImg.height);
ground.tileW = groundImg.width;
ground.y = h-groundImg.height;
// Load, crop and create penguin's frame
var data = new createjs.SpriteSheet({
"images": [loader.getResult("penguin")],
// Frames are important for penguin's rotation
"frames": {"width": 92, "height": 64, "regX": 46, "regY": 32, "count": 3},
// Define animations used
"animations": {"fly": [0, 2, "fly", 0.21], "dive": [1, 1, "dive", 1]}
});
// Create penguin sprite with fly animation
penguin = new createjs.Sprite(data, "fly");
// Position variables
startX = (w/2) - (92/2);
startY = 512;
wiggleDelta = 18;
// Set initial position
penguin.setTransform(startX, startY, 1, 1);
penguin.framerate = 30;
// Wiggle the penguin at the begining
createjs.Tween.get(penguin, {loop:true}).to({y:startY + wiggleDelta}, 380, createjs.Ease.sineInOut).to({y:startY}, 380, createjs.Ease.sineInOut);
// Prepare pipes
pipes = new createjs.Container();
stage.addChild(pipes);
// Stage ground after pipes for the overlay
stage.addChild(penguin, ground);
// Handle jump
stage.addEventListener("stagemousedown", handleJumpStart);
// Prepare counter
counter = new createjs.Text(0, "86px 'Arial'", "#ffffff");
counterOutline = new createjs.Text(0, "86px 'Arial'", "#000000");
counterOutline.outline = 5;
counterOutline.textAlign = 'center';
counter.textAlign = 'center';
counterOutline.x = w/2;
counterOutline.y = 150;
counter.x = w/2;
counter.y = 150;
counter.alpha = 1;
counterOutline.alpha = 1;
stage.addChild(counter, counterOutline);
// Prepare buttons Save and Load
prepareButtonsNewGame();
// Ticker configuration
createjs.Ticker.timingMode = createjs.Ticker.RAF;
createjs.Ticker.addEventListener("tick", tick);
}
/*********************************
* HANDLE KEYS PRESSED
********************************/
function handleKeyDown(e) {
// Cross-browser issue retrieve event
if(!e) {
var e = window.event;
}
// If space, start jump function
switch(e.keyCode) {
case KEYCODE_SPACE: handleJumpStart();
}
}
/*********************************
* JUMP ACTION
********************************/
function handleJumpStart() {
// If the penguin is not dead
if(!dead) {
if(double) {
// Clean penguin animations
createjs.Tween.removeTweens(penguin);
// Display jump animation
penguin.gotoAndPlay("jump");
startJump = true;
if(!started) {
started = true;
counterShow = true;
}
} else {
double = true;
}
}
}
/*********************************
* DIE FUNCTION
********************************/
function die() {
dead = true;
// Remove Save button
stage.removeChild(btnSave);
// Update animation
penguin.gotoAndPlay("dive");
createjs.Tween.removeTweens(penguin);
// Move the penguin down to the ground
createjs.Tween.get(penguin).wait(0).to({y:penguin.y + 200, rotation: 90}, (380)/1.5, createjs.Ease.linear) // Rotate back
.to({y:ground.y - 30}, (h - (penguin.y+200))/1.5, createjs.Ease.linear); // Drop to the bedrock
// Prepare restart button
btnRestart = new createjs.Bitmap(loader.getResult("btnRestart"));
btnRestart.alpha = 0;
btnRestart.x = w/2 - btnRestart.image.width/2;
btnRestart.y = h/2 - btnRestart.image.height/2 - 150;
stage.addChild(btnRestart);
// Prepare share button
btnShare = new createjs.Bitmap(loader.getResult("btnShare"));
btnShare.alpha = 0;
btnShare.x = w/2 - btnShare.image.width/2;
btnShare.y = h/2 - btnShare.image.height/2 - 50;
stage.addChild(btnShare);
// Buttons apparition
createjs.Tween.get(btnRestart).to({alpha:1, y: btnRestart.y + 50}, 400, createjs.Ease.sineIn);
createjs.Tween.get(btnShare).to({alpha:1, y: btnShare.y + 50}, 400, createjs.Ease.sineIn);
addButtonsListerner();
}
/*********************************
* RESTART FUNCTION
********************************/
function restartGame() {
// Remove all pipes
pipes.removeAllChildren();
createjs.Tween.get(btnRestart).to({y:btnRestart.y + 10}, 50).call(removeButtons);
// Refresh variables
counter.text = 0;
counterOutline.text = 0;
counterOutline.alpha = 1;
counter.alpha = 1;
counter.show = true;
pipeDelay = masterPipeDelay;
dead = false;
started = false;
startJump = false;
double = false;
btnLoadRemoved = false;
btnSaveDisplayed = false;
// Prepare buttons Save and Load
prepareButtonsNewGame();
// Prepare pinguin
createjs.Tween.removeTweens(penguin);
penguin.x = startX;
penguin.y = startY;
penguin.rotation = 0;
createjs.Tween.get(penguin, {loop:true}).to({y:startY + wiggleDelta}, 380, createjs.Ease.sineInOut).to({y:startY}, 380, createjs.Ease.sineInOut);
}
/*********************************
* BUTTON MANAGEMENT
********************************/
function prepareButtonsNewGame() {
// Prepare load and save buttons
btnLoad = new createjs.Bitmap(loader.getResult("btnLoad"));
btnLoad.alpha = 0;
btnLoad.x = w/2 - btnLoad.image.width/2;
btnLoad.y = 10;
stage.addChild(btnLoad);
btnSave = new createjs.Bitmap(loader.getResult("btnSave"));
btnSave.alpha = 0;
btnSave.x = w/2 - btnSave.image.width/2;
btnSave.y = 10;
stage.addChild(btnSave);
// Event Load
btnLoad.addEventListener("click", function() {
var msg = {
"messageType": "LOAD_REQUEST",
};
window.parent.postMessage(msg, "*");
console.log("Sent to window parent: " + JSON.stringify(msg, null, 2));
btnLoadRemoved = true;
});
// Load response handler
window.addEventListener("message", function(evt) {
if(evt.data.messageType === "LOAD") {
counter.text = evt.data.gameState.score;
counterOutline.text = evt.data.gameState.score;
} else if (evt.data.messageType === "ERROR") {
alert(evt.data.info);
}
});
// Event Save
btnSave.addEventListener("click", function() {
var msg = {
"messageType": "SAVE",
"gameState": {
"score": parseFloat(counter.text)
}
};
window.parent.postMessage(msg, "*");
console.log("Sent to window parent: " + JSON.stringify(msg, null, 2));
});
// Apparition Load
createjs.Tween.get(btnLoad).to({alpha:1, y: btnLoad.y + 50}, 400, createjs.Ease.sineIn);
}
function removeButtons() {
stage.removeChild(btnRestart);
stage.removeChild(btnShare);
}
function addButtonsListerner() {
btnRestart.addEventListener("click", restartGame);
btnShare.addEventListener("click", shareScore);
}
/*********************************
* SHARE FUNCTION
********************************/
function shareScore() {
var msg = {
"messageType": "SCORE",
"score": parseFloat(counter.text)
};
window.parent.postMessage(msg, "*");
console.log("Sent to window parent: " + JSON.stringify(msg, null, 2));
}
/*********************************
* TICK TIMMING
********************************/
function tick(event) {
// Variables
var deltaS = event.delta/1000;
var l = pipes.getNumChildren();
// Collision detection
if (penguin.y > (ground.y - 40)) {
if(!dead) {
die();
}
if(penguin.y > (ground.y - 30)) {
createjs.Tween.removeTweens(penguin);
}
}
// Move the ground
if(!dead) {
ground.x = (ground.x-deltaS*300) % ground.tileW;
}
// Game management
if(started && !dead) {
// Remove btnLoad if not clicked
if(!btnLoadRemoved) {
stage.removeChild(btnLoad);
}
// Display btnSave if not displayed
if(!btnSaveDisplayed) {
createjs.Tween.get(btnSave).to({alpha:1, y: btnSave.y + 50}, 400, createjs.Ease.sineIn);
btnSaveDisplayed = true;
}
// Pipe apparitions
if (pipeDelay == 0) {
// Create a new pipe and add it
pipe = new createjs.Bitmap(loader.getResult("pipe"));
pipe.x = w+600;
pipe.y = (ground.y - gap*2) * Math.random() + gap*1.5;
pipes.addChild(pipe);
// Create second pipe top
pipe2 = new createjs.Bitmap(loader.getResult("pipe"));
pipe2.scaleX = -1;
pipe2.rotation = 180;
pipe2.x = pipe.x;
pipe2.y = pipe.y - gap;
pipes.addChild(pipe2);
// Reset the delay
pipeDelay = masterPipeDelay;
} else {
// Decrement the delay
pipeDelay = pipeDelay-1;
}
// Display current pipes
for(var i=0; i<l; i++) {
// Retrieve it
pipe = pipes.getChildAt(i);
if(pipe) {
if(true) {
var collision = ndgmr.checkRectCollision(pipe,penguin,1,true);
if (collision) {
if (collision.width > 8 && collision.height > 8) {
die();
}
}
}
// Move pipe
pipe.x = (pipe.x - deltaS*300);
// Manage score counter when pipres passed
if(pipe.x <= 338 && pipe.rotation == 0 && pipe.name != "counted") {
pipe.name = "counted";
counter.text = counter.text + 1;
counterOutline.text = counterOutline.text + 1;
}
// Remove pipes out of the game
if (pipe.x + pipe.image.width <= -pipe.w) {
pipes.removeChild(pipe)
}
}
}
// Counter show properties
if(counterShow) {
counter.alpha = 1
counterOutline.alpha = 1
counterShow = false
}
}
if(startJump) {
startJump = false
// Display penguin animation
penguin.framerate = 60;
penguin.gotoAndPlay("fly");
// Rotation management()
if (penguin.roation < 0) {
rotationDelta = (penguin.rotation - 20)/5;
} else {
rotationDelta = (penguin.rotation + 20)/5;
}
// Limit position
if (penguin.y < -200) {
penguin.y = -200
}
createjs
.Tween
.get(penguin)
.to({y:penguin.y - rotationDelta, rotation: -20}, rotationDelta, createjs.Ease.linear) // rotate to jump position and jump penguin
.to({y:penguin.y - jumpAmount, rotation: -20}, jumpTime - rotationDelta, createjs.Ease.quadOut) // rotate to jump position and jump penguin
.to({y:penguin.y}, jumpTime, createjs.Ease.quadIn) // reverse jump for smooth arch
.to({y:penguin.y + 200, rotation: 90}, (380)/1.5, createjs.Ease.linear) //rotate back
.to({y:ground.y - 30}, (h - (penguin.y+200))/1.5, createjs.Ease.linear); // drop to the bedrock
}
stage.update(event);
}