const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const ballRadius = 10; let x = canvas.width / 2; let y = canvas.height - 30; let dx, dy; let intervalID; let paddleHeight = 10; let paddleWidth = 500; let paddleX = (canvas.width - paddleWidth) / 2; let rightPressed = false; let leftPressed = false; document.addEventListener("keydown", keyDownHandler); document.addEventListener("keyup", keyUpHandler); function keyDownHandler(e) { if (e.key === "Right" || e.key === "ArrowRight") { rightPressed = true; } else if (e.key === "Left" || e.key === "ArrowLeft") { leftPressed = true; } } function keyUpHandler(e) { if (e.key === "Right" || e.key === "ArrowRight") { rightPressed = false; } else if (e.key === "Left" || e.key === "ArrowLeft") { leftPressed = false; } } function drawPaddle() { ctx.beginPath(); ctx.rect( paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight ); ctx.fillStyle = "red"; ctx.fill(); ctx.closePath(); } function checkCollision() { if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) { dx = -dx; } if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) { dy = -dy; } x += dx; y += dy; checkPaddleWallCollission(); } function checkPaddleWallCollission() { if (paddleX >= canvas.width - paddleWidth) { rightPressed = false; console.log(paddleX); } else if (paddleX <= 0) { leftPressed = false; } } function drawBall() { ctx.beginPath(); ctx.arc(x, y, ballRadius, 0, Math.PI * 2); ctx.fillStyle = "black"; ctx.fill(); ctx.closePath(); } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawBall(); drawPaddle(); checkCollision(); if (rightPressed) { paddleX += 7; } else if (leftPressed) { paddleX -= 7; } console.log("x: " + x + " " + "y: " + y); } function startGame() { if (intervalID) clearInterval(intervalID); intervalID = setInterval(draw, 10); } const runButton = document.getElementById("runButton"); runButton.addEventListener("click", () => { dx = 2; dy = 2; startGame(); }); const exit = document.getElementById("exit"); exit.addEventListener("click", () => { clearInterval(intervalID); dx = 0; dy = 0; });