Contents
- ./card2.py
- ./card.py
- ./deck.py
- ./test.py
./card2.py 1/4
[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 hearts and diamonds and
"black" for spades and clubs
"""
#if self.getSuit() == "hearts" or self.getSuit() == "diamonds":
if self._suit == "hearts" or self._suit == "diamonds":
color = "red"
else:
color = "black"
return color
def getRummyValue(self):
"""
Returns the value of the card in a game
of Rummy.
"""
# if it's an Ace, its value is 15
if self._rank == 14:
rummyValue = 15
# if it's a 10 or face card, its value is 10
elif self._rank <= 13 and self._rank >= 10:
rummyValue = 10
else: # it's a number card
rummyValue = 5
return rummyValue
def main():
c1 = Card(14, "spades")
print(c1)
print(c1.getRummyValue())
c2 = Card(13, "hearts")
print(c2)
c3 = Card(2, "diamonds")
print(c3)
# could put the tests in separate functions
# but want to test the same object in different ways
# 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 ]
# 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.py 2/4
[top][prev][next]
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 getRummyValue(self):
"Returns the value of the card in the game of Rummy."
# using the helper method may not be the best way
# to implement this, but want to show what we can do.
if self._isFaceCard(): # handles face cards
return 10
elif self._rank == 14: # handles Ace
return 15
elif self._rank == 10: # handles 10
return 10
else:
return 5
def __eq__(self, other):
"""Returns true if this object and other are equivalent
based on their rank and suit"""
# 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 __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 _isFaceCard(self):
"Returns True iff the card is a face card."
if self._rank > 10 and self._rank < 14:
return True
return False
def main():
c1 = Card(14, "spades")
print(c1)
c2 = Card(13, "hearts")
print(c2)
c3 = Card(2, "diamonds")
print(c3)
# test getRummyValue
test.testEqual( c1.getRummyValue(), 15 )
test.testEqual( c2.getRummyValue(), 10 )
test.testEqual( c3.getRummyValue(), 5 )
# test equals and less than
test.testEqual( c1 == c2, False)
test.testEqual( c1 < c2, False)
test.testEqual( c2 < c1, True)
print("\nTested cards in sorted order:")
testCases.sort()
for card in testCases:
print(card)
# 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 3/4
[top][prev][next]
# Implementation of a deck of cards.
# by CSCI 111
from card2 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):
myCard = Card(rank, suit)
self._listOfCards.append(myCard)
def __str__(self):
"""Returns a string representing the cards that are
in the deck."""
deckRep= ""
for card in self._listOfCards:
deckRep += str(card) + "\n"
return deckRep
def main():
d = Deck()
print(d)
# 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 4/4
[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
Generated by GNU Enscript 1.6.5.90.