Home  >  Article  >  Web Front-end  >  Puzzle game using html css and js

Puzzle game using html css and js

Susan Sarandon
Susan SarandonOriginal
2024-10-17 16:55:02759browse

Puzzle game using html css and js

https://www.instagram.com/webstreet_code/

HTML CODE:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Jashan's Puzzle Game</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <!-- div.puzzle-piece#piece-$*9>img[src="./j${1}.png" 
    alt="Piece ${1}"] -->
    <div class="puzzle-wrapper">
        <div class="puzzle-container">
            <div class="puzzle-piece" id="piece-1">
            <img src="./j1.png" alt="Piece 1"></div>
            <div class="puzzle-piece" id="piece-2">
            <img src="./j2.png" alt="Piece 2"></div>
            <div class="puzzle-piece" id="piece-3">
            <img src="./j3.png" alt="Piece 3"></div>
            <div class="puzzle-piece" id="piece-4">
            <img src="./j4.png" alt="Piece 4"></div>
            <div class="puzzle-piece" id="piece-5">
            <img src="./j5.png" alt="Piece 5"></div>
            <div class="puzzle-piece" id="piece-6">
            <img src="./j6.png" alt="Piece 6"></div>
            <div class="puzzle-piece" id="piece-7">
            <img src="./j7.png" alt="Piece 7"></div>
            <div class="puzzle-piece" id="piece-8">
            <img src="./j8.png" alt="Piece 8"></div>
            <div class="puzzle-piece" id="piece-9">
            <img src="./j9.png" alt="Piece 9"></div>
        </div>
        <button id="shuffle-btn">Shuffle</button>
    </div>
    <script src="script.js"></script>
</body>
</html>


CSS CODE:

body {
  font-family: "Poppins", sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #121212;
  color: #ffffff;
  margin: 0;
}

.puzzle-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.puzzle-container {
  display: grid;
  grid-template-columns: repeat(3, 100px);
  grid-template-rows: repeat(3, 100px);
  gap: 4px;
  margin-bottom: 20px;
  box-shadow: 0 20px 20px rgba(184, 26, 150, 0.879);
  border-radius: 15px;
  padding: 10px;
  background: #282828;
}

.puzzle-piece {
  position: relative;
  width: 100px;
  height: 100px;
  /* overflow: hidden; */
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(226, 221, 221, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
}

.puzzle-piece img {
  border: 1px solid rgb(86, 10, 84);
  border-radius: 10px;
  width: 100%;
  height: 100%;
  filter: brightness(1) contrast(1);
  /* object-fit: cover; */
}

.puzzle-piece.selected {
  border: 3px solid white;
  transform: scale(1.05);
}

.puzzle-piece:hover {
  box-shadow: 0 6px 12px rgba(255, 255, 255, 0.2);
}

#shuffle-btn {
  padding: 12px 25px;
  background-color: #e71d96;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s, box-shadow 0.3s;
}

#shuffle-btn:hover {
  background-color: #8c0a83;
  box-shadow: 0 4px 8px rgba(0, 255, 204, 0.3);
}


JS CODE

let firstSelectedPiece = null;
let secondSelectedPiece = null;

// Initialize puzzle pieces array
const pieces = Array.from(document.querySelectorAll('.puzzle-piece'));
let shuffled = false;

// Shuffle function
// Shuffle function
function shufflePuzzle() {
    // Create a new array to hold shuffled pieces
    const shuffledPieces = pieces.slice(); // Copy the original pieces array

    // Shuffle the array using Fisher-Yates shuffle algorithm
    for (let i = shuffledPieces.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [shuffledPieces[i], shuffledPieces[j]] = [shuffledPieces[j], shuffledPieces[i]]; // Swap elements
    }

    // Re-insert shuffled pieces into the puzzle container
    const puzzleContainer = document.querySelector('.puzzle-container');
    shuffledPieces.forEach(piece => {
        puzzleContainer.appendChild(piece); // Append shuffled pieces to the container
    });

    shuffled = true; // Mark as shuffled
}


// Swap two selected pieces
function swapPieces(piece1, piece2) {
    setTimeout(() => {
        // Swap the images instead of text content
        const img1 = piece1.querySelector('img').src;
        const img2 = piece2.querySelector('img').src;

        piece1.querySelector('img').src = img2; // Set piece1's img to piece2's img
        piece2.querySelector('img').src = img1; // Set piece2's img to piece1's img

        piece1.classList.remove('selected');
        piece2.classList.remove('selected');

        firstSelectedPiece = null;
        secondSelectedPiece = null;

        checkCompletion();
    }, 300);  // Delay of 300ms for a smoother swap animation
}

// Check if puzzle is completed
function checkCompletion() {
    // Get the current order of images by their src attributes
    const currentOrder = Array.from(document.querySelectorAll('img')).map(img => img.src);


    console.log("currentorderis:", currentOrder)

    // Define the correct order of the images
    const correctOrder = [
        'http://127.0.0.1:5500/htmlcss/j1.png',
        'http://127.0.0.1:5500/htmlcss/j2.png',
        'http://127.0.0.1:5500/htmlcss/j3.png',
        'http://127.0.0.1:5500/htmlcss/j4.png',
        'http://127.0.0.1:5500/htmlcss/j5.png',
        'http://127.0.0.1:5500/htmlcss/j6.png',
        'http://127.0.0.1:5500/htmlcss/j7.png',
        'http://127.0.0.1:5500/htmlcss/j8.png',
        'http://127.0.0.1:5500/htmlcss/j9.png'
    ];

    // Compare the current order with the correct order
    if (JSON.stringify(currentOrder) === JSON.stringify(correctOrder)) {
        setTimeout(() => {
            alert("Congratulations! You completed the puzzle!");
        }, 1000);
    }
}

// Add click event listeners for puzzle pieces
pieces.forEach(piece => {
    piece.addEventListener('click', () => {
        if (!firstSelectedPiece) {
            firstSelectedPiece = piece;
            piece.classList.add('selected');
        } else if (!secondSelectedPiece && piece !== firstSelectedPiece) {
            secondSelectedPiece = piece;
            piece.classList.add('selected');
            swapPieces(firstSelectedPiece, secondSelectedPiece);
        }
    });
});

// Deselect pieces when clicking outside the puzzle
document.addEventListener('click', (event) => {
    if (!event.target.classList.contains('puzzle-piece') && !event.target.closest('.puzzle-piece')) {
        if (firstSelectedPiece) {
            firstSelectedPiece.classList.remove('selected');
            firstSelectedPiece = null;
        }
        if (secondSelectedPiece) {
            secondSelectedPiece.classList.remove('selected');
            secondSelectedPiece = null;
        }
    }
});

// Shuffle the puzzle at the beginning
shufflePuzzle();

// Shuffle button
document.getElementById('shuffle-btn').addEventListener('click', shufflePuzzle);

The above is the detailed content of Puzzle game using html css and js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn