编写网页游戏的JavaScript脚本涉及多个方面,包括游戏逻辑、用户交互、动画效果等。以下是一个简单的示例,展示如何使用JavaScript创建一个基本的网页游戏。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Whack-a-Mole</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="game.js"></script>
</body>
</html>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const moleSize = 50;
const moleSpeed = 2;
let moles = [];
let score = 0;
class Mole {
constructor(x, y) {
this.x = x;
this.y = y;
this.visible = false;
}
show() {
this.visible = true;
ctx.fillStyle = 'brown';
ctx.fillRect(this.x, this.y, moleSize, moleSize);
}
hide() {
this.visible = false;
ctx.clearRect(this.x, this.y, moleSize, moleSize);
}
move() {
if (this.visible) {
this.y += moleSpeed;
if (this.y > canvas.height) {
this.hide();
}
}
}
}
function createMole() {
const x = Math.random() * (canvas.width - moleSize);
const y = -moleSize;
const mole = new Mole(x, y);
moles.push(mole);
mole.show();
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
moles.forEach(mole => mole.move());
requestAnimationFrame(update);
}
canvas.addEventListener('click', (event) => {
const rect = canvas.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
moles.forEach(mole => {
if (mole.visible && mouseX > mole.x && mouseX < mole.x + moleSize && mouseY > mole.y && mouseY < mole.y + moleSize) {
mole.hide();
score++;
console.log(`Score: ${score}`);
}
});
});
setInterval(createMole, 1000);
update();
通过以上示例和解释,你可以开始编写自己的网页游戏。如果有更具体的问题或需要进一步的帮助,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云