输出一个前端小游戏代码
时间: 2024-05-07 14:22:59 浏览: 124
好的,以下是一个简单的打地鼠游戏代码,使用 HTML、CSS、JavaScript 实现:
HTML:
```html
<!DOCTYPE html>
<html>
<head>
<title>打地鼠</title>
<style>
.container {
display: flex;
flex-wrap: wrap;
height: 400px;
width: 400px;
margin: 0 auto;
border: 2px solid black;
border-radius: 5px;
overflow: hidden;
}
.hole {
flex-basis: calc(33.33% - 4px);
height: 100px;
background-color: #8B4513;
border: 2px solid #CD853F;
border-radius: 50%;
position: relative;
transition: all 0.2s ease-in-out;
cursor: pointer;
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
margin: 2px;
}
.hole.active {
background-color: #FF4500;
border-color: #FFA07A;
box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.4);
top: 20px;
}
.score {
text-align: center;
font-size: 24px;
margin-top: 20px;
}
</style>
</head>
<body>
<h1 style="text-align: center;">打地鼠</h1>
<div class="container"></div>
<p class="score">得分:<span>0</span></p>
<script src="script.js"></script>
</body>
</html>
```
CSS:
```css
body {
font-family: Arial, sans-serif;
background-color: #F5DEB3;
}
h1 {
margin-top: 20px;
}
span {
font-weight: bold;
color: #FF4500;
}
```
JavaScript:
```javascript
const holes = document.querySelectorAll('.hole');
const scoreBoard = document.querySelector('.score span');
let lastHole;
let timeUp = false;
let score = 0;
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 === lastHole) {
return randomHole(holes);
}
lastHole = hole;
return hole;
}
function peep() {
const time = randomTime(200, 1000);
const hole = randomHole(holes);
hole.classList.add('active');
setTimeout(() => {
hole.classList.remove('active');
if (!timeUp) {
peep();
}
}, time);
}
function startGame() {
score = 0;
timeUp = false;
scoreBoard.textContent = score;
peep();
setTimeout(() => {
timeUp = true;
}, 10000);
}
function bonk(e) {
if (!e.isTrusted) {
return;
}
score++;
this.classList.remove('active');
scoreBoard.textContent = score;
}
holes.forEach(hole => hole.addEventListener('click', bonk));
```
这个游戏里面有很多值得学习的地方,比如说 DOM 操作、事件监听、CSS 的动画效果等等。希望对你有帮助!
阅读全文