I was programming a little game in pygame and I had to add items to a list from a class, but when I run the code the second "obstacle" doesn't appear because the function "move" in the "obstacle" class does not append the item to the list. Does someone know how to fix that?
Here is some code:
obs = []
class obstacles():
def __init__(self):
self.x = screen_width
self.y = screen_height - ob_height
self.rect = Rect(self.x, self.y, ob_width, ob_height)
self.speed = 4
def draw(self):
pygame.draw.rect(screen, ob_col, self.rect)
def move(self):
self.rect.x -= self.speed
if self.rect.x < 100:
obs.append(obstacles())
def init():
obs.append(obstacles())
ob_disegno = obstacles()
sq_disegno = square()
init()
run = True
while run:
clock.tick(fps)
screen.fill(background)
ob_disegno.move()
sq_disegno.draw()
for i in obs:
ob_disegno.draw()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.update()
pygame.quit()
Of course, the object is added to the list. However, you never draw the objects in the list, so you never see the new objects. You just draw ob_disegno
:
for i in obs: ob_disegno.draw()
You need to move and draw the elements of the list:
for ob in obs:
ob.move()
ob.draw()
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.