2013-05-22 61 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

相關問題