首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在玩游戏时打印1张A,11张杰克,12张皇后和13张国王?

如何在玩游戏时打印1张A,11张杰克,12张皇后和13张国王?
EN

Stack Overflow用户
提问于 2018-08-11 01:45:11
回答 1查看 152关注 0票数 0

如何才能在python程序仍然正常工作的情况下,让它在玩游戏时打印王牌而不是1,打印杰克而不是11,打印皇后而不是12,打印国王而不是13。

有没有一种方法可以在不做太多更改的情况下做到这一点。

这是我的代码:

代码语言:javascript
复制
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')
EN

回答 1

Stack Overflow用户

发布于 2018-08-11 01:49:55

您可以创建一个名称字典,并使用它来提取名称:

代码语言:javascript
复制
card_names = {
   1: 'Ace',
   11: 'Jack',
   12: 'Queen',
   13: 'King',
}

>>> n = 12
>>> print(card_names.get(n, n))
Queen

get的第二个参数确保如果在字典中找不到数字,它将按原样打印出来。

现在,您的代码正在打印列表,这使得它变得更加复杂。您必须为列表中的每个元素查询该字典。

你的代码:

代码语言:javascript
复制
print('You now have the cards,', player_cards)

变成:

代码语言:javascript
复制
print('You now have the cards: ', 
    ', '.join(str(card_names.get(c, c)) for c in player_cards))

这将遍历卡片并逐个查询字典。每次打印列表时都这样做,它就会起作用。

由于每次打印列表时都必须重复该代码片段,因此可以创建一个函数来避免重复:

代码语言:javascript
复制
def format_card_list(card_list):
    return ', '.join(str(card_names.get(c, c)) for c in card_list))

然后在你的代码中使用它:

代码语言:javascript
复制
print('You now have the cards: ', format_card_list(player_cards))
...
print('The dealer has the cards,', format_card_list(dealer_cards))
...

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51791616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档