与其说是一个问题,不如说是一个问题,只是想知道其他人会如何处理这个问题。我在python中工作,通过python的类结构来制作一个21点游戏,并且我已经用卡片作为字符串来制作一个数组。这有助于这样的事实:4张牌值10块,一张牌值1或11。但是,计算一只手的价值是很困难的。甲板在init。这怎么可能更好呢?我考虑过一本字典,但那不能处理复本。任何想法都很感激。抱歉,如果这是个糟糕的职位,我是新来的。
self.deck = [['2']*4, ['3']*4, ['4']*4, ['5']*4, ['6']*4, ['7']*4, \
['8']*4, ['9']*4, ['10']*4, ['J']*4, ['Q']*4, ['K']*4, \
['A']*4]
def bust(self, person):
count = 0
for i in self.cards[person]:
if i == 'A':
count += 1
elif i == '2':
count += 2
elif i == '3':
count += 3
elif i == '4':
count += 4
elif i == '5':
count += 5
elif i == '6':
count += 6发布于 2016-08-23 03:22:06
帮你自己一个忙,得到一张清晰的卡片值图:
CARD_VALUE = {
'2': 2,
'3': 3,
# etc
'A': 1,
'J': 12,
'Q': 13,
'K': 14,
}
# Calculate the value of a hand;
# a hand is a list of cards.
hand_value = sum(CARD_VALUE[card] for card in hand)对于不同的游戏,您可以有不同的值映射,例如Ace值为1或11,您可以将这些映射放入按游戏名称命名的字典中。
另外,我也不会把我的手绘成一张简单的卡片列表。相反,我使用计数来打包重复的值:
# Naive storage, even unsorted:
hand = ['2', '2', '3', '2', 'Q', 'Q']
# Grouped storage using a {card: count} dictionary:
hand = {'2': 3, '3': 1, 'Q': 2}
# Allows for neat operations
got_a_queen = 'Q' in hand
how_many_twos = hand['2'] # only good for present cards.
how_many_fives = hand.get('5', 0) # 0 returned since '5' not found.
hand_value = sum(CARD_VALUE(card) * hand[card] for card in hand)希望这能有所帮助。
发布于 2016-08-23 03:23:47
以下是你能做的:
把你的甲板做成一根绳子
import random
cards = 'A'*4 + '2'*4 + ... + 'K'*4
self.deck = ''.join(random.sample(cards,len(cards)))
values = {'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'T': 10,
'J': 10,
'Q': 10,
'K': 10
}然后将手定义为字符串并使用计数方法:
def counth(hand):
"""Evaluates the "score" of a given hand. """
count = 0
for i in hand:
if i in values:
count += values[i]
else:
pass
for x in hand:
if x == 'A':
## makes exception for aces
if count + 11 > 21:
count += 1
elif hand.count('A') == 1:
count += 11
else:
count += 1
else:
pass
return counthttps://stackoverflow.com/questions/39091677
复制相似问题