const scoreElement = document.getElementById('score');
let velocity = 0;
let isJumping = false;
let score = 0;
let platforms = [];
// 初始化游戏
function init() {
createPlatform(170, 100);
gameLoop();
}
// 游戏主循环
function gameLoop() {
velocity += 0.5; // 重力加速度
let currentBottom = parseFloat(player.style.bottom) || 100;
let newBottom = currentBottom - velocity;
// 碰撞检测
platforms.forEach(platform => {
if (checkCollision(platform)) {
velocity = -15; // 跳跃力度
score += 10;
scoreElement.textContent = `得分: ${score}`;
generatePlatform();
}
});
// 更新玩家位置
player.style.bottom = `${newBottom}px`;
// 游戏结束检测
if (newBottom > 667) {
alert(`游戏结束!最终得分: ${score}`);
location.reload();
}
requestAnimationFrame(gameLoop);
}
// 创建新平台
function generatePlatform() {
const lastPlatform = platforms[platforms.length - 1];
const newX = Math.random() * 300;
const newY = lastPlatform.y - 150;
createPlatform(newX, newY);
}
// 绑定空格键事件
document.addEventListener('keydown', (e) => {
if (e.code === 'Space' && !isJumping) {
velocity = -12;
isJumping = true;
setTimeout(() => isJumping = false, 500);
}
});
init();
// 辅助函数
function createPlatform(x, y) {
const platform = document.createElement('div');
platform.className = 'platform';
platform.style.width = '60px';
platform.style.height = '20px';
platform.style.left = `${x}px`;
platform.style.bottom = `${y}px`;
document.querySelector('.game-container').appendChild(platform);
platforms.push({x, y});
}
function checkCollision(platform) {
const playerRect = player.getBoundingClientRect();
const platformRect = document.querySelector('.platform').getBoundingClientRect();
return !(playerRect.right < platformRect.left ||
playerRect.left > platformRect.right ||
playerRect.bottom < platformRect.top ||
playerRect.top > platformRect.bottom);
}
<html>
<head>
<title>跳一跳</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="game-container">
<div id="player"></div>
<div id="score">得分: 0</div>
</div>
<script src="game.js"></script>
</body>
</html>
```body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #f0f0f0;
}
.game-container {
position: relative;
width: 375px;
height: 667px;
background: linear-gradient(135deg, #89f7fe 0%, #66a6ff 100%);
overflow: hidden;
}
#player {
position: absolute;
width: 30px;
height: 30px;
background: #ff4757;
border-radius: 50%;
bottom: 100px;
left: 172px;
transition: transform 0.3s;
}
.platform {
position: absolute;
background: #2ed573;
border-radius: 4px;
}