python pygame pause function

前端 未结 2 771
死守一世寂寞
死守一世寂寞 2021-01-28 02:58

I am beginner and have a problem with my code. Here you can see a short excerpt of my code.

It\'s a simple snake game I created but I was trying to add a pause. I got it

2条回答
  •  别那么骄傲
    2021-01-28 04:04

    The pause screen is displayed in a separate application loop. You've to get the events in that loop, too. Note, in your code, the content of e never changes in the "pause" loop:

    def checkquit(e):
        global running
        running = True
        pause = False
        for ev in e:
            if ev.type == pygame.QUIT:
                exit(0)
                running = True
            if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
                quit(0)
                running = True
            if ev.type == pygame.KEYDOWN and ev.key == pygame.K_p:
                pause = True
    
        while pause:
    
            # [...]
    
    
            # get the new events
            e = pygame.event.get()
    
            # handle the events in the loop
            for ev in e:
                if ev.type == pygame.QUIT:
                    pause = False
                if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
                    pause = False      
                if ev.type == pygame.KEYDOWN and ev.key == pygame.K_p:
                    pause = True
    

    runnung seems to be a variable in global namespace. You've to use the global statement to change its state. Furthermore it is superfluous to recreate the window surface in the "pause" loop.

    screen = pygame.display.set_mode((800,500))


    I recommend to change the game process. Use 1 application loop. e.g.:

    myfont=pygame.font.SysFont("monospace",50)
    myfonttwo=pygame.font.SysFont("monospace",10)
    text1=myfont.render("Pause!",100,red)
    text2=myfont.render("Please restart the game",100,red)
    
    def checkquit(e):
        global running, pause
        for ev in e:
            if ev.type == pygame.QUIT:
                exit(0)
                running = True
            if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
                if pause:
                    pause = False
                else:
                    quit(0)
                    running = True
            if ev.type == pygame.KEYDOWN and ev.key == pygame.K_p:
                pause = not pause
    
    running, pause = True, False
    while running:
        events = pygame.event.get()
        checkquit(events)
    
        screen.fill((0,0,0))
        if pause:
            # draw pause screen
            screen.blit(text2,(10,200))
            screen.blit(text1,(230,100))
    
        else:
            # draw game
            # [...]
    
        pygame.display.update() 
    

提交回复
热议问题