如何每次初始化新对象以重置Pygame中的游戏

时间:2019-06-13 10:13:01

标签: python pygame

每次用户按下 c 键时,我都试图重新创建新对象,以便可以从起点重新加载游戏。但是我找不到解决办法。

这是我到目前为止尝试过的:

def initializeGame(theGame):

    while run:
        theGame.clock.tick(FPS)

        # This function consists code for Events
        theGame.events()
        # This function consists code from enemy hit events
        theGame.hit_or_not()
        # This function consists code for bullet hit events
        theGame.bulletHit_or_not()
        # This function consists code for player movements
        theGame.movements()
        # This function consists code for drawing the sprites over the screen
        theGame.redrawGameWindow()

def startGame(run):
    first_game = Game()

    while run:
        initializeGame(first_game)

        keys = pygame.key.get_pressed()

        if keys[pygame.K_ESCAPE]:
            run = False

        if keys[pygame.K_c]:
            new_game = Game()
            initializeGame(new_game)

startGame(True)

我要做的只是当我按'c'键时,游戏必须从起点重新开始,为此,我必须重新创建新的'Game()'类对象并初始化游戏

游戏类代码-https://pastebin.com/abAiey34

1 个答案:

答案 0 :(得分:1)

在游戏循环中避免游戏循环,这意味着从initializeGame中删除循环。
名称initializeGame具有误导性,将其命名为runGame

def runGame(theGame):

    # This function consists code for Events
    theGame.events()
    # This function consists code from enemy hit events
    theGame.hit_or_not()
    # This function consists code for bullet hit events
    theGame.bulletHit_or_not()
    # This function consists code for player movements
    theGame.movements()
    # This function consists code for drawing the sprites over the screen
    theGame.redrawGameWindow()

因此只有一个game就足够了,只需创建一个电子游戏对象即可“重置”。
在唯一的一个游戏循环中,必须调用runGame

def startGame(run):

    game = Game()
    while run:
        theGame.clock.tick(FPS)

        # run the game
        runGame(game)

        # get keys
        keys = pygame.key.get_pressed()

        # handle keys
        if keys[pygame.K_ESCAPE]:
            run = False
        if keys[pygame.K_c]:
            game = Game()

startGame(True)

请注意,startGame()已经有一个循环,因此没有必要在任何功能中进行进一步的游戏循环。 runGame()完成游戏框架中的所有工作。 runGame()startGame()的游戏循环中不断被调用。
如果必须开始新游戏,那么创建一个新的Game对象就足够了。


请注意,当pygame.key.get_pressed()pygame.events处理pygame.event.get()时,将评估pygame.event.pump()返回的状态。
事件循环后调用pygame.key.get_pressed()

我希望设计略有不同。在主循环(pygame.event.get())中获取事件,并将其传递给runGame(),然后传递给Game.events()

class Game:

    # [...]

    def events(self, eventlist):

        for event in eventlist:
            # handle events
            # [...]

def runGame(theGame, eventlist):

    # This function consists code for Events
    theGame.events(eventlist)

    # [...]

def startGame(run):

    game = Game()
    while run:
        theGame.clock.tick(FPS)

        # run the game
        eventlist = pygame.event.get()
        runGame(game, eventlist)

        # get keys
        keys = pygame.key.get_pressed()

        # handle keys
        if keys[pygame.K_ESCAPE]:
            run = False
        if keys[pygame.K_c]:
            game = Game()