Skip to content

Instantly share code, notes, and snippets.

@petrblahos
Created December 15, 2023 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petrblahos/e551ce9d4acb713210c3a61f88e70828 to your computer and use it in GitHub Desktop.
Save petrblahos/e551ce9d4acb713210c3a61f88e70828 to your computer and use it in GitHub Desktop.
Simple particles in pygame
import math
import random
import pygame
class Particle(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.start = (x, y)
self.x = x
self.y = y
self.r = 0
self.speed = random.randint(1, 5)
self.image = pygame.Surface((self.r * 2, self.r * 2), pygame.SRCALPHA)
self.rect = self.image.get_rect(center=(self.x, self.y))
def update(self, dt):
self.r += self.speed * dt / 400
self.image = pygame.Surface((self.r * 2, self.r * 2), pygame.SRCALPHA)
pygame.draw.circle(self.image, (192, 255, 255), (self.r, self.r), self.r, width=0)
pygame.draw.circle(self.image, (0, 128, 128), (self.r, self.r), self.r, width=2)
self.rect = self.image.get_rect(center=(self.x, self.y))
class PGMTest:
WIDTH = 1280
HEIGHT = 600
def __init__(self):
pass
def prepare_window(self):
self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
self.screen.fill((0, 0, 255))
def prepare_particles(self, x, y, r):
self.particles = pygame.sprite.Group()
for i in range(100):
angle = random.random() * math.pi * 2
self.particles.add(Particle(x + math.sin(angle) * r, y + math.cos(angle) * r))
def run(self):
dt = 1
clock = pygame.time.Clock()
do_run = True
self.prepare_particles(self.WIDTH / 2, self.HEIGHT / 2, self.HEIGHT // 3)
while do_run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
do_run = False
break
self.screen.fill((0, 0, 0))
self.particles.update(dt=dt)
self.particles.draw(self.screen)
pygame.display.flip()
dt = clock.tick(60)
if "__main__" == __name__:
pygame.init()
pgm = PGMTest()
pgm.prepare_window()
pgm.run()
pygame.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment