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?
11 7536
Please repost your message using [code][/code] tags around all code you post.
- #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?
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: -
class DeckOfCard:
-
def __init__(self, some_kind_of_data):
-
# create deck of cards
-
You already got the shortcut (instead of typing out all 52, spec 13 cards and 4 suits) so finish these: -
rank_desc = {"1":"Ace", "2":"Two", "3":"Trey", "4":"Four",
-
"5":"Five", "6":"Six", "7":"Seven"} # describe each rank in a dictionary
-
suit_desc = {"s":"Spades", "h":"Hearts"} # describe each suit in a dictionary
-
Then write them to a file with -
-
def WriteCardDatabase(filename):
-
""""Create a random collection of card specs.
-
Dictionaries work great because they are not ordered lists."""
-
outputList = [] # an empty list for temporary storage
-
for rank, r_desc in rank_desc.items():
-
for suit, s_desc in suit_desc.items():
-
line = rank + " " + suit + "\n"
-
outputList.append(line)
-
outputFile = file(filename, "w") # open or create a file in "w"rite mode
-
outputFile.writelines(outputList)
-
outputFile.close()
-
Can you do that?
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.
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
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: -
rank_desc = {"1":"Ace", "2":"Two", "3":"Trey", "4":"Four",
-
"5":"Five", "6":"Six", "7":"Seven"} # describe each rank in a dictionary
-
suit_desc = {"s":"Spades", "h":"Hearts"} # describe each suit in a dictionary
-
class PlayingCard:
-
def __init__ ( self, rank, suit ): # Creates a card.
-
self.rank = rank
-
self.suit = suit
-
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)
-
def __str__(self): # Returns a string naming the card. For example: 'Ace of Spades'
-
return "The %s of %s is worth %d Blackjack" %(rank_desc[self.rank],
-
suit_desc[self.suit],
-
self.BJValue())
-
def WriteCardDatabase(filename):
-
""""Create a random collection of card specs.
-
Dictionaries work great because they are not ordered lists."""
-
outputList = [] # an empty list for temporary storage
-
for rank, r_desc in rank_desc.items():
-
for suit, s_desc in suit_desc.items():
-
line = rank + " " + suit + "\n"
-
outputList.append(line)
-
outputFile = file(filename, "w") # open or create a file in "w"rite mode
-
outputFile.writelines(outputList)
-
outputFile.close()
-
def ReadCardDatabase(filename):
-
inputFile = file(filename, "r") # read mode
-
inputList = inputFile.readlines()
-
inputFile.close()
-
return inputList
-
def CreateDeckOfCards(cardspecs):
-
cardList = []
-
for item in cardspecs:
-
cardspec = item.split()
-
rank, suit = cardspec[0], cardspec[1]
-
cardList.append(PlayingCard(rank, suit))
-
return cardList
-
class DeckOfCards:
-
def __init__(self, cardspecs): # Creates a deck of cards in standard order.
-
self.deck = CreateDeckOfCards(cardspecs)
-
def Shuffle(self): # Randomizes the order of the cards.
-
pass
-
def DealCard(self): # Returns a single card from the top of the deck, and removes the card from the deck.
-
return self.deck.pop(0) # pop the first card off the deck
-
def CardsLeft(self): # Returns the number of cards left in the deck
-
return len(self.deck)
-
-
# WriteCardDatabase(r"C:\WINDOWS\Temp\cardlist.txt")
-
cardspecList = ReadCardDatabase(r"C:\WINDOWS\Temp\cardlist.txt")
-
# now that you have a list, you can create a DeckOfCards object
-
### just move this from the module scope to the class scope
-
# myDeck = CreateDeckOfCards(cardspecList)
-
myDeck = DeckOfCards(cardspecList)
-
print myDeck.DealCard()
-
print myDeck.CardsLeft()
-
print myDeck.DealCard()
-
print myDeck.CardsLeft()
-
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]
OK, i worked it out but it is giving me an error here -
Traceback (most recent call last):
-
File "D:\pythonassign2\52cards.py", line 80, in ?
-
myCard = myDeck.DealCard()
-
File "D:\pythonassign2\52cards.py", line 50, in DealCard
-
return self.deck.pop(0) # pop the first card off the deck
-
IndexError: pop from empty list
-
should i place 52 in the empty list, what you reckon it will solve the problem?
bvdet 2,851
Recognized Expert Moderator Specialist -
try:
-
return self.deck.pop(0)
-
except IndexError:
-
return None
This will return the Python null object None and tell the calling function that the deck is empty. Check bartonc's code.
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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...
|
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;
|
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 ' **** ??????? ****
|
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.
|
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...
| |
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,...
|
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...
|
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,...
|
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...
|
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();...
|
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...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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...
| |