#!/usr/bin/python """ Exercise 11, chapter 10 of Zelle's "Intro Python" Jim Mahoney, Oct 30 2006 The test at the bottom (printing some random cards) happen if this is run from the command line, either with 'python play_card.py' or './playing_card.py'. The tests won't happen when this is imported from another module. Here are examples of the defined methods for this object. >>> from playing_card import Playing_Card # load it >>> king_of_diamonds = Playing_Card( rank=13, suit='d' ) # create one >>> random_card = Playing_Card() # create random one >>> print king_of_diamonds # convert to string King of Diamonds >>> print king_of_diamonds.getRank() # get rank 13 >>> print king_of_diamonds.getSuit() # get suit d >>> print king_of_diamonds.BJValue() # get blackjack value 10 """ from random import randint class Playing_Card: """ A single playing card. """ def __init__(self, rank=False, suit=False): """ Playing_card(rank=range(1,14), suit in ('d', 'c', 'h', 's')) or Play_card() returns a random card. """ if not rank: rank = randint(1,13) if not suit: suit = ['d', 'c', 'h', 's'][randint(0,3)] self.rank = rank self.suit = suit def getRank(self): """ return rank of card as integer n, 1<=n<=13 """ return self.rank def getSuit(self): """ return suit of card as a letter in ('d', 'c', 'h', 's')""" # Note that the problem didn't specifiy form of this return value. # I've chosen to use the same form that __init__ takes. return self.suit def BJValue(self): """ Return black jack value of card, 1<= value <= 10. """ if self.rank >= 10: return 10 else: return self.rank suit_names = { 'd' : 'Diamonds', 'c' : 'Clubs', 'h' : 'Hearts', 's' : 'Spades', } rank_names = { 1 : 'Ace', 2 : 'Two', 3 : 'Three', 4 : 'Four', 5 : 'Five', 6 : 'Six', 7 : 'Seven', 8 : 'Eight', 9 : 'Nine', 10: 'Ten', 11: 'Jack', 12: 'Queen', 13: 'King', } def __str__(self): """ Display card as a string, e.g. 'Ace of Spades'. """ # Here the text implied that an english description is required. return self.rank_names[int(self.rank)] + ' of ' + self.suit_names[self.suit] # Test by generating and printing n random cards if running interactively. if __name__ == '__main__': print " - - testing black jack cards - - " n = input(" How many cards? ") for i in range(n): card = Playing_Card() print print " ", str(card) print " ", "black jack value is ", card.BJValue(), "." print print "Done."