帮我用js写一个飞机大战
时间: 2023-06-02 18:04:52 浏览: 78
好的,我会尽力帮您实现这个功能。
以下是一个简单的飞机大战的JavaScript代码示例:
```
// 创建画布
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
// 背景图片
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "background.png";
// 飞机图片
var planeReady = false;
var planeImage = new Image();
planeImage.onload = function () {
planeReady = true;
};
planeImage.src = "plane.png";
// 游戏对象
var plane = {
speed: 256, // 移动速度
x: 0,
y: 0
};
var enemy = {
x: 0,
y: 0
};
var enemiesCaught = 0;
// 处理键盘控制
var keysDown = {};
addEventListener("keydown", function (e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function (e) {
delete keysDown[e.keyCode];
}, false);
// 更新游戏状态
var update = function (modifier) {
if (38 in keysDown) { // 上方向键
plane.y -= plane.speed * modifier;
}
if (40 in keysDown) { // 下方向键
plane.y += plane.speed * modifier;
}
if (37 in keysDown) { // 左方向键
plane.x -= plane.speed * modifier;
}
if (39 in keysDown) { // 右方向键
plane.x += plane.speed * modifier;
}
// 捕获敌机
if (
plane.x <= (enemy.x + 32)
&& enemy.x <= (plane.x + 32)
&& plane.y <= (enemy.y + 32)
&& enemy.y <= (plane.y + 32)
) {
++enemiesCaught;
reset();
}
};
// 重新开始游戏
var reset = function () {
plane.x = canvas.width / 2;
plane.y = canvas.height / 2;
// 随机生成敌机位置
enemy.x = 32 + (Math.random() * (canvas.width - 64));
enemy.y = 32 + (Math.random() * (canvas.height - 64));
};
// 渲染游戏画面
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
if (planeReady) {
ctx.drawImage(planeImage, plane.x, plane.y);
}
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "24px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("敌机已捕获: " + enemiesCaught, 32, 32);
};
// 控制游戏主循环
var main = function () {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
then = now;
requestAnimationFrame(main);
};
// 浏览器兼容性处理
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
// 启动游戏
var then = Date.now();
reset();
main();
```
您可以根据自己的需求修改这个代码,添加更多的游戏元素和特效。希望对您有所帮助!
阅读全文