python-3.x - 虽然true循环给我递归错误

标签 python-3.x recursion crash pygame runtime-error

我正在为我的CompSci class 使用pygame创建游戏。游戏运行良好,但是现在我尝试执行重新启动功能,并且遇到很多错误。

我正在尝试做的基本概述是:

first = True

def check(count):
    if count == 1000:
        return True
    else:
        return False

def start():
    # MAIN MENU
    print ("start")
    count = 0
    while True:
        count += 1
        if check(count) == True:
            Game()

def Game():
    count = 0
    print("Game")
    while True:
       # GAMELOOP
       count += 1
       if check(count) == True:
           restart()

def restart():
    count = 0
    print ("Restart")
    while True:
       # RESTART
       count += 1
       if check(count) == True:
           start()

if first == True:
    first = False
    start()

但是,无论何时运行此命令,python最终都会崩溃:
RecursionError: maximum recursion depth exceeded while calling a Python object

我不确定如何解决这个问题。我希望有人可以建议另一种方法来做同样的事情或我做错了的事情。

实际的重启和菜单功能:
def rest(): #Main Menu
 while True:
    pygame.display.update()
    menu.draw()
    if pygame.mouse.get_pressed()[0]:
            x, y = pygame.mouse.get_pos()
            if x >= 255 and x <= 355 and y >= 400 and y <= 450:
                game()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit() 

def game(): #Gameloop
    while True:
        if bottom.time == 0 or bottom.time < 0 :
            game_screen.fill((0, 0, 0))
            restart()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

def restart():
 while True:
    pygame.display.update()
    menu.restart()
    if pygame.mouse.get_pressed()[0]:
            x, y = pygame.mouse.get_pos()
            if x >= 255 and x <= 355 and y >= 400 and y <= 450:
                game_screen.fill((0, 0, 0))
                rest()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

最佳答案

您是否有一系列函数相互调用以创建indirect recursion
start()计数为1000,然后调用Game(),后者再次计数为1000,然后调用restart(),后者又计数为1000,然后调用start(),关闭递归循环。一旦没有停止条件,您的递归就会一直进行到达到python递归堆栈的深度限制为止,然后您将获得异常。

作为解决方案,您需要在这些函数之一中创建停止条件。

编辑

我不完全了解pygame,但是据我从附加代码获得的信息,到执行for函数(检查事件)中的rest()时,它需要game()函数返回,而这从未发生。您可以在for行之前的行中测试此hyphotesis打印的内容。同样适用于重启功能。

关于python-3.x - 虽然true循环给我递归错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52546901/

相关文章:

xcode - 用 dSYM 和 .ipa 文件符号化崩溃文件

Android:尝试启动 OpenGL Activity ,应用程序崩溃

python-3.x - 如何在networkx 2.2中使用社区模块 "python-louvain"?

python - 如何对 pandas 数据框子集中的列求和

sql - 递归地将字段连接到其解析的段

python - 这个 Python Lambda 递归表达式是如何工作的?

python - 使用元素树python3解析XML文件

python - Django 待办事项检查按钮

java捕获堆栈溢出,获取消息显示和返回问题

android - 避免由于IOException导致应用程序崩溃或互联网丢失