科学教育
标题:
帮我生成飞机大作战代码
[打印本页]
作者:
俞悦
时间:
2025-12-2 14:00
标题:
帮我生成飞机大作战代码
帮我生成飞机大作战代码
作者:
kaia
时间:
2025-12-2 14:00
好的!“飞机大作战”是一个很好玩的小游戏,我们可以用网页的技术来做它,比如用HTML、CSS和JavaScript。
我帮你写一个简单版的飞机大作战代码,里面有一架可以左右移动的飞机,还能发射子弹。
你可以按照下面步骤试试看:
### 1. 新建一个HTML文件,比如叫 `index.html`
### 2. 把下面的代码复制进去:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>飞机大作战</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000;
color: white;
text-align: center;
font-family: Arial, sans-serif;
}
#gameCanvas {
background-color: #111;
display: block;
margin: 20px auto;
border: 2px solid #fff;
}
</style>
</head>
<body>
<h1>飞机大作战</h1>
<canvas id="gameCanvas" width="400" height="600"></canvas>
<p>按左右方向键控制飞机,按空格键发射子弹</p>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// 飞机对象
const plane = {
x: canvas.width / 2 - 20,
y: canvas.height - 60,
width: 40,
height: 60,
speed: 5,
movingLeft: false,
movingRight: false,
draw() {
ctx.fillStyle = 'cyan';
ctx.beginPath();
// 画飞机:一个三角形底部带个矩形
ctx.moveTo(this.x + this.width / 2, this.y); // 顶部点
ctx.lineTo(this.x, this.y + this.height);
ctx.lineTo(this.x + this.width, this.y + this.height);
ctx.closePath();
ctx.fill();
// 飞机机身矩形
ctx.fillRect(this.x + this.width / 2 - 7, this.y + this.height / 2, 14, this.height / 2);
},
update() {
if (this.movingLeft && this.x > 0) {
this.x -= this.speed;
}
if (this.movingRight && this.x + this.width < canvas.width) {
this.x += this.speed;
}
}
};
// 子弹数组
const bullets = [];
// 子弹类
class Bullet {
constructor(x, y) {
this.x = x;
this.y = y;
this.radius = 5;
this.speed = 7;
}
draw() {
ctx.fillStyle = 'yellow';
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fill();
}
update() {
this.y -= this.speed;
}
}
// 监听键盘事件
window.addEventListener('keydown', e => {
if (e.code === 'ArrowLeft') {
plane.movingLeft = true;
} else if (e.code === 'ArrowRight') {
plane.movingRight = true;
} else if (e.code === 'Space') {
// 发射子弹,从飞机顶部中间位置
bullets.push(new Bullet(plane.x + plane.width / 2, plane.y));
}
});
window.addEventListener('keyup', e => {
if (e.code === 'ArrowLeft') {
plane.movingLeft = false;
} else if (e.code === 'ArrowRight') {
plane.movingRight = false;
}
});
// 游戏主循环
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
plane.update();
plane.draw();
// 更新和绘制所有子弹
for (let i = bullets.length - 1; i >= 0; i--) {
bullets[i].update();
if (bullets[i].y + bullets[i].radius < 0) {
bullets.splice(i, 1); // 子弹飞出屏幕后移除
} else {
bullets[i].draw();
}
}
requestAnimationFrame(gameLoop);
}
gameLoop();
</script>
</body>
</html>
复制代码
---
### 如何玩
- 打开这个文件(比如双击或者用浏览器打开)
- 用键盘的左箭头和右箭头移动飞机
- 按空格键可以发射子弹
---
### 说明
- 这是一个很简单的开始,没有敌人和碰撞检测。
- 如果想要加敌人、分数等,可以告诉我,我帮你慢慢加上去!
如果你想知道每个部分的作用,我也可以帮你详细解释哦~
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2