Contents
- card.py
- 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 <=13:
return 10
return 15
def main():
c1 = Card(14, "spades")
print c1
c2 = Card(13, "hearts")
print c2
c3 = Card(2, "diamonds")
print c3
#myString = c3.__str__()
#myString2 = str(c3)
#print myString
#print myString2
if __name__ == '__main__':
main()
deck.py 2/2
[top][prev][next]
from card import *
from random import shuffle
class Deck:
""" A class to represent a deck of playing cards."""
def __init__(self):
"Constructs a new Deck object, with all the standard cards in it."
# the instance variable that represents the cards
self.deck = []
# executes 4 times (once for each suit)
for suit in ["clubs","hearts","diamonds","spades"]:
# executes 13 times (once for each rank)
for rank in range(2,15):
# the body of this loop gets executed a total of 52
# times
card = Card(rank, suit)
self.deck.append(card)
def __str__(self):
"Returns a string representation of the cards in the deck"
# accumulate the cards in the deck in a string
result = ""
for c in self.deck:
# Either of the following two lines do the same thing,
# have the same result:
#result += c.__str__() + "\n"
result += str(c) + "\n"
return result
# TODO: Complete remaining functionality
def shuffle(self):
"Shuffle the cards that are currently in the deck"
shuffle(self.deck) # from random module
def numCardsRemaining(self):
return len(self.deck)
def draw(self):
cardDrawn = self.deck.pop(0)
return cardDrawn
def deal(self, numCards):
cardsDealt =[]
for x in xrange( numCards ):
card = self.draw()
cardsDealt.append(card)
return cardsDealt
def main():
d = Deck()
print d
# TODO: Test the new methods
# 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()
Generated by GNU enscript 1.6.4.