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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • prince99
    New Member
    • Oct 2006
    • 12

    #1

    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.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?
  • brokow
    New Member
    • Oct 2006
    • 7

    #2
    Please repost your message using [code][/code] tags around all code you post.

    Comment

    • prince99
      New Member
      • Oct 2006
      • 12

      #3
      Code:
      #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?

      Comment

      • bartonc
        Recognized Expert Expert
        • Sep 2006
        • 6478

        #4
        Originally posted by prince99
        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:
        Code:
        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:
        Code:
        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
        Code:
         
        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?

        Comment

        • prince99
          New Member
          • Oct 2006
          • 12

          #5
          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.

          Comment

          • prince99
            New Member
            • Oct 2006
            • 12

            #6
            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

            Comment

            • bartonc
              Recognized Expert Expert
              • Sep 2006
              • 6478

              #7
              Originally posted by prince99
              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:
              Code:
              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()

              Comment

              • bartonc
                Recognized Expert Expert
                • Sep 2006
                • 6478

                #8
                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]

                Comment

                • prince99
                  New Member
                  • Oct 2006
                  • 12

                  #9
                  OK, i worked it out but it is giving me an error here

                  Code:
                  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?

                  Comment

                  • bvdet
                    Recognized Expert Specialist
                    • Oct 2006
                    • 2851

                    #10
                    Code:
                    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.

                    Comment

                    • anaroxian
                      New Member
                      • Oct 2006
                      • 1

                      #11
                      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","diamo nds","clubs","h earts"]
                      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()

                      Comment

                      • bartonc
                        Recognized Expert Expert
                        • Sep 2006
                        • 6478

                        #12
                        Originally posted by anaroxian
                        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

                        Comment

                        Working...