写了一款卡牌游戏,分享给疫情前曾经亲自玩过的朋友。它使用 firebase 来获取玩家之间的实时状态,并使用您欢迎的 Card 和 Deck 类。
将卡片呈现为字符串 (asString()) 的答案与已发布的完全可接受的答案相匹配,在地图中查找花色和价值。
有时我们有太多的玩家玩大型浪费纸牌的游戏,所以我在 Card 对象中添加了一个deckId 并让 Deck 对象处理多个“鞋子”。
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
}
}