const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); // 游戏窗口尺寸 const window_x = canvas.width; const window_y = canvas.height; // 定义颜色 const black = '#000000'; const white = '#FFFFFF'; const blue = '#0000FF'; // 球的属性 let ballRadius = 10; let ballX = window_x / 2; let ballY = window_y / 2; let ballSpeedX = Math.random() > 0.5 ? 4 : -4; // 随机方向 let ballSpeedY = Math.random() > 0.5 ? 4 : -4; // 控制板的属性 let paddleWidth = 100; let paddleHeight = 10; let paddleX = (window_x - paddleWidth) / 2; const paddleY = window_y - 30; const paddleSpeed = 10; let rightPressed = false; let leftPressed = false; // 分数 let score = 0; // 游戏状态 let isPaused = 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; } else if (e.key === 'p' || e.key === 'P') { isPaused = !isPaused; // 切换暂停状态 if (!isPaused) { updateGame(); // 恢复游戏 } } } function keyUpHandler(e) { if (e.key === 'Right' || e.key === 'ArrowRight') { rightPressed = false; } else if (e.key === 'Left' || e.key === 'ArrowLeft') { leftPressed = false; } } // 更新分数显示 function drawScore() { document.getElementById('score').textContent = `Score: ${score}`; } // 绘制球 function drawBall() { ctx.beginPath(); ctx.arc(ballX, ballY, ballRadius, 0, Math.PI * 2); ctx.fillStyle = white; ctx.fill(); ctx.closePath(); } // 绘制控制板 function drawPaddle() { ctx.beginPath(); ctx.rect(paddleX, paddleY, paddleWidth, paddleHeight); ctx.fillStyle = blue; ctx.fill(); ctx.closePath(); } // 更新游戏逻辑 function updateGame() { if (isPaused) return; // 如果游戏暂停,则不更新 // 清空画布 ctx.clearRect(0, 0, window_x, window_y); // 画球和控制板 drawBall(); drawPaddle(); drawScore(); // 碰撞检测:球碰到左右边界 if (ballX + ballSpeedX > window_x - ballRadius || ballX + ballSpeedX < ballRadius) { ballSpeedX = -ballSpeedX; } // 碰撞检测:球碰到上边界 if (ballY + ballSpeedY < ballRadius) { ballSpeedY = -ballSpeedY; } // 碰撞检测:球碰到控制板 if (ballY + ballSpeedY > paddleY - ballRadius && ballX > paddleX && ballX < paddleX + paddleWidth) { ballSpeedY = -ballSpeedY; score++; // 每次接住球得分 } // 游戏结束:球触碰到下边界 if (ballY + ballSpeedY > window_y) { alert('Game Over! Your Score: ' + score); resetGame(); // 重置游戏 } // 更新球的位置 ballX += ballSpeedX; ballY += ballSpeedY; // 控制板移动 if (rightPressed && paddleX < window_x - paddleWidth) { paddleX += paddleSpeed; } else if (leftPressed && paddleX > 0) { paddleX -= paddleSpeed; } // 重新绘制 requestAnimationFrame(updateGame); } // 重置游戏 function resetGame() { ballX = window_x / 2; ballY = window_y / 2; ballSpeedX = Math.random() > 0.5 ? 4 : -4; ballSpeedY = Math.random() > 0.5 ? 4 : -4; score = 0; drawScore(); } // 启动游戏 updateGame();