BlackJack - 类解决方案不正确?

时间:2017-07-26 16:18:29

标签: python

我正在通过二十一点游戏作为我在udemy上购买的python课程的作业,我相信我发现该课程提供的解决方案存在问题。我自己对代码进行了更改以使其工作,但我想问一下stackoverflow社区2个问题:1)有人请解释为什么解决方案不起作用?我将在下面做一些猜测,但作为一个初学者,我想明白为什么我自己的利益是错的。 2)我解决这个问题的方法是一个好的解决方案吗?如果没有,我可以用其他方式编写代码吗?

这是给定的解决方案(我只展示了3类:卡片,手和甲板 - 问题在甲板内,特别是甲板的 str 功能)

# Let's start with defining our suits, ranks and values
suits = ('H','D','C','S')
ranking = ('A','2','3','4','5','6','7','8','9','10','J','Q','K')
card_val = {'A':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}

class Card(object):
    # card needs a suit and rank
    def __init__(self, suit, rank):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        return self.suit + self.rank

    def get_suit(self):
        return self.suit

    def get_rank(self):
        return self.rank

    def draw(self):
        print (self.suit + self.rank)

class Hand(object):
    # A hand needs 2 cards and a total value
    def __init__(self):
        self.hand = []
        self.value = 0
        self.ace = False

    def __str__(self):
        hand_comp = ''
        for card in self.hand:
            card_name = card.__str__
            hand_comp += " " + card_name
        return 'The hand has %s' %hand_comp

    def card_add(self, card):
        self.hand.append(card)

    # Check for Aces
    if card.rank == 'A':
        self.ace = True
    self.value += card_val[card.rank]

    def calc_val(self):
    # calculate the value of the hand, make aces an 11 if they don't bust
        if(self.ace == True and self.value < 12):
            return self.value + 10
        else:
            return self.value

    def draw(self, hidden):
        if hidden == True and  playing == True:
            #Don't show first hidden card
            starting_card = 1
        else:
            starting_card = 0
        for x in range(starting_card, len(self.hand)):
            self.hand[x].draw()


    class Deck(object):
    def __init__(self):
        self.deck = []
        for s in suits:
            for r in ranking:
                self.deck.append(Card(s,r))

    def shuffle(self):
        random.shuffle(self.deck)

    def deal(self):
        single_card = self.deck.pop()
        return single_card

    def __str__(self):
        deck_comp = ''
        for card in self.hand:
            deck_comp += " " + deck_comp.__str__()
        return "The deck has " + deck_comp

我的问题在于Deck类下的def str 功能。该解决方案要求程序在... self.hand(在Hand类下)运行for循环。我不明白为什么这会起作用。 self.hand与让一个完整的牌组返回给我没有任何关系。其次,是deck_comp + =“”+ deck_comp。 str ()好的代码?如果我只将循环更改为self.deck,我发现程序会冻结。我创建了一个名为cards_name的新变量并将其分配给卡片。 str ()以获得每张卡片的套装和排名。

这是我将代码更正为:

    def __str__(self):
        deck_comp = ''
        for card in self.deck:
            cards_name = card.__str__()
            deck_comp += " " + cards_name
        return "The deck has " + deck_comp

0 个答案:

没有答案