html拼图游戏代码
时间: 2023-12-26 08:28:34 浏览: 41
以下是一个HTML拼图游戏的代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>拼图游戏</title>
<style>
.puzzle {
display: flex;
flex-wrap: wrap;
width: 300px;
height: 300px;
}
.puzzle div {
width: 100px;
height: 100px;
background-size: 300px 300px;
background-image: url('puzzle.jpg');
border: 1px solid black;
}
</style>
</head>
<body>
<div class="puzzle">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<script>
var puzzle = document.querySelector('.puzzle');
var pieces = puzzle.querySelectorAll('div');
var emptyPiece = pieces[8];
pieces.forEach(function(piece) {
piece.addEventListener('click', function() {
if (isAdjacent(piece, emptyPiece)) {
swapPieces(piece, emptyPiece);
}
});
});
function isAdjacent(piece1, piece2) {
var index1 = Array.from(pieces).indexOf(piece1);
var index2 = Array.from(pieces).indexOf(piece2);
var row1 = Math.floor(index1 / 3);
var col1 = index1 % 3;
var row2 = Math.floor(index2 / 3);
var col2 = index2 % 3;
return (Math.abs(row1 - row2) + Math.abs(col1 - col2)) === 1;
}
function swapPieces(piece1, piece2) {
var temp = piece1.style.order;
piece1.style.order = piece2.style.order;
piece2.style.order = temp;
}
</script>
</body>
</html>
```
这段代码实现了一个九宫格拼图游戏。每个拼图块都是一个`<div>`元素,通过CSS设置了宽度、高度和背景图片。点击两个相邻的拼图块时,它们会交换位置。你可以将图片替换为你喜欢的图片,并根据需要调整拼图的级别和大小。