简体   繁体   English

我的暂停语句不适用于 pygame 循环

[英]My pause statement is not working for pygame loop

My collide_rect function is not working as I expect to be.我的collide_rect 函数没有像我预期的那样工作。 The problem is when press the key 'r', it should be able to reset everything and continue the game.问题是当按“r”键时,它应该能够重置所有内容并继续游戏。 But when I actually press the key 'r', it does not change anything when I add in the pause statement.但是当我实际按下键 'r' 时,当我添加暂停语句时它不会改变任何东西。 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.在用户输入字母 'r' 后,它应该返回运行并重置两个精灵的位置。 The error I am getting is when I press the key 'r', it does not change anything on the surface.我得到的错误是当我按下 'r' 键时,它不会改变表面上的任何东西。

This is my while loop:这是我的while循环:

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.使用 1 个主循环、1 个事件循环和一个指示游戏是否暂停的状态。 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.
    # [...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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