简体   繁体   中英

My pause statement is not working for pygame loop

My collide_rect function is not working as I expect to be. The problem is when press the key 'r', it should be able to reset everything and continue the game. But when I actually press the key 'r', it does not change anything when I add in the pause statement. I want to have the game pause when two of the sprites I have(ball, obstacle) collide. After the user inputs the letter 'r', it should go back to running and reset position for both sprites. The error I am getting is when I press the key 'r', it does not change anything on the surface.

This is my while loop:

paused = False

def display_text(text):
    font = pygame.freetype.Font('helvetica.ttc', 32)
    text_attributed = font.render_to(gameDisplay, (300,300), text, black)


while not crashed:
    time = pygame.time.get_ticks()
    obstacle.change_x()

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

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                ball.jump_true()
            if event.key == pygame.K_SPACE:
                ball.jump_true()
            if event.key == pygame.K_r:
                paused = not paused



    if ball.collide == True:
        gameDisplay.fill(white)
        display_text('You Lost! type "R" to restart')
        paused = True


    if paused == True:
        ball.reset_position()
        obstacle.reset_position()
        pygame.display.flip()
        clock.tick(20)

    else:
        ball.jump()
        ball.test_collision(obstacle)
        gameDisplay.fill(white)
        ball.update()
        obstacle.update()
        pygame.display.flip()
        clock.tick(60)
pygame.quit()
sys.exit()

Don't overcomplicate things. You don't need multiple event loops. Use 1 main loop, 1 event loop and a state which indicates if the game is paused. eg:

paused = False
run = True
while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_r

                # Toggle pause
                paused = not paused

    if paused:

        # "pause" mode
        # [...]

    else

        # "run" mode
        # [...]

    # update display etc.
    # [...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM