In this tutorial, we will see a JavaScript program to create a cards deck, shuffle a deck of cards, and pick a random n card from it.
In a deck, there are four types of cards "Spades", "Diamonds", "Club", "Heart" with the thirteen different values start from Ace, 2 to 10, and Jack, Queen, King.
To generate a deck of cards that will be a total of 52 cards, 4 card types with 13 different values. We will create two arrays that will represent card types and values and then form a card with a unique combination of both.
const cardTypes = ["Spades", "Diamonds", "Club", "Heart"];
const cardValues = [
"Ace",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"Jack",
"Queen",
"King",
];
// cards deck array
let deck = [];
// create a deck of cards
// total 4 (cardTypes) * 13 (cardValues) = 52 cards
for (let i = 0; i < cardTypes.length; i++) {
for (let x = 0; x < cardValues.length; x++) {
let card = { value: cardValues[x], type: cardTypes[i] };
deck.push(card);
}
}
Once we have the deck of cards, to shuffle them, we will iterate all the cards in the deck and generate a random number (between 1 and 52) and swap the card at the current index with this random card.
// shuffle the cards
// iterate all the cards of the deck
for (let i = deck.length - 1; i > 0; i--) {
// randomly pick a card from the deck
// swap it with the current card index
let j = Math.floor(Math.random() * i);
let temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
The shuffling is happening in place, we are updating the cards in the same array. Now to pick a random n card, we will get the cards from this shuffled deck.
// display 3 random cards from the shuffled deck
for (let i = 0; i < 3; i++) {
console.log(`${deck[i].value} of ${deck[i].type}`)
}
"Jack of Spades"
"3 of Diamonds"
"4 of Spades"