写一个 js 的飞机大战
- User
写一个 js 的飞机大战
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
写一个 js 的飞机大战
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
好的,下面是一个简单的 JavaScript 飞机大战游戏示例。这个游戏使用了 HTML Canvas 元素进行绘制,并且包含了以下基本功能:
HTML (index.html):
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-G8">
<title>飞机大战</title>
<style>
body { margin: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; background-color: #f0f0f0; }
canvas { border: 1px solid black; background-color: #333; }
#controls { margin-top: 10px; font-family: sans-serif; }
#scoreBoard { font-size: 1.2em; margin-bottom: 10px; color: #333; }
button { padding: 10px 15px; font-size: 1em; cursor: pointer; }
</style>
</head>
<body>
<div id="scoreBoard">分数: 0 | 生命: 3</div>
<canvas id="gameCanvas" width="480" height="640"></canvas>
<div id="controls">
<p>控制: ← → 移动, Space 开火</p>
<button id="restartButton" style="display:none;">重新开始</button>
</div>
<script src="game.js"></script>
</body>
</html>
JavaScript (game.js):
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreBoard = document.getElementById('scoreBoard');
const restartButton = document.getElementById('restartButton');
let score = 0;
let lives = 3;
let gameRunning = true;
let animationFrameId;
const player = {
x: canvas.width / 2 - 25,
y: canvas.height - 60,
width: 50,
height: 50,
speed: 7,
color: 'skyblue',
bullets: [],
shootCooldown: 0, // 射击冷却计时器
shootInterval: 15 // 射击间隔 (帧)
};
const bullets = [];
const enemies = [];
const keys = {
ArrowLeft: false,
ArrowRight: false,
Space: false
};
// --- 初始化 ---
function initGame() {
score = 0;
lives = 3;
player.x = canvas.width / 2 - player.width / 2;
player.y = canvas.height - player.height - 10;
player.bullets = [];
player.shootCooldown = 0;
bullets.length = 0; // 清空全局子弹数组
enemies.length = 0;
gameRunning = true;
restartButton.style.display = 'none';
updateScoreBoard();
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
gameLoop();
}
// --- 游戏对象绘制 ---
function drawRect(x, y, width, height, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, width, height);
}
function drawPlayer() {
// 简单绘制飞机形状
ctx.fillStyle = player.color;
ctx.beginPath();
ctx.moveTo(player.x + player.width / 2, player.y);
ctx.lineTo(player.x, player.y + player.height);
ctx.lineTo(player.x + player.width, player.y + player.height);
ctx.closePath();
ctx.fill();
}
function drawBullet(bullet) {
drawRect(bullet.x, bullet.y, bullet.width, bullet.height, bullet.color);
}
function drawEnemy(enemy) {
// 简单绘制敌机形状
ctx.fillStyle = enemy.color;
ctx.beginPath();
ctx.moveTo(enemy.x + enemy.width / 2, enemy.y + enemy.height);
ctx.lineTo(enemy.x, enemy.y);
ctx.lineTo(enemy.x + enemy.width, enemy.y);
ctx.closePath();
ctx.fill();
}
// --- 游戏逻辑更新 ---
function updatePlayer() {
if (keys.ArrowLeft && player.x > 0) {
player.x -= player.speed;
}
if (keys.ArrowRight && player.x < canvas.width - player.width) {
player.x += player.speed;
}
if (player.shootCooldown > 0) {
player.shootCooldown--;
}
if (keys.Space && player.shootCooldown === 0) {
bullets.push({
x: player.x + player.width / 2 - 2.5,
y: player.y,
width: 5,
height: 10,
speed: 10,
color: 'yellow'
});
player.shootCooldown = player.shootInterval; // 重置冷却
}
}
function updateBullets() {
for (let i = bullets.length - 1; i >= 0; i--) {
const bullet = bullets[i];
bullet.y -= bullet.speed;
if (bullet.y < 0) {
bullets.splice(i, 1); // 子弹出界则移除
}
}
}
function spawnEnemy() {
if (Math.random() < 0.02 && gameRunning) { // 约每秒生成一个 (基于60FPS)
const size = Math.random() * 20 + 20; // 20-40px
const x = Math.random() * (canvas.width - size);
const speed = Math.random() * 2 + 1; // 1-3 px/frame
enemies.push({
x: x,
y: 0 - size, // 从屏幕上方开始
width: size,
height: size,
speed: speed,
color: `hsl(${Math.random() * 360}, 70%, 50%)` // 随机颜色
});
}
}
function updateEnemies() {
for (let i = enemies.length - 1; i >= 0; i--) {
const enemy = enemies[i];
enemy.y += enemy.speed;
// 敌机与玩家碰撞
if (isColliding(player, enemy)) {
enemies.splice(i, 1);
lives--;
updateScoreBoard();
if (lives <= 0) {
gameOver();
return;
}
// 可以添加一个短暂的无敌时间或闪烁效果
break; // 一次只处理一个碰撞,避免连锁反应
}
if (enemy.y > canvas.height) {
enemies.splice(i, 1); // 敌机出界则移除
// 也可以在这里扣分或减生命
}
}
}
// --- 碰撞检测 ---
function isColliding(rect1, rect2) {
return rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y;
}
function checkCollisions() {
// 子弹与敌机碰撞
for (let i = bullets.length - 1; i >= 0; i--) {
for (let j = enemies.length - 1; j >= 0; j--) {
if (bullets[i] && enemies[j] && isColliding(bullets[i], enemies[j])) {
enemies.splice(j, 1);
bullets.splice(i, 1);
score += 10;
updateScoreBoard();
break; // 子弹已消耗,跳出内层循环
}
}
}
}
// --- UI 更新 ---
function updateScoreBoard() {
scoreBoard.textContent = `分数: ${score} | 生命: ${lives}`;
}
// --- 游戏结束 ---
function gameOver() {
gameRunning = false;
ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'white';
ctx.font = '48px sans-serif';
ctx.textAlign = 'center';
ctx.fillText('游戏结束!', canvas.width / 2, canvas.height / 2 - 30);
ctx.font = '24px sans-serif';
ctx.fillText(`最终得分: ${score}`, canvas.width / 2, canvas.height / 2 + 20);
restartButton.style.display = 'block';
cancelAnimationFrame(animationFrameId); // 停止游戏循环
}
// --- 游戏主循环 ---
function gameLoop() {
if (!gameRunning) return;
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清屏
updatePlayer();
updateBullets();
spawnEnemy();
updateEnemies();
checkCollisions(); // 必须在更新位置之后
drawPlayer();
bullets.forEach(drawBullet);
enemies.forEach(drawEnemy);
if (lives <= 0 && gameRunning) { // 再次检查,以防在updateEnemies中已调用gameOver
gameOver();
}
animationFrameId = requestAnimationFrame(gameLoop);
}
// --- 事件监听 ---
window.addEventListener('keydown', (e) => {
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight' || e.key === ' ') { // 空格键
e.preventDefault(); // 防止页面滚动
keys[e.key === ' ' ? 'Space' : e.key] = true;
}
});
window.addEventListener('keyup', (e) => {
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight' || e.key === ' ') {
keys[e.key === ' ' ? 'Space' : e.key] = false;
}
});
restartButton.addEventListener('click', initGame);
// --- 启动游戏 ---
initGame();
如何运行:
index.html。game.js,并与 index.html 放在同一个文件夹下。index.html 文件。可改进之处:
这个示例提供了一个基本框架,你可以基于此进行扩展和优化,制作出更完善的飞机大战游戏。