473,385 Members | 1,863 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Cards in python (classes PlayingCard & DeckOfCards) [solved]

i am worlking on the cards class so it can do several things.

My code is as before but need to change the things to solve given problem

Create a new class Deck that represents a pack of 52 cards. The class should support the following methods:
__init__ ( self ) Creates a deck of cards in standard order.
shuffle(self) Randomizes the order of the cards.
dealCard(self) Returns a single card from the top of the deck, and removes the card from the deck.
cardsLeft(self) Returns the number of cards left in the deck.
Test your class by having it deals out a sequence of n cards where n is a number input by the user. The program should either print out the cards, or display them in a window.

The last code was : -

#card.py
import string
n = input("Enter the value: ")
rank_desc = (None, "Ace", "Two", "Three", "Four") # describe each rank in a tuple
suit_desc = {"s":"Spades", "h":"Hearts", "c": "Clubs", "d": "Diamonds"} # describe each suit in a dictionary
class PlayingCard:
def __init__ ( self, rank, suit ): # Creates a card.
self.rank = rank
self.suit = suit
def __str__(self): # Returns a string naming the card. For example: 'Ace of Spades'
return "The %s of %s is worth %d in Blackjack" %(rank_desc[self.rank],
suit_desc[self.suit], self.BJValue())
def getRank(self): #Returns the rank of the card.
return self.rank
def getSuit(self): # Returns the suit of the card.
return self.suit
def BJValue(self): # Returns the 'Blackjack value' of the card (Ace;1, Face card:10)
return min(self.rank, 10)

AceOfSpades = PlayingCard(1, 's')
print AceOfSpades
print AceOfSpades.getRank()

AceOfHearts = PlayingCard(2, 'h')
print AceOfHearts
print AceOfSpades.getRank()

AceOfClubs = PlayingCard(3, 'c')
print AceOfClubs
print AceOfSpades.getRank()

AceOfDiamonds = PlayingCard(4, 'd')
print AceOfDiamonds
print AceOfSpades.getRank()

what should i change in this code to make it possible and solve out the above given problem?
Oct 29 '06 #1
11 7488
brokow
7
Please repost your message using [code][/code] tags around all code you post.
Oct 29 '06 #2
Expand|Select|Wrap|Line Numbers
  1. #card.py
  2. import string
  3.     n = input("Enter the value: ")
  4. rank_desc = (None, "Ace", "Two", "Three", "Four") # describe each rank in a tuple
  5. suit_desc = {"s":"Spades", "h":"Hearts", "c": "Clubs", "d": "Diamonds"} # describe each suit in a dictionary
  6.    class PlayingCard:
  7.            def __init__ ( self, rank, suit ): # Creates a card.
  8.                              self.rank = rank
  9.                              self.suit = suit
  10.           def __str__(self): # Returns a string naming the card. For example: 'Ace of Spades'
  11.         return "The %s of %s is worth %d in Blackjack" %(rank_desc[self.rank],
  12.               suit_desc[self.suit], self.BJValue())
  13. def getRank(self): #Returns the rank of the card.
  14. return self.rank
  15. def getSuit(self): # Returns the suit of the card. 
  16. return self.suit
  17. def BJValue(self): # Returns the 'Blackjack value' of the card (Ace;1, Face card:10) 
  18. return min(self.rank, 10)
  19.  
  20. AceOfSpades = PlayingCard(1, 's')
  21. print AceOfSpades
  22. print AceOfSpades.getRank()
  23.  
  24. AceOfHearts = PlayingCard(2, 'h')
  25. print AceOfHearts
  26. print AceOfSpades.getRank()
  27.  
  28. AceOfClubs = PlayingCard(3, 'c')
  29. print AceOfClubs
  30. print AceOfSpades.getRank()
  31.  
  32. AceOfDiamonds = PlayingCard(4, 'd')
  33. print AceOfDiamonds
  34. print AceOfSpades.getRank()
  35.  
what should i change in this code to make it possible and solve out the above given problem?
Oct 29 '06 #3
bartonc
6,596 Expert 4TB
i am worlking on the cards class so it can do several things.

My code is as before but need to change the things to solve given problem

Create a new class Deck that represents a pack of 52 cards. The class should support the following methods:
__init__ ( self ) Creates a deck of cards in standard order.
shuffle(self) Randomizes the order of the cards.
dealCard(self) Returns a single card from the top of the deck, and removes the card from the deck.
cardsLeft(self) Returns the number of cards left in the deck.
Test your class by having it deals out a sequence of n cards where n is a number input by the user. The program should either print out the cards, or display them in a window.

