编写一个html5小游戏:数字游戏
时间: 2023-09-06 19:08:41 浏览: 135
好的,我可以帮你编写一个数字游戏。以下是一个简单的HTML5数字游戏的示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>数字游戏</title>
<style>
body {
background-color: #F5F5F5;
font-family: Arial, sans-serif;
}
h1 {
text-align: center;
color: #333;
}
.container {
margin: 50px auto;
width: 300px;
height: 300px;
background-color: #FFF;
border-radius: 10px;
padding: 20px;
box-shadow: 0px 0px 10px 0px #888;
position: relative;
}
.number {
display: inline-block;
width: 60px;
height: 60px;
background-color: #4CAF50;
color: #FFF;
font-size: 28px;
text-align: center;
line-height: 60px;
border-radius: 50%;
margin: 10px;
cursor: pointer;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.number:hover {
background-color: #3E8E41;
}
.win {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 50px;
color: #4CAF50;
display: none;
}
.reset {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
background-color: #4CAF50;
color: #FFF;
padding: 10px 20px;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
display: none;
}
</style>
</head>
<body>
<h1>数字游戏</h1>
<div class="container">
<div class="number">1</div>
<div class="number">2</div>
<div class="number">3</div>
<div class="number">4</div>
<div class="number">5</div>
<div class="number">6</div>
<div class="number">7</div>
<div class="number">8</div>
<div class="number">9</div>
<div class="win">你赢了!</div>
<button class="reset">重新开始</button>
</div>
<script>
var numbers = document.querySelectorAll('.number');
var win = document.querySelector('.win');
var reset = document.querySelector('.reset');
var shuffle = function() {
var random = Math.floor(Math.random() * 9);
numbers[random].style.order = 9;
for (var i = 0; i < 9; i++) {
if (i !== random) {
numbers[i].style.order = i + 1;
}
}
};
var checkWin = function() {
var order = '';
for (var i = 0; i < 9; i++) {
order += numbers[i].style.order;
}
if (order === '123456789') {
win.style.display = 'block';
reset.style.display = 'block';
}
};
for (var i = 0; i < 9; i++) {
numbers[i].addEventListener('click', function() {
var empty = document.querySelector('.number[style="order: 9;"]');
var current = this;
var emptyOrder = empty.style.order;
var currentOrder = current.style.order;
if (emptyOrder === parseInt(currentOrder) + 3 || emptyOrder === parseInt(currentOrder) - 3 || emptyOrder === parseInt(currentOrder) + 1 && emptyOrder % 3 !== 1 || emptyOrder === parseInt(currentOrder) - 1 && emptyOrder % 3 !== 0) {
empty.style.order = currentOrder;
current.style.order = emptyOrder;
checkWin();
}
});
}
reset.addEventListener('click', function() {
win.style.display = 'none';
reset.style.display = 'none';
for (var i = 0; i < 9; i++) {
numbers[i].style.order = i + 1;
}
shuffle();
});
shuffle();
</script>
</body>
</html>
```
这个游戏是一个数字拼图游戏,玩家需要点击数字方块来移动它们,以使数字按正确的顺序排列。当玩家完成拼图时,会出现一个“你赢了!”的消息,并且可以点击“重新开始”按钮来开始一个新的游戏。
阅读全文