这是一个基本的HTML5和JavaScript示例,用于创建一个简单的打飞机游戏。这个示例将创建一个画布,允许玩家移动一个飞机并发射子弹,同时飞机会自动生成敌人。请注意,这只是一个非常简单的示例,您可以根据需求扩展和改进它。
<!DOCTYPE html>
<html>
<head>
<title>打飞机游戏</title>
<style>
canvas {
border: 1px solid black;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// 飞机参数
const planeWidth = 50;
const planeHeight = 50;
let planeX = canvas.width / 2 - planeWidth / 2;
const planeY = canvas.height - planeHeight - 10;
const planeSpeed = 5;
// 子弹参数
const bulletWidth = 5;
const bulletHeight = 15;
const bulletSpeed = 5;
let bullets = [];
// 敌人参数
const enemyWidth = 30;
const enemyHeight = 30;
let enemies = [];
function drawPlane() {
ctx.fillStyle = 'blue';
ctx.fillRect(planeX, planeY, planeWidth, planeHeight);
}
function movePlane(event) {
if (event.key === 'ArrowLeft' && planeX > 0) {
planeX -= planeSpeed;
}
if (event.key === 'ArrowRight' && planeX < canvas.width - planeWidth) {
planeX += planeSpeed;
}
}
function drawBullets() {
ctx.fillStyle = 'red';
bullets.forEach(bullet => {
ctx.fillRect(bullet.x, bullet.y, bulletWidth, bulletHeight);
bullet.y -= bulletSpeed;
// 移除超出画布的子弹
if (bullet.y < 0) {
bullets.shift();
}
});
}
function createBullet() {
bullets.push({
x: planeX + planeWidth / 2 - bulletWidth / 2,
y: planeY
});
}
function drawEnemies() {
ctx.fillStyle = 'green';
enemies.forEach(enemy => {
ctx.fillRect(enemy.x, enemy.y, enemyWidth, enemyHeight);
enemy.y += 1;
// 检查是否有子弹命中敌人
bullets.forEach((bullet, bulletIndex) => {
if (bullet.x < enemy.x + enemyWidth &&
bullet.x + bulletWidth > enemy.x &&
bullet.y < enemy.y + enemyHeight &&
bullet.y + bulletHeight > enemy.y) {
// 命中,移除子弹和敌人
bullets.splice(bulletIndex, 1);
enemies.splice(enemies.indexOf(enemy), 1);
}
});
});
}
function createEnemy() {
const x = Math.random() * (canvas.width - enemyWidth);
enemies.push({ x, y: 0 });
}
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlane();
drawBullets();
drawEnemies();
createEnemy();
requestAnimationFrame(gameLoop);
}
document.addEventListener('keydown', movePlane);
document.addEventListener('keydown', event => {
if (event.key === ' ') {
createBullet();
}
});
gameLoop();
</script>
</body>
</html>
这是一个简单的示例,您可以根据需求来添加更多功能,如分数、关卡、不同类型的敌人等。此示例主要用于展示如何创建一个基本的HTML5和JavaScript飞机射击游戏。