what should i change in this code to make it possible and solve out the above given problem?
First, change the way you post (see below and lots of other places).
Second, give this an honest attempt from the pieces that you have been given already (we really like to see you learning and don't want to think that we are doing all your work for you).
You will need specifications for all 52 cards to give to the:
Expand|Select|Wrap|Line Numbers
  1. class DeckOfCard:
  2.     def __init__(self, some_kind_of_data):
  3.         # create deck of cards
  4.  
You already got the shortcut (instead of typing out all 52, spec 13 cards and 4 suits) so finish these:
Expand|Select|Wrap|Line Numbers
  1. rank_desc = {"1":"Ace", "2":"Two", "3":"Trey", "4":"Four",
  2.              "5":"Five", "6":"Six", "7":"Seven"}    # describe each rank in a dictionary
  3. suit_desc = {"s":"Spades", "h":"Hearts"}    # describe each suit in a dictionary
  4.  
Then write them to a file with
Expand|Select|Wrap|Line Numbers
  1.  
  2. def WriteCardDatabase(filename):
  3.     """"Create a random collection of card specs.
  4.     Dictionaries work great because they are not ordered lists."""
  5.     outputList = []   # an empty list for temporary storage
  6.     for rank, r_desc in rank_desc.items():
  7.         for suit, s_desc in suit_desc.items():
  8.             line  = rank + " " + suit + "\n"
  9.             outputList.append(line)
  10.     outputFile = file(filename, "w")   # open or create a file in "w"rite mode
  11.     outputFile.writelines(outputList)
  12.     outputFile.close()
  13.  
Can you do that?
Oct 29 '06 #4
yeah i can do this but it is said that we have to write it in the new window or we have to print out the cards.
Oct 29 '06 #5
i am sorry if i am bothering anyone of you but i am learning the language, so thats y i want help if i didnot see your style of programming then how i will learn, i want to see how people program and how different it is from the book. As you people know all people have thier own way and style of programming. Please don't bother if you don't wanna answer.

thanx
Oct 29 '06 #6
bartonc
6,596 Expert 4TB
i am sorry if i am bothering anyone of you but i am learning the language, so thats y i want help if i didnot see your style of programming then how i will learn, i want to see how people program and how different it is from the book. As you people know all people have thier own way and style of programming. Please don't bother if you don't wanna answer.

thanx
It's not a bother, really. What you say is very true. I meant that we want to see your style as you learn. So post you working (or not) code so that we can help you improve even more! Here is some working (unfinished) code to get you started:
Expand|Select|Wrap|Line Numbers
  1. rank_desc = {"1":"Ace", "2":"Two", "3":"Trey", "4":"Four",
  2.              "5":"Five", "6":"Six", "7":"Seven"}    # describe each rank in a dictionary
  3. suit_desc = {"s":"Spades", "h":"Hearts"}    # describe each suit in a dictionary
  4. class PlayingCard:
  5.     def __init__ ( self, rank, suit ): # Creates a card.
  6.         self.rank = rank
  7.         self.suit = suit
  8.     def getRank(self): #Returns the rank of the card.
  9.         return self.rank
  10.     def getSuit(self): # Returns the suit of the card. 
  11.         return self.suit
  12.     def BJValue(self): # Returns the 'Blackjack value' of the card (Ace;1, Face card:10) 
  13.         return min(self.rank, 10)
  14.     def __str__(self): # Returns a string naming the card. For example: 'Ace of Spades'
  15.         return "The %s of %s is worth %d Blackjack" %(rank_desc[self.rank],
  16.                                                  suit_desc[self.suit],
  17.                                                  self.BJValue())
  18. def WriteCardDatabase(filename):
  19.     """"Create a random collection of card specs.
  20.     Dictionaries work great because they are not ordered lists."""
  21.     outputList = [] # an empty list for temporary storage
  22.     for rank, r_desc in rank_desc.items():
  23.         for suit, s_desc in suit_desc.items():
  24.             line = rank + " " + suit + "\n"
  25.             outputList.append(line)
  26.     outputFile = file(filename, "w") # open or create a file in "w"rite mode
  27.     outputFile.writelines(outputList)
  28.     outputFile.close()
  29. def ReadCardDatabase(filename):
  30.     inputFile = file(filename, "r")    # read mode
  31.     inputList = inputFile.readlines()
  32.     inputFile.close()
  33.     return inputList
  34. def CreateDeckOfCards(cardspecs):
  35.     cardList = []
  36.     for item in cardspecs:
  37.         cardspec = item.split()
  38.         rank, suit = cardspec[0], cardspec[1]
  39.         cardList.append(PlayingCard(rank, suit))
  40.     return cardList
  41. class DeckOfCards:
  42.     def __init__(self, cardspecs): # Creates a deck of cards in standard order.
  43.         self.deck = CreateDeckOfCards(cardspecs)
  44.     def Shuffle(self): # Randomizes the order of the cards.
  45.         pass
  46.     def DealCard(self): # Returns a single card from the top of the deck, and removes the card from the deck.
  47.         return self.deck.pop(0) # pop the first card off the deck
  48.     def CardsLeft(self): # Returns the number of cards left in the deck
  49.         return len(self.deck)
  50.  
  51. # WriteCardDatabase(r"C:\WINDOWS\Temp\cardlist.txt")
  52. cardspecList = ReadCardDatabase(r"C:\WINDOWS\Temp\cardlist.txt")
  53. # now that you have a list, you can create a DeckOfCards object
  54. ### just move this from the module scope to the class scope
  55. # myDeck = CreateDeckOfCards(cardspecList)
  56. myDeck = DeckOfCards(cardspecList)
  57. print myDeck.DealCard()
  58. print myDeck.CardsLeft()
  59. print myDeck.DealCard()
  60. print myDeck.CardsLeft()
  61.  
Oct 29 '06 #7
bartonc
6,596 Expert 4TB
Here is a shuffle method that mostly works and an improved (no error dealing from an empty deck) dealcard method and a print routine:

[HTML]
def Shuffle(self): # Randomizes the order of the cards.
nCards = len(self.deck) - 1 # initialize working variables
tempList = copy.copy(self.deck)
index = randint(0, nCards)
positionList = [index]
for item in tempList: # find next random position in the deck
self.deck[index] = item
while (index in positionList) and (len(positionList) <= nCards):
index = randint(0, nCards)
positionList.append(index) # mark this position as used
def DealCard(self): # Returns a single card from the top of the deck, and removes the card from the deck.
try:
return self.deck.pop(0) # pop the first card off the deck
except IndexError:
return None


myDeck = DeckOfCards(cardspecList)
myDeck.Shuffle()
myCard = myDeck.DealCard()
while myCard:
print myCard
print myDeck.CardsLeft()
myCard = myDeck.DealCard()
[/HTML]
Oct 29 '06 #8
OK, i worked it out but it is giving me an error here

Expand|Select|Wrap|Line Numbers
  1. Traceback (most recent call last):
  2.   File "D:\pythonassign2\52cards.py", line 80, in ?
  3.     myCard = myDeck.DealCard()
  4.   File "D:\pythonassign2\52cards.py", line 50, in DealCard
  5.     return self.deck.pop(0) # pop the first card off the deck
  6. IndexError: pop from empty list
  7.  
should i place 52 in the empty list, what you reckon it will solve the problem?
Oct 29 '06 #9
bvdet
2,851 Expert Mod 2GB
Expand|Select|Wrap|Line Numbers
  1. try:
  2.         return self.deck.pop(0)
  3. except IndexError:
  4.         return None
This will return the Python null object None and tell the calling function that the deck is empty. Check bartonc's code.
Oct 29 '06 #10
i think u need this code i hope it will work for u ...

from random import*
#from Card import Card
from string import*
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
self.ranks = [None, "ace", "2", "3", "4", "5", "6", "7", "8","9", "10", "jack", "queen", "king"]
self.suits = [None, "spades","diamonds","clubs","hearts"]
self.BJ = [None, 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

def getRank(self):
"Returns the rank of the card."
return self.rank

def getSuit(self):
"Returns the suit of the card."
return self.suit

def BJValue(self):
"Returns the Blackjack value of the card."
return 0 ## temporary

def __str__(self):
#"Returns a string that names the card."
return "The %s of %s is worth (%s) in Blackjack" % (self.ranks[self.rank],
self.suits[self.suit], self.BJ[self.rank])

def main():
# Ask the user to select the number of cards
n = input("Enter the number of cards to draw >>")
for i in range(n):
x = randrange(1,13)
y = randrange(1,4)
z=Card(x,y)
print z
main()
Oct 31 '06 #11
bartonc
6,596 Expert 4TB
i think u need this code i hope it will work for u ...
Welcome to the python formum and thank you for posting.
Please use [code] tags around you code next time. Thanks, again,
Forum Moderator
Oct 31 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

54
by: Brandon J. Van Every | last post by:
I'm realizing I didn't frame my question well. What's ***TOTALLY COMPELLING*** about Ruby over Python? What makes you jump up in your chair and scream "Wow! Ruby has *that*? That is SO...
2
by: kelvSYC | last post by:
I'm trying to program something along the lines of a "trading card" idea: I have a single copy of the "card" in the program, yet there may be multiple "instances" of the "card", with differing...
7
by: GrandpaB | last post by:
While writing this plea for help, I think I solved my dilemma, but I don't know why the statement that solved the problem is necessary. The inspiration for the statement came from an undocumented...
11
by: cazconv2007 | last post by:
hi i have homework due tomorrow been trying to do java homework all week and nothings happening really starting to stress out i dont understand what the program is meant to do or how to use three...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.