如何才能在python程序仍然正常工作的情况下,让它在玩游戏时打印王牌而不是1,打印杰克而不是11,打印皇后而不是12,打印国王而不是13。
有没有一种方法可以在不做太多更改的情况下做到这一点。
这是我的代码:
import random
dealer_cards = []
player_cards = []
while len(dealer_cards) != 2:
dealer_cards.append(random.randint(1, 13))
if len(dealer_cards) == 2:
print('The dealer has a hidden card and', dealer_cards[1])
while len(player_cards) != 2:
player_cards.append(random.randint(1, 11))
if len(player_cards) == 2:
print('You have the cards,', player_cards)
if sum(dealer_cards) == 21:
print('The dealer has the cards,', dealer_cards)
print('The dealer has won because he has 21!')
exit()
if sum(player_cards) == 21 and sum(dealer_cards) == 21:
print('draw')
exit()
elif sum(dealer_cards) > 21:
print('The dealer has the cards,', dealer_cards)
print('The dealer has bust because he has over 21!')
exit()
while sum(player_cards) < 21:
choice = str(input('Choose twist or stick? '))
if choice == 'twist':
player_cards.append(random.randint(1, 11))
print('You now have the cards,', player_cards)
else:
print('The dealer has the cards,', dealer_cards)
print('You have the cards,', player_cards)
if sum(dealer_cards) > sum(player_cards):
print('The dealer has won!')
break
else:
print('You have won!')
break
if sum(player_cards) > 21:
print('You have bust because you are over 21!')
elif sum(player_cards) == 21:
print('You have won because you have 21')发布于 2018-08-11 01:49:55
您可以创建一个名称字典,并使用它来提取名称:
card_names = {
1: 'Ace',
11: 'Jack',
12: 'Queen',
13: 'King',
}
>>> n = 12
>>> print(card_names.get(n, n))
Queenget的第二个参数确保如果在字典中找不到数字,它将按原样打印出来。
现在,您的代码正在打印列表,这使得它变得更加复杂。您必须为列表中的每个元素查询该字典。
你的代码:
print('You now have the cards,', player_cards)变成:
print('You now have the cards: ',
', '.join(str(card_names.get(c, c)) for c in player_cards))这将遍历卡片并逐个查询字典。每次打印列表时都这样做,它就会起作用。
由于每次打印列表时都必须重复该代码片段,因此可以创建一个函数来避免重复:
def format_card_list(card_list):
return ', '.join(str(card_names.get(c, c)) for c in card_list))然后在你的代码中使用它:
print('You now have the cards: ', format_card_list(player_cards))
...
print('The dealer has the cards,', format_card_list(dealer_cards))
...等
https://stackoverflow.com/questions/51791616
复制相似问题