JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

HTML

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

CSS

.card {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10px;
  font-size: 24px;
  font-weight: bold;
  border: 2px solid #333;
  cursor: pointer;
}

.flipped {
  background-color: #eee;
}

.memory-game {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  margin-top: 50px;
}

body {
  font-family: Arial, sans-serif;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
}

JavaScript

const cardsArray = ["A", "B", "C", "D", "E", "F", "G", "H", "A", "B", "C", "D", "E", "F", "G", "H"];
    const memoryGame = document.getElementById("memory-game");

    let cards = shuffle(cardsArray);
    let flippedIndices = [];
    let matchedPairs = [];

    function handleClick(index) {
      if (flippedIndices.length === 1 && flippedIndices[0] === index) return;

      flippedIndices.push(index);

      if (flippedIndices.length === 2) {
        const [firstIndex, secondIndex] = flippedIndices;
        if (cards[firstIndex] === cards[secondIndex]) {
          matchedPairs.push(cards[firstIndex]);
        }
        setTimeout(() => {
          flippedIndices = [];
          renderCards();
        }, 1000);
      } else {
        renderCards();
      }
    }

    function renderCards() {
      memoryGame.innerHTML = "";
      cards.forEach((card, index) => {
        const div = document.createElement("div");
        div.className = `card ${flippedIndices.includes(index) || matchedPairs.includes(card) ? "flipped" : ""}`;
        div.innerText = flippedIndices.includes(index) || matchedPairs.includes(card) ? card : "?";
        div.addEventListener("click", () => handleClick(index));
        memoryGame.appendChild(div);
      });
    }

    function shuffle(array) {
      let shuffledArray = array.slice();
      for (let i = shuffledArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
      }
      return shuffledArray;
    }

    renderCards();