2013-05-22 63 views
1

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

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' 

我会很高兴地感谢所有帮助,这是我第一次来这里,所以我道歉,如果我打破了规则或什么。

+0

当你说“当我运行这个”,你做了什么:3? – TerryA

+0

我从源代码编译Python,所以我输入了./python /blackjack.py – Silbern

+0

您是否创建了该类的实例?即,你是否做过类似'player1 = BlackjackPlayer('params')' – TerryA

回答

2

我不确定你的问题在于你已经显示的代码,因为你实际上并不是在中调用get_value()

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

例如:

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

最重要的是,你的得分似乎没有考虑到一个事实,即王牌可软(1)或硬(11)。

+2

+1为'一眼吉姆' –

+0

感谢您的帮助!令人尴尬的是,我没有正确地调用它。感谢您的时间和帮助! – Silbern

0

BlackjackPlayer.hit()可能是您造成麻烦的原因。如果你想使用类中的函数,你必须创建该类的一个实例。然而,当你调用从类中的函数,你可以简单地做:

self.hit() 

另外:

total += BlackjackPlayer[-1] 

我不知道你打算在这里是什么,但如果你想访问hand列表,这样做:

total += self.hand[-1] 
+0

感谢提示,他们非常有帮助! – Silbern

相关问题