// JavaScript Fisher-Yates algorithm
function shuffle(deck)
{
// for 1000(?) shuffles
// Switch the values of two randomly selected cards
for (let i = 0; i < 1000; i++)
{
let location1 = Math.floor((Math.random() * deck.length));
let location2 = Math.floor((Math.random() * deck.length));
let tmp = deck[location1];
deck[location1] = deck[location2];
deck[location2] = tmp;
}
}
After this shuffle, our deck array contains 52 objects randomly sorted. But it's more amusing to see this (play the demo here) than have me talk about it, so our next "trick", I'm going to make these cards magically appear in Unicode!
"πππππ
ππππππππ"
The render function iterates through each "card object" in the deck Array and creates a visual sprite in the "createCards" function. Having 52 sprites suddenly appear in our game might be too much of a "load". So, as an alternative to using sprite graphics, we could simply use text! Yeap! The Internet has Unicode code poker deck cards.
Game Prototype Summary
At this point, we have the functions to create a new card deck, shuffle them, and display them in our game. Some card games need several decks (one for each player?). The solution is ...
Creating Multiple Decks
var deck1 = getDeck();
var deck2 = getDeck();
Once the decks are created they are passed to the remaining helper functions as needed.
var deck1 = getDeck();
shuffle(deck1);
renderDeck(deck1);
Now that the decks are created, we can work on "dealing out" the cards.