dimanche 1 août 2021

Need help to make that only two cards would be possible to click until they are matched

I'm new to javascript/jquery. I'm trying to create a card match game. Need help to make that only two cards would be possible to click at the time. To prevent clicking while two cards being check if they match.

Tried to give unbind method to an element when there are in total two divs with .open class, but it removes the click event entirely, and to pass the click event back with (.bind('click' function())) doesn't work, because I don't have a function to give as an argument. Is there a way to do it or maybe I could do it differently? Thanks.

$('.card').click(function() {
    $(this).addClass('open flip');
      var numToMatch = $(this).find('.face').text();
      
   if($('.open').length === 2) {
      if($('.open').first().find('.face').text() == $('.open').last().find('.face').text()){
        $('.open').each(function() {
          $(this).removeClass('open').unbind('click');
        });
      } else {
          setTimeout (function(){
          $('.open').each(function() {
              $(this).removeClass('open flip');
            });
          }, 1000);
      };
    };
});
* {
  maring: 0;
  padding: 0;
}

.div-container {
  display: grid;
  grid-template-columns: repeat(3, auto);
  justify-content: center;
  perspective: 500px;
}

.card {
  width: 90px;
  height: 140px;
  margin: 5px;
  display: relative;
  transform-style: preserve-3d;
  transition: transform 0.5s ease-in-out;
}

.card.flip {
   transform: rotateY(180deg);
}

.face {
  width: 100%;
  height: 100%;
  background-color: lightblue;
  transform: rotateY(180deg);
  backface-visibility: hidden;
  transition: transform 500ms ease-in-out;
  display: flex;
  font-size: 5em;
  justify-content: center;
  align-items: center;
}

.back {
  width: 100%;
  height: 100%;
  background-color: green;
  transition: transform 500ms ease-in-out;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='div-container'>
<div class='card'>
  <div class='back'></div>
  <div class='face three'>3</div>
</div>
<div class='card'>
  <div class='back'></div>
  <div class='face one'>1</div>
</div><div class='card'>
  <div class='back'></div>
  <div class='face one'>1</div>
</div><div class='card'>
  <div class='back'></div>
  <div class='face two'>2</div>
</div><div class='card'>
  <div class='back'></div>
  <div class='face two'>2</div>
</div><div class='card'>
  <div class='back'></div>
  <div class='face three'>3</div>
</div>
</div>

Aucun commentaire:

Enregistrer un commentaire