javascript飞机大战游戏
时间: 2023-08-22 07:05:36 浏览: 94
好的,下面是一个简单的 JavaScript 实现飞机大战游戏的示例,希望能帮到你:
HTML 代码:
```
<html>
<head>
<title>飞机大战游戏</title>
<style>
#game-board {
width: 400px;
height: 600px;
margin: 0 auto;
border: 1px solid #ccc;
position: relative;
}
#player {
width: 50px;
height: 50px;
position: absolute;
bottom: 0;
left: 50%;
margin-left: -25px;
background-color: red;
}
.bullet {
width: 5px;
height: 10px;
position: absolute;
bottom: 50px;
left: 50%;
margin-left: -2px;
background-color: blue;
}
.enemy {
width: 50px;
height: 50px;
position: absolute;
top: -50px;
left: 50%;
margin-left: -25px;
background-color: green;
}
</style>
</head>
<body>
<div id="game-board">
<div id="player"></div>
</div>
<script src="game.js"></script>
</body>
</html>
```
JavaScript 代码:
```
var player = document.getElementById('player');
var gameBoard = document.getElementById('game-board');
var enemies = [];
var bullets = [];
function movePlayer(event) {
if (event.keyCode === 37) {
player.style.left = Math.max(0, player.offsetLeft - 10) + 'px';
} else if (event.keyCode === 39) {
player.style.left = Math.min(gameBoard.offsetWidth - player.offsetWidth, player.offsetLeft + 10) + 'px';
}
}
function createEnemy() {
var enemy = document.createElement('div');
enemy.className = 'enemy';
enemy.style.left = Math.floor(Math.random() * (gameBoard.offsetWidth - enemy.offsetWidth)) + 'px';
gameBoard.appendChild(enemy);
enemies.push(enemy);
}
function moveEnemies() {
for (var i = 0; i < enemies.length; i++) {
var enemy = enemies[i];
enemy.style.top = enemy.offsetTop + 10 + 'px';
if (enemy.offsetTop >= gameBoard.offsetHeight) {
gameBoard.removeChild(enemy);
enemies.splice(i, 1);
i--;
}
}
}
function createBullet() {
var bullet = document.createElement('div');
bullet.className = 'bullet';
bullet.style.left = (player.offsetLeft + player.offsetWidth / 2) + 'px';
gameBoard.appendChild(bullet);
bullets.push(bullet);
}
function moveBullets() {
for (var i = 0; i < bullets.length; i++) {
var bullet = bullets[i];
bullet.style.top = bullet.offsetTop - 10 + 'px';
if (bullet.offsetTop <= 0) {
gameBoard.removeChild(bullet);
bullets.splice(i, 1);
i--;
} else {
for (var j = 0; j < enemies.length; j++) {
var enemy = enemies[j];
if (isCollide(bullet, enemy)) {
gameBoard.removeChild(bullet);
bullets.splice(i, 1);
i--;
gameBoard.removeChild(enemy);
enemies.splice(j, 1);
break;
}
}
}
}
}
function isCollide(a, b) {
var aRect = a.getBoundingClientRect();
var bRect = b.getBoundingClientRect();
return !(
(aRect.bottom < bRect.top) || (aRect.top > bRect.bottom) ||
(aRect.right < bRect.left) || (aRect.left > bRect.right)
);
}
document.addEventListener('keydown', movePlayer);
setInterval(function() {
createEnemy();
}, 1000);
setInterval(function() {
moveEnemies();
moveBullets();
}, 50);
setInterval(function() {
createBullet();
}, 200);
```
这个示例中,我们创建了一个飞机大战游戏的简单版本。玩家通过左右方向键来移动飞机,按空格键发射子弹,敌人会从顶部出现并向下移动,玩家需要尽可能地消灭敌人。
希望这个示例对你有帮助!
阅读全文