Cara Membuat Game Pencocokan Memori

Pertama tama kita siapin file nya 

Sekarang kita buat file index.html

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Game Pencocokan Memori</title>

    <link rel="stylesheet" href="style.css">

</head>

<body>

    <h1>Game Pencocokan Memori</h1>

    <div id="game-board" class="board"></div>

    <script src="games.js"></script>

</body>

</html>

selanjut nya kita buat file style.css
body {

    font-family: 'Arial', sans-serif;

    text-align: center;

    margin: 0;

    display: flex;

    flex-direction: column;

    align-items: center;

    justify-content: center;

    height: 100vh;

    background-color: #04f3e7;

}

h1 {

    color: #333;

}

.board {

    display: grid;

    grid-template-columns: repeat(4, 100px);

    gap: 10px;

}

.card {

    width: 100px;

    height: 100px;

    background-color: #ddd;

    display: flex;

    align-items: center;

    justify-content: center;

    font-size: 1.5em;

    cursor: pointer;

    user-select: none;

}

.matched {

    background-color: #7CFC00; /* LawnGreen */

    cursor: default;

}
Selanjut nya kita buat ile games.js
const cards = [

  "A",

  "G",

  "B",

  "C",

  "H",

  "C",

  "B",

  "D",

  "E",

  "D",

  "E",

  "F",

  "F",

  "G",

  "H",

  "A",

];

let flippedCards = [];

let matchedCards = [];

document.addEventListener("DOMContentLoaded", function () {

  createGameBoard();

});

function createGameBoard() {

  const gameBoard = document.getElementById("game-board");

  cards.forEach((card, index) => {

    const cardElement = document.createElement("div");

    cardElement.classList.add("card");

    cardElement.dataset.index = index;

    cardElement.addEventListener("click", flipCard);

    gameBoard.appendChild(cardElement);

  });

}

function flipCard() {

  const selectedCard = this;

  if (!flippedCards.includes(selectedCard) && flippedCards.length < 2) {

    flippedCards.push(selectedCard);

    selectedCard.innerHTML = cards[selectedCard.dataset.index];

    if (flippedCards.length === 2) {

      setTimeout(checkMatch, 800);

    }

  }

}

function checkMatch() {

  const [card1, card2] = flippedCards;

  const index1 = card1.dataset.index;

  const index2 = card2.dataset.index;

  if (cards[index1] === cards[index2]) {

    card1.classList.add("matched");

    card2.classList.add("matched");

    matchedCards.push(card1, card2);

    if (matchedCards.length === cards.length) {

      alert("Congratulations! You matched all the cards! Please like!");

    }

  } else {

    card1.innerHTML = "";

    card2.innerHTML = "";

  }

  flippedCards = [];

}
Hasil nya akan seperti ini
 
 
 

Related Articles

Comments