如何解决有没有办法控制pygame中函数的迭代?
我在Pygame中进行一个项目,该项目需要在特定时间从equations
列表中绘制一个随机方程。为此,我编写了一个函数来渲染该函数,但遇到了两个问题。
-
第一个问题是,迭代函数的次数超出了我的实际需求,我希望函数仅迭代一次。我的意思是,它是从列表ONCE中选择一个随机方程,并使其呈现ONCE,这是没有发生的。
-
第二个问题在代码的第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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。