Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to implement a deck for a card game in python

Tags:

python

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?

like image 412
matt1024 Avatar asked Mar 25 '10 19:03

matt1024


2 Answers

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

like image 73
FogleBird Avatar answered Nov 03 '22 20:11

FogleBird


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')]
like image 35
Ned Batchelder Avatar answered Nov 03 '22 20:11

Ned Batchelder