为了账号安全,请及时绑定邮箱和手机立即绑定

尝试模块化python代码但出现递归错误:最大递归深度

尝试模块化python代码但出现递归错误:最大递归深度

杨魅力 2023-09-26 14:06:30
您可以在此处找到所有代码https://github.com/Ninedeadeyes/7-Dungeons-Deep您需要运行 modularize game.py 来识别递归错误以下函数位于 Enemy.py 中(在 Enemy 类中)我很久以前写了一个动作角色扮演游戏,它全部工作但在一个 python 文件(game.py)中,现在我试图将它模块化。我已经模块化了很大一部分代码,但我仍然无法分离敌人的类问题出在敌人类中带有turtle.ontimer的“移动”函数的最底层。在原始文件(game.py)中,它将重复敌人.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)) '''
查看完整描述

1 回答

?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

self.move(block,bob)不是一个函数 - 相反,它是对该函数的立即递归调用。

修复:将此调用转换为不带参数的函数

turtle.ontimer(lambda: self.move(block,bob),t=random.randint(100,300))


查看完整回答
反对 回复 2023-09-26
  • 1 回答
  • 0 关注
  • 67 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信