我正在 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)
添加回答
舉報
0/150
提交
取消