问题描述
您可以在此处找到所有代码
https://github.com/Ninedeadeyes/7-Dungeons-Deep
您将需要运行模块化game.py来识别 递归错误
下面的函数在Enemy.py中(在Enemy类中)
很久以前,我编写了一个动作rpg,该动作全部有效,但是在一个python文件(game.py)中,现在我试图对其进行模块化。我已经对大量代码进行了模块化,但是我被困在分离敌人的班次上
问题出在turtle.ontimer的敌人阶级中,“移动”功能的最底层。在原始文件(game.py)中,它将重复invalid.move函数,以便一旦最初触发了move函数但敌人将继续移动,但是一旦我对其进行模块化,它将返回错误RecursionError:超过最大递归深度同时调用Python对象。任何建议,以使这项工作。我试图将“ ontimer”功能输入到游戏循环中,但随后变得太笨拙而无法玩。任何解释为什么在单个文件中都没有递归错误的原因也将不胜感激。
'''
def move(self,block,bob):
if self.direction =="up":
dx= 0
dy= 24
self.shape(".\\art\\orkup.gif")
elif self.direction =="down":
dx= 0
dy= -24
self.shape(".\\art\\ork.gif")
elif self.direction =="left":
dx= -24
dy= 0
self.shape(".\\art\\orkleft.gif")
elif self.direction =="right":
dx= 24
dy= 0
self.shape(".\\art\\orkright.gif")
else:
dx = 0
dy = 0
if self.is_close(bob):
if bob.xcor()<self.xcor():
self.direction="left"
elif bob.xcor()>self.xcor():
self.direction="right"
elif bob.ycor()<self.ycor():
self.direction="down"
elif bob.ycor()>self.ycor():
self.direction="up"
# Calculate the spot to move to
move_to_x = self.xcor()+ dx
move_to_y = self.ycor()+ dy
if (move_to_x,move_to_y) not in block:
self.goto(move_to_x,move_to_y)
else:
self.direction=random.choice(["up","down","left","right"])
turtle.ontimer(self.move(block,bob),t=random.randint(100,300))
'''
解决方法
self.move(block,bob)
不是函数-而是对函数的立即递归调用。
修复:将此调用转换为无参数的函数
turtle.ontimer(lambda: self.move(block,bob),t=random.randint(100,300))