《植物大战僵尸》是一款非常受欢迎的塔防游戏。以下是一个简单的JavaScript示例代码,用于创建一个基本的植物大战僵尸游戏框架。这个示例将展示如何使用HTML5 Canvas和JavaScript来实现游戏的基本逻辑。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>植物大战僵尸</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script src="game.js"></script>
</body>
</html>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
class Plant {
constructor(x, y) {
this.x = x;
this.y = y;
this.width = 50;
this.height = 50;
}
draw() {
ctx.fillStyle = 'green';
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
class Zombie {
constructor(x, y) {
this.x = x;
this.y = y;
this.width = 50;
this.height = 50;
this.speed = 1;
}
draw() {
ctx.fillStyle = 'red';
ctx.fillRect(this.x, this.y, this.width, this.height);
}
update() {
this.x -= this.speed;
}
}
const plants = [new Plant(100, 500)];
const zombies = [new Zombie(700, 500)];
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
plants.forEach(plant => plant.draw());
zombies.forEach(zombie => {
zombie.update();
zombie.draw();
});
requestAnimationFrame(gameLoop);
}
gameLoop();
通过这些基础概念和示例代码,你可以开始构建自己的《植物大战僵尸》游戏,并根据需要进行扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云