问题描述
我正在使用 Python3 开发一个简单的基于文本的 Dungeon 游戏.首先提示用户从 screen.py 文件中选择英雄.
来自游戏导入 *类游戏屏幕:'''以基于文本的格式显示游戏的当前状态.这个类已经完全实现,不需要学生的额外作业.'''def initialize_game(self):'''(游戏画面)->无类型使用新的用户选择的英雄类初始化新游戏和开始房间文件.'''英雄 = 无而英雄是无:c = input("选择英雄类型:\n(R)ogue (M)age (B)arbarian\n")c = c.lower()如果 c == 'r':英雄 = 盗贼()elif c == 'm':英雄 = 法师()elif c == 'b':英雄 = 野蛮人()self.game = Game("rooms/startroom", hero)定义播放(自我):'''(游戏)->无类型主游戏循环.'''退出 = 错误虽然不退出:打印(自己)如果 self.game.game_over():休息c = input("下一个:")如果 ['q', 'x'] 中的 c:print("感谢您的参与!")退出 = 真elif c == 'w': # 向上self.game.move_hero(-1, 0)elif c == 's': # 向下self.game.move_hero(1, 0)elif c == 'a': # 左self.game.move_hero(0, -1)elif c == 'd': # 对self.game.move_hero(0, 1)elif c == 'r':##重新开始游戏self.initialize_game()别的:经过def __str__(self):'''(游戏画面)->无类型返回一个表示当前房间的字符串.包括游戏的英雄字符串表示和一个上次执行操作的状态消息.'''房间 = self.game.current_rooms = ""如果 self.game.game_over():#渲染一个 GAME OVER 屏幕,文本大部分居中#在角色死亡的房间的空间中.#顶行s += "X" * (2 + room.cols) + "\n"#GAME OVER上方的空行对于列表中的 i(range(floor((room.rows - 2)/2))):s += "X" + " " * room.cols + "X\n"# GAME OVER 行s += ("X" + " " * floor((room.cols - 4)/2) +"游戏" + " " * ceil((room.cols - 4)/2) + "X\n")s += ("X" + " " * floor((room.cols - 4)/2) +"OVER" + " " * ceil((room.cols - 4)/2) + "X\n")#GAME OVER 下方的空行对于列表中的 i(range(ceil((room.rows - 2)/2))):s += "X" + " " * room.cols + "X\n"#底行s += "X" * (2 + room.cols) + "\n"别的:对于我在范围内(room.rows):对于 room.grid[i] 中的 j:如果 j 不是 None:如果 j.visible:s += j.symbol()别的:#这是尚未探索"的符号:?s +=?"s += "\n"#英雄代表s += str(self.game.hero)#最后的状态信息s += 房间状态返回如果 __name__ == '__main__':gs = 游戏画面()gs.initialize_game()gs.play()
每当我运行此代码时,我都会收到此错误:TypeError: init() 需要至少 2 个参数(给定 1 个),这与 Rogue() 或其他英雄类有关.这是 hero.py.
类盗贼(平铺):'''代表冒险进入地牢的英雄的班级.英雄有以下属性:名字、物品列表、生命值、力量、金币和视野范围.英雄从 Tile 继承可见布尔值.'''def __init__(self, rogue, bonuses=(0, 0, 0)):'''(Rogue, str, list) ->无类型创建一个名为 Rogue 的新英雄,一个空的物品和奖金列表指定的 hp、力量、黄金和半径在奖金'''self.rogue = 流氓self.items = []self.hp = 10 + 奖金[0]self.strength = 2 + 奖金[1]self.radius = 2 + 奖金[2]Tile.__init__(self, True)定义符号(自我):'''(流氓)->字符串返回 Hero 的地图表示符号:O.'''#return "\u263b"返回O"def __str__(self):'''(项目)->字符串返回英雄的名字.'''返回 "{}\nHP:{:2d} STR:{:2d} RAD:{:2d}\n".format(self.rogue, self.hp, self.strength, self.radius)def take(self, item):'''在此处添加签名将物品添加到英雄的物品中并因此更新他们的统计数据.'''# 在这里实施采取方法经过def 战斗(自我,坏人):'''在此处添加签名 ->字符串与坏人战斗并返回结果字符串格式的战斗.'''#坏蛋先出手# 直到一名对手死亡# 攻击者造成等于其力量的伤害# 攻击者和防御者交替如果 self.hp
我做错了什么?
问题
在GameScreen.initialize_game()
中,你设置了hero=Rogue()
,但是Rogue
构造函数接受了rogue代码> 作为参数.(换句话说,
Rogue
的 __init__
要求传入 rogue
.)当您设置 时,您可能会遇到同样的问题hero=Mage
和 hero=Barbarian
.
解决方案
幸运的是修复很简单;您可以将 hero=Rogue()
更改为 hero=Rogue("MyRogueName")
.也许您可以在 initialize_game
中提示用户输入一个名称,然后使用该名称.
关于至少 2 个参数(给定 1 个)"的注释
当您看到这样的错误时,这意味着您调用了一个函数或一个方法,而没有向它传递足够的参数.(__init__
只是一个在对象初始化时调用的特殊方法.)所以以后在调试这样的东西时,看看你在哪里调用函数/方法,以及在哪里定义它,并确保两者具有相同数量的参数.
关于这些类型的错误有点棘手的事情是被传递的 self
.
在那个例子中,人们可能会想,奇怪,我初始化了 myObj
,所以 MyClass.__init__
被调用了;为什么我不必为自己
?"答案是每当使用object.method()"表示法时,self
就会被有效地传入.希望这有助于清除错误并解释将来如何调试.
I am developing a simple text based Dungeon game using Python3. First the user is prompted to select the hero from screen.py file.
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()
Whenever I run this code, I get this error: TypeError: init() takes at least 2 arguments (1 given) which has to do with Rogue() or other hero classes. Here's the 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"
What am I doing wrong?
The Problem
In GameScreen.initialize_game()
, you set hero=Rogue()
, but the Rogue
constructor takes rogue
as an argument. (Said another way, the __init__
of Rogue
requires that rogue
be passed in.) You likely have this same issue when you set hero=Mage
and hero=Barbarian
.
The Solution
Luckily the fix is simple; you can just change hero=Rogue()
to hero=Rogue("MyRogueName")
. Maybe you could prompt the user for a name in initialize_game
, and then use that name.
Notes on "at least 2 arguments (1 given)"
When you see errors like this, it means that you have called a function or a method without passing enough arguments to it. (__init__
is just a special method that is called when an object is initialized.) So when debugging stuff like this in the future, look at where you call a function/method, and where you define it, and make sure that the two have the same number of parameters.
One thing that is sort of tricky about these kinds of errors, is the self
that gets passed around.
>>> class MyClass:
... def __init__(self):
... self.foo = 'foo'
...
>>> myObj = MyClass()
In that example, one might think, "Weird, I initialized myObj
, so MyClass.__init__
was called; why didn't I have to pass in something for self
?" The answer is that self
is effectively passed in whenever the "object.method()" notation is used. Hopefully that helps clear up the error and explains how to debug it in the future.
这篇关于类型错误:__init__() 需要至少 2 个参数(给定 1 个)错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!