Let’s talk about particles in python and pygame. Let’s show a very simple effect, in this first part. In the next one we will see how to use it in a game.
The video
The code
import pygame
import random
class Particles:
''' position x y
color col
starting pos sx xy '''
def __init__(self, x=515, y=500, col=(0, 0, 0)):
"Initial position with random height"
self.x, self.y = 515, random.randint(0, y)
self.sx = x
self.sy = y
self.col = col
def move(self):
"When particle reaches top goes back down"
if self.y < 0:
self.x = self.sx
self.y = self.sy
else:
self.y -= 1
self.x += random.randrange(-1, 2)
pygame.draw.circle(screen, self.col, (self.x, self.y), 2)
def particles_list(number: int) -> list:
"Create a list of particles"
particles = []
for part in range(number):
col = (255, 255, 0) if part % 2 > 0 else (255, 0, 0)
particles.append(Particles(col=col))
return particles
def def_close_window():
"Close the window with [x] button or ESC"
loop = 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
loop = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
loop = 0
return loop
def show_particles(particles):
for p in particles:
p.move()
pygame.init()
screen = pygame.display.set_mode((1000, 600))
clock = pygame.time.Clock()
def start():
particles = particles_list(100)
loop = 1
while loop:
loop = def_close_window()
screen.fill((0, 0, 0))
show_particles(particles)
pygame.display.update()
clock.tick(60)
pygame.quit()
start()
Subscribe to the newsletter for updates
Tkinter templatesTwitter: @pythonprogrammi - python_pygame
Claude's Games
1. Memory gameVideos
Speech recognition gamePygame's Platform Game