Вызов функции по нажатию кнопки в Pygame - PullRequest
1 голос
/ 16 мая 2019

Я получил экран с кнопками в Pygame здесь в коде ниже.Теперь я хочу нажать кнопку, затем запускается функция random(), и через 5 секунд она возвращается к экрану с самого начала с помощью кнопок, и я могу снова щелкнуть и снова вызвать случайную функцию.

def loop():
    clock = pygame.time.Clock()
    number = 0
    # The button is just a rect.
    button = pygame.Rect(300,300,205,80)
    done = False
    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:
                    # `event.pos` is the mouse position.
                    if button.collidepoint(event.pos):
                        # Incremt the number.
                        number += 1

random()
loop()
pygame.quit()

1 Ответ

1 голос
/ 19 мая 2019

Добавить переменную состояния (runRandom), которая указывает, должна ли выполняться функция random:

runRandom = False
while not done:

    # [...]

    if runRandom:
        random()

Добавить пользовательский pygame.event, который можно использовать для таймера:

runRandomEvent = pygame.USEREVENT + 1
for event in pygame.event.get():

   # [...]

   elif event.type == runRandomEvent:
      # [...]

Разрешить нажатие кнопки, если random ins not running . Если кнопка нажата, введите runRandom и запустите таймер (pygame.time.set_timer()) с установленным периодом времени (например, 5000 миллисекунд = 5 секунд):

# [...]

elif event.type == pygame.MOUSEBUTTONDOWN:
    if event.button == 1:
        if button.collidepoint(event.pos) and not runRandom:
            # [...]

            runRandom = True
            pygame.time.set_timer(runRandomEvent, 5000)

По истечении времени остановка запускается random на runRandom = False и остановка таймера:

# [...]

elif event.type == runRandomEvent:
    runRandom = False
    pygame.time.set_timer(runRandomEvent, 0)

Примените предложение к своему коду примерно так:

# define user event for the timer
runRandomEvent = pygame.USEREVENT + 1

def loop():
    clock = pygame.time.Clock()
    number = 0
    # The button is just a rect.
    button = pygame.Rect(300,300,205,80)
    done = False
    runRandom = False
    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:
                    # `event.pos` is the mouse position and  "random" is not running
                    if button.collidepoint(event.pos) and not runRandom:
                        # Incremt the number.
                        number += 1

                        # Start timer and enable running "random"
                        runRandom = True
                        pygame.time.set_timer(runRandomEvent, 5000) # 5000 milliseconds

            elif event.type == runRandomEvent:
                runRandom = False
                pygame.time.set_timer(runRandomEvent, 0)

        # [...]

        # run "random"
        if runRandom:
            random()

        # [...]  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...