Функция вызова по нажатию кнопки несколько раз? - PullRequest
2 голосов
/ 16 мая 2019

моя программа python / Pygame запускается с кнопки, которая вызывает функцию, и кнопки, которая выходит из игры. Я хочу нажать эту первую кнопку, затем однажды вызывается функция, и после этого она должна вернуться к начальному экрану кнопок и позволить мне снова вызвать функцию нажатием кнопки. Как я могу это сделать? В настоящее время я могу только нажать кнопку, вызвать функцию, и тогда игра заканчивается. В приведенном ниже коде вы видите наиболее важные части кода.

 def function():
 ....

 def main():
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    done = False

 def quit_game():  # A callback function for the button.
        nonlocal done
        done = True

    button1 = create_button(100, 100, 250, 80, 'function', function)
    button2 = create_button(100, 200, 250, 80, 'quit', quit_game)
        # A list that contains all buttons.
        button_list = [button1, button2]

        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
                # This block is executed once for each MOUSEBUTTONDOWN event.
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    # 1 is the left mouse button, 2 is middle, 3 is right.
                    if event.button == 1:
                        for button in button_list:
                            # `event.pos` is the mouse position.
                            if button['rect'].collidepoint(event.pos):
                                # Increment the number by calling the callback
                                # function in the button list.
                                button['callback']()


            screen.fill(WHITE)
            for button in button_list:
                draw_button(button, screen)
            pygame.display.update()
            clock.tick(30)


    main()

1 Ответ

2 голосов
/ 16 мая 2019

Здесь вам нужно выделить каждый экран / игровой цикл в его собственную специальную функцию:

Итак, для моего экрана кнопок я могу сделать такую ​​функцию:

def title():
    button1 = create_button(100, 100, 250, 80, 'game', game) # This will call the game function later in the file
    button2 = create_button(100, 200, 250, 80, 'quit_game', quit_game)
    # A list that contains all buttons.
    button_list = [button1, button2]
    # And so on with the rest of the code...

Для основной игры вы можете сделать то же самое:

def game():
    button1 = create_button(100, 100, 250, 80, 'Exit', title) # This button will return you to the title
    # And whatever else you need     

После этого, в конце файла, вы можете добавить это:

if __name__ == '__main__':
    pygame.init()
    title() # Call the title first, and then further functions
    pygame.quit()

Вы должны заметить, что когда вы активируете функцию обратного вызова кнопок, для разгрузки этого экрана потребуется return, иначе вы просто наложите игровые петли поверх друг друга.

Итак, во время цикла событий:

if event.button == 1:
    for button in button_list:
        # `event.pos` is the mouse position.
        if button['rect'].collidepoint(event.pos):
            # Increment the number by calling the callback
            # function in the button list.
            button['callback']()
            return # Leave the function now that the new one is called.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...