I recently watched Tech with Mike's space invaders video, and I thought the group lists were interesting. I tried to make a particle list with it. It works until the particles fall to the bottom, and I'm having trouble recycling them. It doesn't render everything, only one cube.
import pygame
import random
pygame.init()
win_height=600
win_width=800
win=pygame.display.set_mode((win_width,win_height))
pygame.display.set_caption("List practice")
white=(255,255,255)
black=(0,0,0)
clock=pygame.time.Clock()
class particle_class(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface((25,25))
self.image.fill(white)
self.rect=self.image.get_rect()
self.speed=0
def update(self):
self.rect.y+=self.speed
particles=pygame.sprite.Group()
for i in range(100):
particle=particle_class()
particle.speed=random.randrange(5,11)
particle.rect.y=0
particle.rect.x=random.randrange(0,win_width+1)
particles.add(particle)
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
win.fill(black)
particles.update()
particles.draw(win)
pygame.display.update()
for i in particles:
if particle.rect.y>win_height:
particle.rect.y=0
You want to iterate through the list of particles
. The for
loop runs on each item in the list (iterable) and gives you access to the current item in the list. If you do for i in particles:
, i
is an element of the list. i
is just the name of the variable that refers to the current item in the list. You can use any name you want at this place (i
, particle
, hugo
, ...). You just need to use the same name (variable) in the loop to access the item. See for
statements.
Either
for i in particles:
if i.rect.y > win_height:
i.rect.y = 0
or
for particle in particles:
if particle.rect.y > win_height:
particle.rect.y = 0