以下是一个简单的JavaScript拼图游戏的源码示例:
HTML部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拼图游戏</title>
<style>
#puzzle-container {
display: grid;
gap: 2px;
width: 300px;
height: 300px;
}
.puzzle-piece {
background-size: cover;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<div id="puzzle-container"></div>
<script src="puzzle.js"></script>
</body>
</html>
JavaScript部分(puzzle.js):
// 拼图相关变量
const container = document.getElementById('puzzle-container');
const rows = 3;
const cols = 3;
let pieces = [];
let emptyPiece = { row: 2, col: 2 };
// 加载图片并创建拼图块
function initPuzzle() {
const img = new Image();
img.src = 'your-image.jpg'; // 这里替换为你的图片路径
img.onload = () => {
const pieceWidth = container.clientWidth / cols;
const pieceHeight = container.clientHeight / rows;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
if (!(row === emptyPiece.row && col === emptyPiece.col)) {
const piece = document.createElement('div');
piece.classList.add('puzzle-piece');
piece.style.backgroundImage = `url(${img.src})`;
piece.style.backgroundPosition = `-${col * pieceWidth}px -${row * pieceHeight}px`;
piece.style.width = `${pieceWidth}px`;
piece.style.height = `${pieceHeight}px`;
piece.row = row;
piece.col = col;
piece.addEventListener('click', () => movePiece(piece));
container.appendChild(piece);
pieces.push(piece);
}
}
}
};
}
// 移动拼图块
function movePiece(piece) {
if ((Math.abs(piece.row - emptyPiece.row) + Math.abs(piece.col - emptyPiece.col)) === 1) {
// 交换位置
[piece.row, emptyPiece.row] = [emptyPiece.row, piece.row];
[piece.col, emptyPiece.col] = [emptyPiece.col, piece.col];
updatePositions();
checkWin();
}
}
// 更新所有拼图块的位置
function updatePositions() {
pieces.forEach(p => {
p.style.backgroundPosition = `-${p.col * (container.clientWidth / cols)}px -${p.row * (container.clientHeight / rows)}px`;
});
}
// 检查是否获胜
function checkWin() {
let win = true;
pieces.forEach(p => {
if (p.row!== Math.floor(pieces.indexOf(p) / cols) || p.col!== pieces.indexOf(p) % cols) {
win = false;
}
});
if (win) {
alert('恭喜你完成拼图!');
}
}
initPuzzle();
基础概念:
优势:
应用场景:
可能遇到的问题及解决方法:
领取专属 10元无门槛券
手把手带您无忧上云