Skip to main content
 首页 » 编程设计

python之通过点击 "Enter"重新启动

2025年05月04日8hnrainll

我不确定为什么我在 python 上重启游戏的代码(使用 pygame)不起作用? 在我的主要功能完成后(当游戏通过屏幕上没有更多项目赢得比赛时,即一个空的“熊”数组)我将 startGame 变量更改为“False”: IE。

 if len(bears) == 0: 
    startGame = False 

然后在我写完之后:

   #draw the window 
    pygame.display.update() 
    mainClock.tick(40) 
 
 
play_again() 
pygame.display.quit() 
pygame.quit() 

play_again() 函数是我定义“重启”按钮的尝试。它的代码是:

def play_again(): 
    windowSurface.blit(text, (90, 104)) 
    windowSurface.blit(restart, (80,180)) 
    clock = pygame.time.Clock() 
    pygame.display.flip() 
    in_main_menu = True 
    while in_main_menu: 
        clock.tick(50) 
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT: 
                in_main_menu = False 
                pygame.display.quit() 
                pygame.quit() 
            if event.type == KEYDOWN: 
                if event.key == K_RETURN: 
                    global startGame 
                    startGame = True 
                    in_main_menu = False 

我不确定为什么这个方法不起作用。 (另外,如果有人想知道,我之前已经定义了“text”和“restart”变量,它们没问题)

请您参考如下方法:

至于我,你离开主循环,调用 play_again() 但你在循环之外,所以你可以返回到代码的开头。

您需要另一个外部循环来返回(在 play_again() 之后)到代码的开头。

它可能类似于这样:

while StartGame: 
 
    while game: 
 
            # game 
 
    #StartGame = play_again() 
    play_again() 
 
pygame.display.quit() 
pygame.quit() 

请记住:如果您遇到问题,请添加大量包含一些信息的print 以查看您的代码中发生了什么-(“我在循环中”, “我离开循环”,“变量 StarGame 是:” 等)