2012-10-18 1 views
7

내가 Python3를 사용하여 간단한 텍스트 기반의 던전 게임을 개발하고있다. 먼저 screen.py 파일에서 영웅을 선택하라는 메시지가 표시됩니다. 형식 오류 : (부여 1) 초기화() 소요 적어도 2 인자 악성() 또는 다른 영웅 클래스와 관련이있다 나는이 코드를 실행 할 때마다형식 오류 : __init의 __()는 적어도 2 개 인자를 (1 주어진) 오류

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

, 나는이 오류가 발생합니다. 여기 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 걸립니다. (사이드 또 다른 방법은, Rogue__init__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이 효과적으로 전달된다는 것입니다. 다행히 오류를 해결하는 데 도움이되며 앞으로 오류를 디버그하는 방법을 설명합니다. 당신의 Rogue 클래스의

+0

지금이 오류를 얻기처럼 몇 가지 적절한 매개 변수를 전달합니다! TypeError : __init __()는 내가 통과 할 때 정확히 2 개의 위치 인수 (3 개)를받습니다. hero = Rogue ('hello') – sachitad

+0

예, Mage와 Barbarian에서도 동일한 오류가 발생합니다. 나는이 오류 ('안녕하세요') 도적를 호출하는 동안 지금 때마다 내가 인수를 전달 : – sachitad

+0

오 미안 실수를 "형식 오류 __init의 __()는 정확히 2 위치 인수 (주어진 3)이 소요됩니다."지금은 잘 작동합니다. 좋은 설명을 해주셔서 정말 고마워요. 나는 객체 지향 개념과 첫 번째 매개 변수 "self"의 사용을 분명히 이해했다. – sachitad

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

__init__ 매개 변수 rogue이 필요하지만 당신은 initialize_gamehero = Rogue()로 인스턴스화된다.

당신은 hero = Rogue('somename')

+0

지금이 오류를 받으시는 중! TypeError : __init __()은 hero = Rogue ('hello')를 전달할 때 정확히 2 개의 위치 인수 (3 개)를받습니다. – sachitad

관련 문제