473,769 Members | 2,365 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

12 New Member
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.get Rank()

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

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

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

what should i change in this code to make it possible and solve out the above given problem?
Oct 29 '06 #1
11 7536
brokow
7 New Member
Please repost your message using [code][/code] tags around all code you post.
Oct 29 '06 #2
prince99
12 New Member
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 Recognized Expert Expert
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
prince99
12 New Member
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
prince99
12 New Member
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 Recognized Expert Expert
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 Recognized Expert Expert
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(positionLi st) <= nCards):
index = randint(0, nCards)
positionList.ap pend(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(car dspecList)
myDeck.Shuffle( )
myCard = myDeck.DealCard ()
while myCard:
print myCard
print myDeck.CardsLef t()
myCard = myDeck.DealCard ()
[/HTML]
Oct 29 '06 #8
prince99
12 New Member
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 Recognized Expert Moderator Specialist
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

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

Similar topics

54
6576
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 FRICKIN' COOL!!! ***MAN*** that would save me a buttload of work and make my life sooooo much easier!" As opposed to minor differences of this feature here, that feature there. Variations on style are of no interest to me. I'm coming at this from a...
2
2173
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 information (such as the owner of the "card") in each instance. struct Person; Person Bob; Person Joe;
7
2369
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 VB example I found on the web. I would be most appreciative if someone could explain why this statement is necessary and what does it do? MyArt = New Art ' **** ??????? ****
11
14153
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 classes The program This week you are going to write three classes: Card.java, Deck.java and DeckTester.java. The specification for each class is given below. Card.Java This is a simple class that represents a playing card.
0
9586
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10043
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9861
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5298
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2814
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.