0

I'm new to programming and I need a way to limit the randomization of the variable food_choice so it doesn't print tons of images on my pygame screen.

Here is a section of my code. I believe the problem is because my function draw_food() is inside of the main loop, meaning that everytime the game runs with the determined tick, the function draw_food() is then run again, picking another food, causing an endless randomization. I need to way to limit this randomization to once per x seconds.

def draw_food():

    food_choice = random.choice(food_types)

    for object in object_list[:]:
        screen.blit(food_choice, (foodx, foody))
        object.deter -= 0.035

        if object.deter < 1: 
            object_list.remove(object)

def draw_game_window():
    
    screen.blit(bg, (0, 0))

    draw_food()

    cat.draw(screen)

    pygame.display.update()


# main loop
cat = player(200, 355, 67, 65)
run = True 

object_list = []
time_interval = 5000 # 200 milliseconds == 0.2 seconds
next_object_time = 0

while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    
    draw_game_window()

    current_time = pygame.time.get_ticks()

    if current_time > next_object_time:
        next_object_time += time_interval
        object_list.append(Object())

pygame.quit()```
itstelk
  • 11
  • 1
  • Hey man, could you please limit the code to just the part relevant to the question? It's a pain to figure out what's going on otherwise, and it's probably why someone downvoted you. – Arkleseisure Dec 18 '21 at 00:59
  • @Arkleseisure done, sorry I'm new here, thanks for the advice – itstelk Dec 18 '21 at 05:53

2 Answers2

2

You can create a randomizeFood event every second like this.

randomizeFood = pygame.USEREVENT + 0
pygame.time.set_timer(randomizeFood, 1000) #time in ms

Then in your event loop, create random food when this event is generated.

for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == randomizeFood:
            food_choice = random.choice(food_types)
1

Eiter use a timer event as already explained in an answer, or use pygame.time.get_ticks. This function returns the number of milliseconds since the application was started.
Use global variables to store the time and the food. You have to use the global statement to change a global variable within a function

food_choice = None
next_choice_time = 0

def draw_food():

    current_time = pygame.time.get_ticks()
    if current_time >= next_choice_time:
        next_choice_time = current_time + 1000 # in 1 second (1000 millisecodns)

        food_choice = random.choice(food_types)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174