3

I've been playing around with this memory game and was wondering how I'd go about limiting a users attempts.

The user in the default game gets their attempts counted and displayed which is also put into a star rating system. They lose a star after X attempts.

When they've matched all cards a congratulatory popup is displayed with their score etc.

I was trying to make it so that if they failed (i.e. lost all 3 stars) it would create a similar popup informing them they lost (game over). As it stands they have unlimited attempts to match the cards.

The game can be found here: https://codepen.io/Digital-Adam/pen/xJyvrL

The bit I added recently to try and achieve some sort of failure result is this bit:

    // Game over
function gameOver(rating) {
    if (rating === 0) {
      alert('Game Over');
            return;
    }
}

Full JS:

var symbols = ['bicycle', 'bicycle', 'leaf', 'leaf', 'cube', 'cube', 'anchor', 'anchor', 'paper-plane-o', 'paper-plane-o', 'bolt', 'bolt', 'bomb', 'bomb', 'diamond', 'diamond'],
        opened = [],
        match = 0,
        moves = 0,
        $deck = $('.deck'),
        $scorePanel = $('#score-panel'),
        $moveNum = $scorePanel.find('.moves'),
        $ratingStars = $scorePanel.find('i'),
        $restart = $scorePanel.find('.restart'),
        delay = 800,
        gameCardsQTY = symbols.length / 2,
        rank3stars = gameCardsQTY + 2,
        rank2stars = gameCardsQTY + 6,
        rank1stars = gameCardsQTY + 10;

// Shuffle function From http://stackoverflow.com/a/2450976
function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

// Initial Game
function initGame() {
    var cards = shuffle(symbols);
  $deck.empty();
  match = 0;
  moves = 0;
  $moveNum.html(moves);
  $ratingStars.removeClass('fa-star-o').addClass('fa-star');
    for (var i = 0; i < cards.length; i++) {
        $deck.append($('<li class="card"><i class="fa fa-' + cards[i] + '"></i></li>'))
    }
};

// Set Rating and final Score
function setRating(moves) {
    var rating = 3;
    if (moves > rank3stars && moves < rank2stars) {
        $ratingStars.eq(2).removeClass('fa-star').addClass('fa-star-o');
        rating = 2;
    } else if (moves > rank2stars && moves < rank1stars) {
        $ratingStars.eq(1).removeClass('fa-star').addClass('fa-star-o');
        rating = 1;
    } else if (moves > rank1stars) {
        $ratingStars.eq(0).removeClass('fa-star').addClass('fa-star-o');
        rating = 0;
    }   
    return { score: rating };
};


// Game over
function gameOver(rating) {
    if (rating === 0) {
      alert('Game Over');
            return;
    }
}

// End Game
function endGame(moves, score) {
    swal({
        allowEscapeKey: false,
        allowOutsideClick: false,
        title: 'Congratulations! You Won!',
        text: 'With ' + moves + ' Moves and ' + score + ' Stars.\nBoom Shaka Lak!',
        type: 'success',
        confirmButtonColor: '#9BCB3C',
        confirmButtonText: 'Play again!'
    }).then(function(isConfirm) {
        if (isConfirm) {
            initGame();
        }
    })
}

// Restart Game
$restart.on('click', function() {
  swal({
    allowEscapeKey: false,
    allowOutsideClick: false,
    title: 'Are you sure?',
    text: "Your progress will be Lost!",
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#9BCB3C',
    cancelButtonColor: '#EE0E51',
    confirmButtonText: 'Yes, Restart Game!'
  }).then(function(isConfirm) {
    if (isConfirm) {
      initGame();
    }
  })
});

// Card flip
$deck.on('click', '.card:not(".match, .open")', function() {
    if($('.show').length > 1) { return true; }

    var $this = $(this),
            card = $this.context.innerHTML;
  $this.addClass('open show');
    opened.push(card);

    // Compare with opened card
  if (opened.length > 1) {
    if (card === opened[0]) {
      $deck.find('.open').addClass('match animated infinite rubberBand');
      setTimeout(function() {
        $deck.find('.match').removeClass('open show animated infinite rubberBand');
      }, delay);
      match++;
    } else {
      $deck.find('.open').addClass('notmatch animated infinite wobble');
            setTimeout(function() {
                $deck.find('.open').removeClass('animated infinite wobble');
            }, delay / 1.5);
      setTimeout(function() {
        $deck.find('.open').removeClass('open show notmatch animated infinite wobble');
      }, delay);
    }
    opened = [];
        moves++;
        setRating(moves);
        $moveNum.html(moves);
  }

    // End Game if match all cards
    if (gameCardsQTY === match) {
        setRating(moves);
        var score = setRating(moves).score;
        setTimeout(function() {
            endGame(moves, score);
        }, 500);
  }
});

initGame();
Adam R
  • 77
  • 7
  • 4
    `if (rating = 0)` is incorrect. This sets rating to 0, since `=` assigns values, `==` weak compares and `===` strong compares. So try `if ( rating === 0 )`. – Shilly Aug 08 '18 at 13:46
  • Thanks. That seems so obvious now. Unfortunately, I still can't trigger a notification with the edited version. – Adam R Aug 08 '18 at 13:58
  • that was one mistake of two, check the solution bellow – Neji Soltani Aug 08 '18 at 14:10

1 Answers1

3

I have checked your code I found two mistakes:

The first one is as @Shilly said your condition is wrong, it will always return true so you have to resolve that, so instead of using just = which stands for assignment operator, use the comparison operator ==, check this for better understanding (I guess you already know that from the rest of your code).

The second mistake is that you didn't call you function gameOver anywhere , so you have to call it or it will be just useless lines of code.

Here's the pen with the solutions:

https://codepen.io/anon/pen/NBEWwB

Neji Soltani
  • 1,522
  • 4
  • 22
  • 41
  • Thanks, both such obvious things I missed. I appreciate the fast response. I'm still getting to grips with JS generally, trying tutorials etc but I'll be taking a proper course at the end of the year with it. – Adam R Aug 08 '18 at 14:14
  • It's fine, we are all making mistakes and that's important step of learning, and by the way I find that your game is awesome it has nice UI and animations :) – Neji Soltani Aug 08 '18 at 14:22