7

Python3 を使用して、単純なテキスト ベースのダンジョン ゲームを開発しています。最初に、ユーザーは screen.py ファイルからヒーローを選択するように求められます。

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

このコードを実行するたびに、次のエラーが発生します: TypeError: init () は、Rogue() または他のヒーロー クラスに関係する少なくとも 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"

私は何を間違っていますか?

4

2 に答える 2

9

問題

ではGameScreen.initialize_game()を設定hero=Rogue()しますが、Rogueコンストラクタはrogue引数として取ります。(別の言い方をすれば、__init__of には を渡すRogue必要があります。) と を設定すると、これと同じ問題が発生する可能性があります。roguehero=Magehero=Barbarian

ソリューション

幸いなことに、修正は簡単です。hero=Rogue()に変更するだけですhero=Rogue("MyRogueName")。でユーザーに名前の入力を求め、initialize_gameその名前を使用することができます。

「少なくとも 2 つの引数 (1 つを指定)」に関する注意事項

このようなエラーが表示された場合は、十分な引数を渡さずに関数またはメソッドを呼び出したことを意味します。(__init__オブジェクトが初期化されるときに呼び出される特別なメソッドです。)したがって、将来このようなものをデバッグするときは、関数/メソッドを呼び出す場所と定義する場所を見て、2つに同じ数のパラメータ。

この種のエラーでややこしいことの 1 つは、selfが渡されることです。

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

その例では、「奇妙なことに、 を初期化myObjしたのでMyClass.__init__呼び出されたのに、なぜ に何かを渡す必要がなかったのselfか?」と思うかもしれません。答えはself、「object.method()」表記が使用されるたびに効果的に渡されるということです。うまくいけば、それがエラーを解決し、将来的にデバッグする方法を説明するのに役立ちます.

于 2012-10-18T05:23:10.703 に答える
1
Class Rogue:
    ...
    def __init__(self, rogue, bonuses=(0, 0, 0)):
       ...

__init__あなたのRogueクラスのにはパラメータrogueが必要ですが、のようにインスタンス化していhero = Rogue()ますinitialize_game

次のような適切なパラメーターを渡す必要がありますhero = Rogue('somename')

于 2012-10-18T05:24:36.720 に答える