-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathindex.js
4130 lines (3819 loc) · 109 KB
/
index.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
/*
* Kontra.js v4.0.1 (Custom Build on 2018-08-21) | MIT
* Build: https://straker.github.io/kontra/download?files=gameLoop+keyboard+sprite+store
*/
kontra={init(t){var n=this.canvas=document.getElementById(t)||t||document.querySelector("canvas");this.context=n.getContext("2d")},_noop:new Function,_tick:new Function};
kontra.gameLoop=function(e){let t,n,a,r,o=(e=e||{}).fps||60,i=0,p=1e3/o,c=1/o,s=!1===e.clearCanvas?kontra._noop:function(){kontra.context.clearRect(0,0,kontra.canvas.width,kontra.canvas.height)};function d(){if(n=requestAnimationFrame(d),a=performance.now(),r=a-t,t=a,!(r>1e3)){for(kontra._tick(),i+=r;i>=p;)m.update(c),i-=p;s(),m.render()}}let m={update:e.update,render:e.render,isStopped:!0,start(){t=performance.now(),this.isStopped=!1,requestAnimationFrame(d)},stop(){this.isStopped=!0,cancelAnimationFrame(n)}};return m};
!function(){let n={},t={},e={13:"enter",27:"esc",32:"space",37:"left",38:"up",39:"right",40:"down"};for(let n=0;n<26;n++)e[65+n]=(10+n).toString(36);for(i=0;i<10;i++)e[48+i]=""+i;addEventListener("keydown",function(i){let c=e[i.which];t[c]=!0,n[c]&&n[c](i)}),addEventListener("keyup",function(n){t[e[n.which]]=!1}),addEventListener("blur",function(n){t={}}),kontra.keys={bind(t,e){[].concat(t).map(function(t){n[t]=e})},unbind(t,e){[].concat(t).map(function(t){n[t]=e})},pressed:n=>!!t[n]}}();
!function(){class t{constructor(t,i){this._x=t||0,this._y=i||0}add(t,i){this.x+=(t.x||0)*(i||1),this.y+=(t.y||0)*(i||1)}clamp(t,i,h,s){this._c=!0,this._a=t,this._b=i,this._d=h,this._e=s}get x(){return this._x}get y(){return this._y}set x(t){this._x=this._c?Math.min(Math.max(this._a,t),this._d):t}set y(t){this._y=this._c?Math.min(Math.max(this._b,t),this._e):t}}kontra.vector=((i,h)=>new t(i,h)),kontra.vector.prototype=t.prototype;class i{init(t,i,h,s){for(i in t=t||{},this.position=kontra.vector(t.x,t.y),this.velocity=kontra.vector(t.dx,t.dy),this.acceleration=kontra.vector(t.ddx,t.ddy),this.width=this.height=0,this.context=kontra.context,t)this[i]=t[i];if(h=t.image)this.image=h,this.width=h.width,this.height=h.height;else if(h=t.animations){for(i in h)this.animations[i]=h[i].clone(),s=s||h[i];this._ca=s,this.width=s.width,this.height=s.height}return this}get x(){return this.position.x}get y(){return this.position.y}get dx(){return this.velocity.x}get dy(){return this.velocity.y}get ddx(){return this.acceleration.x}get ddy(){return this.acceleration.y}set x(t){this.position.x=t}set y(t){this.position.y=t}set dx(t){this.velocity.x=t}set dy(t){this.velocity.y=t}set ddx(t){this.acceleration.x=t}set ddy(t){this.acceleration.y=t}isAlive(){return this.ttl>0}collidesWith(t){return this.x<t.x+t.width&&this.x+this.width>t.x&&this.y<t.y+t.height&&this.y+this.height>t.y}update(t){this.advance(t)}render(){this.draw()}playAnimation(t){this._ca=this.animations[t],this._ca.loop||this._ca.reset()}advance(t){this.velocity.add(this.acceleration,t),this.position.add(this.velocity,t),this.ttl--,this._ca&&this._ca.update(t)}draw(){this.image?this.context.drawImage(this.image,this.x,this.y):this._ca?this._ca.render(this):(this.context.fillStyle=this.color,this.context.fillRect(this.x,this.y,this.width,this.height))}}kontra.sprite=(t=>(new i).init(t)),kontra.sprite.prototype=i.prototype}();
kontra.store={set(t,e){void 0===e?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(e))},get(t){let e=localStorage.getItem(t);try{e=JSON.parse(e)}catch(t){}return e}};
let mergedPeaks;
let splitPeaks;
/**
* Wave code taken from wavesurfer.js
* @see https://github.com/katspaugh/wavesurfer.js
*/
function exportPCM(length, accuracy, noWindow, start) {
length = length || 1024;
start = start || 0;
accuracy = accuracy || 10000;
const peaks = getPeaks(length, start);
// find largest peak and treat it as peaks of 1 and normalize rest of peaks
let maxPeak = 0;
let arr = [].map.call(peaks, peak => {
if (peak > maxPeak) {
maxPeak = peak;
}
return peak;
});
let normalizePeak = 1 - maxPeak;
arr = arr.map(peak => Math.round((peak + normalizePeak) * accuracy) / accuracy);
return arr;
}
function setLength(length) {
splitPeaks = [];
mergedPeaks = [];
// Set the last element of the sparse array so the peak arrays are
// appropriately sized for other calculations.
const channels = buffer ? buffer.numberOfChannels : 1;
let c;
for (c = 0; c < channels; c++) {
splitPeaks[c] = [];
splitPeaks[c][2 * (length - 1)] = 0;
splitPeaks[c][2 * (length - 1) + 1] = 0;
}
mergedPeaks[2 * (length - 1)] = 0;
mergedPeaks[2 * (length - 1) + 1] = 0;
}
function getPeaks(length, first, last) {
first = first || 0;
last = last || length - 1;
setLength(length);
/**
* The following snippet fixes a buffering data issue on the Safari
* browser which returned undefined It creates the missing buffer based
* on 1 channel, 4096 samples and the sampleRate from the current
* webaudio context 4096 samples seemed to be the best fit for rendering
* will review this code once a stable version of Safari TP is out
*/
// if (!buffer.length) {
// const newBuffer = this.createBuffer(1, 4096, this.sampleRate);
// buffer = newBuffer.buffer;
// }
const sampleSize = buffer.length / length;
const sampleStep = ~~(sampleSize / 10) || 1;
const channels = buffer.numberOfChannels;
let c;
for (c = 0; c < channels; c++) {
const peaks = splitPeaks[c];
const chan = buffer.getChannelData(c);
let i;
for (i = first; i <= last; i++) {
const start = ~~(i * sampleSize);
const end = ~~(start + sampleSize);
let min = 0;
let max = 0;
let j;
for (j = start; j < end; j += sampleStep) {
const value = chan[j];
if (value > max) {
max = value;
}
if (value < min) {
min = value;
}
}
peaks[2 * i] = max;
peaks[2 * i + 1] = min;
if (c == 0 || max > mergedPeaks[2 * i]) {
mergedPeaks[2 * i] = max;
}
if (c == 0 || min < mergedPeaks[2 * i + 1]) {
mergedPeaks[2 * i + 1] = min;
}
}
}
return mergedPeaks;
}
kontra.init();
//------------------------------------------------------------
// Global variables
//------------------------------------------------------------
const ctx = kontra.context;
const mid = kontra.canvas.height / 2; // midpoint of the canvas
const waveWidth = 2;
const waveHeight = 215;
const maxLength = kontra.canvas.width / waveWidth + 2 | 0; // maximum number of peaks to show on screen
const defaultOptions = {
volume: 1,
uiScale: 1,
gameSpeed: 1
};
let audio; // audio file for playing/pausing
let peaks; // peak data of the audio file
let waveData; // array of wave audio objects based on peak data
let startBuffer; // duplicated wave data added to the front of waveData to let the game start in the middle of the screen
let loop; // game loop
let songName = 'AudioDashDefault.mp3'; // name of the song
let bestTimes; // object of best times for all songs
let bestTime; // best time for a single song
let activeScenes = []; // currently active scenes
let focusedBtn; // currently focused button
let options = Object.assign( // options for the game
{},
defaultOptions,
JSON.parse(localStorage.getItem('js13k-2018:options'))
);
let fontMeasurement; // size of text letter
let gamepad; // gamepad state
let lastUsedInput; // keep track of last used input device
let objectUrl; // in-memory url of audio files
let fadeTime = 450; // how long a scene takes to fade
//------------------------------------------------------------
// Helper functions
//------------------------------------------------------------
/**
* Clamp a value between min and max values.
* @param {number} value - Value to clamp.
* @param {number} min - Min value.
* @param {number} max - Max value.
*/
function clamp(value, min, max) {
return Math.min( Math.max(min, value), max);
}
function getRandom(min, max) {
return Math.random() * (max - min) + min;
}
function collidesWithShip(y, height) {
return ship.y < y + height && ship.y + ship.height > y;
}
//------------------------------------------------------------
// Main functions
//------------------------------------------------------------
/**
* Start the game.
*/
function start() {
startMove = -kontra.canvas.width / 2 | 0;
startCount = 0;
audio.currentTime = 0;
audio.volume = options.volume;
audio.playbackRate = options.gameSpeed;
ship.points = [];
ship.y = mid;
showTutorialBars = true;
isTutorial = true;
tutorialScene.show();
}
/**
* Show game over scene.
*/
function gameOver() {
audio.pause();
setBestTime();
gameOverScene.show(() => restartBtn.focus());
}
/**
* Show win scene.
*/
function win() {
audio.pause();
setBestTime();
winScene.show(() => winMenuBtn.focus());
}
//------------------------------------------------------------
// Button
//------------------------------------------------------------
let uiSpacer = 5;
/**
* Set the dimensions of the UI element.
* @param {object} uiEl - UI element
*/
function setDimensions(uiEl) {
let text = typeof uiEl.text === 'function' ? uiEl.text() : uiEl.text;
uiEl.width = text.length * fontMeasurement + fontMeasurement * 2;
uiEl.height = fontMeasurement * 3;
if (uiEl.center || uiEl.type === 'button') {
uiEl.x = uiEl.orgX - uiEl.width / 2;
}
// set the y position based on the position of another element
if (uiEl.prev) {
uiEl.y = uiEl.prev.y + uiEl.prev.height * 1.5 + uiSpacer / options.uiScale;
}
else {
uiEl.y = uiEl.orgY - uiEl.height / 2;
}
uiEl.y += uiEl.margin || 0;
}
/**
* Button UI element.
* @param {object} props - Properties of the button
*/
function Button(props) {
props.orgX = props.x;
props.orgY = props.y;
props.type = 'button';
setDimensions(props);
props.render = function() {
setDimensions(this);
ctx.save();
setFont(25);
ctx.fillStyle = '#222';
if (button.disabled) {
ctx.globalAlpha = clamp(this.parent.alpha - 0.65, 0, 1);
}
let args = [this.x, this.y, this.width, this.height];
ctx.fillRect.apply(ctx, args);
if (this.focused) {
args.push(255, 0, 0);
}
else if (this.disabled) {
args.push(100, 100, 100);
}
else {
args.push(0, 163, 220);
}
neonRect.apply(null, args);
ctx.fillStyle = '#fff';
ctx.fillText(this.text, this.x + fontMeasurement, this.y + fontMeasurement * 2);
ctx.restore();
};
props.focus = function() {
if (focusedBtn && focusedBtn.blur) focusedBtn.blur();
focusedBtn = this;
this.focused = true;
this.domEl.focus();
};
props.blur = function() {
this.focused = false;
focusedBtn = null;
};
let button = kontra.sprite(props);
// create accessible html button for screen readers
let el = document.createElement('button');
el.textContent = button.label || button.text;
el.addEventListener('focus', button.focus.bind(button));
button.domEl = el;
Object.defineProperty(button, 'disabled', {
get() { return this.domEl.disabled },
set(value) { this.domEl.disabled = value }
});
return button;
}
//------------------------------------------------------------
// Text
//------------------------------------------------------------
function Text(props) {
props.orgX = props.x;
props.orgY = props.y;
setDimensions(props);
props.render = function() {
setDimensions(this);
let text = typeof this.text === 'function' ? this.text() : this.text;
if (this.lastText !== text) {
this.lastText = text;
this.domEl.textContent = text;
}
ctx.save();
ctx.fillStyle = '#fff';
setFont(25);
ctx.fillText(text, this.x + fontMeasurement, this.y + fontMeasurement * 2);
ctx.restore();
};
let text = kontra.sprite(props);
// create accessible html text for screen readers
let el = document.createElement('div');
// announce changes to screen reader
if (typeof props.text === 'function') {
el.setAttribute('role', 'alert');
el.setAttribute('aria-live', 'assertive');
el.setAttribute('aria-atomic', true);
}
text.domEl = el;
return text;
}
//------------------------------------------------------------
// Audio functions
//------------------------------------------------------------
let context = new (window.AudioContext || window.webkitAudioContext)();
uploadFile.addEventListener('change', uploadAudio);
/**
* Load audio file as an ArrayBuffer.
* @param {string} url - URL of the audio file
* @returns {Promise} resolves with decoded audio data
*/
function loadAudioBuffer(url) {
// we can't use fetch because response.arrayBuffer() isn't supported
// in lots of browsers
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.responseType = 'arraybuffer';
request.onload = function() {
context.decodeAudioData(request.response, decodedData => {
resolve(decodedData)
});
};
request.open('GET', url, true);
request.send();
});
}
/**
* Load audio file as an Audio element.
* @param {string} url - URL of the audio file
* @returns {Promise} resolves with audio element
*/
function loadAudio(url) {
return new Promise((resolve, reject) => {
let audioEl = document.createElement('audio');
audioEl.addEventListener('canplay', function() {
resolve(this);
});
audioEl.onerror = function(e) {
console.error('e:', e);
reject(e);
};
audioEl.src = url;
audioEl.load();
})
}
/**
* Upload an audio file from the users computer.
* @param {Event} e - File change event
*/
async function uploadAudio(e) {
menuScene.hide();
loadingScene.show();
// clear any previous uploaded song
URL.revokeObjectURL(objectUrl);
let file = e.currentTarget.files[0];
objectUrl = URL.createObjectURL(file);
songName = uploadFile.value.replace(/^.*fakepath/, '').substr(1);
await fetchAudio(objectUrl);
getBestTime();
loadingScene.hide();
startBtn.onDown();
}
/**
* Generate the wave data for an audio file.
* @param {string} url - URL of the audio file
*/
async function fetchAudio(url) {
buffer = await loadAudioBuffer(url);
audio = await loadAudio(url);
generateWaveData();
return Promise.resolve();
}
function generateWaveData() {
// numPeaks determines the speed of the game, the less peaks per duration, the
// slower the game plays
let numPeaks = audio.duration / 8 | 0;
peaks = exportPCM(1024 * numPeaks); // change this by increments of 1024 to get more peaks
startBuffer = new Array(maxLength / 2 | 0).fill(0);
// remove all negative peaks
let waves = peaks
.map((peak, index) => peak >= 0 ? peak : peaks[index-1]);
let pos = mid; // position of next turn
let lastPos = 0; // position of the last turn
let gapDistance = maxLength; // how long to get to the next turn
let step = 0; // increment of each peak to pos
let offset = 0; // offset the wave data position to create curves
let minBarDistance = 270; // min distance between top and bottom wave bars
let heightDt = minBarDistance - waveHeight + 10; // distance between max height and wave height
let heightStep = heightDt / (startBuffer.length + waves.length); // game should reach the max bar height by end of the song
let counter = 0;
let peakVisited = false;
let obstacle;
let prevObstacle;
let yPos = 0;
let yLastPos = 0;
let yGapDistance = maxLength;
let yStep = 0;
let yOffset = 0;
let yCounter = 0;
let isIntroSong = songName === 'AudioDashDefault.mp3';
Random.setValues(peaks);
waveData = startBuffer
.concat(waves)
.map((peak, index, waves) => {
// if (index === 13146) {
// debugger;
// }
let maxPos = (190 - heightStep * index) / 2;
// for the intro song give the player some time to get use to the controls
// before adding curves (numbers are tailored to points in the song)
let firstCurveIndex = maxLength * (isIntroSong ? 4 : 1);
if (index >= firstCurveIndex) {
offset += step;
// the steeper the slope the less drastic position changes we should have
yOffset += Math.abs(step) > 1
? yStep / (Math.abs(step) * 1.25)
: yStep;
if (yPos < 0 && yOffset < yPos ||
yPos > 0 && yOffset > yPos) {
yOffset = yPos;
}
// all calculations are based on the peaks data so that the path is the
// same every time
let peakIndex = index - startBuffer.length;
Random.seed(peakIndex);
if (++counter >= gapDistance) {
counter = 0;
lastPos = pos;
pos = mid + Random.getNext(200);
gapDistance = 300 + Random.getNext(100);
step = (pos - lastPos) / gapDistance;
}
if (++yCounter >= yGapDistance) {
yCounter = 0;
lastYPos = yPos;
yGapDistance = 110 + Random.getNext(23);
yPos = Random.getNext(maxPos);
yStep = (yPos - lastYPos) / yGapDistance;
}
}
// a song is more or less "intense" based on how much it switches between
// high and low peaks. a song like "Through the Fire and the Flames" has
// a high rate of switching so is more intense. need to look a few peaks
// before to ensure we find the low peaks
let peakThreshold = 0.38; // increase or decrease to get less or more obstacles
let lowPeak = 1;
for (let i = index - 5; i < index; i++) {
if (waves[i] < lowPeak) {
lowPeak = waves[i];
}
}
let maxPeak = 0;
for (let i = index - 20; i < index+20; i++) {
if (waves[i] > maxPeak) {
maxPeak = waves[i];
}
}
// for the intro song give the player some time to get use to the controls
// before adding obstacles (numbers are tailored to points in the song)
let firstObstacleIndex = maxLength * (isIntroSong ? 15 : 3);
// don't create obstacles when the slope of the offset is too large
let addObstacle = index > firstObstacleIndex && peak - lowPeak >= peakThreshold && Math.abs(step) < 1.35;
let height = addObstacle
? kontra.canvas.height / 2 - Math.max(65, 35 * (1 / peak))
: 160 + peak * waveHeight + heightStep * index;
// a song that goes from a low peak to a really high peak while the current
// yOffset is close to the top or bottom needs to drop the yOffset a bit so
// there's enough of a gap between the peaks
// if (Math.abs(yOffset) > (minBarDistance - heightStep * index) / 2 &&
// maxPeak - lowPeak > peakThreshold) {
// yOffset += -getSign(yOffset) * 65;
// console.log('hit here');
// }
// a song that goes from a low peak to a really high peak while in an obstacle
// would create a spike in the obstacle that is too narrow to pass so we need
// to match the height to the others
// if (addObstacle && maxPeak - peak > peakThreshold) {
// height = kontra.canvas.height / 2 - Math.max(65, 35 * (1 / maxPeak));
// }
return {
x: index * waveWidth,
y: 0,
width: waveWidth,
height: height,
offset: offset,
yOffset: addObstacle && index > firstObstacleIndex ? yOffset : 0,
yPos: yPos
};
});
}
//------------------------------------------------------------
// Drawing functions
//------------------------------------------------------------
/**
* Draw a neon rectangle in the given color.
* @see https://codepen.io/agar3s/pen/pJpoya?editors=0010#0
* Don't use shadow blur as it is terrible for performance
* @see https://stackoverflow.com/questions/15706856/how-to-improve-performance-when-context-shadow-canvas-html5-javascript
*
* @param {number} x - X position of the rectangle
* @param {number} y - Y position of the rectangle
* @param {number} w - Width of the rectangle
* @param {number} h - Height of the rectangle
* @param {number} r - Red value
* @param {number} g - Green value
* @param {number} b - Blue value
*/
function neonRect(x, y, w, h, r, g, b) {
ctx.save();
ctx.strokeStyle = "rgba(" + r + "," + g + "," + b + ",0.2)";
ctx.lineWidth = 10.5;
ctx.strokeRect(x, y, w, h);
ctx.lineWidth = 8;
ctx.strokeRect(x, y, w, h);
ctx.lineWidth = 5.5;
ctx.strokeRect(x, y, w, h);
ctx.lineWidth = 3;
ctx.strokeRect(x, y, w, h);
ctx.strokeStyle = "#fff";
ctx.lineWidth = 1.5;
ctx.strokeRect(x, y, w, h);
ctx.restore();
}
/**
* Line to each point.
* @param {object[]} points - Object of x, y positions
* @param {number} move - distance to move each point by
*/
function drawLines(points, move) {
ctx.beginPath();
ctx.moveTo(points[0].x - move, points[0].y);
points.forEach(point => {
ctx.lineTo(point.x - move, point.y);
});
ctx.stroke();
}
/**
* Draw a neon line between points in the given color.
* @param {object[]} points - Object of x, y positions
* @param {number} move - Distance to move each point by
* @param {number} r - Red value
* @param {number} g - Green value
* @param {number} b - Blue value
*/
function neonLine(points, move, r, g, b) {
if (!points.length) return;
ctx.save();
ctx.strokeStyle = "rgba(" + r + "," + g + "," + b + ",0.2)";
ctx.lineWidth = 10.5;
drawLines(points, move);
ctx.lineWidth = 8;
drawLines(points, move);
ctx.lineWidth = 5.5;
drawLines(points, move);
ctx.lineWidth = 3;
drawLines(points, move);
ctx.strokeStyle = "#fff";
ctx.lineWidth = 1.5;
drawLines(points, move);
ctx.restore();
}
/**
* Draw neon text in the given color
* @param {string} text - Text to render
* @param {number} x - X position of the text
* @param {number} y - Y position of the text
* @param {number} r - Red value
* @param {number} g - Green value
* @param {number} b - Blue value
*/
function neonText(text, x, y, r, g, b, alhpa) {
ctx.save();
ctx.globalAlpha = 0.2;
ctx.strokeStyle = "rgb(" + r + "," + g + "," + b + ")";
ctx.lineWidth = 10.5;
ctx.strokeText(text, x, y);
ctx.lineWidth = 8;
ctx.strokeText(text, x, y);
ctx.lineWidth = 5.5;
ctx.strokeText(text, x, y);
ctx.lineWidth = 3;
ctx.strokeText(text, x, y);
ctx.globalAlpha = 1;
ctx.strokeStyle = "#fff";
ctx.lineWidth = 1.5;
ctx.strokeText(text, x, y);
ctx.restore();
};
/**
* Draw the top and bottom time bars
*/
function drawTimeUi() {
ctx.save();
ctx.fillStyle = '#222';
// top bar
ctx.beginPath();
ctx.moveTo(0, 43 * options.uiScale);
ctx.lineTo(80 * options.uiScale, 43 * options.uiScale);
for (let i = 1; i <= 10 * options.uiScale | 0; i++) {
ctx.lineTo(80 * options.uiScale +i*2, 43 * options.uiScale -i*2);
ctx.lineTo(80 * options.uiScale +i*2+2, 43 * options.uiScale -i*2);
}
ctx.lineTo(170 * options.uiScale, 23 * options.uiScale);
for (let i = 1; i <= 10 * options.uiScale | 0; i++) {
ctx.lineTo(170 * options.uiScale +i*2, 23 * options.uiScale -i*2);
ctx.lineTo(170 * options.uiScale +i*2+2, 23 * options.uiScale -i*2);
}
ctx.lineTo(192 * options.uiScale, 0);
ctx.lineTo(0, 0);
ctx.closePath();
ctx.fill();
// bottom bar
ctx.beginPath();
let y = kontra.canvas.height - 25 * options.uiScale;
ctx.moveTo(0, y);
ctx.lineTo(125 * options.uiScale, y);
for (let i = 1; i <= 10 * options.uiScale | 0; i++) {
ctx.lineTo(125 * options.uiScale +i*2, y+i*2);
ctx.lineTo(125 * options.uiScale +i*2+2, y+i*2);
}
ctx.lineTo(147 * options.uiScale, kontra.canvas.height);
ctx.lineTo(0, kontra.canvas.height);
ctx.closePath();
ctx.fill();
ctx.fillStyle = '#fdfdfd';
let time = getTime(audio.currentTime);
setFont(40);
ctx.fillText(getSeconds(time).padStart(3, ' '), 5 * options.uiScale, 35 * options.uiScale);
setFont(18);
ctx.fillText(':' + getMilliseconds(time).padStart(2, '0') + '\nTIME', 80 * options.uiScale, 17 * options.uiScale);
ctx.fillText(bestTime.padStart(6, ' ') + '\nBEST', 5 * options.uiScale, kontra.canvas.height - 5 * options.uiScale);
ctx.restore();
}
/**
* Draw the XBOX A button.
* @param {number} x - X position
* @param {number} y - Y position
*/
function drawAButton(x, y) {
ctx.save();
ctx.fillStyle = 'green';
ctx.beginPath();
ctx.arc(x, y, fontMeasurement, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = 'black';
setFont(27);
ctx.fillText('A', x - fontMeasurement / 2, y + fontMeasurement / 2);
ctx.fillStyle = 'white';
setFont(25);
ctx.fillText('A', x - fontMeasurement / 2, y + fontMeasurement / 2);
ctx.restore();
}
/**
* Show help text in bottom left corner of screen base don input.
*/
function showHelpText() {
ctx.save();
if (lastUsedInput === 'keyboard') {
setFont(18);
ctx.fillStyle = 'white';
ctx.fillText('[Spacebar] Select', 50 - fontMeasurement, kontra.canvas.height - 50 + fontMeasurement / 2.5);
}
else if (lastUsedInput === 'gamepad') {
drawAButton(50, kontra.canvas.height - 50);
setFont(18);
ctx.fillStyle = 'white';
ctx.fillText('Select', 50 + fontMeasurement * 1.75, kontra.canvas.height - 50 + fontMeasurement / 2.5);
}
ctx.restore();
}
/**
* Set font size.
* @param {number} size - Size of font
*/
function setFont(size) {
ctx.font = size * options.uiScale + "px 'Lucida Console', Monaco, monospace";
}
/**
* Set font measurement
*/
function setFontMeasurement() {
fontMeasurement = 15 * options.uiScale;
}
//------------------------------------------------------------
// Input Handlers
//------------------------------------------------------------
let touchPressed;
let lastInputTime = 0;
window.addEventListener('mousedown', handleOnDown);
window.addEventListener('touchstart', handleOnDown);
window.addEventListener('mouseup', handleOnUp);
window.addEventListener('touchend', handleOnUp);
window.addEventListener('blur', handleOnUp);
window.addEventListener('beforeunload', () => {
URL.revokeObjectURL(objectUrl);
});
// remove contextmenu as holding tap on mobile opens it
window.addEventListener('contextmenu', e => {
e.preventDefault();
e.stopPropagation();
return false;
});
/**
* Detect if a button was clicked.
*/
function handleOnDown(e) {
touchPressed = true;
uploadBtn.disabled = false;
let pageX, pageY;
if (e.type.indexOf('mouse') !== -1) {
// there's a bug in chrome where it fires a mousedown event right after
// tapping, so we need to ignore them to get the correct last input
if (lastUsedInput === 'touch' && performance.now() - lastInputTime < 1000) return;
lastUsedInput = 'mouse';
pageX = e.pageX;
pageY = e.pageY;
}
else {
lastUsedInput = 'touch';
// touchstart uses touches while touchend uses changedTouches
// @see https://stackoverflow.com/questions/17957593/how-to-capture-touchend-coordinates
pageX = (e.touches[0] || e.changedTouches[0]).pageX;
pageY = (e.touches[0] || e.changedTouches[0]).pageY;
}
let x = pageX - kontra.canvas.offsetLeft;
let y = pageY - kontra.canvas.offsetTop;
let el = kontra.canvas;
while ( (el = el.offsetParent) ) {
x -= el.offsetLeft;
y -= el.offsetTop;
}
// take into account the canvas scale
let scale = kontra.canvas.offsetHeight / kontra.canvas.height;
x /= scale;
y /= scale;
// last added scene is on top
for (let i = activeScenes.length - 1, activeScene; activeScene = activeScenes[i]; i--) {
if (activeScene.children) {
activeScene.children.forEach(child => {
if (!child.disabled && child.parent.active && child.onDown && child.collidesWith({
// center the click
x: x - 5,
y: y - 5,
width: 10,
height: 10
})) {
child.onDown();
child.blur();
return;
}
});
}
}
lastInputTime = performance.now();
}
/**
* Release button press.
*/
function handleOnUp() {
touchPressed = false;
}
/**
* Move the focused button up or down.
* @param {number} inc - Direction to move the focus button (1 = down, -1 = up).
*/
function handleArrowDownUp(inc) {
let activeScene = activeScenes[activeScenes.length - 1];
let index = activeScene.children.indexOf(focusedBtn);
while (true) {
index += inc;
// if we get to the beginning or end we're already focused on the first/last
// element
if (index < 0 || index > activeScene.children.length - 1) {
return;
}
let child = activeScene.children[index];
if (child && child.focus && !child.disabled) {
child.focus();
break;
}
}
}
// select button
kontra.keys.bind('space', () => {
lastUsedInput = 'keyboard';
uploadBtn.disabled = false;
if (focusedBtn && focusedBtn.onDown) {
focusedBtn.onDown();
}
});
// move focus button with arrow keys
kontra.keys.bind('up', (e) => {
lastUsedInput = 'keyboard';
uploadBtn.disabled = false;
e.preventDefault();
handleArrowDownUp(-1);
});
kontra.keys.bind('down', (e) => {
lastUsedInput = 'keyboard';
uploadBtn.disabled = false;
e.preventDefault();
handleArrowDownUp(1);
});
/**
* Don't active controller sticks unless it passes a threshold.
* @see https://www.smashingmagazine.com/2015/11/gamepad-api-in-web-games/
* @param {number} number - Thumbstick axes
* @param {number} threshold
*/
function applyDeadzone(number, threshold){
percentage = (Math.abs(number) - threshold) / (1 - threshold);
if(percentage < 0) {
percentage = 0;
}
return percentage * (number > 0 ? 1 : -1);
}
/**
* Track gamepad use every frame.
*/
let aDt = 1;
let aDuration = 0;
let axesDt = 1;
let axesDuration = 0;
function updateGamepad() {
if (!navigator.getGamepads) return;
gamepad = navigator.getGamepads()[0];
if (!gamepad) return;
// A button press
if (gamepad.buttons[0].pressed) {
lastUsedInput = 'gamepad';
aDuration += 1/60;
aDt += 1/60;
// it seems the browser won't open the file dialog window when using a
// controller as the input, even when programmatically calling the click
// event on the file input
uploadBtn.disabled = true;
}
else {
aDuration = 0;
aDt = 1;
}
// run the first time immediately then hold for a bit before letting the user
// continue to press the button down
if ((aDt > 0.30 || (aDuration > 0.3 && aDt > 0.10)) &&
gamepad.buttons[0].pressed && focusedBtn && focusedBtn.onDown) {
aDt = 0;
focusedBtn.onDown()
}