JavaScript滑板小游戏:实现点击启动、避免碰撞后自动刷新
修改后完整代码
HTML
<div id="game"> <div id="skate"></div> <div id="rock"></div> </div> <h1 id="score">0</h1> <button id="startBtn">开始游戏</button>
CSS
#score { text-align: center; } #startBtn { display: block; margin: 10px auto; padding: 8px 16px; cursor: pointer; } #game { width: 600px; height: 300px; border: 2px solid black; margin: auto; background-image: url("./background.gif"); background-size: cover; } #skate { height: 75px; width: 75px; top: 220px; position: relative; background-image: url("./skateboard.png"); background-size: cover; } #rock { width: 50px; height: 50px; position: relative; top: 175px; left: 550px; background-image: url("./rock.png"); background-size: cover; animation: rock 1.33s infinite; animation-play-state: paused; } @keyframes rock { 0%{left: 550px;} 100%{left: -50px;} } .jump-animation { animation: jump 0.5s; } @keyframes jump { 0%{top: 225px;} 50%{top: 75px;} 75%{top: 75px;} 100%{top: 225px;} } .rock-active { animation-play-state: running; }
JavaScript
const skate = document.getElementById("skate"); const rock = document.getElementById("rock"); const score = document.getElementById("score"); const startBtn = document.getElementById("startBtn"); let isGameRunning = false; let gameLoop = null; function jump() { skate.classList.add("jump-animation"); setTimeout(() => skate.classList.remove("jump-animation"), 500); } document.addEventListener('keypress', (event) => { if (!isGameRunning) return; if (!skate.classList.contains('jump-animation')) jump(); }) function resetGame() { isGameRunning = false; clearInterval(gameLoop); rock.classList.remove("rock-active"); score.innerText = 0; rock.style.left = '550px'; skate.style.top = '220px'; startBtn.innerText = "开始游戏"; } startBtn.addEventListener('click', () => { resetGame(); isGameRunning = true; startBtn.innerText = "游戏进行中"; rock.classList.add("rock-active"); gameLoop = setInterval(() => { const skateTop = parseInt(window.getComputedStyle(skate).getPropertyValue('top')); const rockLeft = parseInt(window.getComputedStyle(rock).getPropertyValue('left')); score.innerText++; rock.style.display = rockLeft < 0 ? 'none' : ''; if (rockLeft < 50 && rockLeft > 0 && skateTop > 150) { resetGame(); startBtn.innerText = "重新开始"; } }, 50); });
实现效果说明
- 页面加载后障碍物、角色动画、计分逻辑全部处于停止状态,仅可点击开始按钮启动游戏
- 点击开始按钮后,障碍物开始移动、计分正常累加、按键跳跃逻辑生效
- 碰撞触发后自动停止所有游戏逻辑、重置元素状态,按钮显示为「重新开始」,不会刷新页面
- 再次点击按钮可直接开启新一局游戏
内容的提问来源于stack exchange,提问作者James Graham
相关产品推荐
相关产品推荐

