What is the best way to store the cards and suits in python so that I can hold a reference to these values in another variable?
For example, if I have a list called hand (cards in players hand), how could I hold values that could refer to the names of suits and values of specific cards, and how would these names and values of suits and cards be stored?
Poker servers tend to use a 2-character string to identify each card, which is nice because it's easy to deal with programmatically and just as easy to read for a human.
>>> import random
>>> import itertools
>>> SUITS = 'cdhs'
>>> RANKS = '23456789TJQKA'
>>> DECK = tuple(''.join(card) for card in itertools.product(RANKS, SUITS))
>>> hand = random.sample(DECK, 5)
>>> print hand
['Kh', 'Kc', '6c', '7d', '3d']
Edit: This is actually straight from a poker module I wrote to evaluate poker hands, you can see more here: http://pastebin.com/mzNmCdV5
The simplest thing would be to use a list of tuples, where the cards are ints and the suits are strings:
hand = [(1, 'spade'), (10, 'club'), ...]
But simplest may not be what you want. Maybe you want a class to represent a card:
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __repr__(self):
letters = {1:'A', 11:'J', 12:'Q', 13:'K'}
letter = letters.get(self.rank, str(self.rank))
return "<Card %s %s>" % (letter, self.suit)
hand = [Card(1, 'spade'), Card(10, 'club')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With