【问题标题】:How to restart a turtle graphics program back to the beginning?如何重新启动乌龟图形程序回到开头?
【发布时间】:2021-01-11 16:31:49
【问题描述】:

有没有人知道如何重启程序,比如当一个玩家达到5分时,在“玩家a Wins”文本之后会给出一定的时间延迟,然后直接从0 0重新开始游戏。我创建了分数,但是一旦达到 5 分就卡在重新启动程序?

一开始我已经将turtle 导入为游戏。

if (scoreboard_a > 4):
    win.write("Player A WINS!", font=textfont2)
    game.reset()
elif (scoreboard_b > 4):
    win.write("Player B WINS!", font=textfont2)
    game.reset()

【问题讨论】:

    标签: python turtle-graphics restart python-turtle


    【解决方案1】:

    你可以像这样重启整个程序:

    import os
    import sys
    import time
    time.sleep(2)
    os.execl(sys.executable, sys.executable, *sys.argv)
    

    或者,您可以重置分数和其他元素,例如:

    time.sleep(2)
    # reset variables 
    

    【讨论】:

    • 谢谢你,帮我重新启动游戏@Programmer
    【解决方案2】:

    您可以使用while 循环;将 all 您的代码(可能不是导入)放入 while 循环中:

    import turtle
    from time import sleep
    
    while True:
        # All your game code here
        scoreboard_a = 0
        scoreboard_b = 0
        if (scoreboard_a > 4):
            win.write("Player A WINS!", font=textfont2)
        elif (scoreboard_b > 4):
            win.write("Player B WINS!", font=textfont2)
        sleep(2)
    

    如果您的游戏已经处于while 循环中,请在游戏结束时使用break

    import turtle
    from time import sleep
    
    while True:
        # All your game code here
        scoreboard_a = 0
        scoreboard_b = 0
        while True:
            # All your game code here
            if (scoreboard_a > 4):
                win.write("Player A WINS!", font=textfont2)
                sleep(2)
                break
            elif (scoreboard_b > 4):
                win.write("Player B WINS!", font=textfont2)
                sleep(2)
                break
    

    【讨论】:

    • 这里有一个提示,使用 while 循环或time.sleep() 对于事件驱动程序来说不是一个好主意,因为它可能会使 GUI 无响应。所以,不要使用time.sleep(),而是使用海龟的ontimer()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-30
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多