How to approach the implementation of "Class Card" as required by the Python tutorial

I am currently working on programming in the John Zel Python Language: An Introduction to Computer Science and Getting Trapped in Chapter 10. I have a conceptual problem understanding the reasons and ways of this exercise and need some help on how to approach the problem. The exercise asks me to create a program that displays n number of cards using a class named Card

and requires the following methods. It must also be called from an application that generates n number of random cards:

  • __init__(self, rank, suit):

  • getRank(self)

  • getSuite(self)

  • BJValue(self)

  • __str__(self)

As funny as it should be, I hit the wall trying to implement this class. I created a simple application that will generate a 52-card deck, ask the user for the number of cards they want, and then fills in the hand with those cards. I just can't figure out where I would benefit from a certain class of card after the hand is created. Here is my working code:

import random

class Card:
    def __init__(self, rank, suite):
        self.rank = rank
        self.suite = suite

    def getRank(self):
        return self.rank

    def getSuite(self):
        return self.suite

    def BJValue(self):
        if self.rank == 'Ace':
            return 1
        elif self.rank == 'Jack' or self.rank == 'Queen' or self.rank == 'King':
            return 10
        else:
        return int(self.rank)

    def __str__(self):
        return ('{0} of {1}'.format(self.rank, self.suite))


def shuffled_deck():
    deck = []
    for suite in ['Clubs', 'Diamonds', 'Hearts', 'Spades']:
        for num in ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']:
            deck.append([num, suite])
    random.shuffle(deck)
    return deck


def main():
    deck = shuffled_deck()
    hand = []
    print('>> Card Generator v1 <<')
    while True:
        try:
            n = int(input('Please enter the number of cards to display (1-7): '))
        except ValueError:
            print('Invalid input, please enter a number!\n')
        else:
            if n < 1 or n > 7:
                print('Please enter a number between 1-7!\n')
            else:
                break
    print('Your hand is:')
    for i in range(n):
        hand.append(deck[i])



main()

      

So, once I've created a hand of random n cards, I don't see how I would benefit from using the Card class, or even where to implement it. Since n is a random number between 1-7, I will need n number of variables to store each map object, then assign each variable to an instance Card

. I can show each card in my hand hand[i]

where I am iterating up to range(n)

without the need for a special class Card

, but that is not what is expected of this project. I'm looking for advice on how to think about this problem so that I can use this required class.

+3


source to share


2 answers


It looks like the only thing you need to change in your code is to change the line:

deck.append([num, suite])

      

to

deck.append(Card(num, suite))

      

This turns the variable deck

into a list of 52 Card

objects. This is useful because objects Card

have built-in functions that don't have a two-element list (for example [num, suite]

).


Two examples: if you add the line



print hand

      

after your code, your current code will print something like

[["Jack", "Clubs"], ["9", "Spades"]]

      

while your new code will print

[Jack of Clubs, 9 of Spades]

      

(The string print "\n".join(map(str, hand)))

might be closer to what you want in practice). You can also get the total blackjack value of your hand with the line:

sum(c.BJValue() for c in hand)

      

+11


source


I think any map class in python should have an __unicode__ method that uses u "\ u2263" etc. - just for fun. I would also recommend decorating it with @ functools.total_ordering along with the __eq__ and __gt__ methods so that the map can be matched; also, the "sorted" inline will sort the list of cards accordingly.



0


source







All Articles