HTML5乒乓球小游戲源代碼
<!DOCTYPE html> <html> <head> <title>HTML5乒乓球小游戲</title> <meta charset="UTF-8"> <style> canvas { border: 1px solid #000; } </style> </head> <body> <canvas id="gameCanvas" width="600" height="400"></canvas> <script> var canvas = document.getElementById("gameCanvas"); var context = canvas.getContext("2d"); var ball = { x: canvas.width/2, y: canvas.height/2, radius: 10, color: "red", speedX: 5, speedY: 5 }; var player = { x: 20, y: canvas.height/2 - 50, width: 5, height: 100, color: "blue", score: 0 }; var computer = { x: canvas.width - 25, y: canvas.height/2 - 50, width: 5, height: 100, color: "green", score: 0 }; function drawBall() { context.beginPath(); context.arc(ball.x, ball.y, ball.radius, 0, Math.PI*2); context.fillStyle = ball.color; context.fill(); context.closePath(); } function drawPaddle(x, y, width, height, color) { context.fillStyle = color; context.fillRect(x, y, width, height); } function drawScore() { context.font = "20px Arial"; context.fillText("Player: " + player.score, 20, 30); context.fillText("Computer: " + computer.score, canvas.width - 150, 30); } function update() { ball.x += ball.speedX; ball.y += ball.speedY; if(ball.x + ball.radius >canvas.width - computer.width || ball.x - ball.radius< player.width) { resetBall(); } if(ball.y + ball.radius >canvas.height || ball.y - ball.radius< 0) { ball.speedY *= -1; } var paddle = (ball.x + ball.radius< canvas.width/2) ? player : computer; if(collision(ball, paddle)) { var direction = (ball.x + ball.radius< canvas.width/2) ? 1 : -1; ball.speedX = direction * ((Math.abs(ball.y - paddle.y - paddle.height/2)/paddle.height/2) + 0.5) * 10; ball.speedY = -1 * ((Math.abs(ball.y - paddle.y - paddle.height/2)/paddle.height/2) + 0.5) * 10; } if(ball.x - ball.radius< player.width) { computer.score += 1; resetBall(); } else if(ball.x + ball.radius >canvas.width - computer.width) { player.score += 1; resetBall(); } } function resetBall() { ball.x = canvas.width/2; ball.y = canvas.height/2; ball.speedX = -1 * ball.speedX; ball.speedY = 5; } function collision(ball, paddle) { return ball.y + ball.radius >paddle.y && ball.y - ball.radius< paddle.y + paddle.height && ball.x + ball.radius >paddle.x && ball.x - ball.radius< paddle.x + paddle.width; } function gameLoop() { context.clearRect(0, 0, canvas.width, canvas.height); drawBall(); drawPaddle(player.x, player.y, player.width, player.height, player.color); drawPaddle(computer.x, computer.y, computer.width, computer.height, computer.color); drawScore(); update(); } setInterval(gameLoop, 1000/60); </script> </body> </html>
上一篇html5主頁代碼
下一篇mysql中支持的運算符