Shokhrukh Valiev
Shokhrukh Valiev

Reputation: 107

Is there a way to control of the iteration of a function in pygame?

I was making a project in Pygame which required rendering a random equation from the equations list at a specific time. To accomplish that I wrote a function where it rendered the function but I came across 2 problems.

  1. The 1st problem is that it iterates the function more than I really want it, I want the function to simply iterate once. What I mean by that is for it to choose a random equation from the list ONCE, and render it ONCE, which is not happening.

  2. The 2nd problem is on the 30th line of code. It says if tks > 5000: display_equation() But if I run the code the game starts iterating over the function as soon as the game starts instead of waiting for the 5000th millisecond of the game to start calling the function.

Thanks!

import pygame
import random

pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
done = False

equations = ['2 + 2', '3 + 1', '4 + 4', '7 - 4']


font = pygame.font.SysFont("comicsansms", 72)

tks = pygame.time.get_ticks()

def display_equation():
        text = font.render(random.choice(list(equations)), True, (0, 128, 0))
        screen.blit(text, (320 - text.get_width() // 2, 240 - text.get_height() // 2))

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            done = True
    
    screen.fill((255, 255, 255))
    tks = pygame.time.get_ticks()
    if tks > 5000:
        display_equation()
    
    display_equation()
    pygame.display.update()
    clock.tick(60)

Upvotes: 1

Views: 100

Answers (1)

Mike67
Mike67

Reputation: 11342

For the code to run the way you want, make two changes:

  • Render the background only once, before the loop
  • Create a flag to indicate that the equation has been rendered and there is no need to re-render it

Try this code:

eq_done = False
screen.fill((255, 255, 255))
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            done = True
    
    tks = pygame.time.get_ticks()
    if tks > 5000 and not eq_done:
        display_equation()
        eq_done = True  # only render once
    
    pygame.display.update()
    clock.tick(60)

Upvotes: 1

Related Questions