以下是一个简单的 9×9 拼图游戏的 JavaScript 源代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>9×9 拼图游戏</title>
<style>
#puzzle {
display: grid;
grid-template-columns: repeat(9, 50px);
grid-gap: 2px;
}
.piece {
width: 50px;
height: 50px;
background-color: #f0f0f0;
border: 1px solid #ccc;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
</style>
</head>
<body>
<div id="puzzle"></div>
<script>
const puzzleSize = 9;
const totalPieces = puzzleSize * puzzleSize;
let pieces = [];
// 生成拼图块
for (let i = 0; i < totalPieces; i++) {
const piece = document.createElement('div');
piece.classList.add('piece');
piece.textContent = i + 1;
piece.onclick = () => movePiece(piece);
pieces.push(piece);
}
// 打乱拼图块顺序
shuffleArray(pieces);
// 将拼图块添加到页面
const puzzleContainer = document.getElementById('puzzle');
pieces.forEach(piece => puzzleContainer.appendChild(piece));
let emptyPiece = pieces[totalPieces - 1];
// 移动拼图块
function movePiece(piece) {
const emptyIndex = pieces.indexOf(emptyPiece);
const pieceIndex = pieces.indexOf(piece);
if (isAdjacent(emptyIndex, pieceIndex)) {
[pieces[emptyIndex], pieces[pieceIndex]] = [pieces[pieceIndex], pieces[emptyIndex]];
emptyPiece = piece;
renderPuzzle();
}
}
// 判断两个拼图块是否相邻
function isAdjacent(index1, index2) {
const row1 = Math.floor(index1 / puzzleSize);
const col1 = index1 % puzzleSize;
const row2 = Math.floor(index2 / puzzleSize);
const col2 = index2 % puzzleSize;
return (Math.abs(row1 - row2) === 1 && col1 === col2) || (Math.abs(col1 - col2) === 1 && row1 === row2);
}
// 打乱数组顺序
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
// 渲染拼图
function renderPuzzle() {
pieces.forEach(piece => puzzleContainer.appendChild(piece));
}
</script>
</body>
</html>
基础概念:
优势:
类型:
应用场景:
常见问题及解决方法:
isAdjacent
函数。shuffleArray
函数。希望这个示例对你有所帮助!如果你还有其他问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云