I am trying to create a card dealer that deals 5 cards when a button is clicked on the web page.
Basically, I want to create a card object with 2 attributes, ‘suit’ and ‘value’, once that is done I want to create an array of 52 card objects with random suits and values but ideally they should all be unique.
Out of those 52 card objects, I would like 5 to be selected and displayed when the button is clicked.
I am not getting any output from my function that is invoked from my button and I don’t really understand why.
I am really new to Javascript and the professor teaching the intro class I am taking right now isn’t very helpful, unfortunately.
Here is my current 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
function cards(value, suit) {
this.value = value;
this.suit = suit;
}
// Creating array of 52 card objects
var deck = new Array();
function getDeck() {
for (i = 0; i < 52; i++) {
let cardObject = new cards(
values[Math.random()],
suits[Math.random()]
);
deck.push(cardObject);
}
return deck;
}
// Dealing hand of 5 card objects / outputting it to HTML
const dealHand = () => {
for (i = 0; i < 6; i++) {
$("#card_hand").html(getDeck());
}
return false; // prevent page reload
};
</script>
</body>
2
Answers
Here is a tidied up version of your script, involving a Durstenfeld shuffle and a simple array containing the 52 cards deck. The first 5 cards of the shuffled deck are being dealt:
OK, lets take a look at how you might approach this using objects.
At the moment you’re just iterating 52 times and selecting suits/values at random. What you probably should do is create the deck first by iterating over the suits and values, shuffle them, and then return the top five cards (like a casino would do).
There’s a couple of bits of code here that you might not be familiar with but I’ll include some notes, and some links to documentation at the end. I did get a little carried away with this but I hope that some of it is useful.
Additional documentation
map
Template strings
CSS Grid
join