I wrote a card game to share with my friends who used to play in person before the epidemic. It uses firebase for real-time state between the players, and it uses these Card and Deck classes to which you're welcome.
The answer to rendering a card as a string (asString()
) matches the perfectly acceptable already posted answer, looking up suit and value in a map.
We sometimes have too many players playing large, card-wasting games, so I added a deckId
to the Card object and let the Deck object deal through multiple 'shoes'.
class Card {
constructor(suit, value, deckId) {
this.suit = suit
this.value = value
this.deckId = deckId
}
static isEqual(card) {
return this.value === card.value && this.suit === card.suit && this.deckId === card.deckId
}
asString() {
const valueNames = { 1:'A', 2:'2', 3:'3', 4:'4', 5:'5', 6:'6', 7:'7', 8:'8', 9:'9', 10:'19', 11:'J', 12:'Q', 13:'K' }
// feel free to replace these with unicode equivalents (my UI uses images)
const suitNames = { 'h': 'hearts', 'd': 'diamonds', 'c':'clubs', 's':'spades' }
return `${valuesNames[this.value]} of ${suitNames[this.suit]}`
}
}
class Deck {
constructor() {
this.deckId = this.randomId()
this.cards = this.freshDeck()
}
static randomId () {
let chars ='abcdefghijklmnopqrstuvwxyz0123456789'.split('')
this.shuffle(chars)
return chars.join('').substring(0,8)
}
freshDeck () {
let cards = []
let suits = ['h', 'c', 'd', 's']
suits.forEach(suit => {
for (let value = 1; value <= 13; value++) {
cards.push(new Card(suit, value, this.deckId))
}
})
return cards
}
// fischer-yates shuffle
static shuffle (array) {
let currentIndex = array.length, temp, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex)
currentIndex -= 1
temp = array[currentIndex]
array[currentIndex] = array[randomIndex]
array[randomIndex] = temp
}
}
shuffle () {
Deck.shuffle(this.cards)
return this
}
dealOne () {
if (this.cards.length === 0) {
this.deckId = this.randomId()
this.cards = this.freshDeck()
this.shuffle()
}
let card = this.cards[0]
this.cards = this.cards.slice(1)
return card
}
}