A resetting powerup timer

Question:

Im learning how to use pygame from a youtube and now im done with the video ive taken the game further by adding new enemies altering speeds and background objects .i’d also like to take the game further by adding a feature that allows you to do a ‘mega jump’ to avoid a large amount of enemies but i want to make it so it can only be used once every 5 seconds and when you use it the 5 second timer resets.

i will link the code below

if event.type == pygame.KEYDOWN: #if any key pressed
    if event.key == pygame.K_w: #checking for specific key
        if player_rect.bottom > 299:
            player_grav = -22.5
    if event.key == pygame.K_e: #checking for specific key
        if player_rect.bottom > 299:
            player_grav -= 30 #here is where the jump should be but i have no idea what to do
Asked By: Jamie Cooper

||

Answers:

Use pygame.time.get_ticks() to measure the time in milliseconds. Set the time when the mega jump may be performed and check if the current time is greater than this time:

next_mega_jump = 5000 # 5000 milliseconds == 5 seconds
run = True
while run:
    current_time = pygame.time.get_ticks()

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

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                if player_rect.bottom > 299:
                    player_grav = -22.5
                    print("jump")

            if event.key == pygame.K_e:
                if player_rect.bottom > 299 and current_time > next_mega_jump:
                    next_mega_jump = current_time + 5000
                    player_grav = -30 
                    print("mega jump")
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.