搜尋
首頁web前端js教程使用 html css 和 js 的益智遊戲

Puzzle game using html css and js

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

HTML CODE:



    <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">


    <!-- 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="/static/imghwm/default1.png" data-src="./j1.png" class="lazy" alt="Piece 1">
</div>
            <div class="puzzle-piece" id="piece-2">
            <img src="/static/imghwm/default1.png" data-src="./j2.png" class="lazy" alt="Piece 2">
</div>
            <div class="puzzle-piece" id="piece-3">
            <img src="/static/imghwm/default1.png" data-src="./j3.png" class="lazy" alt="Piece 3">
</div>
            <div class="puzzle-piece" id="piece-4">
            <img src="/static/imghwm/default1.png" data-src="./j4.png" class="lazy" alt="Piece 4">
</div>
            <div class="puzzle-piece" id="piece-5">
            <img src="/static/imghwm/default1.png" data-src="./j5.png" class="lazy" alt="Piece 5">
</div>
            <div class="puzzle-piece" id="piece-6">
            <img src="/static/imghwm/default1.png" data-src="./j6.png" class="lazy" alt="Piece 6">
</div>
            <div class="puzzle-piece" id="piece-7">
            <img src="/static/imghwm/default1.png" data-src="./j7.png" class="lazy" alt="Piece 7">
</div>
            <div class="puzzle-piece" id="piece-8">
            <img src="/static/imghwm/default1.png" data-src="./j8.png" class="lazy" alt="Piece 8">
</div>
            <div class="puzzle-piece" id="piece-9">
            <img src="/static/imghwm/default1.png" data-src="./j9.png" class="lazy" alt="Piece 9">
</div>
        </div>
        <button id="shuffle-btn">Shuffle</button>
    </div>
    <script src="script.js"></script>




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);

以上是使用 html css 和 js 的益智遊戲的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript數據類型:瀏覽器和nodejs之間是否有區別?JavaScript數據類型:瀏覽器和nodejs之間是否有區別?May 14, 2025 am 12:15 AM

JavaScript核心數據類型在瀏覽器和Node.js中一致,但處理方式和額外類型有所不同。 1)全局對像在瀏覽器中為window,在Node.js中為global。 2)Node.js獨有Buffer對象,用於處理二進制數據。 3)性能和時間處理在兩者間也有差異,需根據環境調整代碼。

JavaScript評論:使用//和 / * * / * / * /JavaScript評論:使用//和 / * * / * / * /May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript:開發人員的比較分析Python vs. JavaScript:開發人員的比較分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

Python vs. JavaScript:選擇合適的工具Python vs. JavaScript:選擇合適的工具May 08, 2025 am 12:10 AM

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript:了解每個的優勢Python和JavaScript:了解每個的優勢May 06, 2025 am 12:15 AM

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

JavaScript的核心:它是在C還是C上構建的?JavaScript的核心:它是在C還是C上構建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript應用程序:從前端到後端JavaScript應用程序:從前端到後端May 04, 2025 am 12:12 AM

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

Python vs. JavaScript:您應該學到哪種語言?Python vs. JavaScript:您應該學到哪種語言?May 03, 2025 am 12:10 AM

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具