简体   繁体   中英

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

i am working on a program in Python and using Pygame. this is what the basic code looks like:

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()

what i want to do is have the object's function of draw_circle() to be constantly updated by the loop so that the drawn circle is shown for all objects in the list, but since the list is iterated it updates the new object added and the objects already appended are not updated.

The program, works, it draws the circles upon user input but the update problem is the only issue i need to solve. Is there any possible way to have all elements in the list of objects being updated by the while loop? i have tried for many days and i have not been able to find a good solution. any ideas are appreciated. Thanks

To draw all the circles in your list, just iterate through them and draw them before each call to update:

for circle in circle_list:
    circle.draw_circle()

Edit: the OP had posted incorrectly formatted code, but says the actual code is fine, so removed that suggestion

You need to redraw the whole list after your blit(it covers the whole screen with the surface 'background' and 'erases' it), its not conditional, you need to iterate over the whole list and draw it. Them in the event part you decides who enters and who leaves the list.

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.

edit: I thought you already tried : https://stackoverflow.com/a/11172885/341744

The program, works, it draws the circles upon user input but the update problem is the only issue i need to solve. Is there any possible way to have all elements in the list of objects being updated by the while loop?

You could iterate on a temporary list, for example, if you kill actors while iterating.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM