2012-10-18 33 views
7

Tôi đang phát triển một trò chơi Dungeon dựa trên văn bản đơn giản sử dụng Python3. Đầu tiên người dùng được nhắc chọn hero từ file screen.py.TypeError: __init __() có ít nhất 2 đối số (1 đã cho) lỗi

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() 

Bất cứ khi nào tôi chạy mã này, tôi nhận được lỗi này: Lỗi Loại: init() phải mất ít nhất 2 đối số (1 nhất định) mà đã làm với Rogue() hoặc lớp anh hùng khác. Đây là 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" 

Tôi đang làm gì sai?

Trả lời

9

Vấn đề

Trong GameScreen.initialize_game(), bạn thiết lập hero=Rogue(), nhưng các nhà xây dựng Rogue mất rogue như một cuộc tranh cãi. (Nói cách khác, số __init__ của số Rogue yêu cầu rogue được chuyển vào.) Bạn có thể có cùng sự cố này khi bạn đặt hero=Magehero=Barbarian.

Giải pháp

May mắn việc sửa chữa rất đơn giản; bạn chỉ có thể thay đổi hero=Rogue() thành hero=Rogue("MyRogueName"). Có thể bạn có thể nhắc người dùng nhập tên trong initialize_game và sau đó sử dụng tên đó.

Ghi chú về "ít nhất 2 đối số (1 nhất định)"

Khi bạn thấy lỗi như thế này, nó có nghĩa là bạn đã kêu gọi một hàm hoặc một phương pháp mà không đi đủ lý lẽ để nó. (__init__ chỉ là một phương pháp đặc biệt được gọi khi một đối tượng được khởi tạo.) Vì vậy, khi gỡ lỗi các công cụ như thế này trong tương lai, hãy nhìn vào nơi bạn gọi một hàm/phương thức, và nơi bạn xác định nó, và đảm bảo rằng cùng một số tham số.

Một điều khó hiểu về các loại lỗi này, là self được truyền xung quanh.

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

Trong ví dụ đó, người ta có thể nghĩ rằng, "Weird, tôi khởi myObj, vì vậy MyClass.__init__ được gọi là, tại sao tôi không phải vượt qua trong một cái gì đó cho self?" Câu trả lời là self được truyền vào bất cứ khi nào ký hiệu "object.method()" được sử dụng. Hy vọng rằng sẽ giúp xóa lỗi và giải thích cách gỡ lỗi trong tương lai.

+0

Nhận lỗi này ngay bây giờ! TypeError: __init __() lấy chính xác 2 đối số vị trí (3 đã cho) khi tôi vượt qua hero = Rogue ('hello') – sachitad

+0

Vâng, tôi cũng gặp lỗi tương tự trong Mage và Barbarian. Bây giờ, bất cứ khi nào tôi vượt qua đối số trong khi gọi Rogue ('Hello') tôi nhận được lỗi này "TypeError: __init __() lấy chính xác 2 đối số vị trí (3 đã cho)" – sachitad

+0

oh Xin lỗi tôi đã phạm sai lầm.Nó hoạt động tốt ngay bây giờ. Cảm ơn bạn rất nhiều vì lời giải thích tốt. Tôi hiểu rõ khái niệm hướng đối tượng và sử dụng tham số đầu tiên "tự". – sachitad

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

__init__ của lớp Rogue của bạn cần tham số rogue, nhưng bạn đang instantiating nó như hero = Rogue() trong initialize_game.

Bạn cần chuyển một số thông số thích hợp cho nó như hero = Rogue('somename')

+0

Nhận lỗi này ngay bây giờ! TypeError: __init __() lấy chính xác 2 đối số vị trí (3 đã cho) khi tôi chuyển hero = Rogue ('hello') – sachitad

Các vấn đề liên quan