以下是一个简单的拼图游戏的 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>拼图游戏</title>
<style>
#puzzle-container {
display: grid;
grid-gap: 5px;
margin: 20px;
}
.puzzle-piece {
width: 100px;
height: 100px;
background-size: 400px 400px;
background-repeat: no-repeat;
cursor: pointer;
}
</style>
</head>
<body>
<div id="puzzle-container"></div>
<script>
const imageSrc = 'your-image.jpg';
const rows = 2;
const cols = 2;
const container = document.getElementById('puzzle-container');
let pieces = [];
let emptyPiece = { row: rows - 1, col: cols - 1 };
function createPieces() {
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const piece = document.createElement('div');
piece.classList.add('puzzle-piece');
const offsetX = col * (400 / cols);
const offsetY = row * (400 / rows);
piece.style.backgroundImage = `url(${imageSrc})`;
piece.style.backgroundPosition = `-${offsetX}px -${offsetY}px`;
piece.row = row;
piece.col = col;
piece.addEventListener('click', () => movePiece(piece));
container.appendChild(piece);
pieces.push(piece);
}
}
}
function movePiece(piece) {
if (canMove(piece)) {
[piece.style.backgroundPosition, pieces[emptyPiece.row * cols + emptyPiece.col].style.backgroundPosition] =
[pieces[emptyPiece.row * cols + emptyPiece.col].style.backgroundPosition, piece.style.backgroundPosition];
emptyPiece.row = piece.row;
emptyPiece.col = piece.col;
}
checkWin();
}
function canMove(piece) {
return (Math.abs(piece.row - emptyPiece.row) + Math.abs(piece.col - emptyPiece.col)) === 1;
}
function checkWin() {
for (let i = 0; i < pieces.length - 1; i++) {
const row = Math.floor(i / cols);
const col = i % cols;
const offsetX = col * (400 / cols);
const offsetY = row * (400 / rows);
if (pieces[i].style.backgroundPosition!== `-${offsetX}px -${offsetY}px`) {
return;
}
}
alert('恭喜完成拼图!');
}
createPieces();
</script>
</body>
</html>
这个示例实现了一个简单的 2x2 的拼图游戏:
可能遇到的问题及解决方法:
领取专属 10元无门槛券
手把手带您无忧上云