-
Notifications
You must be signed in to change notification settings - Fork 0
/
firecyclist.js
2406 lines (2123 loc) · 97.7 KB
/
firecyclist.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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// (c) Wilson Berkow
// Firecyclist.js
/*globals
window requestAnimationFrame performance
*/
(function () {
"use strict";
var bgCanvas = document.getElementById("bgCanvas");
var mainCanvas = document.getElementById("canvas");
var btnCanvas = document.getElementById("btnCanvas");
var overlayCanvas = document.getElementById("overlayCanvas");
var gameWidth = 576 / 2;
var gameHeight = 1024 / 2;
// Resize and center game canvases:
var pageScaleFactor = 1, calcTouchPos;
(function () {
var htmlModule = document.getElementById("Main"),
windowDims = {
// The defaulting expression (.documentElement....) is for IE
width: window.innerWidth || document.documentElement.clientWidth,
height: window.innerHeight || document.documentElement.clientHeight
},
scaleX = windowDims.width / gameWidth,
scaleY = windowDims.height / gameHeight,
moduleOffsetX = 0;
pageScaleFactor = Math.min(scaleX, scaleY);
if (scaleX > scaleY) {
// If the game is as tall as the screen but not as wide, center it
moduleOffsetX = (windowDims.width - gameWidth * pageScaleFactor) / 2;
htmlModule.setAttribute("style", "position: fixed; left: " + Math.floor(moduleOffsetX) + "px;");
// <body> is sky-blue while page is loading, but once it has loaded,
// the canvas handles all color in the 288x576 so for phones with
// resolutions not at exactly 2:1 screens, turn bg black:
document.body.setAttribute("style", "background-color: black;");
}
calcTouchPos = function (event) {
var literalX, literalY;
if (typeof event.clientX === "number") {
// These are tried to allow mouse to be instead of touches
literalX = event.clientX;
literalY = event.clientY;
} else {
literalX = event.changedTouches[0].clientX;
literalY = event.changedTouches[0].clientY;
// `event.changedTouches[0]` works when handling touchend,
// at which point `event.touches[0]` would be undefined.
}
return {
x: (literalX - moduleOffsetX) / pageScaleFactor,
y: literalY / pageScaleFactor,
rawX: literalX,
rawY: literalY
};
};
[bgCanvas, mainCanvas, btnCanvas, overlayCanvas].forEach(function (canvas) {
canvas.width *= pageScaleFactor;
canvas.height *= pageScaleFactor;
});
}());
// Touch system:
var Touch = (function () {
var touchesCount = 0;
document.addEventListener("touchmove", function (event) {
var xy = calcTouchPos(event);
if (Touch.curTouch) {
// Condition fails when a platfm has been materialized,
// and thus curTouch was reset to null
Touch.curTouch.x1 = xy.x;
Touch.curTouch.y1 = xy.y;
Touch.curTouch.rawX1 = xy.rawX;
Touch.curTouch.rawY1 = xy.rawY;
}
// `preventDefault()' to stop Chrome from moving
// through browser history on swipes
event.preventDefault();
});
document.addEventListener("touchstart", function (event) {
var now = Date.now(), xy = calcTouchPos(event);
Touch.curTouch = {
t0: now,
id: touchesCount,
x0: xy.x,
y0: xy.y,
rawX0: xy.rawX,
rawY0: xy.rawY,
x1: xy.x,
y1: xy.y,
rawX1: xy.rawX,
rawY1: xy.rawY
};
touchesCount += 1;
});
document.addEventListener("touchend", function () {
if (Touch.curTouch) {
if (typeof Touch.onTouchend === "function") {
Touch.onTouchend(Touch.curTouch);
}
Touch.curTouch = null;
}
});
return Object.seal({
curTouch: null,
// `onTouchend' can be set, specifying a handler, called above
onTouchend: null,
touchIsValidAsTap: function (t) {
if (Math.abs(t.rawX1 - t.rawX0) < 12
&& Math.abs(t.rawY1 - t.rawY0) < 12) {
if (Date.now() - t.t0 < 350) {
return true;
}
}
return false;
},
copy: function (t) {
return {
t0: t.t0,
id: t.id,
x0: t.x0,
y0: t.y0,
x1: t.x1,
y1: t.y1
};
},
zeroLength: function (t) {
return t.x0 === t.x1 && t.y0 === t.y1;
}
});
}());
// Generic util:
var
forEachInObject = function (obj, f) {
var keys = Object.keys(obj), i;
for (i = 0; i < keys.length; i += 1) {
f(keys[i], obj[keys[i]]);
}
},
modulo = function (num, modBy) {
return num - modBy * Math.floor(num / modBy);
},
oneDegree = Math.PI / 180,
trig = (function () {
var
// Sine and cosine tables are used so that the approximation
// doesn't have to be done more than once for any given angle.
// The angle inputs are rounded down to the nearest degree.
sines = [],
cosines = [],
sin = function (radians) {
return sines[modulo(Math.round(radians / oneDegree), 360)];
},
cos = function (radians) {
return cosines[modulo(Math.round(radians / oneDegree), 360)];
},
i;
for (i = 0; i < 360; i += 1) {
sines[i] = Math.sin(i * oneDegree);
cosines[i] = Math.cos(i * oneDegree);
}
return {sin: sin, cos: cos};
}()),
quickSqrt = (function () {
var i;
// Square root of x is at sqrtsLarge[x].
// `sqrtsLarge' is defined initially for 0 <= x < 250,
// but is extensible by memoization
var sqrtsLarge = {};
for (i = 0; i < 250; i += 1) {
sqrtsLarge[i] = Math.sqrt(i);
}
// Square root of x is at sqrtsSmall[x * 50].
// `sqrtsSmall' is defined for 0 <= x < 10
var sqrtsSmallMax = 10;
var sqrtsSmall = {};
for (i = 0; i < sqrtsSmallMax * 50; i += 1) {
sqrtsSmall[i] = Math.sqrt(i / 50);
}
return function (x) {
if (x < sqrtsSmallMax) {
return sqrtsSmall[Math.round(x * 50)];
}
var pos = Math.round(x);
if (sqrtsLarge[pos] === undefined) {
sqrtsLarge[pos] = Math.sqrt(pos);
}
return sqrtsLarge[pos];
};
}()),
distanceSquared = function (x0, y0, x1, y1) {
var dx = x1 - x0;
var dy = y1 - y0;
return dx * dx + dy * dy;
},
distLT = function (x0, y0, x1, y1, compareWith) {
var distSquared = distanceSquared(x0, y0, x1, y1);
return distSquared < compareWith * compareWith;
},
dist = function (x0, y0, x1, y1) {
return quickSqrt(distanceSquared(x0, y0, x1, y1));
},
padNumericPeriod = function (num) {
// E.g., if given 34, returns "034"
return num < 10 ? "00" + num :
num < 100 ? "0" + num :
"" + num;
};
// Is space-mode rendering on:
var starfieldActive = false;
// Velocity config:
var
fbRiseRate = 0.1,
playerGrav = 0.00075,
coinRiseRate = 0.1,
platfmRiseRate = 0.15,
activePowerupTravelTime = 250,
activePowerupLifespan = 10000;
// Other numeric config:
var
fbRadius = 10,
fbNumRecordedFrames = 300,
fbCreationChanceFactor = 1 / 12250,
coinRadius = 10,
coinValue = 11,
coinStartingY = gameHeight + coinRadius,
totalFbHeight = 10,
platfmThickness = 6,
playerTorsoLen = 9.375,
playerRadius = 7.5,
playerHeadRadius = 5.625,
playerElbowXDiff = 5,
playerWheelToHeadDist = playerTorsoLen + playerRadius + playerHeadRadius,
playerDuckingXDiff = -3,
playerDuckingYDiff = -10,
inGamePointsPxSize = 30,
inGamePointsXPos = 16,
inGamePointsYPos = 9,
activePowerupsStartingXPos = gameWidth - 78,
powerupBubbleRadius = 18,
powerupCreationChanceFactor = 1 / 75000,
powerupTotalLifespan = 5500, // in milliseconds
powerupX2Width = 36,
powerupX2Height = 23,
powerupSlowRadius = 12,
powerupMagnetRadius = 9,
powerupMagnetThickness = 8,
powerupWeightHandleHeight = 4,
powerupWeightBlockUpperXMargin = 3,
powerupWeightBlockLowerWidth = 30,
powerupWeightBlockHeight = 20,
powerupWeightHeight = powerupWeightBlockHeight + powerupWeightHandleHeight,
btnShadowOffset = 2,
maxFpsForSlowFrame = 40;
// Button util and config:
var
mkBtn = function (data) {
data.tintedRed = !!data.tintedRed;
data.textWDiff = data.textWDiff || 0;
data.textHDiff = data.textHDiff || 0;
data.textXOffset = data.textXOffset || 0;
// `textXOffset' is for small adjustments to alignment
// which make the button text *appear* better centered
data.edgeX = data.x - data.w / 2;
return Object.freeze(data);
},
menuPlayBtn = mkBtn({
text: "Play",
font: "italic bold 53px font0",
x: gameWidth / 2,
y: 280,
w: 121,
h: 57,
textHDiff: -13
}),
replayBtn = mkBtn({
text: "Replay",
font: "bold 33px font0",
x: gameWidth / 2,
y: 323,
w: 110,
h: 45,
textHDiff: -12,
textWDiff: -5,
tintedRed: true
}),
resumeBtn = mkBtn({
text: "Resume",
font: "bold 30px font0",
x: gameWidth / 2,
y: replayBtn.y - 68,
w: replayBtn.w + 9,
h: replayBtn.h - 3,
textXOffset: 1,
textHDiff: -12,
textWDiff: -5,
tintedRed: true
}),
pauseBtn = (function () {
var margin = 30;
var s = 40;
return mkBtn({
text: ":pause",
x: gameWidth - margin,
y: margin - s / 2,
w: s,
h: s,
textHDiff: -17
});
}()),
touchIsInsideBtn = function (xy, btn) {
var withinHeight = xy.y1 >= btn.y && xy.y1 <= btn.y + btn.h;
var withinWidth = xy.x1 >= btn.edgeX && xy.x1 <= btn.edgeX + btn.w;
return withinHeight && withinWidth;
},
touchIsInPauseBtn = function (xy) {
// Checks whether a touch is above and to the right of the
// bottom-left bound of the pause btn. A more inclusive and
// useful test than whether the touch is exactly in the btn.
return xy.y1 <= pauseBtn.y + pauseBtn.h &&
xy.x1 >= pauseBtn.edgeX;
};
// Highscore update and storage:
var
mkHighscores = function (identifier) {
// In `scores', highest scores are at the beginning, `null'
// represents an empty slot (when fewer than 3 games have
// been played)
// By default, `scores' is three empty slots
var scores = [null, null, null];
var fromLocal = localStorage.getItem(identifier);
if (fromLocal !== null) {
fromLocal = JSON.parse(fromLocal);
if (fromLocal) {
// Update `scores' with the stored highscores
scores = fromLocal;
}
}
return Object.freeze({
each: function (f) {
scores.forEach(function (score) {
if (score !== null) {
f(score);
}
});
},
sendScore: function (score) {
var i, result = false;
for (i = 0; i < scores.length; i += 1) {
if (score > scores[i] || scores[i] === null) {
scores.splice(i, 0, score);
scores.splice(scores.length - 1, 1);
result = true;
break;
}
}
localStorage.setItem(identifier, JSON.stringify(scores));
return result;
}
});
},
highscores = mkHighscores("highscores");
// Vector and line util:
var Vector = Object.freeze({
create: function (x, y) {
return {vx: x, vy: y};
},
findMagnitude: function (vect) {
return quickSqrt(vect.vx * vect.vx + vect.vy * vect.vy);
},
setMagnitude: function (vect, mag) {
var angle = Math.atan2(vect.vy, vect.vx);
vect.vx = trig.cos(angle) * mag;
vect.vy = trig.sin(angle) * mag;
}
});
var runLoop = (function () {
var fallbackFps = 35;
var mustFallback = false;
// Run a game-loop with requestAnimationFrame (raf) to time ticks
var rafLoop = function (tick, isLagTooGreat, handleDowngrade) {
var deltas = [];
var detlasMaxLength = 100;
var prevTime = performance.now() - 20;
var firstFrame = true;
var stop = false;
isLagTooGreat = isLagTooGreat || function () {
return false;
};
requestAnimationFrame(function repeat(now) {
if (stop) {
return;
}
requestAnimationFrame(repeat);
if (!firstFrame && deltas.length < detlasMaxLength) {
deltas.push(now - prevTime);
} else {
firstFrame = false;
}
stop = tick(now, true);
if (deltas.length < detlasMaxLength
&& isLagTooGreat(deltas)) {
stop = true;
mustFallback = true;
handleDowngrade(tick, fallbackFps);
}
prevTime = now;
});
return deltas;
};
// Run a game-loop with setInterval to time ticks
var intervalLoop = function (tick, fps) {
var deltas = [];
var prevTime = performance.now() - 20;
var firstFrame = true;
var intervalId = setInterval(function () {
var now = performance.now();
if (!firstFrame) {
deltas.push(now - prevTime);
} else {
firstFrame = true;
}
var stop = tick(now, false);
if (stop) {
clearInterval(intervalId);
}
prevTime = now;
}, 1000 / fps);
return deltas;
};
var frameTooSlow = function (dt) {
return 1000 / dt < maxFpsForSlowFrame;
};
var lagThresholdReached = function (deltas) {
// TODO: Test more on Galaxy Note 3 and refine
var lastFew = deltas.slice(-10);
var numSlow = lastFew.filter(frameTooSlow).length;
if (deltas.length <= 5) {
if (numSlow >= 4) {
return true;
}
}
return numSlow > 3;
};
return function (tick) {
if (mustFallback) {
intervalLoop(tick, fallbackFps);
} else {
rafLoop(tick, lagThresholdReached, intervalLoop);
}
};
}());
// Constructors for in-game objects:
var
createPlayer = function (x, y, vx, vy) {
return {
x: x,
y: y,
vx: vx,
vy: vy,
wheelAngle: 0, // in degrees
ducking: false
};
},
createPlatfm = function (x0, y0, x1, y1) {
return {
x0: x0,
y0: y0,
x1: x1,
y1: y1,
time_left: 800,
lengthSquared: distanceSquared(x0, y0, x1, y1),
// `maybeGetPlatfmFromTouch' ensures that for all hand-drawn
// platfms, platfm.x1 !== platfm.x0, so that the following
// slope calculation does not blow up:
slope: (y1 - y0) / (x1 - x0),
bounceSpeedX: undefined,
bounceVy: undefined,
bounceSpeed: undefined
// bounceSpeed is a cache of the magnitude of
// the vector (bounceVx, bounceVy)
};
},
createCoin = function (x, y, groupId) {
return {x: x, y: y, groupId: groupId};
},
createFb = function (x, y) {
return {x: x, y: y, frame: Math.floor(Math.random() * fbNumRecordedFrames)};
},
createPowerup = function (y, powerupType) {
return {
offsetY: y,
lifetime: 0,
type: powerupType
};
},
calcPowerupXPos = function (powerup) {
return powerup.lifetime / powerupTotalLifespan * gameWidth;
},
calcPowerupYPos = function (powerup) {
// y position of a powerup is a sin function of its x
// position, with stretched period and amplitude
return powerup.offsetY + trig.sin(calcPowerupXPos(powerup) / 20) * 40;
},
createActivePowerup = function (type, srcX, srcY) {
var lifetime = type === "slow"
? activePowerupLifespan * 2 / 3
: activePowerupLifespan;
return {
type: type,
totalLifetime: lifetime,
lifetime: lifetime,
srcX: srcX,
srcY: srcY,
timeSinceAcquired: 0
};
},
createGame = function () {
return {
player: createPlayer(gameWidth / 2, 50, 0, 0),
platfms: [],
// `previewPlatfmTouch' holds the current touch object, if a
// platfm is being drawn. Otherwise, it holds `null'
previewPlatfmTouch: null,
// 'fb' is short for 'fireball'
fbs: [],
coins: [],
// `game.coinGroups[i]` holds the number of still-living
// coins in the coinGroup with ID `i'
coinGroups: {},
// The id to use for the next coin group:
nextCoinGroupId: 0,
// `game.coinGroupBonuses[i]` holds the extra points to be
// gained once the every coin in group `i' has been obtained
coinGroupBonuses: {},
// Holds the current on-screen congratulatory notifications:
coinGroupGottenNotifs: [],
coinReleaseMode: "random",
// In "random" coin mode, whether to switch modes is determined
// randomly, without a timeout, so the following is `null'
coinReleaseModeTimeLeft: null,
// `coinGridOffset' is explained in detail in
// the `gUpdaters.coins' function
coinGridOffset: 0,
powerups: {},
activePowerups: [],
points: 0,
// How many of those points were gotten from coins directly:
pointsFromCoins: 0,
// `pointsFromCoins' is kept track of because the difficulty
// curve is a function of points not gotten from coins directly
paused: false,
dead: false,
// Is the pause button currently drawn in the pressed position?
pauseBtnDown: false,
// For debugging
statsPrev: {},
stats: {}
};
};
// Rendering:
var Render = (function () {
var bgCtx = bgCanvas.getContext("2d");
var mainCtx = mainCanvas.getContext("2d");
var btnCtx = btnCanvas.getContext("2d");
var overlayCtx = overlayCanvas.getContext("2d");
bgCtx.scale(pageScaleFactor, pageScaleFactor);
mainCtx.scale(pageScaleFactor, pageScaleFactor);
btnCtx.scale(pageScaleFactor, pageScaleFactor);
overlayCtx.scale(pageScaleFactor, pageScaleFactor);
// The following translations are a trick to make lines sharper:
// (No translation on bgCtx because clouds benefit
// from extra bluriness, and stars are unaffected.)
mainCtx.translate(0.5, 0.5);
btnCtx.translate(0.5, 0.5);
overlayCtx.translate(0.5, 0.5);
// For caching drawings on an off-screen canvas:
var offScreenRender = function (width, height, render) {
var newCanvas = document.createElement('canvas');
newCanvas.width = width;
newCanvas.height = height;
var ctx = newCanvas.getContext('2d');
ctx.translate(0.5, 0.5);
render(ctx, width, height);
return newCanvas;
};
// Renderers:
var
fillShadowyText = function (ctx, text, x, y, reverse, offsetAmt, w, h) {
// Doesn't set things like ctx.font and ctx.textAlign so that they
// can be set on ctx by the caller, before invoking.
var neutralClr = starfieldActive ? "white" : "black";
var brightClr = starfieldActive ? "royalblue" : "darkOrange";
var clr0 = reverse ? neutralClr : brightClr;
var clr1 = reverse ? brightClr : neutralClr;
var offset = offsetAmt || 1;
var setW = w !== undefined;
ctx.fillStyle = clr0;
if (setW) {
ctx.fillText(text, x, y, w, h);
} else {
ctx.fillText(text, x, y);
}
ctx.fillStyle = clr1;
if (setW) {
ctx.fillText(text, x + offset, y - offset, w, h);
} else {
ctx.fillText(text, x + offset, y - offset);
}
},
drawCircle = function (ctx, x, y, radius, color, fillOrStroke) {
ctx.beginPath();
ctx[fillOrStroke + "Style"] = color;
ctx.arc(x, y, radius, 0, 2 * Math.PI, true);
ctx[fillOrStroke]();
},
circleAt = function (ctx, x, y, radius) {
// The `+ radius' in the `moveTo' call below prevents a line
// from being drawn from the edge of the circle to its center
ctx.moveTo(x + radius, y);
ctx.arc(x, y, radius, 0, 2 * Math.PI, true);
},
lineFromTo = function (ctx, x0, y0, x1, y1) {
ctx.moveTo(x0, y0);
ctx.lineTo(x1, y1);
},
drawPlayerDuckingAt = (function () {
var w = playerRadius * 3;
var h = playerRadius * 3 + 6;
var hToWheelCenter = h - 3 - playerRadius;
var forClouds = new Image();
forClouds.src = "img/player-ducking-spritesheet_clouds.png";
var forStars = new Image();
forStars.src = "img/player-ducking-spritesheet_stars.png";
return function (ctx, x, y, wheelAngle) {
var sourceX = modulo(Math.trunc(wheelAngle), 60) * w - w / 2;
ctx.drawImage(
starfieldActive ? forStars : forClouds,
// source x, y:
sourceX, hToWheelCenter,
w, h,
// target x, y (position to draw in `ctx'):
x - w / 2, y - hToWheelCenter,
w, h
);
};
}()),
drawPlayerAt = (function () {
var w = 4 * playerElbowXDiff + 4 + 1;
var h = 42;
var hToWheelCenter = playerHeadRadius * 2 + playerTorsoLen + playerRadius + 3;
var forClouds = new Image();
forClouds.src = "img/player-spritesheet_clouds.png";
var forStars = new Image();
forStars.src = "img/player-spritesheet_stars.png";
return function (ctx, x, y, wheelAngle) {
var sourceX = modulo(Math.trunc(wheelAngle), 60) * w;
ctx.drawImage(
starfieldActive ? forStars : forClouds,
// source x, y:
sourceX, 0,
w, h,
// target x, y (position to draw in `ctx'):
x - w / 2, y - hToWheelCenter,
w, h
);
};
}()),
drawFb = (function () {
// Dimensions occupied by each frame in img/fb-frames.png
var w = 30;
var h = 70;
// Distance to center from top edge and left edge of sprite:
var radiusToCenter = w / 2;
var frames = new Image();
frames.src = "img/fb-frames.png";
return function (ctx, fb) {
var i = fb.frame % fbNumRecordedFrames;
ctx.drawImage(
frames, // source image
i * w, // source x
0, // source y
w,
h,
fb.x - radiusToCenter, // target x
fb.y - radiusToCenter, // target y
w,
h
);
};
}()),
drawCoin = (function () {
var s = coinRadius * 2.5; // width and height of png sprites
var gold = new Image();
gold.src = "img/coin_clouds.png";
var green = new Image();
green.src = "img/coin_stars.png";
return function (ctx, coin) {
ctx.drawImage(starfieldActive ? green : gold, coin.x - s / 2, coin.y - s / 2);
};
}()),
drawCoinGroupGottenNotif = (function () {
var notif = document.createElement("canvas");
var pxSize = 18;
notif.width = pxSize * 4;
notif.height = pxSize * 1.5;
// Some constants:
var message = "100%";
var clrOuter = "#DD0B11";
var clrInner = "#ECB435";
var innerX = 8;
var innerY = 20;
var ctx = notif.getContext("2d");
// Set up styling of first text-draw immediately:
ctx.lineWidth = 6;
ctx.strokeStyle = clrOuter;
// Wait for onload to ensure that the correct font has loaded:
window.addEventListener("load", function () {
ctx.font = "italic " + pxSize + "px font0";
ctx.strokeText(message, innerX, innerY);
ctx.lineWidth = 4;
ctx.strokeStyle = clrInner;
ctx.strokeText(message, innerX, innerY);
}, false);
return function (ctx, x, y) {
ctx.drawImage(notif, x, y);
};
}()),
setupGenericPlatfmChars = function (ctx) {
ctx.strokeStyle = starfieldActive ? "white" : "black";
ctx.lineWidth = platfmThickness;
ctx.lineCap = "round";
ctx.lineJoin = "smooth";
},
drawPlatfm = function (ctx, p) { // Must be run after setupGenericPlatfmChars
ctx.beginPath();
if (starfieldActive) {
ctx.globalAlpha = Math.max(0, Math.min(400, p.time_left) / 400);
} else {
ctx.globalAlpha = Math.max(0, p.time_left / 1000);
}
ctx.moveTo(p.x0, p.y0);
ctx.lineTo(p.x1, p.y1);
ctx.stroke();
},
drawPreviewPlatfm = function (ctx, touch) { // Must be run after setupGenericPlatfmChars
ctx.beginPath();
ctx.strokeStyle = starfieldActive ? "white" : "grey";
ctx.moveTo(touch.x0, touch.y0);
ctx.lineTo(touch.x1, touch.y1);
ctx.stroke();
},
updateInGamePointsDisplay = (function () {
// Clear the canvas in the area taken up by the least
// significant digits of the player's points-display
// and draw over that area the new least significant
// digits of the player's points. Redraws as few
// digits as possible--usually only one digit or none.
// Get png images for each digit 0-9:
var i;
var digits = [];
for (i = 0; i < 10; i += 1) {
digits[i] = new Image();
digits[i].src = "img/scores/score-" + i + ".png";
}
Object.freeze(digits);
// `digitWidths[i]' is the width allocated to `i' as a
// score digit when drawn below
var digitWidths = Object.freeze([
19, 13, 17, 17, 17, 18, 17, 16, 17, 17
]);
var drawScoreDigitsAt = function (ctx, scoreStr, startX) {
// Clear the digit space in which we'll draw `scoreStr':
ctx.clearRect(
startX,
inGamePointsYPos,
pauseBtn.edgeX - startX - 5,
inGamePointsPxSize
);
// Draw in the new digits (i.e. `scoreStr'):
var i;
var digitX = startX;
for (i = 0; i < scoreStr.length; i += 1) {
ctx.drawImage(digits[scoreStr[i]], digitX, inGamePointsYPos);
digitX += digitWidths[scoreStr[i]];
}
};
return function (ctx, game) {
var sPrev = "" + Math.floor(game.prevPoints);
var sNow = "" + Math.floor(game.points);
if (sNow === sPrev) {
return;
}
var i;
var x = inGamePointsXPos;
for (i = 0; i < sNow.length; i += 1) {
if (sNow[i] !== sPrev[i]) {
return drawScoreDigitsAt(ctx, sNow.slice(i), x);
}
x += digitWidths[sNow[i]];
}
};
}()),
drawPowerupBubble = function (ctx, x, y) {
ctx.beginPath();
circleAt(ctx, x, y, powerupBubbleRadius);
ctx.fillStyle = "rgba(255, 215, 0, 0.35)";
ctx.fill();
},
drawPowerup = (function () {
var canvases = {
"X2": offScreenRender(powerupX2Width, powerupX2Height, function (ctx, w, h) {
ctx.fillStyle = "gold";
ctx.textAlign = "left";
ctx.font = "bold italic 22px arial";
ctx.lineWidth = 1;
ctx.fillText("X2", 5, h * 0.82, w, h);
ctx.strokeStyle = "orange";
ctx.strokeText("X2", 5, h * 0.82, w, h);
}),
"slow": offScreenRender(powerupSlowRadius * 2 + 5, powerupSlowRadius * 2 + 5, function (ctx, w, h) {
var cx = w / 2, cy = h / 2;
ctx.lineWidth = 2;
drawCircle(ctx, cx, cy, powerupSlowRadius, "black", "stroke");
drawCircle(ctx, cx, cy, powerupSlowRadius, "white", "fill");
// Hour hand
ctx.lineWidth = 1;
ctx.beginPath();
lineFromTo(ctx, cx, cy, cx + powerupSlowRadius * 0.7, cy);
ctx.stroke();
// 12 tick marks
var i, angle, cos, sin;
var tickOuterR = powerupSlowRadius * 0.85;
var tickInnerR = powerupSlowRadius * 0.8;
ctx.beginPath();
for (i = 0; i < 12; i += 1) {
angle = Math.PI * 2 * (i / 12);
cos = trig.cos(angle);
sin = trig.sin(angle);
lineFromTo(
ctx,
cx + cos * tickOuterR,
cy + sin * tickOuterR,
cx + cos * tickInnerR,
cy + sin * tickInnerR
);
}
ctx.stroke();
// Second hand
ctx.beginPath();
lineFromTo(ctx, cx, cy, cx, cy - powerupSlowRadius * 0.95);
ctx.strokeStyle = "red";
ctx.stroke();
}),
"weight": offScreenRender(powerupWeightBlockLowerWidth, powerupWeightHeight, function (ctx, w, fullHeight) {
var cx = w / 2;
var blockHeight = powerupWeightBlockHeight;
var handleHeight = powerupWeightHandleHeight;
// Solid black block:
ctx.beginPath();
ctx.moveTo(powerupWeightBlockUpperXMargin, handleHeight);
ctx.lineTo(w - powerupWeightBlockUpperXMargin, handleHeight);
ctx.lineTo(w, handleHeight + blockHeight - 2);
ctx.lineTo(0, fullHeight - 2);
ctx.fillStyle = "black";
ctx.fill();