1
votes

I'm trying to create a Memory Card Game in JavaScript. I'm trying to add a reset button now that allows me to start the whole game again. Any ideas as to how I can flip my cards backward once I've finished the game and matched everything? I appreciate the help. Below is my JS code:

"use strict";

const cards = document.querySelectorAll(".memory-card");

let cardFlipped = false;
let lock = false;
let firstCard, secondCard;

function flip() {
    if(lock) return;
    if(this === firstCard) return;

    this.classList.add("flip");

    if (!cardFlipped) {
        cardFlipped = true;
        firstCard = this;
        return;
    } 
        cardFlipped = false;
        secondCard = this;

        checkMatch();
};

function checkMatch() {
    let isMatch = firstCard.dataset.image === secondCard.dataset.image;
      isMatch ? disable() : unflip();
};

function disable() {
    firstCard.removeEventListener("click", flip);
    secondCard.removeEventListener("click", flip);
    reset();
};

function unflip() {
    lock = true;
    setTimeout(() => {
        firstCard.classList.remove("flip");
        secondCard.classList.remove("flip");
        reset();
    }, 1000);
};

function reset() {
    [cardFlipped, lock] = [false, false];
    [firstCard, secondCard] = [null, null];
};

(function shuffle() {
    cards.forEach(card => {
        let randomPlace = Math.floor(Math.random() * 12);
        card.style.order = randomPlace;
    });
})();

cards.forEach(card => card.addEventListener("click", flip));


document.querySelector(".btn").addEventListener("click", () => {

    cards.forEach(card => {
        card.classList.remove("flip");
    })
});

1
what's wrong with the code you have? does it not work? - Jaromanda X
Why not just re-generate and shuffle an entirely new deck? As for your specific question... without even knowing Javascript but following patterns in your existing code, wouldn't something like cards.forEach(card => card.reset()); be what you're looking for? - paddy

1 Answers

0
votes

You can map through each class with the .memory-card class and then reset its classes.

document.querySelectorAll(".memory-card").forEach((card) => {
  card.classList.remove("flip"); //will make all cards turn back down
});

Also then just set:

cardFlipped = false;
lock = false
firstCard = null;
secondCard = null;

So that you have nothing selected. You may also then shuffle the deck.