我正在用python编写一个扑克游戏,我需要打印一个易于为用户阅读的扑克牌。它不打印我需要打印的东西。我知道有一个解决方案,我只是没有看到它。这是代码:
userCards = ['AC','KD','4C','4S','7H']
print('Your cards:')
for card in range(len(userCards)):
print('%s) %-2s of %-9s' % (card,cvalue,csuit))
我已经定义了userCards,value和suit。我只需要打印出这样的手:
'您的卡片:'
1)黑桃王牌
2)钻石之王
3)4个俱乐部
4)黑桃4中
5)7个心中
提前致谢!
答案 0 :(得分:2)
我建议使用词典,而不是使用扩展卡级别和功能的功能。字典是一种紧凑而有效的方式来做这类事情。
此代码应适用于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 = ranks.get(rank, rank)
。
somedict.get(key, default)
尝试在key
中查找somedict
。如果该键存在,则返回关联的值,就像您执行somedict[key]
一样。但是如果密钥不存在,则返回default
。因此rank = ranks.get(rank, rank)
会返回展开的rank
(如果存在),否则它只会返回原始的rank
字符串。因此,A
会转换为Ace
,但数字字符串保持不变。
获取卡片索引的干净方法是使用内置的enumerate
功能。我们提供start
参数1到enumerate
以获得基于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
最后,这是一个新版本,它使用zip
和all
函数来检测手是否包含刷新。如果是,则返回套装信函,否则返回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