Home > Enterprise >  Trying to control the delay by using the keyboard in Pygame
Trying to control the delay by using the keyboard in Pygame

Time:10-06

I would like to control delay for my program, now is set to pygame.time.delay(50) as default value, below is my code snippet.

    pygame.time.delay(50)
    pygame.display.update()
    clockobject = pygame.time.Clock()
    clockobject.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                quit()
            if event.key == pygame.K_1:
                print('K_1')
            if event.key == pygame.K_2:
                print('K_2')

I tried to control it by changing the values.

            if event.key == pygame.K_1:
                pygame.time.delay(20)
                pygame.display.update()
                print('K_1')
            if event.key == pygame.K_2:
                pygame.time.delay(90)
                pygame.display.update()
                print('K_2')

When i press the keys the print value returns on my terminal but i doesn't slow down or accelerate!

CodePudding user response:

You have to use a variable for the delay:

time_delay = 50

while run:
    pygame.time.delay(time_delay)

    # [...]

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_1:
                if time_delay > 0:
                    time_delay -= 10
            if event.key == pygame.K_2:
                if time_delay < 100:
                    time_delay  = 10

CodePudding user response:

Pygame.time.delay() delays the time your code runs on the window, there is no way that pygame.time.delay() delays your keyboard inputs so what you can do is set a variable to like 20 and then if a user presses a, decrease the variable by 1 and if that variable reaches 0 or below, then do what you want to do.

  • Related