Contents

  1. card.py
  2. deck.py

card.py 1/2

[
top][prev][next]
class Card:
    """
    A class to represent a standard playing card. The ranks are ints:
    2-10 for numbered cards, 11=Jack, 12=Queen, 13=King, 14=Ace.
    The suits are strings: 'clubs', 'spades', 'hearts', 'diamonds'.
    """
    
    def __init__(self, rank, suit):
        "Constructs a new Card object with the given rank (an int) and suit (a string)."
        self._rank = rank
        self._suit = suit

    def __str__(self):
        "Returns a string describing the card as 'rank of suit'."
        result = ""
        if self._rank == 11:
            result += "Jack"
        elif self._rank == 12:
            result += "Queen"
        elif self._rank == 13:
            result += "King"
        elif self._rank == 14:
            result += "Ace"
        else:
            result += str(self._rank)
        result += " of " + self._suit
        return result
        
    def getRank(self):
        "Returns rank."	
        return self._rank

    def getSuit(self):
        "Returns suit."
        return self._suit
        
    def getRummyValue(self):
        "Returns the value of this card in the game of Rummy"
        if self._rank < 10:
            return 5
        if self._rank < 14:
            return 10
        return 15
    
    def _isFaceCard(self):
        "Returns True iff the card is a face card."
        if self.rank > 10 and self.rank < 14:
            return True
        return False
     
    def __lt__(self, other):
        """ Compares Card objects by their rank"""
        
        # verify that self and other are the same type
        if type(self) != type(other):
            return False
            
        # do comparison
        return self.rank < other.rank
        
    def __eq__(self, other):
        """Returns true if this object and other are equivalent
        based on ..."""
        
        # verify that self and other are the same type
        if type(self) != type(other):
            return False
        # do comparison
        return self.rank == other.rank and self.suit == other.suit


        
def main():
    c1 = Card(14, "spades")
    print(c1)
    c2 = Card(13, "hearts")
    print(c2)
    c3 = Card(2, "diamonds")
    print(c3)
    
    

# Since I am probably going to import this script into another script,
# I only want to call main() when it's *not* imported
if __name__ == '__main__':
    main()

deck.py 2/2

[
top][prev][next]
# Implementation of a deck of cards.
# by CSCI 111

from card import *
from random import shuffle

class Deck:
    """ A class to represent a deck of playing cards."""
    
    def __init__(self):
        """Creates a new Deck object, filled with one of each
        unique card."""
        
        self._listOfCards = []
        for suit in ["clubs","hearts","diamonds","spades"]:
            for rank in range(2,15):
                self._listOfCards.append(Card(rank, suit))

    def __str__(self):
        """Returns a string representing the cards that are
        in the deck."""
        
        deckRep= ""
        for c in self._listOfCards:
            deckRep += str(c) + "\n"
        return deckRep

    def shuffle(self):
        """shuffles the deck, in place."""
        return shuffle(self._listOfCards)
        
    def draw(self, numCards):
        """Takes the number of cards to draw and 
        returns a list of those cards drawn
        """
        hand = []
        for card in range(numCards):
            drawnCard = self._listOfCards.pop(0)
            hand.append(drawnCard)
        return hand
        
    def isEmpty(self):
        """Returns True if and only if the deck is empty."""
        return len(self._listOfCards) == 0
        
    def deal(self, numPlayers, numCards):
        """Returns a list of the hands (a list of cards) for
        each player."""
        listOfHands = []
        for player in range(numPlayers):
            # generate a hand of cards for each player
            playerHand = self.draw(numCards)
            listOfHands.append(playerHand)
        return listOfHands
    
    def burn(self, numCards):
        self.draw(1)
        return self.draw(numCards)
        
def main():
    d = Deck()
    d.shuffle()
    #print(d)
    print("Draw one card:")
    hand = d.draw(4)
    for card in hand:
        print(card)
        
    print("Is the deck empty?", d.isEmpty())
    
    numPlayers = 2
    numCards = 3
    
    playerHands = d.deal(numPlayers, numCards)
    for numPlayer in range(numPlayers):
        print("Player", numPlayer+1, ":")
        for card in playerHands[numPlayer]:
            print(card)
    
    # The below code will cause an error because we don't have 52 cards in the
    # deck.
    for i in range(52):
        d.draw(1)
    
    print("Is the deck empty?", d.isEmpty())
    
    
if __name__ == "__main__":
    main()

Generated by GNU Enscript 1.6.6.