html益智游戏拼图游戏源代码
以下是一个简单的HTML和JavaScript代码示例,用于创建一个网页上的拼图游戏。这个示例使用了一个简单的9块图片的拼图游戏,并假设所有图片都已经预先排列好,并隐藏在HTML中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Puzzle Game</title>
<style>
.puzzle-container {
width: 300px;
height: 300px;
position: relative;
user-select: none;
}
.puzzle-piece {
position: absolute;
width: 100px;
height: 100px;
image-rendering: pixelated;
}
</style>
</head>
<body>
<div class="puzzle-container" id="puzzleContainer">
<img class="puzzle-piece" src="piece1.png" data-position="0">
<img class="puzzle-piece" src="piece2.png" data-position="1">
<img class="puzzle-piece" src="piece3.png" data-position="2">
<img class="puzzle-piece" src="piece4.png" data-position="3">
<img class="puzzle-piece" src="piece5.png" data-position="4">
<img class="puzzle-piece" src="piece6.png" data-position="5">
<img class="puzzle-piece" src="piece7.png" data-position="6">
<img class="puzzle-piece" src="piece8.png" data-position="7">
<img class="puzzle-piece" src="piece9.png" data-position="8">
</div>
<script>
const puzzleContainer = document.getElementById('puzzleContainer');
const pieces = document.querySelectorAll('.puzzle-piece');
const numPieces = pieces.length;
const blankIndex = numPieces - 1;
// Shuffle the pieces
const shuffle = (arr) => {
let currentIndex = arr.length;
while (0 !== currentIndex) {
let randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[arr[currentIndex], arr[randomIndex]] = [
arr[randomIndex], arr[currentIndex]];
}
return arr;
};
// Move a piece
const movePiece = (piece, position) => {
piece.style.left = `${position % 3 * 100}px`;
piece.style.top = `${Math.floor(position / 3) * 100}px`;
};
// Setup the puzzle
const setupPuzzle = () => {
const shuffledPieces = shuffle([...pieces]);
puzzleContainer.append(...shuffledPieces);
shuffledPieces[blankIndex].style.visibility = 'hidden';
};
// Check if the puzzle is solved
const checkSolved = () => {
return [...pieces].every((piece, index) => piece.getAttribute('data-position') === index);
};
// Handle piece drag
pieces.forEach((piece, index) => {
piece.addEventListener('dragstart', (e) => {
e.dataTransfer.setData('text/plain', '');
});
piece.addEventListener('drag',
评论已关闭