我希望构建一个包含两个字符串变量的函数,并将组合返回给一副牌的每一张牌。
playCard({ suit: 'HEARTS', value: 2 }) to return 2♥
playCard({ suit: 'SPADES', value: 10 }) to return T♠
playCard({ suit: 'SPADES', value: 11 }) to return J♠
发布于 2020-10-12 08:05:43
您可以使用2个简单的查找表或关联数组来做到这一点
const suitsMap = {
'HEARTS' : '♥',
'SPADES' : '♠'
// etc
}
const valuesMap = {
2 : '2',
10: 'T',
11: 'J'
// etc
}
function playCard({value,suit}){
return valuesMap[value] + suitsMap[suit];
}
console.log(playCard({ suit: 'HEARTS', value: 2 }))
console.log(playCard({ suit: 'SPADES', value: 10 }))
console.log(playCard({ suit: 'SPADES', value: 11 }))
playCard
也可以写成这样:
function playCard(card){
return valuesMap[card.value] + suitsMap[card.suit];
}
在上面的示例中,它简单地使用了对象解构赋值:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
发布于 2020-10-21 23:18:34
我写了一个纸牌游戏,与我的朋友们分享,他们在疫情之前经常亲自下棋。它使用firebase实现玩家之间的实时状态,并使用这些您欢迎使用的Card和Deck类。
将卡片呈现为字符串(asString()
)的答案与已经发布的完全可接受的答案相匹配,在地图中查找花色和值。
有时我们有太多的玩家在玩大型的、浪费卡片的游戏,所以我在卡片对象中添加了一个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
}
}
https://stackoverflow.com/questions/64313803
复制