在游戏循环中,如何使用嵌套类或循环正确重启游戏?

In game loop, how do I restart game properly using nested class or loop?

提问人:Von 提问时间:10/14/2022 最后编辑:Von 更新时间:10/14/2022 访问量:124

问:

我使用 pygame 在 python3 中制作游戏,我的游戏逻辑循环发生。 我的问题是如何在不使用嵌套类和循环的情况下重新启动游戏,如下例所示?run

我担心当玩家死亡足够多的时候,这段代码会占用太多内存,但也许我对这段代码的理解是错误的?(我假设,当玩家每次制作新职业时都会死亡,新变量也会死亡。game

class Game:
    def init:
        #code goes here
    def run(self,deathcount):
        while self.running==True:
        #code goes here
        if player dies
           deathcount+=1
           game = Game()
           self.running=False
           game.run(death_count)

if name == "main":
    game = Game()
    game.run(death_count=0)
Python 循环 pygame 嵌套

评论

1赞 AKX 10/14/2022
只需让相同的游戏实例重置您需要重置的任何游戏状态,不要创建一个新的..?
0赞 Tim Roberts 10/14/2022
或者,在玩家死亡时返回,并使用主循环中的代码重新启动。 应该只运行一个游戏,然后就完成了。runrun
0赞 Von 10/14/2022
好吧,我这样做是因为游戏类包含有关玩家的信息,我需要重置这些信息。
1赞 AKX 10/14/2022
好吧,将该代码重构为 例如,并在 死亡中调用它。__init__reset_player()if

答:

1赞 Rabbid76 10/14/2022 #1

一般的方法是有一个外循环。只要游戏未终止,外部循环就会运行。在循环中,创建对象并执行应用程序循环:Game

class Game:
    def __init__(self):
        # [...]

    def run(self, death_count):
        
        quit_game = False
        game_over = False
        while not quit_game and not game_over:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    quit_game = True

            # [...]

            if player_dies:
                game_over = True

        return quit_game
           
if name == "main":
    death_count = 0
    quit_game = False
    while not quit_game:
        game = Game()
        quit_game = game.run(death_count)
        death_count += 1