gpt4 book ai didi

python - 如何在Python中打印用户友好的扑克牌?

转载 作者:行者123 更新时间:2023-12-01 04:00:25 25 4
gpt4 key购买 nike

我正在用 python 编写一个扑克游戏,我需要打印出一手扑克牌,以便用户阅读。它没有打印我需要打印的内容。我知道有一个解决方案,只是我没有看到它。这是代码:

userCards = ['AC','KD','4C','4S','7H']
print('Your cards:')
for card in range(len(userCards)):
print('%s) %-2s of %-9s' % (card,cvalue,csuit))

我已经定义了用户卡、值和花色。我只需要它像这样打印出手:

'Your cards:'

1) Ace of Spades

2) King of diamonds

3)4 of Clubs

4)4 of Spades

5)7 of Hearts

提前致谢!

最佳答案

我建议使用字典,而不是使用扩展卡牌等级和花色的函数。字典是完成这类事情的一种紧凑而有效的方式。

此代码应该适用于 Python 2 或 Python 3。

from __future__ import print_function

suits = {'C': 'Clubs', 'D': 'Diamonds', 'H': 'Hearts', 'S': 'Spades'}
ranks = {'J': 'Jack', 'Q': 'Queen', 'K': 'King', 'A': 'Ace'}

def show_hand(hand):
print('Your cards:')
for rank, suit in hand:
rank = ranks.get(rank, rank)
suit = suits[suit]
print('%s of %s' % (rank, suit))

#Test
userCards = ['AC', 'KD', '4C', '4S', '7H']
show_hand(userCards)

输出

Your cards:
Ace of Clubs
King of Diamonds
4 of Clubs
4 of Spades
7 of Hearts
<小时/>

我想我应该解释一下rank =rank.get(rank,rank)

somedict.get(key, default)

尝试在somedict中查找key。如果该键存在,则返回关联的值,就像您执行somedict[key]一样。但如果 key 存在,则返回default。因此,rank =rank.get(rank,rank) 返回扩展后的 rank(如果存在),否则仅返回原始 rank 字符串。因此,A 被转换为 Ace,但数字字符串保持原样。

<小时/>

获取卡索引的简洁方法是使用内置 enumerate功能。我们向 enumerate 提供一个 start 参数 1 来获取基于 1 的索引:

def show_hand(hand):
print('Your cards:')
for i, (rank, suit) in enumerate(hand, 1):
rank = ranks.get(rank, rank)
suit = suits[suit]
print('%d: %s of %s' % (i, rank, suit))

输出

Your cards:
1: Ace of Clubs
2: King of Diamonds
3: 4 of Clubs
4: 4 of Spades
5: 7 of Hearts
<小时/>

最后,这是一个新版本,它使用 zipall 函数来检测手牌是否包含同花。如果是,则返回诉讼信,否则返回 None

from __future__ import print_function

suits = {'C': 'Clubs', 'D': 'Diamonds', 'H': 'Hearts', 'S': 'Spades'}
ranks = {'J': 'Jack', 'Q': 'Queen', 'K': 'King', 'A': 'Ace'}

def show_hand(hand):
print('Your cards:')
for i, (rank, suit) in enumerate(hand, 1):
rank = ranks.get(rank, rank)
suit = suits[suit]
print('%d: %s of %s' % (i, rank, suit))

def is_flush(hand):
#Get suits
suit_list = zip(*hand)[1]
#Test if all the cards match the suit of the first card
suit = suit_list[0]
return suit if all(s == suit for s in suit_list) else None

#Test
userCards = ['AC', 'KD', '4C', '4S', '7H']
flushCards = '3D 5D AD QD 7D'.split()
hands = (userCards, flushCards)

for hand in hands:
show_hand(hand)
suit = is_flush(hand)
if suit is None:
print('Not a flush')
else:
print('Flush in %s' % suits[suit])
print()

输出

Your cards:
1: Ace of Clubs
2: King of Diamonds
3: 4 of Clubs
4: 4 of Spades
5: 7 of Hearts
Not a flush

Your cards:
1: 3 of Diamonds
2: 5 of Diamonds
3: Ace of Diamonds
4: Queen of Diamonds
5: 7 of Diamonds
Flush in Diamonds

关于python - 如何在Python中打印用户友好的扑克牌?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36661924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com