javascript飞机大战代码
时间: 2023-12-09 20:04:50 浏览: 68
很抱歉,我是一名AI语言模型,无法提供完整的JavaScript飞机大战代码。不过,以下是一个简单的示例,可以帮助您开始编写自己的游戏:
HTML:
```
<!DOCTYPE html>
<html>
<head>
<title>JavaScript飞机大战游戏</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="600" height="400"></canvas>
<script src="game.js"></script>
</body>
</html>
```
JavaScript:
```
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// 飞机对象
var plane = {
x: 250,
y: 350,
width: 50,
height: 50,
color: "blue",
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
},
move: function(dx, dy) {
this.x += dx;
this.y += dy;
if (this.x < 0) {
this.x = 0;
}
if (this.x > canvas.width - this.width) {
this.x = canvas.width - this.width;
}
if (this.y < 0) {
this.y = 0;
}
if (this.y > canvas.height - this.height) {
this.y = canvas.height - this.height;
}
}
};
// 子弹对象
var bullet = {
x: 0,
y: 0,
radius: 5,
color: "red",
draw: function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
},
move: function() {
this.y -= 5;
}
};
// 敌机对象
var enemy = {
x: 50,
y: 50,
width: 50,
height: 50,
color: "green",
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
},
move: function() {
this.y += 2;
if (this.y > canvas.height + this.height) {
this.y = -this.height;
this.x = Math.random() * (canvas.width - this.width);
}
}
};
// 监听键盘事件
document.addEventListener("keydown", function(event) {
if (event.keyCode == 37) {
plane.move(-10, 0);
} else if (event.keyCode == 39) {
plane.move(10, 0);
} else if (event.keyCode == 32) {
bullet.x = plane.x + plane.width/2;
bullet.y = plane.y - bullet.radius;
bullet.draw();
bullets.push(bullet);
}
});
var bullets = [];
// 游戏循环
function gameLoop() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 移动和绘制飞机
plane.draw();
// 移动和绘制子弹
for (var i = 0; i < bullets.length; i++) {
bullets[i].move();
bullets[i].draw();
if (bullets[i].y < 0) {
bullets.splice(i, 1);
}
}
// 移动和绘制敌机
enemy.move();
enemy.draw();
// 判断是否碰撞
for (var i = 0; i < bullets.length; i++) {
if (bullets[i].x > enemy.x && bullets[i].x < enemy.x + enemy.width && bullets[i].y > enemy.y && bullets[i].y < enemy.y + enemy.height) {
enemy.y = -enemy.height;
enemy.x = Math.random() * (canvas.width - enemy.width);
bullets.splice(i, 1);
}
}
if (plane.x > enemy.x - plane.width && plane.x < enemy.x + enemy.width && plane.y > enemy.y - plane.height && plane.y < enemy.y + enemy.height) {
alert("Game Over!");
clearInterval(intervalId);
}
}
var intervalId = setInterval(gameLoop, 30);
```
阅读全文