JS飞机大战游戏代码示例 - 从零开始
以下是一个简单的飞机大战游戏代码示例,使用HTML、CSS和JavaScript编写:
HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>飞机大战</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="game-container">
<div id="player"></div>
</div>
<script src="game.js"></script>
</body>
</html>
CSS代码:
#game-container {
width: 400px;
height: 500px;
background-color: #ccc;
position: relative;
}
#player {
width: 50px;
height: 50px;
background-image: url('player.png');
position: absolute;
bottom: 0;
left: 175px;
}
JavaScript代码:
var player = document.getElementById('player');
var gameContainer = document.getElementById('game-container');
var gameWidth = gameContainer.clientWidth;
var playerWidth = player.clientWidth;
var playerSpeed = 10;
function movePlayer(event) {
switch(event.keyCode) {
case 37: // left arrow key
if(player.offsetLeft > 0) {
player.style.left = player.offsetLeft - playerSpeed + 'px';
}
break;
case 39: // right arrow key
if(player.offsetLeft < gameWidth - playerWidth) {
player.style.left = player.offsetLeft + playerSpeed + 'px';
}
break;
}
}
document.addEventListener('keydown', movePlayer);
这个游戏非常简单,只有一个玩家飞机,可以左右移动。您可以使用该代码作为基础,并添加其他功能,例如敌人飞机、子弹、分数等。
原文地址: https://www.cveoy.top/t/topic/mEZB 著作权归作者所有。请勿转载和采集!