Next page | Contents page |

Shuffling the deck

A simple way to shuffle the deck is to repeatedly swap randomly chosen pairs of cards. The number of times I chose to do this is 3 times the size of the deck. So this is my version of the shuffle method:

Deck.prototype.shuffle = function ()
{ const L =;
  for (var i = 0; i < 3 * L; i++)
  { var a = Math.floor (Math.random () * L);// 0..L-1
    var b = Math.floor (Math.random () * L);
    if (a !== b)// Swap a and b:
    { var temp = [a]; [a] = [b]; [b] = temp;
  } }

Math.random() returns a number from 0 to (just under) 1 so it needs scaling to the size of the deck. Math.floor() is needed because the index for the cards array must be an integer. If you are not sure about such details search online for "MDN " + the thing you want.

We then need to test that shuffling really works. I decided to do that by adding one more method to deckA.js, for testing purposes:

// For testing:
Deck.prototype.toHTML = function ()
{ var s = "";
  for (const CARD of s += CARD.getName () + "<br>";
  s += "(" + + " cards)";
  return s;

That method returns a string that can be set as the innerHTML of the info div in the HTML file. More specifically, add this function to gameA.js and call it at the end of run():

function testDeck ()
{ GAME.deck = new Deck (2, 4);
  GAME.deck.shuffle ();
  document.getElementById ("info").innerHTML = GAME.deck.toHTML ();

As noted earlier, you may choose to output to the browser's developer console instead of the info div.

deckA.js is now complete. We will not change it in subsequent pages.

Next page | Contents page |