Shuffling the Deck: A JavaScript Card Game Example
Building the Deck
To create a standard deck of 52 cards, we need to define two arrays: suits
and values
. The suits
array contains the four suit names, while the values
array holds the 13 card values.
const suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'];
const values = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'];
Creating the Deck Array
We use a nested for
loop to iterate over each suit and value, creating an object for each card combination. The resulting deck
array contains 52 objects, each with a Value
and Suit
property.
let deck = [];
for (let suit of suits) {
for (let value of values) {
deck.push({ Value: value, Suit: suit });
}
}
For example, one object in the deck
array might look like this: { Value: "Ace", Suit: "Spades" }
.
Shuffling the Deck
To randomize the deck, we employ a second for
loop that leverages the Math.random()
and Math.floor()
functions. This generates a random number between 0 and 51, allowing us to swap two card positions. By repeating this process, we effectively shuffle the deck.
for (let i = deck.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[deck[i], deck[j]] = [deck[j], deck[i]];
}
Dealing the Cards
Finally, a third for
loop is used to display the first five cards in the newly shuffled deck. This provides a glimpse into the randomly ordered deck, showcasing the program’s effectiveness.
for (let i = 0; i < 5; i++) {
console.log(`Card ${i + 1}: ${deck[i].Value} of ${deck[i].Suit}`);
}
This example demonstrates a fundamental understanding of JavaScript arrays, loops, and object manipulation. By combining these concepts, we’ve created a functional deck of cards that can be shuffled and dealt – a testament to the power of programming.
- Arrays: We used arrays to represent the suits, values, and deck of cards.
- Loops: We employed nested for loops to create the deck array and shuffle the deck.
- Object manipulation: We created objects for each card combination and manipulated them to shuffle the deck.