写一个跳一跳游戏 js
时间: 2023-07-07 17:21:22 浏览: 44
好的,下面是一个简单的跳一跳游戏的 JavaScript 实现:
HTML:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>跳一跳</title>
<style>
#game {
width: 500px;
height: 500px;
border: 1px solid black;
position: relative;
}
#player {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
bottom: 0;
}
#block {
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
bottom: 50px;
left: 200px;
}
</style>
</head>
<body>
<div id="game">
<div id="player"></div>
<div id="block"></div>
</div>
<button onclick="jump()">跳一跳</button>
<script src="game.js"></script>
</body>
</html>
```
JavaScript:
```js
const player = document.getElementById('player');
const block = document.getElementById('block');
let jumping = false;
function jump() {
if (!jumping) {
jumping = true;
let count = 0;
const jumpInterval = setInterval(() => {
const playerBottom = parseInt(getComputedStyle(player).bottom);
const blockLeft = parseInt(getComputedStyle(block).left);
if (count === 15) {
clearInterval(jumpInterval);
let downCount = 0;
const fallInterval = setInterval(() => {
const playerBottom = parseInt(getComputedStyle(player).bottom);
if (playerBottom <= 0) {
clearInterval(fallInterval);
jumping = false;
} else {
player.style.bottom = `${playerBottom - 5}px`;
}
}, 20);
} else if (playerBottom >= 50 && playerBottom <= 100 && blockLeft >= 50 && blockLeft <= 100) {
clearInterval(jumpInterval);
let downCount = 0;
const fallInterval = setInterval(() => {
const playerBottom = parseInt(getComputedStyle(player).bottom);
if (playerBottom <= 0) {
clearInterval(fallInterval);
jumping = false;
} else {
player.style.bottom = `${playerBottom - 5}px`;
}
}, 20);
} else {
player.style.bottom = `${playerBottom + 5}px`;
}
count++;
}, 20);
}
}
```
这个实现中,当点击“跳一跳”按钮时,会触发 `jump` 函数。在 `jump` 函数中,首先判断玩家是否正在跳跃中,如果不是,则将 `jumping` 置为 `true`,并设置一个计数器 `count`,然后每 20 毫秒调整玩家的位置,直到达到跳跃的最高点(即 `count` 等于 15)或者玩家撞到了方块。如果达到了跳跃的最高点,就开始下落,直到玩家落到了地面。如果玩家撞到了方块,也开始下落,直到玩家落到了地面。在跳跃和下落过程中,将玩家的位置通过修改 `bottom` 样式属性来改变。