-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
655 lines (554 loc) · 20.5 KB
/
script.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
Math.minmax = (value, limit) => {
return Math.max(Math.min(value, limit), -limit);
};
const distance2D = (p1, p2) => {
return Math.sqrt((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2);
};
const getAngle = (p1, p2) => {
let angle = Math.atan((p2.y - p1.y) / (p2.x - p1.x));
if (p2.x - p1.x < 0) angle += Math.PI;
return angle;
};
const closestItCanBe = (cap, ball) => {
let angle = getAngle(cap, ball);
const deltaX = Math.cos(angle) * (wallW / 2 + ballSize / 2);
const deltaY = Math.sin(angle) * (wallW / 2 + ballSize / 2);
return { x: cap.x + deltaX, y: cap.y + deltaY };
};
const rollAroundCap = (cap, ball) => {
let impactAngle = getAngle(ball, cap);
let heading = getAngle(
{ x: 0, y: 0 },
{ x: ball.velocityX, y: ball.velocityY }
);
let impactHeadingAngle = impactAngle - heading;
const velocityMagnitude = distance2D(
{ x: 0, y: 0 },
{ x: ball.velocityX, y: ball.velocityY }
);
const velocityMagnitudeDiagonalToTheImpact =
Math.sin(impactHeadingAngle) * velocityMagnitude;
const closestDistance = wallW / 2 + ballSize / 2;
const rotationAngle = Math.atan(
velocityMagnitudeDiagonalToTheImpact / closestDistance
);
const deltaFromCap = {
x: Math.cos(impactAngle + Math.PI - rotationAngle) * closestDistance,
y: Math.sin(impactAngle + Math.PI - rotationAngle) * closestDistance
};
const x = ball.x;
const y = ball.y;
const velocityX = ball.x - (cap.x + deltaFromCap.x);
const velocityY = ball.y - (cap.y + deltaFromCap.y);
const nextX = x + velocityX;
const nextY = y + velocityY;
return { x, y, velocityX, velocityY, nextX, nextY };
};
const slow = (number, difference) => {
if (Math.abs(number) <= difference) return 0;
if (number > difference) return number - difference;
return number + difference;
};
const mazeElement = document.getElementById("maze");
const joystickHeadElement = document.getElementById("joystick-head");
const noteElement = document.getElementById("note")
let hardMode = false;
let previousTimestamp;
let gameInProgress;
let mouseStartX;
let mouseStartY;
let accelerationX;
let accelerationY;
let frictionX;
let frictionY;
const pathW = 25;
const wallW = 10;
const ballSize = 10;
const holeSize = 18;
const debugMode = false;
let balls = [];
let ballElements = [];
let holeElements = [];
resetGame();
balls.forEach(({ x, y }) => {
const ball = document.createElement("div");
ball.setAttribute("class", "ball");
ball.style.cssText = `left: ${x}px; top: ${y}px; `;
mazeElement.appendChild(ball);
ballElements.push(ball);
});
const walls = [
{ column: 0, row: 0, horizontal: true, length: 10 },
{ column: 0, row: 0, horizontal: false, length: 9 },
{ column: 0, row: 9, horizontal: true, length: 10 },
{ column: 10, row: 0, horizontal: false, length: 9 },
{ column: 0, row: 6, horizontal: true, length: 1 },
{ column: 0, row: 8, horizontal: true, length: 1 },
{ column: 1, row: 1, horizontal: true, length: 2 },
{ column: 1, row: 7, horizontal: true, length: 1 },
{ column: 2, row: 2, horizontal: true, length: 2 },
{ column: 2, row: 4, horizontal: true, length: 1 },
{ column: 2, row: 5, horizontal: true, length: 1 },
{ column: 2, row: 6, horizontal: true, length: 1 },
{ column: 3, row: 3, horizontal: true, length: 1 },
{ column: 3, row: 8, horizontal: true, length: 3 },
// Horizontal lines starting in 5th column
{ column: 4, row: 6, horizontal: true, length: 1 },
// Horizontal lines starting in 6th column
{ column: 5, row: 2, horizontal: true, length: 2 },
{ column: 5, row: 7, horizontal: true, length: 1 },
// Horizontal lines starting in 7th column
{ column: 6, row: 1, horizontal: true, length: 1 },
{ column: 6, row: 6, horizontal: true, length: 2 },
// Horizontal lines starting in 8th column
{ column: 7, row: 3, horizontal: true, length: 2 },
{ column: 7, row: 7, horizontal: true, length: 2 },
// Horizontal lines starting in 9th column
{ column: 8, row: 1, horizontal: true, length: 1 },
{ column: 8, row: 2, horizontal: true, length: 1 },
{ column: 8, row: 3, horizontal: true, length: 1 },
{ column: 8, row: 4, horizontal: true, length: 2 },
{ column: 8, row: 8, horizontal: true, length: 2 },
// Vertical lines after the 1st column
{ column: 1, row: 1, horizontal: false, length: 2 },
{ column: 1, row: 4, horizontal: false, length: 2 },
// Vertical lines after the 2nd column
{ column: 2, row: 2, horizontal: false, length: 2 },
{ column: 2, row: 5, horizontal: false, length: 1 },
{ column: 2, row: 7, horizontal: false, length: 2 },
// Vertical lines after the 3rd column
{ column: 3, row: 0, horizontal: false, length: 1 },
{ column: 3, row: 4, horizontal: false, length: 1 },
{ column: 3, row: 6, horizontal: false, length: 2 },
// Vertical lines after the 4th column
{ column: 4, row: 1, horizontal: false, length: 2 },
{ column: 4, row: 6, horizontal: false, length: 1 },
// Vertical lines after the 5th column
{ column: 5, row: 0, horizontal: false, length: 2 },
{ column: 5, row: 6, horizontal: false, length: 1 },
{ column: 5, row: 8, horizontal: false, length: 1 },
// Vertical lines after the 6th column
{ column: 6, row: 4, horizontal: false, length: 1 },
{ column: 6, row: 6, horizontal: false, length: 1 },
// Vertical lines after the 7th column
{ column: 7, row: 1, horizontal: false, length: 4 },
{ column: 7, row: 7, horizontal: false, length: 2 },
// Vertical lines after the 8th column
{ column: 8, row: 2, horizontal: false, length: 1 },
{ column: 8, row: 4, horizontal: false, length: 2 },
// Vertical lines after the 9th column
{ column: 9, row: 1, horizontal: false, length: 1 },
{ column: 9, row: 5, horizontal: false, length: 2 }
].map((wall) => ({
x: wall.column * (pathW + wallW),
y: wall.row * (pathW + wallW),
horizontal: wall.horizontal,
length: wall.length * (pathW + wallW)
}));
// Draw walls
walls.forEach(({ x, y, horizontal, length }) => {
const wall = document.createElement("div");
wall.setAttribute("class", "wall");
wall.style.cssText = `
left: ${x}px;
top: ${y}px;
width: ${wallW}px;
height: ${length}px;
transform: rotate(${horizontal ? -90 : 0}deg);
`;
mazeElement.appendChild(wall);
});
const holes = [
{ column: 0, row: 5 },
{ column: 2, row: 0 },
{ column: 2, row: 4 },
{ column: 4, row: 6 },
{ column: 6, row: 2 },
{ column: 6, row: 8 },
{ column: 8, row: 1 },
{ column: 8, row: 2 }
].map((hole) => ({
x: hole.column * (wallW + pathW) + (wallW / 2 + pathW / 2),
y: hole.row * (wallW + pathW) + (wallW / 2 + pathW / 2)
}));
joystickHeadElement.addEventListener("mousedown", function (event) {
if (!gameInProgress) {
mouseStartX = event.clientX;
mouseStartY = event.clientY;
gameInProgress = true;
window.requestAnimationFrame(main);
noteElement.style.opacity = 0;
joystickHeadElement.style.cssText = `
animation: none;
cursor: grabbing;
`;
}
});
window.addEventListener("mousemove", function (event) {
if (gameInProgress) {
const mouseDeltaX = -Math.minmax(mouseStartX - event.clientX, 15);
const mouseDeltaY = -Math.minmax(mouseStartY - event.clientY, 15);
joystickHeadElement.style.cssText = `
left: ${mouseDeltaX}px;
top: ${mouseDeltaY}px;
animation: none;
cursor: grabbing;
`;
const rotationY = mouseDeltaX * 0.8; // Max rotation = 12
const rotationX = mouseDeltaY * 0.8;
mazeElement.style.cssText = `
transform: rotateY(${rotationY}deg) rotateX(${-rotationX}deg)
`;
const gravity = 2;
const friction = 0.01; // Coefficients of friction
accelerationX = gravity * Math.sin((rotationY / 180) * Math.PI);
accelerationY = gravity * Math.sin((rotationX / 180) * Math.PI);
frictionX = gravity * Math.cos((rotationY / 180) * Math.PI) * friction;
frictionY = gravity * Math.cos((rotationX / 180) * Math.PI) * friction;
}
});
window.addEventListener("keydown", function (event) {
// If not an arrow key or space or H was pressed then return
if (![" ", "H", "h", "E", "e"].includes(event.key)) return;
// If an arrow key was pressed then first prevent default
event.preventDefault();
// If space was pressed restart the game
if (event.key == " ") {
resetGame();
return;
}
// Set Hard mode
if (event.key == "H" || event.key == "h") {
hardMode = true;
resetGame();
return;
}
// Set Easy mode
if (event.key == "E" || event.key == "e") {
hardMode = false;
resetGame();
return;
}
});
function resetGame() {
previousTimestamp = undefined;
gameInProgress = false;
mouseStartX = undefined;
mouseStartY = undefined;
accelerationX = undefined;
accelerationY = undefined;
frictionX = undefined;
frictionY = undefined;
mazeElement.style.cssText = `
transform: rotateY(0deg) rotateX(0deg)
`;
joystickHeadElement.style.cssText = `
left: 0;
top: 0;
animation: glow;
cursor: grab;
`;
if (hardMode) {
noteElement.innerHTML = `Click The Controller To Start!
<p>If You Want A HARDER MODE THAN PRESS H!</p>`;
} else {
noteElement.innerHTML = `Click The Controller To Start!
<p>If You Want A HARDER MODE THAN PRESS H!</p>`;
}
noteElement.style.opacity = 1;
balls = [
{ column: 0, row: 0 },
{ column: 9, row: 0 },
{ column: 0, row: 8 },
{ column: 9, row: 8 }
].map((ball) => ({
x: ball.column * (wallW + pathW) + (wallW / 2 + pathW / 2),
y: ball.row * (wallW + pathW) + (wallW / 2 + pathW / 2),
velocityX: 0,
velocityY: 0
}));
if (ballElements.length) {
balls.forEach(({ x, y }, index) => {
ballElements[index].style.cssText = `left: ${x}px; top: ${y}px; `;
});
}
// Remove previous hole elements
holeElements.forEach((holeElement) => {
mazeElement.removeChild(holeElement);
});
holeElements = [];
// Reset hole elements if hard mode
if (hardMode) {
holes.forEach(({ x, y }) => {
const ball = document.createElement("div");
ball.setAttribute("class", "black-hole");
ball.style.cssText = `left: ${x}px; top: ${y}px; `;
mazeElement.appendChild(ball);
holeElements.push(ball);
});
}
}
function main(timestamp) {
// It is possible to reset the game mid-game. This case the look should stop
if (!gameInProgress) return;
if (previousTimestamp === undefined) {
previousTimestamp = timestamp;
window.requestAnimationFrame(main);
return;
}
const maxVelocity = 1.5;
// Time passed since last cycle divided by 16
// This function gets called every 16 ms on average so dividing by 16 will result in 1
const timeElapsed = (timestamp - previousTimestamp) / 16;
try {
// If mouse didn't move yet don't do anything
if (accelerationX != undefined && accelerationY != undefined) {
const velocityChangeX = accelerationX * timeElapsed;
const velocityChangeY = accelerationY * timeElapsed;
const frictionDeltaX = frictionX * timeElapsed;
const frictionDeltaY = frictionY * timeElapsed;
balls.forEach((ball) => {
if (velocityChangeX == 0) {
// No rotation, the plane is flat
// On flat surface friction can only slow down, but not reverse movement
ball.velocityX = slow(ball.velocityX, frictionDeltaX);
} else {
ball.velocityX = ball.velocityX + velocityChangeX;
ball.velocityX = Math.max(Math.min(ball.velocityX, 1.5), -1.5);
ball.velocityX =
ball.velocityX - Math.sign(velocityChangeX) * frictionDeltaX;
ball.velocityX = Math.minmax(ball.velocityX, maxVelocity);
}
if (velocityChangeY == 0) {
// No rotation, the plane is flat
// On flat surface friction can only slow down, but not reverse movement
ball.velocityY = slow(ball.velocityY, frictionDeltaY);
} else {
ball.velocityY = ball.velocityY + velocityChangeY;
ball.velocityY =
ball.velocityY - Math.sign(velocityChangeY) * frictionDeltaY;
ball.velocityY = Math.minmax(ball.velocityY, maxVelocity);
}
// Preliminary next ball position, only becomes true if no hit occurs
// Used only for hit testing, does not mean that the ball will reach this position
ball.nextX = ball.x + ball.velocityX;
ball.nextY = ball.y + ball.velocityY;
if (debugMode) console.log("tick", ball);
walls.forEach((wall, wi) => {
if (wall.horizontal) {
// Horizontal wall
if (
ball.nextY + ballSize / 2 >= wall.y - wallW / 2 &&
ball.nextY - ballSize / 2 <= wall.y + wallW / 2
) {
// Ball got within the strip of the wall
// (not necessarily hit it, could be before or after)
const wallStart = {
x: wall.x,
y: wall.y
};
const wallEnd = {
x: wall.x + wall.length,
y: wall.y
};
if (
ball.nextX + ballSize / 2 >= wallStart.x - wallW / 2 &&
ball.nextX < wallStart.x
) {
// Ball might hit the left cap of a horizontal wall
const distance = distance2D(wallStart, {
x: ball.nextX,
y: ball.nextY
});
if (distance < ballSize / 2 + wallW / 2) {
if (debugMode && wi > 4)
console.warn("too close h head", distance, ball);
// Ball hits the left cap of a horizontal wall
const closest = closestItCanBe(wallStart, {
x: ball.nextX,
y: ball.nextY
});
const rolled = rollAroundCap(wallStart, {
x: closest.x,
y: closest.y,
velocityX: ball.velocityX,
velocityY: ball.velocityY
});
Object.assign(ball, rolled);
}
}
if (
ball.nextX - ballSize / 2 <= wallEnd.x + wallW / 2 &&
ball.nextX > wallEnd.x
) {
// Ball might hit the right cap of a horizontal wall
const distance = distance2D(wallEnd, {
x: ball.nextX,
y: ball.nextY
});
if (distance < ballSize / 2 + wallW / 2) {
if (debugMode && wi > 4)
console.warn("too close h tail", distance, ball);
// Ball hits the right cap of a horizontal wall
const closest = closestItCanBe(wallEnd, {
x: ball.nextX,
y: ball.nextY
});
const rolled = rollAroundCap(wallEnd, {
x: closest.x,
y: closest.y,
velocityX: ball.velocityX,
velocityY: ball.velocityY
});
Object.assign(ball, rolled);
}
}
if (ball.nextX >= wallStart.x && ball.nextX <= wallEnd.x) {
// The ball got inside the main body of the wall
if (ball.nextY < wall.y) {
// Hit horizontal wall from top
ball.nextY = wall.y - wallW / 2 - ballSize / 2;
} else {
// Hit horizontal wall from bottom
ball.nextY = wall.y + wallW / 2 + ballSize / 2;
}
ball.y = ball.nextY;
ball.velocityY = -ball.velocityY / 3;
if (debugMode && wi > 4)
console.error("crossing h line, HIT", ball);
}
}
} else {
// Vertical wall
if (
ball.nextX + ballSize / 2 >= wall.x - wallW / 2 &&
ball.nextX - ballSize / 2 <= wall.x + wallW / 2
) {
// Ball got within the strip of the wall
// (not necessarily hit it, could be before or after)
const wallStart = {
x: wall.x,
y: wall.y
};
const wallEnd = {
x: wall.x,
y: wall.y + wall.length
};
if (
ball.nextY + ballSize / 2 >= wallStart.y - wallW / 2 &&
ball.nextY < wallStart.y
) {
// Ball might hit the top cap of a horizontal wall
const distance = distance2D(wallStart, {
x: ball.nextX,
y: ball.nextY
});
if (distance < ballSize / 2 + wallW / 2) {
if (debugMode && wi > 4)
console.warn("too close v head", distance, ball);
// Ball hits the left cap of a horizontal wall
const closest = closestItCanBe(wallStart, {
x: ball.nextX,
y: ball.nextY
});
const rolled = rollAroundCap(wallStart, {
x: closest.x,
y: closest.y,
velocityX: ball.velocityX,
velocityY: ball.velocityY
});
Object.assign(ball, rolled);
}
}
if (
ball.nextY - ballSize / 2 <= wallEnd.y + wallW / 2 &&
ball.nextY > wallEnd.y
) {
// Ball might hit the bottom cap of a horizontal wall
const distance = distance2D(wallEnd, {
x: ball.nextX,
y: ball.nextY
});
if (distance < ballSize / 2 + wallW / 2) {
if (debugMode && wi > 4)
console.warn("too close v tail", distance, ball);
// Ball hits the right cap of a horizontal wall
const closest = closestItCanBe(wallEnd, {
x: ball.nextX,
y: ball.nextY
});
const rolled = rollAroundCap(wallEnd, {
x: closest.x,
y: closest.y,
velocityX: ball.velocityX,
velocityY: ball.velocityY
});
Object.assign(ball, rolled);
}
}
if (ball.nextY >= wallStart.y && ball.nextY <= wallEnd.y) {
// The ball got inside the main body of the wall
if (ball.nextX < wall.x) {
// Hit vertical wall from left
ball.nextX = wall.x - wallW / 2 - ballSize / 2;
} else {
// Hit vertical wall from right
ball.nextX = wall.x + wallW / 2 + ballSize / 2;
}
ball.x = ball.nextX;
ball.velocityX = -ball.velocityX / 3;
if (debugMode && wi > 4)
console.error("crossing v line, HIT", ball);
}
}
}
});
// Detect is a ball fell into a hole
if (hardMode) {
holes.forEach((hole, hi) => {
const distance = distance2D(hole, {
x: ball.nextX,
y: ball.nextY
});
if (distance <= holeSize / 2) {
// The ball fell into a hole
holeElements[hi].style.backgroundColor = "red";
throw Error("The ball fell into a hole");
}
});
}
// Adjust ball metadata
ball.x = ball.x + ball.velocityX;
ball.y = ball.y + ball.velocityY;
});
// Move balls to their new position on the UI
balls.forEach(({ x, y }, index) => {
ballElements[index].style.cssText = `left: ${x}px; top: ${y}px; `;
});
}
// Win detection
if (
balls.every(
(ball) => distance2D(ball, { x: 350 / 2, y: 315 / 2 }) < 65 / 2
)
) {
noteElement.innerHTML = `Congrats, you did it!
${!hardMode ? "<p>Press H for hard mode</p>" : ""}
`;
noteElement.style.opacity = 1;
gameInProgress = false;
} else {
previousTimestamp = timestamp;
window.requestAnimationFrame(main);
}
} catch (error) {
if (error.message == "The ball fell into a hole") {
noteElement.innerHTML = `You Lost A Ball, Press Space To Reset The Game!
<p>
Don't Rage Quit Just Go Back To Easy Mode By Pressing E!
</p>`;
noteElement.style.opacity = 1;
gameInProgress = false;
} else throw error;
}
}