|
|
好呀!我帮你写一个简单的“飞机大战”网页游戏代码,里面有你的飞机,可以用键盘左右移动,还能发射子弹打敌机。这个代码用HTML和JavaScript做的,放到浏览器里就能玩。
下面是完整代码,你可以复制到一个叫`plane.html`的文件里,用浏览器打开就能开始玩啦!
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>简单飞机大战</title>
<style>
body {
margin: 0;
overflow: hidden;
background: black;
}
#gameCanvas {
background: #111;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="600"></canvas>
<script>
// 获取画布和上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const planeWidth = 40;
const planeHeight = 60;
// 玩家飞机对象
const player = {
x: canvas.width / 2 - planeWidth / 2,
y: canvas.height - planeHeight - 10,
width: planeWidth,
height: planeHeight,
speed: 5,
bullets: [],
};
// 敌机数组
let enemies = [];
// 得分
let score = 0;
// 控制按键
const keys = {};
// 发射子弹类
class Bullet {
constructor(x, y){
this.x = x;
this.y = y;
this.width = 5;
this.height = 10;
this.speed = 7;
}
move(){
this.y -= this.speed;
}
draw(){
ctx.fillStyle = 'yellow';
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
// 敌机类
class Enemy {
constructor(x, y, speed){
this.x = x;
this.y = y;
this.width = 40;
this.height = 40;
this.speed = speed;
}
move(){
this.y += this.speed;
}
draw(){
ctx.fillStyle = 'red';
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
// 监听按键
window.addEventListener('keydown', function(e){
keys[e.key] = true;
});
window.addEventListener('keyup', function(e){
keys[e.key] = false;
});
// 发射子弹
function shoot(){
// 子弹从飞机中间上方发射
const bulletX = player.x + player.width/2 - 2.5;
const bulletY = player.y;
player.bullets.push(new Bullet(bulletX, bulletY));
}
// 生成敌机
function createEnemy(){
// 敌机随机x坐标,速度随机
const x = Math.random() * (canvas.width - 40);
const speed = 2 + Math.random() * |
|