Skip to content

Commit

Permalink
add a graph with scores over time
Browse files Browse the repository at this point in the history
Resolves vnglst#16
  • Loading branch information
tyomitch committed Feb 6, 2024
1 parent d0c70cb commit 989577d
Showing 1 changed file with 31 additions and 10 deletions.
41 changes: 31 additions & 10 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@

<body>
<div id="container">
<canvas id="pongCanvas" width="800" height="800"></canvas>
<canvas id="pongCanvas" width="700" height="800"></canvas>
<div id="score"></div>
<p id="made">
made by <a href="https://koenvangilst.nl">Koen van Gilst</a> | source on
Expand All @@ -92,7 +92,7 @@
// Idea for Pong wars: https://twitter.com/nicolasdnl/status/1749715070928433161

const canvas = document.getElementById("pongCanvas");
const ctx = canvas.getContext("2d");
const ctx = canvas.getContext("2d", { willReadFrequently: true });
const scoreElement = document.getElementById("score");

const DAY_COLOR = colorPalette.MysticMint;
Expand All @@ -102,9 +102,10 @@
const NIGHT_BALL_COLOR = colorPalette.MysticMint;

const SQUARE_SIZE = 25;
const fieldHeight = canvas.width;

const numSquaresX = canvas.width / SQUARE_SIZE;
const numSquaresY = canvas.height / SQUARE_SIZE;
const numSquaresY = fieldHeight / SQUARE_SIZE;

let squares = [];

Expand All @@ -116,12 +117,12 @@
}

let x1 = canvas.width / 4;
let y1 = canvas.height / 2;
let y1 = fieldHeight / 2;
let dx1 = 12.5;
let dy1 = -12.5;

let x2 = (canvas.width / 4) * 3;
let y2 = canvas.height / 2;
let y2 = fieldHeight / 2;
let dx2 = -12.5;
let dy2 = 12.5;

Expand Down Expand Up @@ -192,24 +193,44 @@
}

scoreElement.textContent = `day ${dayScore} | night ${nightScore}`;
if (iteration % 10 !== 0) {
return;
}

const graphHeight = canvas.height - fieldHeight;
const dayPart = graphHeight * dayScore / (numSquaresX * numSquaresY);

const imageData = ctx.getImageData(1, fieldHeight, canvas.width, graphHeight);
ctx.putImageData(imageData, 0, fieldHeight);

ctx.strokeStyle = DAY_COLOR;
ctx.beginPath();
ctx.moveTo(canvas.width, fieldHeight);
ctx.lineTo(canvas.width, fieldHeight + dayPart);
ctx.lineWidth = 2;
ctx.stroke();

ctx.strokeStyle = NIGHT_COLOR;
ctx.beginPath();
ctx.moveTo(canvas.width, fieldHeight + dayPart);
ctx.lineTo(canvas.width, canvas.height);
ctx.lineWidth = 2;
ctx.stroke();
}

function checkBoundaryCollision(x, y, dx, dy) {
if (x + dx > canvas.width - SQUARE_SIZE / 2 || x + dx < SQUARE_SIZE / 2) {
dx = -dx;
}
if (
y + dy > canvas.height - SQUARE_SIZE / 2 ||
y + dy < SQUARE_SIZE / 2
) {
if (y + dy > fieldHeight - SQUARE_SIZE / 2 || y + dy < SQUARE_SIZE / 2) {
dy = -dy;
}

return { dx: dx, dy: dy };
}

function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.clearRect(0, 0, canvas.width, fieldHeight);
drawSquares();

drawBall(x1, y1, DAY_BALL_COLOR);
Expand Down

0 comments on commit 989577d

Please sign in to comment.