Contents

  1. card2.py
  2. card_byid.py
  3. card.py
  4. deck.py
  5. test.py
  6. war.py

card2.py 1/6

[
top][prev][next]
# Card class and demonstration of use.
# 
# by CSCI111

import test

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 getCardColor(self):
        """
        Returns the color of the card's suit.  This will be "red" for
        for hearts and diamonds and "black" for spades and clubs
        """
        if self._suit == "hearts" or self._suit == "diamonds":
            return "red"
        else:
            return "black"
        
    def getRummyValue(self):
        """
        """
        if self._rank > 9 and self._rank <= 13:
            rummyValue = 10
        elif self._rank == 14:
            rummyValue = 15
        else:
            rummyValue = 5
        return rummyValue

def main():
    c1 = Card(14, "spades")
    print(c1)
    c2 = Card(13, "hearts")
    print(c2)
    c3 = Card(2, "diamonds")
    print(c3)
    
    # could put the tests in separate functions
    
    # test the getSuit() method and constructor
    test.testEqual(c1.getSuit(), "spades")
    test.testEqual(c2.getSuit(), "hearts")
    test.testEqual(c3.getSuit(), "diamonds")

    # test the getRank() method and constructor
    test.testEqual(c1.getRank(), 14)
    test.testEqual(c2.getRank(), 13)
    test.testEqual(c3.getRank(), 2)
    
    # test the __str__ method
    test.testEqual( str(c1), "Ace of spades")
    test.testEqual( str(c2), "King of hearts")
    test.testEqual( str(c3), "2 of diamonds")
    
    # test the getCardColor method
    test.testEqual(c1.getCardColor(), "black")
    test.testEqual(c2.getCardColor(), "red")
    test.testEqual(c3.getCardColor(), "red")

    # test the getRummyValue method
    test.testEqual(c1.getRummyValue(), 15)
    test.testEqual(c2.getRummyValue(), 10)
    test.testEqual(c3.getRummyValue(), 5)

    myHand = [ c1, c2, c3 ]
    
    rummyValue = 0
    for card in myHand:
        rummyValue += card.getRummyValue()
    
    print( rummyValue)
    
    # Problem: determine the rummy value of this hand
    

    
    # showing other ways to call the str method 
    #myString = c3.__str__()
    #myString2 = str(c3)
    
    #print(myString)
    #print(myString2)
    
# Since I am probably going to import this class into another script,
# I only want to call main() when it's *not* imported
if __name__ == '__main__':
    main()

card_byid.py 2/6

[
top][prev][next]
# Demonstrates abstraction: has same interface as card.py
# but different implementation, i.e., defining state using an id.

import test

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):
        "Constructor for class Card takes int rank and string suit."
        # card ids go from 2 to 55
        self._cardid = rank
        if suit == "clubs":
            self._cardid += 13
        elif suit == "hearts":
            self._cardid += 26
        elif suit == "diamonds":
            self._cardid += 39

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

    def getRank(self):
        "Returns rank."
        return (self._cardid-2) % 13 + 2

    def getSuit(self):
        "Returns suit."
        suits = ["spades", "clubs", "hearts", "diamonds"]
        whichsuit = (self._cardid-2)//13
        return suits[whichsuit]

    def getRummyValue(self):
        "Returns the value of the card in Rummy"

        myRank = self.getRank()

        if myRank == 14:
            return 15
        elif myRank >= 10:
            return 10
        else:
            return 5
        
def main():
    c1 = Card(14, "spades")
    print(c1)
    c2 = Card(13, "hearts")
    print(c2)
    c3 = Card(2, "diamonds")
    print(c3)
    
    # could put the tests in separate functions
    
    # test the getSuit() method and constructor
    test.testEqual(c1.getSuit(), "spades")
    test.testEqual(c2.getSuit(), "hearts")
    test.testEqual(c3.getSuit(), "diamonds")

    # test the getRank() method and constructor
    test.testEqual(c1.getRank(), 14)
    test.testEqual(c2.getRank(), 13)
    test.testEqual(c3.getRank(), 2)
    
    # test the __str__ method
    test.testEqual( str(c1), "Ace of spades")
    test.testEqual( str(c2), "King of hearts")
    test.testEqual( str(c3), "2 of diamonds")

    # test the getRummyValue method
    test.testEqual(c1.getRummyValue(), 15)
    test.testEqual(c2.getRummyValue(), 10)
    test.testEqual(c3.getRummyValue(), 5)
    
if __name__ == '__main__':
    main()


card.py 3/6

[
top][prev][next]
# Card class and demonstration of use
# by CSCI111

import test

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 main():
    c1 = Card(14, "spades")
    print(c1)
    c2 = Card(13, "hearts")
    print(c2)
    c3 = Card(2, "diamonds")
    print(c3)
    
    # could put the tests in separate functions
    
    # test the getSuit() method and constructor
    test.testEqual(c1.getSuit(), "spades")
    test.testEqual(c2.getSuit(), "hearts")
    test.testEqual(c3.getSuit(), "diamonds")

    # test the getRank() method and constructor
    test.testEqual(c1.getRank(), 14)
    test.testEqual(c2.getRank(), 13)
    test.testEqual(c3.getRank(), 2)
    
    # test the __str__ method
    test.testEqual( str(c1), "Ace of spades")
    test.testEqual( str(c2), "King of hearts")
    test.testEqual( str(c3), "2 of diamonds")
    
    # showing other ways to call the str method 
    #myString = c3.__str__()
    #myString2 = str(c3)
    
    #print(myString)
    #print(myString2)
    
# Since I am probably going to import this class into another script,
# I only want to call main() when it's *not* imported
if __name__ == '__main__':
    main()

deck.py 4/6

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

from card import *

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 main():
    d = Deck()
    print(d)
    print("The number of cards remaining in the deck is", d.numRemaining())
    
# 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()

test.py 5/6

[
top][prev][next]
# From How to Think Like a Computer Scientist textbook

def testEqual(actual,expected,places=5):
    '''
    Does the actual value equal the expected value?
    For floats, places indicates how many places, right of the decimal, must be correct
    '''
    if isinstance(expected,float):
        if abs(actual-expected) < 10**(-places):
            print('\tPass')
            return True
    else:
        if actual == expected:
            print('\tPass')
            return True
    print('\tTest Failed: expected {} but got {}'.format(expected,actual))
    return False

war.py 6/6

[
top][prev][next]
# Simple implementation of the game of War
# There are some issues in simulation's accuracy.
# Pedagogical goal: practice calling object's methods to solve a problem.
# Sara Sprenkle

from card import *
from random import *

def main():
    player1Card = genRandomCard()
    player2Card = genRandomCard()

    print("Player 1 draws a", player1Card)
    print("Player 2 draws a", player2Card)
    print()
    print(" --> ", end="")
    

def genRandomCard():
    """ Returns a randomly generated Card object.
    Assumes an infinite number of decks of cards available."""
    
    suits = ["hearts", "diamonds", "clubs", "spades"]
    
    randRank = randint(2, 14) # generate a random rank
    randSuit = suits[randint(0, 3)]  # generate a random suit
    
    # create a new Card object from randomly generated rank and suit
    randomCard = Card( randRank, randSuit )
    
    return randomCard
    
main()

Generated by GNU Enscript 1.6.6.