pythonpygamepygame-clockpygame-tick

Pygame - Run event for 3 seconds only once


I am fairly new to PyGame and I am creating a space shooter game. Part of this game are powerups and when a specific powerup is picked up by the player, I want the player not to be able to shoot for 3 seconds. Shooting is done by mouse click.

I can pick up the powerup, I know what powerup the player last picked up, but I am struggling with the event. How I am thinking of implementing is:

  1. Can't Shoot power up is picked up -> that's done
  2. Block mouse buttons
  3. Wait 3 seconds, while the rest of the game is still running
  4. Unblock mouse buttons.

I am aware that Python functions, such as wait, won't help.

Any ideas/suggestions? Thanks


Solution

  • When you call clock.tick() it returns time since the last call. So save that time: dt = clock.tick() and then use that variable to count down your seconds.

    Example:

    dt = clock.tick() # only call once per iteration
    if attack_blocked:
        attack_block_count += dt
        if attack_block_count >= 3000: # dt is in ms
            attack_blocked = False
    

    Example 2:

    while True:
        dt = clock.tick(60)
        for event....
            if block_attack_power_up:
                attack_blocked = True
                attack_block_count = 0
        if not attack_blocked:
            # do your attack
        if attack_blocked:
            attack_block_count += dt
            if attack_block_count >= 3000:
                attack_blocked = False