[Edu-sig] Cards n stuff...

Kirby Urner pdx4d@teleport.com
Tue, 13 Mar 2001 12:10:25 -0800


Variation on the 'deck of cards' theme:

"""
this is cards.py
"""

import random             # used when shuffling deck
from operator import add  # used to add card values

# putting suites and ranks at the module level makes them global

suites = ['Hearts','Diamonds','Spades','Clubs']

# creating a dictionary pairing character rank with integer value,
# i.e. ranks['Queen'] = 12.  Could do this with a loop instead of 
# with such a complicated eval expression -- below works in Python 2.0+

ranks = eval('{' + ','.join(["'%s':%s" % x for x in
                zip(['Ace']+map(str,range(2,11))+['Jack','Queen','King'],
                range(1,15))])+'}')

class Card:
  """
  a single card
  """
  def __init__(self, suite, rank):
    self.suite = suite
    self.rank = rank

  def value(self):
    """
    return how much I'm worth (in some games, all face
    cards might have same value)
    """
    return ranks[self.rank]  # my dictionary value

  def __repr__(self):
    """
    my fancier name
    """
    return self.rank + ' of ' + self.suite

class Deck:
  """
  a single deck of cards
  """
    
  def __init__(self):
    """
    Initialize me automatically
    -- including a shuffle
    """
    self.cards = []
    for suite in suites:
      for rank in ranks.keys():
        newCard = Card(suite, rank)
        self.cards.append(newCard)
    self.shuffle()

  def shuffle(self):
      """
      shuffle any time
      """
      newdeck = []
      while len(newdeck)<52:
          randomcard = random.choice(self.cards)
          newdeck.append(randomcard)
          self.cards.remove(randomcard)
      self.cards = newdeck

  def deal(self,numcards,hand):
      """
      deal numcards off the top to hand object
      """
      hand.cards = self.cards[:numcards]
      self.cards = self.cards[numcards:]

class Hand:
  """
  a single hand
  """

  def __init__(self):
      self.cards = []

  def __repr__(self):
      return str(self.cards)

  def value(self):
      """
      add the values of all cards in hand
      """
      return reduce(add,[card.value() for card in self.cards])

def setup():
    
    global thedeck,myhand
    
    thedeck = Deck()
    thedeck.shuffle()
    myhand = Hand()
    thedeck.deal(2,myhand)
    
===========

Usage:

  >>> reload(cards)
  <module 'cards' from 'g:\python21\ocn\cards.py'>
  >>> cards.setup()
  >>> cards.myhand
  [4 of Diamonds, 5 of Diamonds]
  >>> cards.myhand.value()
  9

  >>> cards.setup()
  >>> cards.myhand
  [7 of Spades, 8 of Hearts]
  >>> cards.myhand.value()
  15

  >>> mydeck = cards.Deck() # make me a deck
  >>> mydeck.cards[0:3]     # peak at top 3 cards
  [3 of Diamonds, Ace of Hearts, 6 of Spades]
  >>> myhand = cards.Hand() # initialize a hand..
  >>> mydeck.deal(2,myhand) # and deal it 2 cards from mydeck
  >>> myhand.cards          # hand gets first 2 cards off the top
  [3 of Diamonds, Ace of Hearts]
  >>> mydeck.cards[0:3]     # deck now has 6 of Spades as top card
  [6 of Spades, 7 of Spades, Queen of Spades]