const canvas = document.createElement('canvas'); canvas.width = 800; canvas.height = 600; const ctx = canvas.getContext('2d'); const paddle = { x: 250, y: 460, width: 200, height: 20, speed: 7 }; const ball = { x: 400, y: 300, radius: 15, speed: 10 }; const scoreElement = document.createElement('div'); scoreElement.textContent = 'Score'; scoreElement.style.position = 'absolute'; scoreElement.style.bottom = '20px'; scoreElement.style.left = '50%'; scoreElement.style.transform = 'translateX(-50%)'; scoreElement.style.fontSize = '24px'; scoreElement.style.color = 'white'; document.body.appendChild(scoreElement); const scoreDisplay = { text: '', update: function() { scoreDisplay.text = document.getElementById('score').textContent; } }; document.getElementById('score').textContent = 'Score'; function drawPaddle() { ctx.fillStyle = 'white'; ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height); ctx.fillStyle = 'black'; ctx.fillRect(paddle.x, paddle.y, paddle.width, 4); } function drawBall() { ctx.beginPath(); ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2); ctx.fillStyle = 'white'; ctx.fill(); } function drawGrid() { ctx.strokeStyle = 'rgba(255, 255, 255, 0.2)'; ctx.lineWidth = 1; for (let i = 0; i <= 8; i++) { ctx.beginPath(); ctx.moveTo(i * 100, 0); ctx.lineTo(i * 100, canvas.height); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, i * 100); ctx.lineTo(canvas.width, i * 100); ctx.stroke(); } } function update() { // Move paddle based on arrow keys const arrowLeft = document.dispatchEvent(new Event('keydown')); const arrowRight = document.dispatchEvent(new Event('keydown')); if (arrowLeft || arrowRight) { if (arrowLeft) { paddle.x -= paddle.speed; if (paddle.x < 0) { paddle.x = 0; } } else if (arrowRight) { paddle.x += paddle.speed; if (paddle.x + paddle.width > canvas.width) { paddle.x = canvas.width - paddle.width; } } } // Move ball ball.x += ball.speed; ball.y -= ball.speed; // Ball bounces off walls if (ball.x + ball.radius > canvas.width) { ball.x = canvas.width - ball.radius; } if (ball.x - ball.radius < 0) { ball.x = ball.radius; } if (ball.y - ball.radius < 0) { ball.y = ball.radius; } if (ball.y + ball.radius > canvas.height) { ball.y = canvas.height - ball.radius; } // Check collision with paddle if (ball.y + ball.radius > paddle.y && ball.y - ball.radius < paddle.y + paddle.height && ball.x > paddle.x && ball.x < paddle.x + paddle.width) { ball.y = paddle.y + paddle.height + ball.radius; ball.speed = Math.abs(ball.speed); } // Check collision with score display if (ball.y > scoreDisplay.text) { scoreDisplay.text = (parseInt(scoreDisplay.text) + 1).toString(); } drawGrid(); drawPaddle(); drawBall(); } function gameLoop() { update(); requestAnimationFrame(gameLoop); } gameLoop();