我正在尝试在python中制作一个二十一点游戏。就像一个7s值是7但是,一个千斤顶值是10所以:
cards = ['ace','king','queen'....'3','2'
firstCard = random.choice(cards)
secondCard = random.choice(cards); remove.cards(firstCard)
print(int(firstCard) + int(secondCard))
我怎么能为国王或王牌做这件事......
答案 0 :(得分:6)
您可以使用字典,密钥为'ace'
,'king'
,'queen'
,值为对应的数值。根据游戏规则,您可以根据需要映射键和值。
mydict = {"ace": 1, "king": 13, "queen": 12}
num_of_queen = mydict["queen"] # gets the numeric value
答案 1 :(得分:0)
使用字典可以提供帮助!
cards = {1:"ace": 1, 13:"king", 12:"queen"}
firstCard = random.choice(cards.keys())
secondCard = random.choice(cards.keys());
remove.cards(firstCard)
print(firstCard + secondCard)
要获取卡的名称,您可以:
cards[firstCard]
答案 2 :(得分:0)
我建议在一个类中包含一个常规字典,以使它更容易使用:
class BlackJackDeck:
class NoSuchCard(Exception):
pass
values = {'king': 10,
'jack': 10,
'queen': 10,
'ace-high': 11,
'ace-low': 1}
values.update(zip(range(2, 11), range(2, 11)))
def __getitem__(self, item):
try:
item = int(item)
except (ValueError, TypeError):
item = item.lower()
try:
return self.values[item]
except KeyError:
raise self.NoSuchCard
演示:
>>> d = BlackJackDeck()
>>> d[2]
2
>>> d['7']
7
>>> d['KING']
10
>>> d['ace-high']
11
>>> d[100]
[...]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "...", line 21, in __getitem__
raise self.NoSuchCard
d.NoSuchCard
这允许您通过整数或字符串键查找卡片,不关心大写,并在卡片不存在时抛出有意义的异常。