0

newbie web-developer here, I'm currently creating a memory game where a pair of cards are found the image of that card will show in the pop-out. unfortunately, I encounter this problem where when I flipped a pair of cards it will stop the timer and show the image of the cards in the pop-out but when I resume the game the timer is still stopped. Here is my code:

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

let hasFlippedCard = false;
let lockBoard = false;
let firstCard, secondCard;
let matchCounter=0;
let timerCtrl = null; // store the return value of setInterval

function flipCard() {
  if (lockBoard) return;
  if (this === firstCard) return;

  this.classList.add('flip');

  if (!hasFlippedCard) {
    hasFlippedCard = true;
    firstCard = this;

    return;
  }

  secondCard = this;
  checkForMatch();
}

function checkForMatch() {
  let isMatch = firstCard.dataset.framework === secondCard.dataset.framework;
  if(isMatch){
      matchCounter+=1;
      disableCards();
      Swal.fire({
        html:
          '<a href="//sweetalert2.github.io">links</a> ',
        imageUrl: 'https://unsplash.it/400/200',
        imageWidth:150,
        imageHeight: 150,
        imageAlt: 'Custom image',
        confirmButtonText: 'Resume Game',
        allowOutsideClick: false
        
      })

        clearInterval(timerCtrl); 
          if(matchCounter==(cards.length/2)){
            Swal.fire({
              title: 'Congratualtions!!!',
              text: 'You finish the game '+ counterVal +' Moves. Thank you for playing',
              allowOutsideClick: false
            })
            setTimeout(timerCtrl, 1000); // it will stop the timer
            }
        }
          else{ unflipCards(); }

  
}

function disableCards() {
  firstCard.removeEventListener('click', flipCard);
  secondCard.removeEventListener('click', flipCard);

  resetBoard();
}

function unflipCards() {
  lockBoard = true;

  setTimeout(() => {
    firstCard.classList.remove('flip');
    secondCard.classList.remove('flip');

    resetBoard();
  }, 500);
}

function resetBoard() {
  hasFlippedCard = false;
  lockBoard = false;
  firstCard = null;
  secondCard = null;
 
  
}

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

cards.forEach(card => card.addEventListener('click', flipCard));

function restartButton(){
  location.reload();
}
var i = 0;
function timer(id){
if(id == '1'){
  i++;
  if(i === 1){
    time();
  }
}else if(id=='2'){
  //dri nimo e butang ang pause nga function
}else if(id == '3'){
  //function for continue time
}
}

var numr = 0;
function countClick(){
  numr ++;
  console.log(numr);
}

/*Timer*/
 
function time(){
 
  // var target = document.getElementsById("back");
  // target.removeAttribute("onclick");
  var minutesLabel = document.getElementById("minutes");
  var secondsLabel = document.getElementById("seconds");
  var totalSeconds = 0;
  timerCtrl = setInterval(setTime, 1000);
  
  function setTime() {
    ++totalSeconds;
    secondsLabel.innerHTML = pad(totalSeconds % 60);
    minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
  }
  
  function pad(val) {
    var valString = val + "";
    if (valString.length < 2) {
      return "0" + valString;
    } else {
      return valString;
    }
  }
}

var counterVal = 0;

function incrementClick(){
  updateDisplay(++counterVal);
}
function resetCounter(){
  counterVal = 0;
  updateDisplay(counterVal);
}
function updateDisplay(val){
  document.getElementById("counter-label").innerHTML = val;
}
* {
  margin: 0;
  box-sizing: border-box;
}

body {
  background: url('https://github.com/FoxyStoat/memory-game/blob/master/assets/img/ignasi_pattern_s.png?raw=true');
  ;
}
h1{
  font-weight: 400;
  text-shadow: 1px 1px 2px rgba(80, 80, 80, 0.6);
}

