I wrote some Javascript code to create a very simple card dealer for a homework assignment. In essence, you click a button to draw 5 cards from an array of 52 cards (in this case it had to be 52 card objects), and those 5 cards get displayed like this:
- 7 of Clubs
- 6 of Spades
- 7 of Hearts
- 10 of Spades
- 10 of Spades
The part I can't seem to figure out though is that each card in the array needs to be unique and as you can see in my example which I took from the output of my code, there are duplicates. I don't quite know how to go about filling the array with 52 unique card objects, i.e every combination of suits and values.
Here is my code:
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<h1>Robo Dealer</h1>
<button onclick="dealHand();">Deal Hand</button>
<hr />
<div id="card_hand"></div>
<script>
// Declaring arrays for suits and values
const suits = ["Hearts", "Spades", "Clubs", "Diamonds"];
const values = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"];
// Creating the card object
class Card {
constructor(suit, value) {
this.suit = suit;
this.value = value;
}
}
const deck = [];
function createDeck() {
for (i = 0; i < suits.length; i++) {
for (j = 0; j < values.length; j++) {
const card = { value: values[j], suit: suits[i] };
deck.push(card);
}
}
return deck;
}
var hand = new Array();
function getDeck() {
for (i = 0; i < 5; i++) {
let x = Math.floor(Math.random() * 52);
hand.push(deck[x]);
}
return hand;
}
// Dealing hand of 5 card objects / outputting it to HTML
const dealHand = () => {
let callCreateDeck = createDeck();
let callGetDeck = getDeck();
let str = "";
for (i = 0; i < hand.length; i++) {
let obj = hand[i];
str += `- ${obj["value"]} of ${obj["suit"]} <br> `;
$("#card_hand").html(str);
}
return false; // prevent page reload
};
</script>
</body>
Additionally, whenever the button is clicked, another set of 5 cards is drawn and I would like to make it so that when the button is clicked while a set of 5 cards is already being displayed, those cards get cleared/ replaced by the new set of cards and you can only draw more cards until there are no more remaining cards.