-4

I am creating a tic tac toe game where i have a condition, that if player does not respond within 5 seconds he loses the game. player responds by clicking a button. Do we have something like this to do?

i tried implementing this by having a list of times when the button was clicked and check whether a new button click happened in the next 5 seconds or not. it works well on the first click but complexities arise when multiple clicks are added.

code of what i tried

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
pavan
  • 102
  • 2
  • 11

1 Answers1

2

You can create a class that records the last time a button was clicked, with a method that returns whether the next click was within 5 seconds.

class ClickCheck:
    def __init__(self):
        self.last_click = None

    def clicked_in_time(self) -> bool:
        # Handle the first click.
        if self.last_click is None:
            self.last_click = time.time()
            return True
        
        # Handle later clicks.
        new_click = time.time()
        if new_click - self.last_click > 5:
            return False
        self.last_click = new_click
        return True

You will need to create an instance of ClickCheck, and create a callback function that is called when your button is clicked. Inside that callback, call the clicked_in_time method of your ClickCheck instance and it will tell you whether it was clicked in time. The rest of the code in your callback function can then decide how to handle ending or continuing the game.

MichaelCG8
  • 579
  • 2
  • 14