Entry 2941
cards.py
Submitted by anonymous
on Jan. 8, 2010 at 11:54 a.m.
Language: Python. Code size: 2.2 KB.
#!/usr/bin/env python # A module to support the simulation of card games. # # AP # 2009-10-31 '''Functions to support the simulation of card games.''' import random RANKS = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2'] SUITS = ['S', 'H', 'D', 'C'] RANK_NAMES = {'A': 'Ace', 'K': 'King', 'Q': 'Queen', 'J': 'Jack', 'T': 'Ten', '9': 'Nine', '8': 'Eight', '7': 'Seven', '6': 'Six', '5': 'Five', '4': 'Four', '3': 'Three', '2': 'Two' } SUIT_NAMES = {'S': 'Spades', 'H': 'Hearts', 'D': 'Diamonds', 'C': 'Clubs' } def card_name (card): '''Returns the full name of the given card.''' rank = card[0] suit = card[1] return '%s of %s' % (RANK_NAMES[rank], SUIT_NAMES[suit]) def display (cards): '''Displays a collection of cards on a single line.''' print short_hand (cards) def short_hand (cards): '''Returns a short string for a collection of cards.''' return ' '.join (cards) def shuffle (cards): '''Shuffles a collection of cards randomly.''' random.shuffle (cards) def sort (cards): '''Sorts a collection of cards by suit, then by rank.''' cards.sort (key=position) def position (card): '''Returns the (zero-based) position that the given card would have in a sorted deck of cards.''' rank = card[0] suit = card[1] return len (RANKS) * SUITS.index (suit) + RANKS.index (rank) def create_deck (): '''Returns a standard deck of 52 playing cards.''' deck = [] for suit in SUITS: for rank in RANKS: card = rank + suit deck.append (card) return deck def display_deck (deck): '''Prints the given deck neatly on standard output, as up to four rows of cards with up to thirteen cards per row.''' for index in 0, 13, 26, 39: cards = [] for card in deck [index:index+13]: cards.append ('%3s' % card) line = ''.join (cards) if line: print line def deal (deck, n=1): '''Removes and returns one or more cards from the given deck.''' if n > 1: cards = [] for i in range (n): cards.append (deck.pop (0)) return cards else: return deck.pop (0)
This snippet took 0.01 seconds to highlight.
Back to the Entry List or Home.