为了账号安全,请及时绑定邮箱和手机立即绑定

有没有办法控制 pygame 中函数的迭代?

有没有办法控制 pygame 中函数的迭代?

守着星空守着你 2023-07-05 10:28:32
我正在 Pygame 中制作一个项目,需要equations在特定时间从列表中渲染一个随机方程。为了实现这一目标,我编写了一个函数来呈现该函数,但我遇到了两个问题。第一个问题是它对函数的迭代次数超出了我真正想要的次数,我希望函数只迭代一次。我的意思是它从列表中选择一个随机方程一次,并渲染一次,但这并没有发生。第二个问题出现在第30行代码上。它说if tks > 5000: display_equation()但是如果我运行代码,游戏一开始就会开始迭代该函数,而不是等待游戏的第 5000 毫秒开始调用该函数。谢谢!import pygameimport randompygame.init()screen = pygame.display.set_mode((640, 480))clock = pygame.time.Clock()done = Falseequations = ['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)
查看完整描述

1 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

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

  • 在循环之前仅渲染背景一次

  • 创建一个标志,表示方程已经渲染完毕,不需要重新渲染

试试这个代码:

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)


查看完整回答
反对 回复 2023-07-05
  • 1 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信