Reputation: 107
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.
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.
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
Reputation: 11342
For the code to run the way you want, make two changes:
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