-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
486 lines (402 loc) · 15 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Pong Wars - Fireball Edition</title>
<meta
name="description"
content="The eternal battle between day and night - good and bad - with the power of the sun. Written in JavaScript with some HTML & CSS in one index.html. Feel free to reuse the code and create your own version."
/>
<link rel="canonical" href="https://pong-wars-fireballs.vercel.app/" />
<link rel="author" href="https://github.com/schlagmichdoch" />
<meta name="theme-color" content="#172B36" />
<meta name="creator" content="schlagmichdoch" />
<style>
html {
height: 100%;
}
body {
height: 100%;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
background: linear-gradient(to bottom, #172b36 0%, #d9e8e3 100%);
}
#container {
display: flex;
align-items: center;
flex-direction: column;
width: min(70vh, 80%);
max-width: 600px;
height: 100%;
}
canvas {
display: block;
border-radius: 4px;
overflow: hidden;
width: 100%;
margin-top: auto;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
}
#score {
font-family: monospace;
margin-top: 30px;
font-size: 16px;
padding-left: 20px;
color: #172b36;
}
#made {
text-align: center;
line-height: 1.5;
font-family: monospace;
margin-top: auto;
margin-bottom: 20px;
font-size: 10px;
}
#made a {
color: #172b36;
}
</style>
</head>
<body>
<div id="container">
<canvas id="pongCanvas" width="720" height="720"></canvas>
<div id="score"></div>
<p id="made">
made by <a href="https://github.com/schlagmichdoch">schlagmichdoch</a> | source on
<a href="https://github.com/schlagmichdoch/yin-yang-pong/tree/fire_balls_bounce">github</a> | based on <a href="https://pong-wars.koenvangilst.nl/">pong-wars</a>
</p>
</div>
</body>
<script>
// Source palette: https://twitter.com/AlexCristache/status/1738610343499157872
// Idea for Pong wars: https://twitter.com/nicolasdnl/status/1749715070928433161
const colorPalette = {
ArcticPowder: "#F1F6F4",
MysticMint: "#D9E8E3",
Forsythia: "#FFC801",
DeepSaffron: "#FF9932",
NocturnalExpedition: "#114C5A",
OceanicNoir: "#172B36",
};
const canvas = document.getElementById("pongCanvas");
const ctx = canvas.getContext("2d");
const scoreElement = document.getElementById("score");
const DAY_COLOR = colorPalette.MysticMint;
const NIGHT_COLOR = colorPalette.NocturnalExpedition;
const FLIPPER_COLOR = colorPalette.DeepSaffron;
const DAY_BALL_COLOR = NIGHT_COLOR;
const NIGHT_BALL_COLOR = DAY_COLOR;
const SPEED = 10;
const SQUARE_SIZE = 30; // must be an even integer and a factor of the canvas size
const BALL_RADIUS = SQUARE_SIZE / 2;
const BALL_CIRCUMFERENCE = 2 * Math.PI * BALL_RADIUS;
// Use diameter to ensure each pixel around the circumference is checked at least once
// Calculate next bigger power of 2 of diameter to ensure relevant angles (0, 1/4, 1/2, 3/4, 1, 5/4, 3/2, 7/4) are always checked
let anglePerPixel = 1 / Math.pow(2, Math.ceil(Math.log2(BALL_CIRCUMFERENCE)));
const numSquaresX = canvas.width / SQUARE_SIZE;
const numSquaresY = canvas.height / SQUARE_SIZE;
const scores = [];
scores[DAY_COLOR] = 0;
scores[NIGHT_COLOR] = 0;
const squares = [];
// Populate the fields, one half day, one half night
for (let i = 0; i < numSquaresX; i++) {
squares[i] = [];
for (let j = 0; j < numSquaresY; j++) {
if (i < numSquaresX / 2) {
squares[i][j] = DAY_COLOR;
scores[DAY_COLOR]++;
}
else {
squares[i][j] = NIGHT_COLOR;
scores[NIGHT_COLOR]++;
}
}
}
// Add flipper
squares[0][0] = FLIPPER_COLOR;
squares[numSquaresX-1][numSquaresY-1] = FLIPPER_COLOR;
const balls = [
{
x: canvas.width / 4,
y: canvas.height / 2,
angle: 2 * Math.random() / 3 - 1 / 3, // radians [-1/3, 1/3)
color: DAY_COLOR,
ballColor: DAY_BALL_COLOR,
fire: false
},
{
x: (canvas.width / 4) * 3,
y: canvas.height / 2,
angle: 2 * Math.random() / 3 - 1 / 3 + 1, // radians [2/3, 4/3)
color: NIGHT_COLOR,
ballColor: NIGHT_BALL_COLOR,
fire: false
}
];
balls.forEach((ball) => {
ball.dx = calculateDxFromAngle(ball.angle);
ball.dy = calculateDyFromAngle(ball.angle);
});
let iteration = 0;
function drawBall(ball) {
ctx.beginPath();
ctx.arc(ball.x, ball.y, BALL_RADIUS, 0, Math.PI * 2, false);
ctx.fillStyle = ball.fire ? FLIPPER_COLOR : ball.ballColor;
ctx.fill();
ctx.closePath();
if (ball.fire) {
ctx.beginPath();
ctx.arc(ball.x, ball.y, BALL_RADIUS / 2, 0, Math.PI * 2, false);
ctx.fillStyle = ball.ballColor;
ctx.fill();
ctx.closePath();
}
}
function drawSquares() {
for (let i = 0; i < numSquaresX; i++) {
for (let j = 0; j < numSquaresY; j++) {
ctx.fillStyle = squares[i][j];
ctx.fillRect(
i * SQUARE_SIZE,
j * SQUARE_SIZE,
SQUARE_SIZE,
SQUARE_SIZE
);
}
}
}
function activateFireball(ball) {
ball.fire = true;
clearTimeout(ball.fireTimeout);
ball.fireTimeout = setTimeout(() => deactivateFireball(ball), 1000);
}
function deactivateFireball(ball) {
clearTimeout(ball.fireTimeout);
ball.fire = false;
}
function calculateDistance(p1, p2) {
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}
function getRoundedAngle(angle) {
return Math.round(1_000_000 * angle) / 1_000_000;
}
function calculateDxFromAngle(angle) {
return Math.round(Math.sqrt(2) * Math.cos(angle * Math.PI) * 1_000_000) / 1_000_000;
}
function calculateDyFromAngle(angle) {
return Math.round(Math.sqrt(2) * Math.sin(angle * Math.PI) * 1_000_000) / 1_000_000;
}
function isAnyOtherBallInSquare(thisBall, square) {
// If this ball and square this is the exclusion zone.
// ---bb------------------ ---------------------------
// --bbbb----------------- ---------------------------
// --bbbb----------------- --------######-------------
// ---bb------------------ -------########------------
// ---------ssss---------- -------##ssss##------------
// ---------ssss---------- -------##ssss##------------
// ---------ssss---------- -------##ssss##------------
// ---------ssss---------- -------##ssss##------------
// ----------------------- -------########------------
// ----------------------- --------######-------------
// ----------------------- ---------------------------
square.x = square.sx * SQUARE_SIZE;
square.y = square.sy * SQUARE_SIZE;
for (let i = 0; i < balls.length; i++) {
let ball = balls[i];
// Do not check this ball
if (ball.color === thisBall.color) continue;
ball.sx = Math.floor(ball.x / SQUARE_SIZE);
ball.sy = Math.floor(ball.y / SQUARE_SIZE);
// Check if ball is inside square
if (ball.sx === square.sx && ball.sy === square.sy) {
return true;
}
// Check if ball is more than one square away
if (Math.abs(ball.sx - square.sx) > 1 || Math.abs(ball.sy - square.sy) > 1) {
// is not in square -> check next ball
continue;
}
// Check if ball is inside orthogonally neighboring square and closer than one radius to the according edge of this square
if (
(square.sx - ball.sx === 1 && square.x - ball.x <= BALL_RADIUS) // Left neighbor
|| (square.sy - ball.sy === 1 && square.y - ball.y <= BALL_RADIUS) // Top neighbor
|| (ball.sx - square.sx === 1 && ball.x - (square.x + SQUARE_SIZE) <= BALL_RADIUS) // Right neighbor
|| (ball.sy - square.sy === 1 && ball.y - (square.y + SQUARE_SIZE) <= BALL_RADIUS) // Bottom neighbor
) {
return true;
}
// Ball must be in diagonally neighboring square
// Check if the distance to any of the corner points of the square is closer than the ball radius -> overlap
if (
calculateDistance(ball, square) <= BALL_RADIUS
|| calculateDistance(ball, { x: square.x + SQUARE_SIZE, y: square.y }) <= BALL_RADIUS
|| calculateDistance(ball, { x: square.x, y: square.y + SQUARE_SIZE }) <= BALL_RADIUS
|| calculateDistance(ball, { x: square.x + SQUARE_SIZE, y: square.y + SQUARE_SIZE }) <= BALL_RADIUS
) {
return true;
}
}
// No ball is in square
return false;
}
function nearSquareCandidateOrBorder(ball) {
let ballSquare = {
sx: Math.floor(ball.x / SQUARE_SIZE),
sy: Math.floor(ball.y / SQUARE_SIZE)
};
// only next squares in direction of travel are candidates
let possibleSquares = [];
possibleSquares.push({
sx: ballSquare.sx + Math.sign(ball.dx),
sy: ballSquare.sy,
});
possibleSquares.push({
sx: ballSquare.sx,
sy: ballSquare.sy + Math.sign(ball.dy),
});
possibleSquares.push({
sx: ballSquare.sx + Math.sign(ball.dx),
sy: ballSquare.sy + Math.sign(ball.dy),
});
for (let i = 0; i < possibleSquares.length; i++) {
let square = possibleSquares[i];
// check if square is out of border
if (!squares[square.sx] || !squares[square.sx][square.sy]){
return true;
}
// check if square is of other color
if (squares[square.sx][square.sy] !== ball.color) {
return true;
}
}
return false;
}
function updateSquareAndBounce(ball) {
let dxUpdated = ball.dx;
let dyUpdated = ball.dy;
let angleUpdated = ball.angle;
let angleCheck = 0;
let angleCols = [];
let squaresToFlip = [];
// Check multiple points around the ball's circumference
for (let i = 0; angleCheck < 2; angleCheck = getRoundedAngle(++i * anglePerPixel)) {
let angleCheckDiff = ball.angle - angleCheck;
// angles must be in range [0,2)
if (Math.sign(angleCheckDiff) === -1) {
angleCheckDiff += 2;
}
// Only check angles in vector direction
if (angleCheckDiff >= 1 / 2 && angleCheckDiff <= 3 / 2) continue;
// check is one out of circle
let check = {
x: ball.x + Math.cos(angleCheck * Math.PI) * BALL_RADIUS,
y: ball.y + Math.sin(angleCheck * Math.PI) * BALL_RADIUS
};
// Depending on which side of the circle we are, we need to round decimal pixels either up or down
// On left and top side of circle we need to reduce by one more to check potential next square.
check.x = angleCheck >= 1 / 2 && angleCheck < 3 / 2
? Math.ceil(check.x) - 1
: Math.floor(check.x);
check.y = angleCheck >= 1 && angleCheck < 2
? Math.ceil(check.y) - 1
: Math.floor(check.y);
// boundary collision
if (check.x < 0 || check.x >= canvas.width || check.y < 0 || check.y >= canvas.height) {
angleCols.push(angleCheck);
}
check.sx = Math.floor(check.x / SQUARE_SIZE);
check.sy = Math.floor(check.y / SQUARE_SIZE);
if (squares[check.sx] && squares[check.sx][check.sy] && squares[check.sx][check.sy] !== ball.color) {
if (squares[check.sx][check.sy] === FLIPPER_COLOR) {
activateFireball(ball);
angleCols.push(angleCheck);
}
else if (!isAnyOtherBallInSquare(ball, check)) {
squaresToFlip.push(check);
if (!ball.fire) {
angleCols.push(angleCheck);
}
}
else {
// Do not flip square if any other ball is inside square but always reflect ball
angleCols.push(angleCheck);
}
}
}
if (angleCols.length >= 1) {
// Determine bounce direction based on the collision angle
let angleReflection;
// Multiple collisions must be combined by their mean difference
let angleColsSum = 0;
for (let i = 0; i < angleCols.length; i++) {
let angleCol = angleCols[i];
if (ball.angle < 0.5 && angleCol >= 1) {
angleCol -= 2;
}
else if (ball.angle >= 1.5 && angleCol < 1) {
angleCol += 2;
}
angleColsSum += angleCol;
}
let angleColsMean = getRoundedAngle(angleColsSum / angleCols.length);
let angleDiffsMean = getRoundedAngle(angleColsMean - ball.angle);
let angleColsInverted = angleColsMean + 1;
// angles must be in range [0,2)
if (angleColsInverted >= 2) {
angleColsInverted -= 2;
}
angleReflection = getRoundedAngle(angleColsInverted + angleDiffsMean);
// angles must be in range [0,2)
while (angleReflection >= 2) {
angleReflection -= 2;
}
while (angleReflection < 0) {
angleReflection += 2;
}
angleUpdated = angleReflection;
dxUpdated = calculateDxFromAngle(angleUpdated);
dyUpdated = calculateDyFromAngle(angleUpdated);
}
// flip square color and change scores
for (let i = 0; i < squaresToFlip.length; i++) {
const oldColor = squares[squaresToFlip[i].sx][squaresToFlip[i].sy];
// ensure each square is only flipped once
if (oldColor === ball.color) continue;
squares[squaresToFlip[i].sx][squaresToFlip[i].sy] = ball.color;
scores[ball.color]++;
scores[oldColor]--;
}
ball.dx = dxUpdated;
ball.dy = dyUpdated;
ball.angle = angleUpdated;
}
function updateScoreElement() {
scoreElement.textContent = `day ${scores[DAY_COLOR]} | night ${scores[NIGHT_COLOR]}`;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
updateScoreElement();
drawSquares();
balls.forEach((ball) => {
drawBall(ball);
});
for (let step = 0; step < SPEED; step++) {
balls.forEach((ball) => {
if (nearSquareCandidateOrBorder(ball)) {
updateSquareAndBounce(ball);
}
ball.x += ball.dx;
ball.y += ball.dy;
});
}
iteration++;
if (iteration % 1_000 === 0) console.log("iteration", iteration);
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
</script>
</html>