1

I created a class that has a function to draw a surface in screen now i want to append it in a list and draw it multiple times but also delete it from list after it has crossed screen

import pygame
pygame.init()
screen=pygame.display.set_mode((1000,600))
obs_list=[]
class obstacle():
    def __init__(self):
        self.surface=pygame.surface.Surface((50,50))
        self.rect=self.surface.get_rect(center=(500,300))
    def draw(self,screen):
        screen.blit(self.surface,self.rect)
        self.move()
    def move(self):
        self.rect.centerx+=2
    def remove(self):
        if self.rect.centerx>=800:
            obs_list.remove(self)
while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()

    screen.fill('white')
    obs_list.append(obstacle())
    for obs in obs_list:
        obs.draw(screen)
    pygame.display.flip()

i did this but it just kinda like drags the square in the screen leaving trail behind i don't know what is happening and if i am doing it wrong way or cant do what i am trying to do without using sprite

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
suyog
  • 43
  • 6

1 Answers1

1

Since the ostacle is append to obs_list in the applicaition loop, the list will keep growing. And all obstacles from all past frames in the list are drawn in each frame. You have to append the obstacle to the list before the application loop instead of in the application loop:

obs_list.append(obstacle())                    # <--- insert

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()

    screen.fill('white')
    #obs_list.append(obstacle())                 <--- delete
    for obs in obs_list:
        obs.draw(screen)
    pygame.display.flip()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174