-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
637 lines (513 loc) · 20.3 KB
/
app.js
File metadata and controls
637 lines (513 loc) · 20.3 KB
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
((d) => {
/* debugging */
const DEBUG = false;
/* difficulty */
const speed = 250; // pixels per second
const minObstacleDistance = 200; // pixels
const maxObstacleDistance = 500; // pixels
/* physics */
const gravity = 800; // pixels per second squared
const initialVelocity = 800; // pixels per second
/* music */
const playMusic = new URLSearchParams(window.location.search).get("annoy") === "true"; // play music - annoying!
const tune = [ // one array per line, each line loops independently
[ // top line
"C5", "_", "_", "G4", "_", "_", "E4", "_", "_",
"A4", "_", "B4", "_", "Bb4", "A4", "_",
"G4", "E5", "G5", "A5", "_",
"F5", "G5", "_", "E5", "_", "C5", "D5", "B4", "_", "_",
],
[ // middle line
"E4", "_", "_", "C4", "_", "_", "G3", "_", "_",
"C4", "_", "D4", "_", "Db4", "C4", "_",
"C4", "G4", "B4", "C5", "_",
"A4", "B4", "_", "A4", "_", "E4", "F4", "D4", "_", "_",
],
[ // bass line
"G3", "_", "_", "E3", "_", "_", "C3", "_", "_",
"F3", "_", "G3", "_", "Gb3", "F3", "_",
"E3", "C4", "E4", "F4", "_",
"D4", "E4", "_", "C4", "_", "A3", "B3", "G3", "_", "_",
],
]; // notes from C0 - B8, C4 is middle C, C#4 - the semi-tone above middle C
const bpm = 240; // notes per minute
/* layout */
const height = 400; // pixels
const width = 800; // pixels
const playerSize = 30; // pixels
const playerXOffset = 50; // pixels
const playerYOffset = 330; // pixels
const landscapeWidth = 400; // pixels
const cloudsWidth = 250; // pixels
const obstacleHeight = 100; // pixels
const obstacleWidth = 100; // pixels
const obstacleYOffset = 280; // pixels
const obstacleXOffset = 400; // pixels
const landscapeSpeed = 50; // pixels per second
const cloudsSpeed = 30; // pixels per second
/* svg */
// which svg elements to include as bounding boxes
// don't want to include title, g, etc.
const shapes = ["rect", "circle", "ellipse", "line", "polyline", "polygon", "path"];
/* useful functions */
// collision detection of two boxes
const collision = (a, b) => a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top;
// generate a range of numbers
const range = (start, stop) => Array(stop - start + 1).fill().map((_, i) => start + i);
// generate a random number between two numbers (inclusive)
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
// get the last item in an array
const last = arr => arr[arr.length - 1];
// generate a bounded random next position for an obstacle
const nextPos = prev => prev + rand(minObstacleDistance + obstacleWidth, maxObstacleDistance + obstacleWidth);
// make sure player doesn't sink
const ground = n => n < playerYOffset ? n : playerYOffset;
// clone an HTML element
const clone = (el, positions) => {
el.remove();
el.removeAttribute("id");
return positions.map(() => el.cloneNode(true));
};
// redux-esque store
const createStore = (reducer, initial) => {
let subscribers = [];
let state = initial;
const getState = () => state;
const subscribe = fn => {
subscribers = [...subscribers, fn];
};
const dispatch = action => {
state = reducer(state, action);
subscribers.forEach(fn => fn(state));
};
return { getState, subscribe, dispatch };
};
/* select elements */
const fragment = d.createDocumentFragment(); // doing to be appending a lot of stuff
// setup the scene
const sceneEl = d.getElementById("scene");
sceneEl.style.height = `${height}px`;
sceneEl.style.width = `${width}px`;
if (DEBUG) {
sceneEl.style.overflow = "visible";
}
// create landscape tiles
const landscapePositions = range(0, Math.ceil(width / landscapeWidth) + 1).map(i => i * landscapeWidth);
const landscapes = clone(d.getElementById("landscape"), landscapePositions);
landscapes.forEach(el => {
fragment.append(el);
el.style.width = `${landscapeWidth}px`;
});
// create cloud tiles
const cloudsPositions = range(0, Math.ceil(width / cloudsWidth) + 1).map(i => i * cloudsWidth);
const clouds = clone(d.getElementById("clouds"), cloudsPositions);
clouds.forEach(el => {
fragment.append(el);
el.style.width = `${cloudsWidth}px`;
});
// find first svg element in obstacle div
const obstacleDiv = d.getElementById("obstacle");
const obstacleEl = obstacleDiv.querySelector("svg") || d.createElement("svg");
obstacleEl.classList.add("obstacle");
// get the boxes of all relevant svg elements
const boxes = Array.from(obstacleEl.querySelectorAll(shapes.join(","))).map(el => el.getBBox());
// generates the correct number of obstacle positions
const obRange = range(1, Math.ceil(width / minObstacleDistance)); // number of obstacles
// tracks the left of the obstacle and all the bounding boxes for collision detection
const nextLeft = lefts => lefts.concat(nextPos(last(lefts))); // add a new left value
const generateObstaclePositions = () => obRange.reduce(nextLeft, [obstacleXOffset]).map(left => ({
left,
right: left + obstacleWidth,
top: obstacleYOffset,
bottom: obstacleYOffset + obstacleHeight,
boxes: boxes.map(({ x, y, height, width }) => ({
top: obstacleYOffset + y,
left: left + x,
bottom: obstacleYOffset + y + height,
right: left + x + width,
})),
}));
const obstaclePositions = generateObstaclePositions();
const obstacles = clone(obstacleEl, obstaclePositions);
// add obstacles to the scene
obstacles.forEach(el => {
fragment.append(el);
Object.assign(el.style, {
height: `${obstacleHeight}px`,
width: `${obstacleWidth}px`,
top: `${obstacleYOffset}px`,
});
});
obstacleDiv.remove(); // remove the div to keep things tidy
// obstacle bounding boxes
const obstacleBBs = obstaclePositions.map(ob => ob.boxes.map(() => {
// only add if debugging
if (DEBUG) {
const el = d.createElement("div");
el.classList.add("bounding-box");
fragment.append(el);
return el;
}
return null;
}));
// the player element
const playerEl = d.getElementById("player");
playerEl.style.height = `${playerSize}px`;
playerEl.style.width = `${playerSize}px`;
// player bounding box
const playerElBB = d.createElement("div");
// only add if debugging
if (DEBUG) {
playerElBB.classList.add("bounding-box");
fragment.append(playerElBB);
}
// select elements for later
const scoreEl = d.getElementById("score");
const gameOverEl = d.getElementById("game-over");
const introEl = d.getElementById("intro");
// append all new elements in one go
sceneEl.append(fragment);
/* initial state */
const initial = {
started: false, // has the game started
score: 0, // current score
player: { // player bounding box
top: playerYOffset,
left: playerXOffset,
bottom: playerYOffset + playerSize,
right: playerXOffset + playerSize,
velocityY: 0,
},
landscapes: landscapePositions, // landscape positions
clouds: cloudsPositions, // cloud positions
obstacles: obstaclePositions, // obstacle positions
};
/* reducer functions */
const startJump = state => {
// if not currently jumping, then start jumping
if (state.started && state.player.top === playerYOffset) {
state.player.velocityY = initialVelocity;
}
return state;
};
const cancelJump = state => {
const newVelocity = initialVelocity / 2;
// if jump is cancelled, reduce the velocity
if (state.started && !(state.player.top === playerYOffset) && state.player.velocityY > newVelocity) {
state.player.velocityY = newVelocity;
}
return state;
};
/*
* All of the "tick" related code runs 60 times a second
* As such it needs to run as quickly as possible
* It should also avoid creating new objects, arrays, functions as these will need
* to be garbage-collected at some point
* As such, rather than using nice array-iterator methods, we'll be using
* a for loop for any looping behaviour. This makes the code less nice to look at
* but should be a bit better for performance
*/
const jumpTick = (multiplier, state) => {
// work out current player position
// make sure it stops when they hit the ground
const top = ground(state.player.top - (state.player.velocityY * multiplier));
state.player.top = top;
state.player.bottom = top + playerSize;
// adjust the vertical velocity
// for realistic jump physics
state.player.velocityY -= gravity * multiplier;
return state;
};
const landscapeTick = (multiplier, state) => {
// move each landscape element leftwards
for (let i = 0; i < state.landscapes.length; i += 1) { // for loop to avoid gc
const pos = state.landscapes[i] - (landscapeSpeed * multiplier);
// wrap around if off-left
state.landscapes[i] = pos < -landscapeWidth ? pos + (state.landscapes.length * landscapeWidth) : pos;
}
return state;
};
const cloudsTick = (multiplier, state) => {
// move each cloud leftwards
for (let i = 0; i < state.clouds.length; i += 1) { // for loop to avoid gc
const pos = state.clouds[i] - (cloudsSpeed * multiplier);
// wrap around if off-left
state.clouds[i] = pos < -cloudsWidth ? pos + (state.clouds.length * cloudsWidth) : pos;
}
return state;
};
const obstaclesTick = (multiplier, state) => {
// move each obstacle
for (let i = 0; i < state.obstacles.length; i += 1) { // for loop to avoid gc
// get obstacle
const o = state.obstacles[i];
// change in left
const dl = speed * multiplier;
// get value of previous item
// for wrap around
const prev = state.obstacles[(i === 0 ? state.obstacles.length : i) - 1].left;
// if it's gone off screen, move to the far right
// nextPos will generate appropriate bounded random value
const offset = (o.left - dl) < -obstacleWidth ? nextPos(prev) - o.left : -dl;
// update obstacle
o.left += offset;
o.right += offset;
// update bounding boxes
for (let j = 0; j < o.boxes.length; j += 1) { // for loop to avoid gc
o.boxes[j].left += offset;
o.boxes[j].right += offset;
}
}
return state;
};
const collisionsTick = state => {
// check if there are any collisions
// if any obstacles' boxes collide with the player, then game over
// would be nice to use state.obstacles.some(ob => ob.boxes.some(box => collision(state.player, box)))
// but that would create a lot of anonymous functions for gc to deal with
for (let i = 0; i < state.obstacles.length; i += 1) {
// check if there's overlap with entire obstacle box
// if not, no point checking the boxes
if (collision(state.player, state.obstacles[i])) {
// if does collide with obstacle box then check if it actually collides
// with any of the boxes
for (let j = 0; j < state.obstacles[i].boxes.length; j += 1) {
if (collision(state.player, state.obstacles[i].boxes[j])) {
state.started = false;
}
}
}
}
return state;
};
const scoreTick = (dt, state) => {
// update score - fairly arbitrary calculation
state.score += Math.ceil(dt * speed / 10);
return state;
};
const tick = (state, { dt }) => {
// if game is running then update all the things
if (state.started) {
const m = dt / 1000;
return jumpTick(m, obstaclesTick(m, cloudsTick(m, landscapeTick(m, collisionsTick(scoreTick(dt, state))))));
}
return state;
};
// IIFE to store some local state
const reset = (() => {
// make a copy of initial state
// store as a JSON string - simple deep clone
const copy = JSON.stringify(initial);
// on first run obstacle positions are already generated
let firstRun = true;
return () => {
// get initial state back from JSON
let state = JSON.parse(copy);
// generate new obstacle positions
state.obstacles = firstRun ? state.obstacles : generateObstaclePositions();
// no longer first run
firstRun = false;
return state;
};
})();
const start = state => {
// reset and start if not started
if (!state.started) {
const clean = reset();
clean.started = true;
return clean;
}
return state;
};
const reducer = (state, action) => {
switch (action.type) {
case "start": return start(state);
case "tick": return tick(state, action);
case "jump": return startJump(state);
case "cancelJump": return cancelJump(state);
case "reset": return reset();
default: return state;
}
};
const store = createStore(reducer, initial);
/* render */
const translate = (x, y) => `translate3d(${x}px, ${y}px, 0)`; // use translate3d to get GPU rendering
const renderMovement = state => {
// update score
scoreEl.textContent = state.score.toLocaleString();
// move player
playerEl.style.transform = translate(state.player.left, state.player.top);
// move obstacles
for (let i = 0; i < obstacles.length; i += 1) { // for loop to avoid gc
obstacles[i].style.transform = translate(state.obstacles[i].left, 0);
}
// move buildings
for (let i = 0; i < landscapes.length; i += 1) { // for loop to avoid gc
landscapes[i].style.transform = translate(state.landscapes[i], 0);
}
// move clouds
for (let i = 0; i < clouds.length; i += 1) { // for loop to avoid gc
clouds[i].style.transform = translate(state.clouds[i], 0);
}
};
// show bounding boxes
const renderBoundingBoxes = state => {
// move player bounding box
Object.assign(playerElBB.style, {
transform: translate(state.player.left, state.player.top),
height: state.player.bottom - state.player.top + "px",
width: state.player.right - state.player.left + "px",
});
// move obstacle bounding boxes
// use for loops to avoid gc
for (let i = 0; i < obstacleBBs.length; i += 1) {
// each obstacle is made of many bounding boxes
for (let j = 0; j < obstacleBBs[i].length; j += 1) {
// get current box's state
const el = obstacleBBs[i][j];
const ob = state.obstacles[i].boxes[j];
Object.assign(el.style, {
transform: translate(ob.left, ob.top),
height: ob.bottom - ob.top + "px",
width: ob.right - ob.left + "px",
});
}
}
};
// IIFE to store some local state
const render = (() => {
// keep track of previous score/started
let lastScore = null;
let lastStarted = null;
return state => {
// avoids re-rending if nothing has changed
if (state.score !== lastScore || state.started !== lastStarted) {
renderMovement(state);
if (DEBUG) {
renderBoundingBoxes(state);
}
// game over when started is false and score is not 0
const method = (!state.started && state.score !== 0) ? "remove" : "add";
gameOverEl.classList[method]("hidden");
// intro when started is false and score is 0
const imethod = (!state.started && state.score === 0) ? "remove" : "add";
introEl.classList[imethod]("hidden");
}
// update previous score/started
lastScore = state.score;
lastStarted = state.started;
};
})();
store.subscribe(render);
/* animation loop */
const loop = (() => {
let tickAction = { type: "tick", dt: 0 }; // reuse same object to avoid gc
let last = 0;
return time => {
requestAnimationFrame(loop);
tickAction.dt = time - last;
store.dispatch(tickAction);
last = time;
};
})();
/* music */
const freq = 60 / bpm;
const A = 440;
const rangeValues = range(0, 8).map(val => [val, val - 4]);
const noteValues = [
["C", -9],
["C#", -8],
["Db", -8],
["D", -7],
["D#", -6],
["Eb", -6],
["E", -5],
["F", -4],
["F#", -3],
["Gb", -3],
["G", -2],
["G#", -1],
["Ab", -1],
["A", 0],
["A#", 1],
["Bb", 1],
["B", 2],
];
// map notes to frequencies - e.g A4 = 440, C#2 ~= 17.32
const notes = rangeValues.reduce((ob, [range, multiplier]) => noteValues.reduce((ob, [note, semitones]) => ({
...ob,
[note + range]: A * Math.pow(2, (semitones + (multiplier * 12)) / 12),
}), ob), {});
const createOscillator = context => {
const oscillator = context.createOscillator();
oscillator.type = "sawtooth";
oscillator.connect(context.destination);
return oscillator;
};
const audioPlayer = (() => {
let inited = false;
let context = null;
let now = null;
const music = (oscillator, part) => {
let seconds = 0;
return () => {
part.forEach((note, i) => {
oscillator.frequency.setValueAtTime(notes[note] || null, now + seconds + (i * freq));
});
seconds += part.length * freq;
};
};
return () => {
if (!playMusic || inited || tune.length === 0) {
return;
}
inited = true;
context = new (window.AudioContext || window.webkitAudioContext)();
now = context.currentTime;
// start the oscillator
tune.forEach(part => {
if (part.length === 0) {
return;
}
let oscillator = createOscillator(context);
let metronome = music(oscillator, part);
// line up the first two runs of music
metronome();
metronome();
// add the next run one run before it's needed
setInterval(metronome, part.length * freq * 1000);
oscillator.start(now);
});
};
})();
/* event handlers */
const up = () => {
audioPlayer();
store.dispatch({ type: "start" });
store.dispatch({ type: "cancelJump" });
};
const down = e => {
e.preventDefault();
store.dispatch({ type: "jump" });
};
// keyboard events
window.addEventListener("keyup", e => {
switch (e.key) {
case "Escape": store.dispatch({ type: "reset" }); break;
case " ": up(e); break;
}
});
window.addEventListener("keydown", e => {
switch (e.key) {
case " ": down(e); break;
}
});
// mouse events
window.addEventListener("mousedown", down);
window.addEventListener("mouseup", up);
// touch events
window.addEventListener("touchstart", down);
window.addEventListener("touchend", up);
/* getting things started */
requestAnimationFrame(loop);
})(document);