【问题标题】:Is there a way to control of the iteration of a function in pygame?有没有办法控制pygame中函数的迭代?
【发布时间】:2020-08-30 02:16:31
【问题描述】:

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

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

  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)

【问题讨论】:

    标签: python python-3.x function math pygame


    【解决方案1】:

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

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

    试试这个代码:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-23
      相关资源
      最近更新 更多