How to detect button press within n seconds

Question:

How would I determine if I pressed the x button within time_between_attacks[hits] with time between checks to be time_between_attacks[hits]/10 using pygame timer.

def display_battle(self,screen,enemy_list):
        print(enemy_list)
        clock = pygame.time.Clock()

        #Addition amount
        hit = 0
        total_hits = 3
        time_between_attacks = [5,4,3]
        run = True
        start_ticks=pygame.time.get_ticks()
        while run:
            seconds=(pygame.time.get_ticks()-start_ticks)/1000
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    exit()          
                keys = pygame.key.get_pressed()
                if keys[pygame.K_x]:
                    seconds=(pygame.time.get_ticks()-start_ticks)/1000
                    print(seconds)
                    #(time_between_attacks[hit]/10)*9
                    if 0 < seconds < time_between_attacks[hit]:
                        hit+=1
                        start_ticks=pygame.time.get_ticks()
            
            screen.fill(white)

            if hit>=total_hits-1 or seconds>time_between_attacks[hit]:
                break
            
            pygame.display.flip()
            clock.tick(time_between_attacks[hit]/10)
Asked By: Arundeep Chohan

||

Answers:

I would simply create a variable that holds the time of the attack. Then, if x is pressed, and current time – time of attack < threshold, the x button has been pressed within the time allocated. Here’s some pseudocode:

hitTime = pygame.time.get_ticks() for point 1.

if keys[pygame.K_x]:
                    if pygame.time.get_ticks() < time_between_attacks[hit]:
                             print("pressed x before the time between attacks has occured")
                              
Answered By: ThatOneCoder
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.