|
|
5#

楼主 |
发表于 2024-7-28 11:06:50
|
只看该作者
好的,我会把代码放在下面:
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>飞机大战</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>飞机大战</h1>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script src="script.js"></script>
</body>
</html>
css:
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #000;
color: #fff;
font-family: Arial, sans-serif;
}
h1 {
margin-bottom: 20px;
}
canvas {
border: 1px solid #fff;
}
js:
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const playerWidth = 50;
const playerHeight = 50;
let playerX = (canvas.width - playerWidth) / 2;
let playerY = canvas.height - playerHeight - 10;
const playerSpeed = 7;
let bullets = [];
let enemies = [];
let score = 0;
document.addEventListener('keydown', movePlayer);
document.addEventListener('keydown', shootBullet);
function movePlayer(e) {
if (e.key === 'ArrowLeft' && playerX > 0) {
playerX -= playerSpeed;
}
if (e.key === 'ArrowRight' && playerX < canvas.width - playerWidth) {
playerX += playerSpeed;
}
}
function shootBullet(e) {
if (e.key === ' ') {
bullets.push({ x: playerX + playerWidth / 2, y: playerY, speed: 10 });
}
}
function drawPlayer() {
ctx.fillStyle = '#00f';
ctx.fillRect(playerX, playerY, playerWidth, playerHeight);
}
function drawBullets() {
ctx.fillStyle = '#ff0';
bullets.forEach((bullet, index) => {
bullet.y -= bullet.speed;
ctx.fillRect(bullet.x, bullet.y, 5, 15);
if (bullet.y < 0) {
bullets.splice(index, 1);
}
});
}
function drawEnemies() {
ctx.fillStyle = '#f00';
enemies.forEach((enemy, index) => {
enemy.y += enemy.speed;
ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
if (enemy.y > canvas.height) {
enemies.splice(index, 1);
gameOver();
}
});
}
function generateEnemies() {
if (Math.random() < 0.02) {
const x = Math.random() * (canvas.width - playerWidth);
enemies.push({ x: x, y: 0, width: 50, height: 50, speed: 3 });
}
}
function detectCollisions() {
bullets.forEach((bullet, bIndex) => {
enemies.forEach((enemy, eIndex) => {
if (bullet.x > enemy.x && bullet.x < enemy.x + enemy.width &&
bullet.y > enemy.y && bullet.y < enemy.y + enemy.height) {
score += 10;
bullets.splice(bIndex, 1);
enemies.splice(eIndex, 1);
}
});
});
enemies.forEach(enemy => {
if (playerX < enemy.x + enemy.width &&
playerX + playerWidth > enemy.x &&
playerY < enemy.y + enemy.height &&
playerY + playerHeight > enemy.y) {
gameOver();
}
});
}
function gameOver() {
alert(`Game Over! Your score is ${score}`);
document.location.reload();
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
drawBullets();
drawEnemies();
detectCollisions();
generateEnemies();
requestAnimationFrame(update);
}
update(); |
|