JavaScript拼图小游戏是一种基于浏览器的互动游戏,玩家需要通过拖拽或点击来重新排列打乱的图片碎片,以完成整张图片的拼接。下面是一个简单的JavaScript拼图小游戏的源码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拼图小游戏</title>
<style>
#puzzle-container {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-gap: 5px;
}
.puzzle-piece {
width: 100px;
height: 100px;
background-size: cover;
background-position: center;
cursor: pointer;
}
</style>
</head>
<body>
<div id="puzzle-container"></div>
<script src="puzzle.js"></script>
</body>
</html>
const container = document.getElementById('puzzle-container');
const pieces = [];
let emptyPiece = { x: 2, y: 2 }; // 初始空白块的位置
// 初始化拼图
function initPuzzle() {
const img = new Image();
img.src = 'path/to/your/image.jpg'; // 替换为你的图片路径
img.onload = () => {
const pieceWidth = img.width / 3;
const pieceHeight = img.height / 3;
for (let y = 0; y < 3; y++) {
for (let x = 0; x < 3; x++) {
const piece = document.createElement('div');
piece.classList.add('puzzle-piece');
piece.style.backgroundImage = `url(${img.src})`;
piece.style.backgroundPosition = `-${x * pieceWidth}px -${y * pieceHeight}px`;
piece.onclick = () => movePiece(x, y);
container.appendChild(piece);
pieces.push({ x, y, element: piece });
}
}
shufflePieces();
};
}
// 打乱拼图块
function shufflePieces() {
for (let i = pieces.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[pieces[i], pieces[j]] = [pieces[j], pieces[i]];
pieces[i].style.order = i;
pieces[j].style.order = j;
}
emptyPiece = { x: 2, y: 2 };
}
// 移动拼图块
function movePiece(x, y) {
if ((Math.abs(emptyPiece.x - x) === 1 && emptyPiece.y === y) ||
(Math.abs(emptyPiece.y - y) === 1 && emptyPiece.x === x)) {
pieces.find(p => p.x === emptyPiece.x && p.y === emptyPiece.y).element.style.order = pieces.findIndex(p => p.x === x && p.y === y);
pieces.find(p => p.x === x && p.y === y).element.style.order = pieces.findIndex(p => p.x === emptyPiece.x && p.y === emptyPiece.y);
[emptyPiece.x, emptyPiece.y] = [x, y];
checkWin();
}
}
// 检查是否完成拼图
function checkWin() {
for (let i = 0; i < pieces.length; i++) {
if (pieces[i].x !== Math.floor(i / 3) || pieces[i].y !== i % 3) return;
}
alert('恭喜你完成了拼图!');
}
initPuzzle();
checkWin
函数正确判断了所有拼图块的位置。通过以上代码和解释,你可以创建一个基本的JavaScript拼图小游戏,并理解其背后的概念和技术。
领取专属 10元无门槛券
手把手带您无忧上云