Play a Simple HTML Game - No Instructions Needed!
Play a Simple HTML Game
This is a straightforward game with no instructions. Your objective is simple: reach the end without losing all your lives.
How to Play
Use the arrow keys on your keyboard to move your character. Press the up arrow key to jump. Watch out for obstacles and jump over them to avoid losing a life.
Good luck and have fun!
<!DOCTYPE html>
<html>
<head>
<title>Simple HTML Game</title>
<style>
#player {
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
bottom: 0;
left: 0;
}
.obstacle {
width: 30px;
height: 30px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div id='player'></div>
<script>
var player = document.getElementById('player');
var xPosition = 0;
var yPosition = 0;
var lives = 3;
var obstacles = [
{ x: 200, y: 0 },
{ x: 400, y: 50 },
{ x: 600, y: 100 },
{ x: 800, y: 150 },
];
function drawObstacles() {
for (var i = 0; i < obstacles.length; i++) {
var obstacle = document.createElement('div');
obstacle.classList.add('obstacle');
obstacle.style.left = obstacles[i].x + 'px';
obstacle.style.bottom = obstacles[i].y + 'px';
document.body.appendChild(obstacle);
}
}
drawObstacles();
function movePlayer(event) {
if (event.keyCode == 39) {
// right arrow
xPosition += 10;
player.style.left = xPosition + 'px';
} else if (event.keyCode == 37) {
// left arrow
xPosition -= 10;
player.style.left = xPosition + 'px';
} else if (event.keyCode == 38) {
// up arrow
yPosition += 100;
player.style.bottom = yPosition + 'px';
}
checkCollision();
}
document.addEventListener('keydown', movePlayer);
function checkCollision() {
for (var i = 0; i < obstacles.length; i++) {
if (
xPosition > obstacles[i].x - 50 &&
xPosition < obstacles[i].x + 30 &&
yPosition < obstacles[i].y + 30
) {
lives--;
if (lives == 0) {
alert('Game Over!');
window.location.reload();
}
}
}
}
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnc5 著作权归作者所有。请勿转载和采集!