用html5做一个简易的九宫格拼图小游戏
时间: 2023-09-25 09:12:59 浏览: 170
好的,下面是一个简单的九宫格拼图小游戏的HTML5代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>九宫格拼图</title>
<style>
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
grid-gap: 10px;
margin: 0 auto;
width: 300px;
height: 300px;
background-color: #eee;
padding: 10px;
}
.tile {
background-color: #fff;
background-position: center;
background-size: 300px 300px;
background-repeat: no-repeat;
cursor: pointer;
transition: all 0.3s ease-in-out;
}
.tile:hover {
transform: scale(1.05);
}
</style>
</head>
<body>
<div class="container">
<div class="tile" id="tile1"></div>
<div class="tile" id="tile2"></div>
<div class="tile" id="tile3"></div>
<div class="tile" id="tile4"></div>
<div class="tile" id="tile5"></div>
<div class="tile" id="tile6"></div>
<div class="tile" id="tile7"></div>
<div class="tile" id="tile8"></div>
<div class="tile" id="tile9"></div>
</div>
<script>
let tiles = document.querySelectorAll('.tile');
let emptyTile = document.getElementById('tile9');
//随机打乱拼图
function shuffle() {
let arr = [1, 2, 3, 4, 5, 6, 7, 8];
arr.sort(() => Math.random() - 0.5);
for (let i = 0; i < tiles.length - 1; i++) {
tiles[i].style.backgroundImage = `url(img/${arr[i]}.jpg)`;
}
}
//判断拼图是否完成
function checkWin() {
let ordered = true;
for (let i = 0; i < tiles.length - 1; i++) {
let tileNumber = parseInt(tiles[i].id.slice(4));
if (tileNumber !== i + 1) {
ordered = false;
break;
}
}
if (ordered) {
alert('你赢了!');
}
}
//交换拼图位置
function swapTiles(tile1, tile2) {
let temp = tile1.style.backgroundImage;
tile1.style.backgroundImage = tile2.style.backgroundImage;
tile2.style.backgroundImage = temp;
checkWin();
}
//初始化拼图
function init() {
shuffle();
emptyTile.style.backgroundImage = '';
}
init();
//拼图点击事件处理
tiles.forEach(tile => {
tile.addEventListener('click', function() {
let row1 = parseInt(emptyTile.style.gridRow);
let col1 = parseInt(emptyTile.style.gridColumn);
let row2 = parseInt(tile.style.gridRow);
let col2 = parseInt(tile.style.gridColumn);
if (row1 === row2 && Math.abs(col1 - col2) === 1 ||
col1 === col2 && Math.abs(row1 - row2) === 1) {
swapTiles(tile, emptyTile);
emptyTile = tile;
}
});
});
</script>
</body>
</html>
```
注意:这段代码需要在一个本地服务器上运行,否则图片加载会出现跨域问题。可以使用Node.js的http-server模块来启动一个本地服务器。将上述代码保存为index.html文件,然后在终端中进入该文件所在的目录,执行以下命令即可:
```
npx http-server
```
然后在浏览器中访问http://127.0.0.1:8080即可运行该小游戏。
阅读全文