简单跳跃小游戏实现
今天给大家分享一个使用 Web 技术栈实现的简单跳跃小游戏,适合初学者学习和参考。
项目结构
本项目包含三个文件:
index.html:定义游戏页面结构。style.css:设置游戏界面样式。game.js:实现游戏逻辑和交互。
代码实现
HTML 文件(index.html)
<!DOCTYPE html>
<html lang="zh-CN">
<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>
<div id="game">
<div id="character"></div>
<div class="block" id="block1"></div>
<div class="block" id="block2"></div>
</div>
<p id="score">得分: 0</p>
<script src="game.js"></script>
</body>
</html>
CSS 文件(style.css)
#game {
width: 800px;
height: 200px;
border: 1px solid black;
margin: auto;
position: relative;
overflow: hidden;
}
#character {
width: 20px;
height: 50px;
background-color: red;
position: relative;
top: 150px;
left: 50px;
}
.block {
width: 20px;
height: 20px;
background-color: blue;
position: relative;
top: 130px;
left: 800px;
}
#score {
text-align: center;
font-family: Arial, sans-serif;
}
JavaScript 文件(game.js)
const character = document.getElementById('character');
const block1 = document.getElementById('block1');
const block2 = document.getElementById('block2');
const scoreElement = document.getElementById('score');
let score = 0;
function jump() {
if (character.classList != 'animate') {
character.classList.add('animate');
}
setTimeout(() => {
character.classList.remove('animate');
}, 500);
}
function addBlockAnimation(block) {
block.classList.add('block-animate');
block.addEventListener('animationiteration', () => {
score++;
scoreElement.textContent = `得分: ${score}`;
});
}
addBlockAnimation(block1);
addBlockAnimation(block2);
setInterval(() => {
const characterTop = parseInt(window.getComputedStyle(character).getPropertyValue('top'));
const block1Left = parseInt(window.getComputedStyle(block1).getPropertyValue('left'));
const block2Left = parseInt(window.getComputedStyle(block2).getPropertyValue('left'));
if ((block1Left < 70 && block1Left > 50 && characterTop >= 130) ||
(block2Left < 70 && block2Left > 50 && characterTop >= 130)) {
alert(`游戏结束!你的得分是: ${score}`);
location.reload();
}
}, 10);
// 添加CSS动画规则
const style = document.createElement('style');
style.textContent = `
#character.animate {
animation: jump 500ms linear;
}
@keyframes jump {
0% {top: 150px;}
30% {top: 100px;}
70% {top: 100px;}
100% {top: 150px;}
}
.block.block-animate {
animation: block 1.5s infinite linear;
}
@keyframes block {
0% {left: 800px;}
100% {left: -20px;}
}
`;
document.head.appendChild(style);
// 监听空格键触发跳跃
document.addEventListener('keydown', (e) => {
if (e.key === ' ' || e.key === 'Spacebar') {
jump();
}
});
运行方式
将上述三个文件放在同一目录下,用浏览器打开 index.html 文件,即可开始游戏。玩家可通过空格键控制角色跳跃,躲避障碍物,游戏结束后会显示得分。