How To Print User Friendly Poker Hand In Python?
Solution 1:
Rather than using functions that expand the card's rank and suit I suggest using dictionaries. Dictionaries are a compact and efficient way to do this sort of thing.
This code should work on Python 2 or 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'}
defshow_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)
output
Your cards:AceofClubsKingofDiamonds4ofClubs4ofSpades7ofHearts
I suppose I should explain rank = ranks.get(rank, rank)
.
somedict.get(key, default)
attempts to look up key
in somedict
. If that key is present then the associated value is returned, just as if you did somedict[key]
. But if the key isn't present, then default
is returned. So rank = ranks.get(rank, rank)
returns the expanded rank
, if one exists, otherwise it just returns the original rank
string. So A
gets translated to Ace
but number strings remain as they are.
The clean way to get the card's index as well is to use the built-in enumerate
function. We supply a start
argument of 1 to enumerate
to get 1-based indices:
defshow_hand(hand):
print('Your cards:')
for i, (rank, suit) inenumerate(hand, 1):
rank = ranks.get(rank, rank)
suit = suits[suit]
print('%d: %s of %s' % (i, rank, suit))
output
Your cards:1:AceofClubs2:KingofDiamonds3:4ofClubs4:4ofSpades5:7ofHearts
Finally, here's a new version that uses the zip
and all
functions to detect if a hand contains a flush. If it does, the suit letter is returned, otherwise None
is returned.
from __future__ import print_function
suits = {'C': 'Clubs', 'D': 'Diamonds', 'H': 'Hearts', 'S': 'Spades'}
ranks = {'J': 'Jack', 'Q': 'Queen', 'K': 'King', 'A': 'Ace'}
defshow_hand(hand):
print('Your cards:')
for i, (rank, suit) inenumerate(hand, 1):
rank = ranks.get(rank, rank)
suit = suits[suit]
print('%d: %s of %s' % (i, rank, suit))
defis_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 ifall(s == suit for s in suit_list) elseNone#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 isNone:
print('Not a flush')
else:
print('Flush in %s' % suits[suit])
print()
output
Your cards:1:AceofClubs2:KingofDiamonds3:4ofClubs4:4ofSpades5:7ofHeartsNotaflushYour cards:1:3ofDiamonds2:5ofDiamonds3:AceofDiamonds4:QueenofDiamonds5:7ofDiamondsFlushinDiamonds
Post a Comment for "How To Print User Friendly Poker Hand In Python?"