有没有一种方法可以控制pygame中函数的迭代



我在Pygame中做了一个项目,需要在特定时间从equations列表中渲染一个随机方程。为了实现这一点,我写了一个函数,它呈现了这个函数,但我遇到了两个问题。

  1. 第一个问题是它迭代函数的次数超过了我真正想要的次数,我希望函数只迭代一次。我的意思是,它从列表中选择一个随机方程一次,并将其渲染一次,但这并没有发生。

  2. 第二个问题出现在代码的第30行。上面写着if tks > 5000: display_equation(),但如果我运行代码,游戏一开始就开始迭代函数,而不是等待游戏的第5000毫秒开始调用函数。

谢谢!

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)

为了让代码以您想要的方式运行,请进行两项更改:

  • 在循环之前只渲染背景一次
  • 创建一个标志,指示方程式已渲染,无需重新渲染

试试这个代码:

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)

最新更新