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

您可以在此处找到所有代码

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

'''


杨魅力
浏览 69回答 1
1回答

斯蒂芬大帝

self.move(block,bob)不是一个函数 - 相反,它是对该函数的立即递归调用。修复:将此调用转换为不带参数的函数turtle.ontimer(lambda:&nbsp;self.move(block,bob),t=random.randint(100,300))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python