简体   繁体   中英

Creating a simple “Memory” card game. Need to allow only two clicks at a time

I am creating a simple Memory card game. I have the structure and card designs set up with CSS, now I just need to enable the actual playing of the game.

I need to have only two clicks allowed at a time. If the two cards match, the cards are removed. If the two cards don't match, they are "flipped" back over.

...I am only including the first row of the game, even though it is a 4x4 setup.

HTML

<div class="cardHolder">
    <div id="card1" class="card" onClick="revealBlueCard()"></div>
    <div id="card2" class="card" onClick="revealGreenCard()"></div>
    <div id="card3" class="card" onClick="revealGreenCard()"></div>
    <div id="card4" class="card" onClick="revealBlueCard()"></div>
</div>

JAVASCRIPT

    // blue cards
    var card1Ref = document.getElementById("card1");
    var card4Ref = document.getElementById("card4");
    card1Ref.addEventListener("click", revealBlueCard);
    card4Ref.addEventListener("click", revealBlueCard);

    function revealBlueCard(event){
        event.target.style.backgroundColor = "#2155a8";
        event.target.innerHTML = "<p>8</p>";
    }

    // green cards
    var card2Ref = document.getElementById("card2");
    var card3Ref = document.getElementById("card3");
    card2Ref.addEventListener("click", revealGreenCard);
    card3Ref.addEventListener("click", revealGreenCard);

    function revealGreenCard(event){
        event.target.style.backgroundColor = "#3cb260";
        event.target.innerHTML = "<p>3</p>";
    }

I am still very new to Javascript. I am assuming I am using a click event for "card" and applying if statements. I am also wondering if I need to apply data attributes to each card.

Why don't you add classes to the cards like blue class and green class.

CSS:

.blue{
  background: #2155a8;
}

.green{
  background: #3cb260
}

and also use event delegation (try to avoid adding event listeners to each card)

document.querySelector('#cardHolder').addEventListener('click', function(evt){
  var clickedCard = evt.target;
  if(clickedCard.classList.contains('blue'){
    //do whatever for blue card
  } else if(clickedCard.classList.contains('green')){
    //do whatever for green card
  }
});

there's a better way: Use onclick="cardClicked(this)" for all your cards. then in js

function cardClicked(elCard) {
if (elCard.classList.contains('flipped')) {
   return;
}
    // Flip it
    elCard.classList.add('flipped');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM