亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法控制 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 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號