.container{
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.memory-game {
  width: 340px;
  height: 340px;
  display: flex;
  flex-wrap: wrap;
  perspective: 100%;
  margin:5px;
}

.memory-card {
  width: calc(25% - 10px);
  height: calc(33.333% - 10px);
  margin:5px;
  /* position: relative; */
  /* transform: scale(1); */
  transform-style: preserve-3d;
  transition: transform .5s;
  box-shadow: 1px 1px 1px rgba(0,0,0,.3);
}

.memory-card:active {
  transform: scale(0.97);
  transition: transform .2s;
}

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

.front-face,
.back-face {
  width: 100%;
  height: 100%;
  /* padding: 1px; */
  position: absolute;
  /* border-radius: 5px; */
  /* background: #1C7CCC; */
  backface-visibility: hidden;
}

.front-face {
  transform: rotateY(180deg);
}

.score-panel {
  text-align: left;
  width: 270px;
  margin-bottom: 10px;
  color: #0d0d0e;
}

.score-panel .stars {
  margin: 0;
  padding: 0;
  display: inline-block;
  margin: 0 5px 0 0;
  color: rgb(24, 23, 23);
}

.score-panel .stars li {
  list-style: none;
  display: inline-block;
}

.score-panel .timer {
  display: inline;
  position: absolute;
  left: 50%;
}

.score-panel .restart {
  float: right;
  cursor: pointer;
}


@media only screen  and (min-device-width: 768px)
  and (max-device-width: 1024px){
     .memory-game{
      width: 860px;
      min-height: 880px;


    }
}
@media only screen
  and (min-device-width: 375px)
  and (max-device-width: 812px) {
    .memory-game{
      width: 860px;
      min-height: 880px;


    }
  }

@media only screen
  and (min-device-width: 320px)
  and (max-device-width: 568px) {
    .memory-game{
      width: 860px;
      min-height: 880px;


    }
  }

  .swal-wide{
    width:850px !important;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">

<title>Memory Game</title>
<link rel = "stylesheet" href ="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet prefetch" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
<link rel="stylesheet prefetch" href="https://fonts.googleapis.com/css?family=Coda">
<link rel="stylesheet prefetch" href="https://fonts.googleapis.com/css?family=Coda">
<link rel="stylesheet prefetch" href="https://fonts.googleapis.com/css?family=Gloria+Hallelujah|Permanent+Marker" >
<link href="<?php echo base_url();?>resources/dist/css/style.css" rel="stylesheet">
</head>
<body>
<div class = "container">
  <h1>Memory Game</h1>
  <section class="score-panel">
            <!-- <ul class="stars">
                <li><i class="fa fa-star"></i></li>
                <li><i class="fa fa-star"></i></li>
                <li><i class="fa fa-star"></i></li>
            </ul> -->

            <span>Moves <span id = "counter-label">0</span></span>

            <div class="timer">
                <label id="minutes">00</label>:<label id="seconds">00</label>
            </div>

            <div class="restart">
                <button onclick="restartButton()" class="fa fa-repeat"></button>
            <!-- <div class="col text-center">
                <button button type = "button" class = "btn btn-danger">Reset</button>
            </div> -->
            </div>
        </section>
        <?php include("header.php")?>

  <div class="memory-game ">
    <div class="memory-card" data-framework="aurelia">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/fb.png" class = "img-fluid"alt="fb" />
      <img onclick = "incrementClick(); timer('1');" id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" />
    </div>

    <div class="memory-card" data-framework="aurelia">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/fb.png" class = "img-fluid"alt="fb" />
      <img onclick = "incrementClick(); timer('1');" id = "back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" />
    </div>

    <div class="memory-card" data-framework="vue">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/js.jpg" class = "img-fluid"alt="js" />
      <img onclick = "incrementClick(); timer('1');" id = "back"id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" />
    </div>
              
    <div class="memory-card" data-framework="vue">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/js.jpg" class = "img-fluid"alt="js" />
      <img onclick = "incrementClick(); timer('1');" id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" />
    </div>

    <!-- <div class="memory-card" data-framework="angular">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/pikachu.jpg" class = "img-fluid"alt="pika" />
      <img onclick = "incrementClick(); timer('1');" id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" />
    </div>

    <div class="memory-card" data-framework="angular">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/pikachu.jpg" class = "img-fluid"alt="pika" />
      <img onclick = "incrementClick(); timer('1');" id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" />
    </div>

    <div class="memory-card" data-framework="ember">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/spider.png" class = "img-fluid"alt="spider" />
      <img onclick = "incrementClick(); timer('1');" class="back-face"  src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" />
    </div>

    <div class="memory-card" data-framework="ember">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/spider.png" class = "img-fluid"alt="spider" />
      <img onclick = "incrementClick(); timer('1');" id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" />
    </div>

    <div class="memory-card" data-framework="backbone">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/lion.jpg" class = "img-fluid"alt="lotus" />
      <img onclick = "incrementClick(); timer('1');"id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" />
    </div>

    <div class="memory-card" data-framework="backbone">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/lion.jpg" class = "img-fluid"alt="lion" />
      <img onclick = "incrementClick(); timer('1'); "id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" />
    </div>

    <div class="memory-card" data-framework="react">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/fairy_tail.png" alt="fairy_tail" />
      <img onclick = "incrementClick();timer('1');" id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"alt="yugioh" />
    </div>

    <div class="memory-card" data-framework="react">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/fairy_tail.png" class = "img-fluid"alt="fairy_tail" />
      <img onclick = "incrementClick(); timer('1');"id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"xalt="yugioh" />
    </div>

    <div class="memory-card" data-framework="ben10">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/ben10.png" class = "img-fluid"alt="fairy_tail" />
      <img onclick = "incrementClick(); timer('1');"id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"xalt="yugioh" />
    </div>

    <div class="memory-card" data-framework="ben10">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/ben10.png" class = "img-fluid"alt="fairy_tail" />
      <img onclick = "incrementClick(); timer('1');"id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"xalt="yugioh" />
    </div>

    <div class="memory-card" data-framework="ragnarok">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/ragnarok.png" class = "img-fluid"alt="fairy_tail" />
      <img onclick = "incrementClick(); timer('1');"id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"xalt="yugioh" />
    </div>

    <div class="memory-card" data-framework="ragnarok">
      <img class="front-face" src="<?php echo base_url();?>/resources/dist/img/ragnarok.png" class = "img-fluid"alt="fairy_tail" />
      <img onclick = "incrementClick(); timer('1');"id="back" class="back-face" src="<?php echo base_url();?>/resources/dist/img/card.png" class = "img-fluid"xalt="yugioh" />
    </div> -->
            
  </div> 

</div>  

  
          <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <script src = "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"></script>
        <script src ="<?php echo base_url();?>resources/dist/js/script.js"></script>
        <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    </body>
</html>

by the way, I used Codeigniter 3, bootstrap, and javascript for this project. Thank you in advance for answering i appreciate your help.

Vasco Wayne
  • 75
  • 1
  • 6
  • The question has too much code to go through, just wondering why you need to use settimeout and other control at all. – vaira Nov 24 '21 at 06:14
  • at first, my professor want to add a timer to the game so I put a timer in it. now he wants the game to pause when a pair of cards are found and timer resume when a card is click/flipped – Vasco Wayne Nov 24 '21 at 06:19
  • You can't resume a timer and then restore it, you've to make a new timer. – Teemu Nov 24 '21 at 06:21
  • can you recommend me something to watch or read so that i can alter my code? – Vasco Wayne Nov 24 '21 at 06:26
  • https://stackoverflow.com/questions/3969475/javascript-pause-settimeout – vaira Nov 24 '21 at 06:31

1 Answers1

0

For your case you can make it so that after the alert is confirmed (resume is clicked) you start a new timer:

Swal.fire({
  imageWidth: 150,
  imageHeight: 150,
  imageAlt: 'Custom image',
  confirmButtonText: 'Resume Game',
  allowOutsideClick: false,
}).then(() => {
  time()
})

Also initilize totalSeconds outside of the time() function so that when you call it again the game time does not get reset to 0.

Here is a working example:

const cards = document.querySelectorAll('.memory-card')

let hasFlippedCard = false
let lockBoard = false
let firstCard, secondCard
let matchCounter = 0
let timerCtrl = null // store the return value of setInterval

function flipCard() {
  if (lockBoard) return
  if (this === firstCard) return

  this.classList.add('flip')

  if (!hasFlippedCard) {
    hasFlippedCard = true
    firstCard = this

    return
  }

  secondCard = this
  checkForMatch()
}

function checkForMatch() {
  let isMatch = firstCard.dataset.framework === secondCard.dataset.framework
  if (isMatch) {
    matchCounter += 1
    disableCards()
    Swal.fire({
      imageWidth: 150,
      imageHeight: 150,
      imageAlt: 'Custom image',
      confirmButtonText: 'Resume Game',
      allowOutsideClick: false,
    }).then(() => {
      time()
    })

    clearInterval(timerCtrl)
    if (matchCounter == cards.length / 2) {
      Swal.fire({
        title: 'Congratualtions!!!',
        text: 'You finish the game ' +
          counterVal +
          ' Moves. Thank you for playing',
        allowOutsideClick: false,
      })
      setTimeout(timerCtrl, 1000) // it will stop the timer
    }
  } else {
    unflipCards()
  }
}

function disableCards() {
  firstCard.removeEventListener('click', flipCard)
  secondCard.removeEventListener('click', flipCard)

  resetBoard()
}

function unflipCards() {
  lockBoard = true

  setTimeout(() => {
    firstCard.classList.remove('flip')
    secondCard.classList.remove('flip')

    resetBoard()
  }, 500)
}

function resetBoard() {
  hasFlippedCard = false
  lockBoard = false
  firstCard = null
  secondCard = null
}

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

cards.forEach(card => card.addEventListener('click', flipCard))

function restartButton() {
  location.reload()
}
var i = 0

function timer(id) {
  if (id == '1') {
    i++
    if (i === 1) {
      time()
    }
  } else if (id == '2') {
    //dri nimo e butang ang pause nga function
  } else if (id == '3') {
    //function for continue time
  }
}

var numr = 0

function countClick() {
  numr++
  console.log(numr)
}


var minutesLabel = document.getElementById('minutes')
var secondsLabel = document.getElementById('seconds')
var totalSeconds = 0

/*Timer*/
function time() {
  function setTime() {
    ++totalSeconds
    secondsLabel.innerHTML = pad(totalSeconds % 60)
    minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60))
  }

  function pad(val) {
    var valString = val + ''
    if (valString.length < 2) {
      return '0' + valString
    } else {
      return valString
    }
  }
  timerCtrl = setInterval(setTime, 1000)
}

