请帮我找一个 实现html css js的桌球游戏的教程
时间: 2023-11-23 16:05:43 浏览: 139
当然可以!以下是一个使用 HTML、CSS 和 JavaScript 实现桌球游戏的教程:
1. HTML 和 CSS 的部分:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>桌球游戏</title>
<style>
#canvas {
border: 1px solid black;
}
</style>
<script src="game.js"></script>
</head>
<body>
<canvas id="canvas" width="640" height="480"></canvas>
</body>
</html>
```
2. JavaScript 的部分:
```javascript
var canvas = document.querySelector("#canvas");
var ctx = canvas.getContext("2d");
var ballX = 320;
var ballY = 240;
var ballR = 15;
var ballSpeedX = 5;
var ballSpeedY = 5;
var player1Y = 200;
var player2Y = 200;
var playerH = 80;
var playerW = 10;
var playerSpeed = 5;
function drawRect(x, y, w, h, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, w, h);
}
function drawCircle(x, y, r, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
function drawNet() {
for (var i = 0; i < canvas.height; i += 40) {
drawRect(canvas.width / 2 - 1, i, 2, 20, "white");
}
}
function reset() {
ballX = canvas.width / 2;
ballY = canvas.height / 2;
ballSpeedX = -ballSpeedX;
ballSpeedY = 5;
}
function move() {
ballX += ballSpeedX;
ballY += ballSpeedY;
if (ballX < 0) {
reset();
}
if (ballX > canvas.width) {
reset();
}
if (ballY < 0) {
ballSpeedY = -ballSpeedY;
}
if (ballY > canvas.height) {
ballSpeedY = -ballSpeedY;
}
var player;
if (ballX < canvas.width / 2) {
player = player1Y;
} else {
player = player2Y;
}
if ((ballX < canvas.width / 2 && ballX > canvas.width / 2 - playerW) ||
(ballX > canvas.width / 2 && ballX < canvas.width / 2 + playerW)) {
if (ballY > player && ballY < player + playerH) {
ballSpeedX = -ballSpeedX;
}
}
}
canvas.addEventListener("mousemove", function (evt) {
var mousePos = getMousePos(evt);
player1Y = mousePos.y - playerH / 2;
});
function getMousePos(evt) {
var rect = canvas.getBoundingClientRect();
var root = document.documentElement;
var mouseX = evt.clientX - rect.left - root.scrollLeft;
var mouseY = evt.clientY - rect.top - root.scrollTop;
return {
x: mouseX,
y: mouseY
};
}
function draw() {
drawRect(0, 0, canvas.width, canvas.height, "black");
drawCircle(ballX, ballY, ballR, "white");
drawRect(0, player1Y, playerW, playerH, "white");
drawRect(canvas.width - playerW, player2Y, playerW, playerH, "white");
drawNet();
}
setInterval(function () {
move();
draw();
}, 30);
```
这个教程中的代码可以在浏览器中运行,实现一个简单的桌球游戏。希望对你有所帮助!
阅读全文