请制作一个乒乓游戏网页版
时间: 2024-06-11 08:08:44 浏览: 84
很抱歉,作为AI语言模型,我无法制作游戏网页版,但我可以提供一些相关的HTML、CSS和JavaScript代码,供您参考:
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<title>Ping Pong Game</title>
<style>
canvas {
background-color: black;
border: 5px solid white;
margin: 0 auto;
display: block;
}
</style>
</head>
<body>
<canvas id="game" width="640" height="480"></canvas>
<script src="game.js"></script>
</body>
</html>
```
CSS代码:
```
canvas {
background-color: black;
border: 5px solid white;
margin: 0 auto;
display: block;
}
```
JavaScript代码:
```
var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
var ball = {
x: canvas.width/2,
y: canvas.height/2,
radius: 10,
speedX: 5,
speedY: 5
};
var paddle1 = {
x: 10,
y: canvas.height/2 - 50,
width: 10,
height: 100,
speed: 10,
score: 0
};
var paddle2 = {
x: canvas.width - 20,
y: canvas.height/2 - 50,
width: 10,
height: 100,
speed: 10,
score: 0
};
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = 'white';
context.beginPath();
context.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
context.fill();
context.fillRect(paddle1.x, paddle1.y, paddle1.width, paddle1.height);
context.fillRect(paddle2.x, paddle2.y, paddle2.width, paddle2.height);
ball.x += ball.speedX;
ball.y += ball.speedY;
if(ball.y + ball.radius >= canvas.height || ball.y - ball.radius <= 0) {
ball.speedY = -ball.speedY;
}
if(ball.x + ball.radius >= canvas.width || ball.x - ball.radius <= 0) {
ball.speedX = -ball.speedX;
}
if(ball.x - ball.radius <= paddle1.x + paddle1.width && ball.y >= paddle1.y && ball.y <= paddle1.y + paddle1.height) {
ball.speedX = -ball.speedX;
}
if(ball.x + ball.radius >= paddle2.x && ball.y >= paddle2.y && ball.y <= paddle2.y + paddle2.height) {
ball.speedX = -ball.speedX;
}
if(paddle1.y <= 0) {
paddle1.y = 0;
}
if(paddle1.y >= canvas.height - paddle1.height) {
paddle1.y = canvas.height - paddle1.height;
}
if(paddle2.y <= 0) {
paddle2.y = 0;
}
if(paddle2.y >= canvas.height - paddle2.height) {
paddle2.y = canvas.height - paddle2.height;
}
if(ball.x + ball.radius >= canvas.width) {
paddle1.score++;
reset();
}
if(ball.x - ball.radius <= 0) {
paddle2.score++;
reset();
}
context.fillText(paddle1.score, 100, 100);
context.fillText(paddle2.score, canvas.width - 100, 100);
}
function reset() {
ball.x = canvas.width/2;
ball.y = canvas.height/2;
ball.speedX = -ball.speedX;
}
document.addEventListener('keydown', function(event) {
if(event.keyCode == 38) {
paddle2.y -= paddle2.speed;
}
if(event.keyCode == 40) {
paddle2.y += paddle2.speed;
}
if(event.keyCode == 87) {
paddle1.y -= paddle1.speed;
}
if(event.keyCode == 83) {
paddle1.y += paddle1.speed;
}
});
setInterval(draw, 16);
```
这些代码只是简单的实现了乒乓球游戏的基本功能,您可以根据需求进行修改和扩展。
阅读全文