0

I'm trying to make a card matching game in JavaScript where every time the user starts the game, the cards shuffle. If they flip two of the same cards the get a point added to their score. I have the card matching aspect working using a data framework on each card div, but this immediately invoked shuffle card function I've added isn't working. Thank you in advance!

JavaScript of Shuffling the Cards:

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

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

HTML of Each Card(16 in total):

<div class="main-card-container">
<div class="the-card" data-framework="twoofhearts">

   <div class="the-back card-face">
      <img src="./images/cardback.png" class="flipped-card" 
   </div>
   <div class="the-front card-face">
      <img src="./images/img-1.png" class="unflipped-card" 
   </div>

</div>        
</div>
vimuth
  • 5,064
  • 33
  • 79
  • 116
bd123
  • 16
  • 2
  • 1
    Assuming you create all cards ahead of time, and collect them as an array in JS, this answer may be pertinent to what you're trying to do. https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – Chaosxmk Jan 28 '23 at 18:24
  • make sure that class="main-card-container" has display: flex set. and seems like your shuffle function can return repeated orders. – Filipe Prado Jan 28 '23 at 18:27

1 Answers1

2

You can use the Fisher-Yates shuffle algorithm which runs in O(n), so there's no way to do it faster.

It's quite simple really:

var inOrder = [1, 2, 3, 4, 5, 6];

function fisherYatesShuffle(array){
  for(let i = array.length -1; i >= 0; i--){
    const newPosition = Math.floor((i + 1) * Math.random());
    const temp = array[newPosition];
    array[newPosition] = array[i];
    array[i] = temp;
  }
  return array;
}

console.log(fisherYatesShuffle(inOrder));

On a side note: how random it really is does depend on how good your random numbers are. Math.random() is not cryptographically secure i.e. not all numbers are equally likely to be generated. If you want that you need to use Crypto.getRandomValues(). Math.random() is however much faster and should do for the randomness required in a game.

For more information on randomness see this blog post Baeldung CS - Understanding Randomness.

Mushroomator
  • 6,516
  • 1
  • 10
  • 27