var counterVal = 0

function incrementClick() {
  updateDisplay(++counterVal)
}

function resetCounter() {
  counterVal = 0
  updateDisplay(counterVal)
}

function updateDisplay(val) {
  document.getElementById('counter-label').innerHTML = val
}
* {
  margin: 0;
  box-sizing: border-box;
}

body {
  background: url('https://github.com/FoxyStoat/memory-game/blob/master/assets/img/ignasi_pattern_s.png?raw=true');
}

h1 {
  font-weight: 400;
  text-shadow: 1px 1px 2px rgba(80, 80, 80, 0.6);
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.memory-game {
  width: 340px;
  height: 340px;
  display: flex;
  flex-wrap: wrap;
  perspective: 100%;
  margin: 5px;
}

.memory-card {
  width: calc(25% - 10px);
  height: calc(33.333% - 10px);
  margin: 5px;
  /* position: relative; */
  /* transform: scale(1); */
  transform-style: preserve-3d;
  transition: transform 0.5s;
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.3);
}

.memory-card:active {
  transform: scale(0.97);
  transition: transform 0.2s;
}

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

.front-face,
.back-face {
  width: 100%;
  height: 100%;
  /* padding: 1px; */
  position: absolute;
  /* border-radius: 5px; */
  /* background: #1C7CCC; */
  backface-visibility: hidden;
}

