One way of doing this is to use the millisecond timer provided by pygame.time.get_ticks(). This returns the number of milliseconds since PyGame started. It's handy for doing time calculations.
So, reading through the comments, you want the player to be invulnerable for some time (0.5 seconds) after taking a hit. So let's get that into a constant:
HIT_CLOCK = 500 # milliseconds player is safe for, after taking a hit
So when the player is hit, we need to wait that long before recording another hit. This is some time in the future from when the player is hit, but that's easy to calculate:
time_now = pygame.time.get_ticks()
player_hit_clock = time_now + HIT_CLOCK # time in the future
And when the code is deciding if the player should be hit, it can just compare that "future time" to ensure it's now past:
if pygame.Rect.colliderect(player_rect, baddude_rect):
time_now = pygame.time.get_ticks()
if time_now > player_hit_clock:
print('hit')
player_hit_clock = time_now + HIT_CLOCK #<<-- reset clock
It's important to ensure player_hit_clock
is initialised before the first use, setting it to 0
would be enough. So, putting all that together:
HIT_CLOCK = 500 # milliseconds player is safe for, after taking a hit
# ...
player_hit_clock = 0 # controls player consecutive damage rate
# ...
if pygame.Rect.colliderect(player_rect, baddude_rect):
time_now = pygame.time.get_ticks()
if time_now > player_hit_clock:
print('hit')
player_hit_clock = time_now + HIT_CLOCK # <<-- reset the hit-clock
else:
print('player hit cooldown')
The benefits of using the millisecond clock are:
- All code just runs normally, waiting for the timer to expire.
- The cost of using the clock is only a fetch of the time, with a single integer comparison.
- (If you use the clock for other things, only one fetch is needed per loop)
- It's real-time, so even if your program drops a few frames, timing is preserved.