How do i delay something with out stoping the rest?

i use this code so the player does not tuch the boss but i dont want it to hapen instant,i thougt about time.sleep but i dont want to stopp the main loop

    if player_zone.colliderect(boss_zone):
        if heart_lost_counter==0:
            heart3=0,0,0
            heart_lost_counter=1
    if player_zone.colliderect(boss_zone):
        if heart_lost_counter==1:
            heart2=0,0,0
            heart_lost_counter=2
    if player_zone.colliderect(boss_zone):
        if heart_lost_counter==2:
            pygame.draw.rect(screen,"red",(0,0,1280,720))
            boss=0
            bosscolor=0,0,0
            bossheigt=720
            heart1=255,0,0
            heart2=255,0,0
            heart3=255,0,0
            heart_lost_counter=0

You could use time.time() to read the current time (seconds since the “epoch”) and then perform the action when it first returns a time >= desired time.

1 Like

perhaps you could use a scheduler to run tasks asynchronously

Ah, so since this is a video game, I’m guessing that your problem is that the when the player touches a bad guy, you want them to lose a heart but the loop runs so fast that they instantly lose all their hearts.

In many video games, you get a few seconds of invulnerability when you touch the bad guy and take damage (often with the player sprite flashing). Sometimes the player also gets knocked back away from the bad guy too to make sure they don’t continue to touch. What you need to do is set up a new variable to record the last time the player touched the bad guy. The player then only takes damage if they are touching the bad guy AND it has been less than, say, 2 seconds since the last time they touched the bad guy.

Your code would look something like this:

last_touched_bad_guy = time.time()  # This goes at the start of the program.

# ...

if last_touched_bad_guy < time.time() + 2 and player_zone.colliderect(boss_zone):
    last_touched_bad_guy = time.time()  # Update the last time the player touched the bad guy
    if heart_lost_counter==0:
        heart3=0,0,0
        heart_lost_counter=1
if last_touched_bad_guy < time.time() + 2 and player_zone.colliderect(boss_zone):
    last_touched_bad_guy = time.time()  # Update the last time the player touched the bad guy
    if heart_lost_counter==1:
        heart2=0,0,0
        heart_lost_counter=2
if last_touched_bad_guy < time.time() + 2 and player_zone.colliderect(boss_zone):
    last_touched_bad_guy = time.time()  # Update the last time the player touched the bad guy
    if heart_lost_counter==2:
        pygame.draw.rect(screen,"red",(0,0,1280,720))
        boss=0
        bosscolor=0,0,0
        bossheigt=720
        heart1=255,0,0
        heart2=255,0,0
        heart3=255,0,0
        heart_lost_counter=0
1 Like