写一个前段小游戏
时间: 2023-10-09 09:13:37 浏览: 74
一个小游戏
好的,我可以为您介绍一个非常简单的前端小游戏,名为"打地鼠"。
游戏规则:
1. 界面上有多个洞口,随机出现地鼠。
2. 玩家需要尽快点击地鼠,以获得分数。
3. 时间限制为30秒,时间结束后,获得最高分数的玩家为胜利者。
接下来是游戏的代码实现:
HTML 代码:
```
<div class="game-container">
<div class="score">Score: <span id="score">0</span></div>
<div class="time">Time: <span id="time">30</span></div>
<div class="holes">
<div class="hole hole1"></div>
<div class="hole hole2"></div>
<div class="hole hole3"></div>
<div class="hole hole4"></div>
<div class="hole hole5"></div>
<div class="hole hole6"></div>
</div>
</div>
```
CSS 代码:
```
.game-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.score,
.time {
font-size: 24px;
margin-bottom: 24px;
}
.holes {
display: flex;
justify-content: space-between;
width: 600px;
}
.hole {
width: 100px;
height: 100px;
background-color: #ffe4b5;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 48px;
cursor: pointer;
transition: background-color 0.2s ease-in-out;
}
.hole:hover {
background-color: #ffa500;
}
```
JavaScript 代码:
```
const holes = document.querySelectorAll('.hole');
const scoreBoard = document.querySelector('#score');
const timeBoard = document.querySelector('#time');
let score = 0;
let time = 30;
let isPlaying = false;
function startGame() {
isPlaying = true;
score = 0;
time = 30;
scoreBoard.textContent = score;
timeBoard.textContent = time;
holes.forEach(hole => hole.addEventListener('click', bonk));
countdown();
}
function bonk(e) {
if (!e.isTrusted) return; // 防止作弊
score++;
this.classList.remove('up');
scoreBoard.textContent = score;
}
function randomTime(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
function randomHole(holes) {
const idx = Math.floor(Math.random() * holes.length);
const hole = holes[idx];
if (hole.classList.contains('up')) {
return randomHole(holes);
}
return hole;
}
function peep() {
const time = randomTime(200, 1000);
const hole = randomHole(holes);
hole.classList.add('up');
setTimeout(() => {
hole.classList.remove('up');
if (isPlaying) {
peep();
}
}, time);
}
function countdown() {
const timerId = setInterval(() => {
time--;
timeBoard.textContent = time;
if (time === 0) {
clearInterval(timerId);
isPlaying = false;
alert(`Time's up! Your score: ${score}`);
holes.forEach(hole => hole.removeEventListener('click', bonk));
}
}, 1000);
}
document.querySelector('#start').addEventListener('click', startGame);
```
这个游戏包含了基本的 HTML、CSS 和 JavaScript,玩家可以在浏览器中直接打开游戏进行游玩。通过这个小游戏,您可以学习到如何使用 JavaScript 操作 DOM 元素、事件监听、定时器等基础知识。当然,如果您想要更加复杂的游戏,还需要学习更多的前端技术。
阅读全文