簡體   English   中英

Python和Pygame:在迭代期間更新循環中列表中的所有元素

[英]Python & Pygame: Updating all elements in a list under a loop during iteration

我正在使用Python並使用Pygame編寫程序。 這是基本代碼的樣子:

while 1:

   screen.blit(background, (0,0))
   for event in pygame.event.get():

      if event.type == QUIT:
        pygame.quit()
        sys.exit()

      if event.type == KEYDOWN and event.key == K_c:
        circle_create = True
        circle_list.append(Circle())

      if event.type == MOUSEBUTTONDOWN and circle_create == True:
        if clicks == 0:
            circle_list[i].center()
        clicks += 1


      if event.type == MOUSEMOTION and clicks == 1 and circle_create == True:
        circle_list[i].stretch()

   if circle_create == True:
     circle_list[i].draw_circle()

   if clicks == 2:
     clicks = 0
     i += 1
     circle_create = False    

 pygame.display.update()

我想要做的是讓循環不斷更新draw_circle()的對象函數,以便為列表中的所有對象顯示繪制的圓,但是由於列表是迭代的,它會更新添加的新對象和對象已經附加的內容未更新。

該程序工作,它根據用戶輸入繪制圓圈,但更新問題是我需要解決的唯一問題。 有沒有辦法讓while循環更新對象列表中的所有元素? 我已經嘗試了很多天,但我找不到一個好的解決方案。 任何想法都表示贊賞。 謝謝

要繪制列表中的所有圓圈,只需遍歷它們並在每次更新調用之前繪制它們:

for circle in circle_list:
    circle.draw_circle()

編輯:OP發布了錯誤格式化的代碼,但說實際代碼很好,所以刪除了該建議

您需要在blit之后重繪整個列表(它覆蓋整個屏幕,表面'背景'和'擦除'它),它不是有條件的,你需要迭代整個列表並繪制它。 他們在事件部分決定誰進入和離開列表。

Loop:
  Blit,starting new

  Event, here you decide who moves, who begin or cease to exist(append/remove)

  Redraw whole list, everyone in the circle_list.

編輯:我以為你已經嘗試過了: https//stackoverflow.com/a/11172885/341744

該程序工作,它根據用戶輸入繪制圓圈,但更新問題是我需要解決的唯一問題。 有沒有辦法讓while循環更新對象列表中的所有元素?

您可以迭代臨時列表,例如,如果您在迭代時殺死actor。

for circle in circles[:]:
    circle.update()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM