简单的射击游戏代码html
时间: 2023-11-15 13:14:25 浏览: 335
H5幸存的士兵射击游戏.zip
Sure! Here's a simple shooting game code using HTML and JavaScript:
```html
<!DOCTYPE html>
<html>
<head>
<title>Simple Shooting Game</title>
<style>
#game-container {
width: 400px;
height: 400px;
border: 1px solid black;
position: relative;
}
#player {
width: 20px;
height: 20px;
background-color: blue;
position: absolute;
bottom: 0;
}
#bullet {
width: 5px;
height: 10px;
background-color: red;
position: absolute;
}
#target {
width: 30px;
height: 30px;
background-color: green;
position: absolute;
top: 0;
}
</style>
</head>
<body>
<div id="game-container">
<div id="player"></div>
<div id="bullet"></div>
<div id="target"></div>
</div>
<script>
var player = document.getElementById("player");
var bullet = document.getElementById("bullet");
var target = document.getElementById("target");
var playerPos = 0;
var bulletPos = 0;
var targetPos = 0;
function shoot() {
bulletPos = playerPos;
bullet.style.bottom = bulletPos + "px";
setInterval(moveBullet, 10);
}
function moveBullet() {
if (bulletPos > targetPos && bulletPos < targetPos + target.offsetHeight) {
alert("You hit the target!");
clearInterval();
resetGame();
return;
}
if (bulletPos > 400) {
alert("You missed the target!");
clearInterval();
resetGame();
return;
}
bulletPos += 5;
bullet.style.bottom = bulletPos + "px";
}
function movePlayer(event) {
if (event.keyCode === 37) {
playerPos -= 10;
player.style.left = playerPos + "px";
} else if (event.keyCode === 39) {
playerPos += 10;
player.style.left = playerPos + "px";
}
}
function resetGame() {
bullet.style.bottom = "0";
player.style.left = "0";
playerPos = 0;
}
window.addEventListener("keydown", movePlayer);
window.addEventListener("keydown", function(event) {
if (event.keyCode === 32) {
shoot();
}
});
</script>
</body>
</html>
```
You can copy and paste this code into an HTML file and open it in a web browser to play the game. Use the left and right arrow keys to move the player, and press the spacebar to shoot a bullet. The goal is to hit the green target with the bullet.
阅读全文