0

我是 Python 新手,需要一些帮助。我正在编写一个二十一点程序作为家庭作业,我想我可能让它工作,但每当我运行它时,它都会抱怨我没有为“自我”提供任何东西。我以为我不必?这是完整的代码:

class BlackjackPlayer:
    '''Represents a player playing blackjack
    This is used to hold the players hand, and to decide if the player has to hit or not.'''
    def __init__(self,Deck):
        '''This constructs the class of the player.
        We need to return the players hand to the deck, get the players hand, add a card from the deck to the playters hand, and to allow the player to play like the dealer.
        In addition to all of that, we need a deck.'''
        self.Deck = Deck
        self.hand = []

    def __str__(self):
        '''This returns the value of the hand.'''
        answer = 'The cards in the hand are:' + str(self.hand)
        return(answer)

    def clean_up(self):
        '''This returns all of the player's cards back to the deck and shuffles the deck.'''
        self.Deck.extend(self.hand)
        self.hand = []
        import random
        random.shuffle(self.Deck)

    def get_value(self):
        '''This gets the value of the player's hand, and returns -1 if busted.'''
        total = 0
        for card in self.hand:
            total += card
        if total > 21:
            return(-1)
        else:
            return(self.hand)

    def hit(self):
        '''add one card from the Deck to the player's hand.'''
        self.hand.append(self.Deck[0])
        self.Deck = self.Deck[1:]
        print(self.hand)

    def play_dealer(self):
        '''This will make the player behave like the dealer.'''
        total = 0
        for card in self.hand:
            total += card
        while total < 17:
            BlackjackPlayer.hit()
            total += BlackjackPlayer[-1]
            print(self.hand)
        if self.hand > 21:
            return -1
        else:
            return total

当我运行它时,我得到:

TypeError: get_value() missing 1 required positional arguments: 'self'

我很乐意为您提供帮助,这是我第一次来这里,所以如果我违反了规则或其他什么,我深表歉意。

4

2 回答 2

3

我不确定您遇到的问题出在您显示的代码中,因为您实际上并没有在其中的任何地方调用。 get_value()

这与您使用此类的方式有关。您需要确保为此类实例化一个对象并使用它来调用该函数。这样,self自动添加到参数列表的前缀。

例如:

oneEyedJim = BlackJackPlayer()
score = oneEyedJim.get_value()

最重要的是,您的得分似乎没有考虑到 A 可以是软 (1) 或硬 (11) 的事实。

于 2013-05-22T05:34:36.610 回答
0

BlackjackPlayer.hit()可能是给你带来麻烦的事情。如果要使用类中的函数,则必须创建该类的实例。但是,当您从类中调用函数时,您可以简单地执行以下操作:

self.hit()

还:

total += BlackjackPlayer[-1]

我不知道您打算在这里做什么,但是如果您想访问该hand列表,请执行以下操作:

total += self.hand[-1]
于 2013-05-22T05:34:54.623 回答