As the title suggests, I’m trying to make a browser card game using a standard deck of 52 cards. I’m trying to not to use others’ code and do as much as I can on my own. I made a rough plan of what I think I need to make for now.
- Make a card object. The card object will contain the values of it’s number and it’s suit.
- Make a deck object. The deck contains an array of card objects, and has the functions shuffle and deal, which both manipulate the array. Shuffle will rearrange the cards, deal will pop() an amount of cards to a player’s hand.
- Make a playerHand array. The array will hold the card objects drawn by the player from the deck object.
- Make a botHand array. Same as playerHand but for opponent (bot).
I just started and am already stuck. I made a Card constructor, and am now working on making the deck object. My main question is how would I create an array inside the deck object that essentially uses the Card constructor I made 52 times. I assume I’d just run a for loop but not sure about proper syntax. This is what I have so far, also any other suggestions for my logic to making the game would be greatly appreciated.
function Card(value, suit) { this.value = value; this.suit = suit; } var deck = { cards: new Array(52), shuffle: function() { }, deal: function() { } }
Advertisement
Answer
Not sure if this is exactly what you want, but, you could do:
for (let i = 1; i < 14; i++){ cards.push(Card(i, 'Spade')); cards.push(Card(i, 'Diamond')); cards.push(Card(i, 'Clubs')); cards.push(Card(i, 'Hearts')); }
The cards array would then have 52 card objects, in the order of:
1 of Spades, 1 of Diamonds, 1 of Clubs, 1 of hearts, 2 of Spades, 2 of Diamonds....