2012-10-18 98 views
7

我正在開發一個使用Python3的簡單的基於文本的Dungeon遊戲。首先提示用戶從screen.py文件中選擇英雄。TypeError:__init __()至少需要2個參數(給出1個)error

from game import * 


class GameScreen: 
    '''Display the current state of a game in a text-based format. 
    This class is fully implemented and needs no 
    additional work from students.''' 

    def initialize_game(self): 
     '''(GameScreen) -> NoneType 
     Initialize new game with new user-selected hero class 
     and starting room files.''' 

     hero = None 
     while hero is None: 
      c = input("Select hero type:\n(R)ogue (M)age (B)arbarian\n") 
      c = c.lower() 
      if c == 'r': 
       hero = Rogue() 
      elif c == 'm': 
       hero = Mage() 
      elif c == 'b': 
       hero = Barbarian() 

     self.game = Game("rooms/startroom", hero) 

    def play(self): 
     '''(Game) -> NoneType 
     The main game loop.''' 

     exit = False 
     while not exit: 
      print(self) 
      if self.game.game_over(): 
       break 
      c = input("Next: ") 
      if c in ['q', 'x']: 
       print("Thanks for playing!") 
       exit = True 
      elif c == 'w': # UP 
       self.game.move_hero(-1, 0) 
      elif c == 's': # DOWN 
       self.game.move_hero(1, 0) 
      elif c == 'a': # LEFT 
       self.game.move_hero(0, -1) 
      elif c == 'd': # RIGHT 
       self.game.move_hero(0, 1) 
      elif c == 'r': 
       ## RESTART GAME 
       self.initialize_game() 
      else: 
       pass 

    def __str__(self): 
     '''(GameScreen) -> NoneType 
     Return a string representing the current room. 
     Include the game's Hero string represetation and a 
     status message from the last action taken.''' 

     room = self.game.current_room 
     s = "" 

     if self.game.game_over(): 
      #render a GAME OVER screen with text mostly centered 
      #in the space of the room in which the character died. 

      #top row 
      s += "X" * (2 + room.cols) + "\n" 
      #empty rows above GAME OVER 
      for i in list(range(floor((room.rows - 2)/2))): 
       s += "X" + " " * room.cols + "X\n" 
      # GAME OVER rows 
      s += ("X" + " " * floor((room.cols - 4)/2) + 
       "GAME" + " " * ceil((room.cols - 4)/2) + "X\n") 
      s += ("X" + " " * floor((room.cols - 4)/2) + 
       "OVER" + " " * ceil((room.cols - 4)/2) + "X\n") 
      #empty rows below GAME OVER 
      for i in list(range(ceil((room.rows - 2)/2))): 
       s += "X" + " " * room.cols + "X\n" 
      #bottom row 
      s += "X" * (2 + room.cols) + "\n" 
     else: 
      for i in range(room.rows): 
       for j in room.grid[i]: 
        if j is not None: 
         if j.visible: 
          s += j.symbol() 
         else: 
          #This is the symbol for 'not yet explored' : ? 
          s += "?" 
       s += "\n" 
     #hero representation 
     s += str(self.game.hero) 
     #last status message 
     s += room.status 
     return s 

if __name__ == '__main__': 
    gs = GameScreen() 
    gs.initialize_game() 
    gs.play() 

每當我運行此代碼,我得到這個錯誤:類型錯誤:初始化()至少需要2個參數(1給出),這與盜賊()或其他英雄職業的事情。這裏是hero.py.

class Rogue(Tile): 
    '''A class representing the hero venturing into the dungeon. 
    Heroes have the following attributes: a name, a list of items, 
    hit points, strength, gold, and a viewing radius. Heroes 
    inherit the visible boolean from Tile.''' 

    def __init__(self, rogue, bonuses=(0, 0, 0)): 
     '''(Rogue, str, list) -> NoneType 
     Create a new hero with name Rogue, 
     an empty list of items and bonuses to 
     hp, strength, gold and radius as specified 
     in bonuses''' 

     self.rogue = rogue 
     self.items = [] 
     self.hp = 10 + bonuses[0] 
     self.strength = 2 + bonuses[1] 
     self.radius = 2 + bonuses[2] 
     Tile.__init__(self, True) 

    def symbol(self): 
     '''(Rogue) -> str 
     Return the map representation symbol of Hero: O.''' 

     #return "\u263b" 
     return "O" 

    def __str__(self): 
     '''(Item) -> str 
     Return the Hero's name.''' 

     return "{}\nHP:{:2d} STR:{:2d} RAD:{:2d}\n".format(
        self.rogue, self.hp, self.strength, self.radius) 

    def take(self, item): 
     '''ADD SIGNATURE HERE 
     Add item to hero's items 
     and update their stats as a result.''' 

     # IMPLEMENT TAKE METHOD HERE 
     pass 

    def fight(self, baddie): 
     '''ADD SIGNATURE HERE -> str 
     Fight baddie and return the outcome of the 
     battle in string format.''' 

     # Baddie strikes first 
     # Until one opponent is dead 
      # attacker deals damage equal to their strength 
      # attacker and defender alternate 
     if self.hp < 0: 
      return "Killed by" 
     return "Defeated" 

我在做什麼錯?

回答

9

的問題

GameScreen.initialize_game(),設置hero=Rogue(),但Rogue構造函數採用rogue作爲參數。 (換言之,__init__Rogue要求傳入rogue。)當您設置hero=Magehero=Barbarian時,您可能會遇到同樣的問題。

幸運的是,解決方法是簡單;您可以將hero=Rogue()更改爲hero=Rogue("MyRogueName")。也許你可以在initialize_game提示用戶輸入名稱,然後使用該名稱。

上「(給1)至少2個參數」 注意

當你看到這樣的錯誤,就意味着你已經調用的函數或不經過足夠的議論它的方法。 (__init__只是一個在對象初始化時調用的特殊方法。)因此,在將來調試這樣的東西時,請查看您調用某個函數/方法的位置以及定義它的位置,並確保它們具有相同數量的參數。

有一點是這類錯誤有點棘手,是self得到傳遞。

>>> class MyClass: 
...  def __init__(self): 
...    self.foo = 'foo' 
... 
>>> myObj = MyClass() 

在這個例子中,人們可能會認爲,「奇怪,我初始化myObj,所以MyClass.__init__叫;爲什麼我沒有在一些以通爲self?」答案是,只要使用「object.method()」符號,就可以有效地傳入self。希望這有助於清除錯誤並解釋將來如何進行調試。

+0

現在收到這個錯誤! TypeError:__init __()在我通過hero = Rogue('hello')時需要2個位置參數(給出3個) – sachitad

+0

是的,我在法師和野蠻人中也遇到同樣的錯誤。現在,每當我調用Rogue('Hello')時傳遞參數,我得到這個錯誤「TypeError:__init __()只需要2個位置參數(給出3)」 – sachitad

+0

哦對不起,我犯了一個錯誤。現在它工作正常。非常感謝你的好解釋。我清楚地理解了面向對象的概念和第一個參數「self」的使用。 – sachitad

1
Class Rogue: 
    ... 
    def __init__(self, rogue, bonuses=(0, 0, 0)): 
     ... 

Rogue__init__需要參數rogue,但你在initialize_game實例作爲hero = Rogue()

你需要通過一些適當的參數,它像hero = Rogue('somename')

+0

現在就得到這個錯誤! TypeError:__init __()當我通過hero = Rogue('hello')時,需要2個位置參數(給出3個參數) – sachitad

相關問題