I want to change the value of a bool
after some time when a user hits enter, whilst keeping the program running.
Pygame's delay or timers don't work as they stop the whole code or repeats a user event over and over again.
I want to change the value of a bool
after some time when a user hits enter, whilst keeping the program running.
Pygame's delay or timers don't work as they stop the whole code or repeats a user event over and over again.
Although pygame has no function to wait while allowing the program to run, there are several ways of doing it without pygame. You can import time, a module that comes with python used for getting the current time. It has a function, time.time()
which returns the amount of seconds since a set time. Therefore, you can do x = time.time()
when the user hits enter, and you continuously check to see if time.time() - x <= delay
in the game loop, and change the value of your boolean if it is true. For example:
import pygame, time, sys
screen = pygame.display.set_mode((100,100))
timer = False # timer is true after the user hits enter and before your boolean changes
delay = 1 # whatever your delay is (seconds)
bool = False
while True: # game loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
x = time.time() # x is the time when you press enter
timer = True # the timer is activated
print(bool)
if timer:
if time.time() - x >= delay: # if the amount of time since enter was pressed is the delay
bool = True #change bool value
This code will wait till you press enter, and then, one second later, change the boolean. If you add anything in the game loop, it will still run while the timer is active. This works because time.time()
gets the current time, and if the difference between the current time and the time when the user pressed enter (represented as x
) is equal to the delay, then that much time passed since the user hit enter and it it changes the boolean.