.front-face {
  transform: rotateY(180deg);
}

.score-panel {
  text-align: left;
  width: 270px;
  margin-bottom: 10px;
  color: #0d0d0e;
}

.score-panel .stars {
  margin: 0;
  padding: 0;
  display: inline-block;
  margin: 0 5px 0 0;
  color: rgb(24, 23, 23);
}

.score-panel .stars li {
  list-style: none;
  display: inline-block;
}

.score-panel .timer {
  display: inline;
  position: absolute;
  left: 50%;
}

.score-panel .restart {
  float: right;
  cursor: pointer;
}

@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  .memory-game {
    width: 860px;
    min-height: 880px;
  }
}

@media only screen and (min-device-width: 375px) and (max-device-width: 812px) {
  .memory-game {
    width: 860px;
    min-height: 880px;
  }
}

@media only screen and (min-device-width: 320px) and (max-device-width: 568px) {
  .memory-game {
    width: 860px;
    min-height: 880px;
  }
}

.swal-wide {
  width: 850px !important;
}
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<div class="container">
  <h1>Memory Game</h1>
  <section class="score-panel">
    <span>Moves <span id="counter-label">0</span></span>

    <div class="timer">
      <label id="minutes">00</label>:<label id="seconds">00</label>
    </div>

    <div class="restart">
      <button onclick="restartButton()" class="fa fa-repeat">Restart</button>
    </div>
  </section>
  <?php include("header.php")?>
  <div class="memory-game">
    <div class="memory-card" data-framework="aurelia">
      <img class="front-face" src="https://www.gravatar.com/avatar/b0ded36026e886f443a5a5adf371c493?s=48&d=identicon&r=PG" class="img-fluid" alt="fb" />
      <img onclick="incrementClick(); timer('1');" id="back" class="back-face" src="https://i.stack.imgur.com/kyqmB.jpg?s=64&g=1" class="img-fluid" alt="yugioh" />
    </div>
    <div class="memory-card" data-framework="aurelia">
      <img class="front-face" src="https://www.gravatar.com/avatar/b0ded36026e886f443a5a5adf371c493?s=48&d=identicon&r=PG" class="img-fluid" alt="fb" />
      <img onclick="incrementClick(); timer('1');" id="back" class="back-face" src="https://i.stack.imgur.com/kyqmB.jpg?s=64&g=1" class="img-fluid" alt="yugioh" />
    </div>
    <div class="memory-card" data-framework="vue">
      <img class="front-face" src="https://lh3.googleusercontent.com/a/AATXAJyjNLYmp4jfrFYKH3rIl_FxI-lAoVkYLfSZdJqW=k-s64" class="img-fluid" alt="js" />
      <img onclick="incrementClick(); timer('1');" id="back" id="back" class="back-face" src="https://i.stack.imgur.com/kyqmB.jpg?s=64&g=1" class="img-fluid" alt="yugioh" />
    </div>

    <div class="memory-card" data-framework="vue">
      <img class="front-face" src="https://lh3.googleusercontent.com/a/AATXAJyjNLYmp4jfrFYKH3rIl_FxI-lAoVkYLfSZdJqW=k-s64" class="img-fluid" alt="js" />
      <img onclick="incrementClick(); timer('1');" id="back" class="back-face" src="https://i.stack.imgur.com/kyqmB.jpg?s=64&g=1" class="img-fluid" alt="yugioh" />
    </div>
  </div>
</div>
aerial
  • 1,188
  • 3
  • 7
  • 15