Python snake game - problem with timer

Python Snake Game - problem activating “set timer” function

Hi, I am trying to implement a booster mode on my snake python code, and make it last only 5 seconds. However, it does not stop once the food is consumed by the snake, I tried modifying the code 100 times but it does not work. Below are the lines of code:
I earlier defined the speed for the booster timer:
booster_timer = pygame.USEREVENT + 1
speed_booster_duration = 5 # 5 seconds
speed_booster_active = False # Initialize the flag for booster activation
speed_booster_start_time = 0

if x1 == booster_foodx and y1 == booster_foody:
if not speed_booster_active:
snake_speed *= 2 # Double the snake speed
speed_booster_active = True
speed_booster_start_time = pygame.time.get_ticks()
pygame.time.set_timer(booster_timer, speed_booster_duration * 1000) # Set the booster timer
spawn_booster = False # Booster disappears when consumed
# Check if the speed boost duration has elapsed
if event.type == booster_timer:
if speed_booster_active:
snake_speed /= 2 # Restore normal speed
speed_booster_active = False # Deactivate the booster

Thanks for your help !

It’s difficult to tell what it’s doing because there’s no indentation. Please paste any code or traceback, and in order to preserve formatting, select the code or traceback that you posted and then click the </> button.

One thing I notice is that you’re not cancelling the event after it occurs, so it’ll repeat. I don’t know if that will affect it, but it’s probably recommended anyway:

pygame.time.set_timer(booster_timer, 0)

It occurred to me much later that it might fail in the way you described if the indentation was wrong, but as there’s no indentation shown at all in what you posted, I don’t know whether that’s actually the problem.

1 Like