From 989577d1603669c10ac104ca9df02b852614ebef Mon Sep 17 00:00:00 2001 From: "A. Skrobov" Date: Tue, 6 Feb 2024 19:43:43 +0200 Subject: [PATCH] add a graph with scores over time Resolves #16 --- index.html | 41 +++++++++++++++++++++++++++++++---------- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/index.html b/index.html index 19ef37f..4de7c29 100644 --- a/index.html +++ b/index.html @@ -69,7 +69,7 @@
- +

made by Koen van Gilst | source on @@ -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; @@ -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 = []; @@ -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; @@ -192,16 +193,36 @@ } 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; } @@ -209,7 +230,7 @@ } function draw() { - ctx.clearRect(0, 0, canvas.width, canvas.height); + ctx.clearRect(0, 0, canvas.width, fieldHeight); drawSquares(); drawBall(x1, y1, DAY_BALL_COLOR);