pythonpygameparticlesparticle-system

Simple Particle System in pygame randomly closes


I'm kinda new to programing and particle systems, so I followed a tutorial and made some modifications but I encountered an unexpected bug...

The code is the following:

import pygame, sys
from random import randint

pygame.init()

screen = pygame.display.set_mode([500, 500])
clock = pygame.time.Clock()


shrink_vel = -0.03

class Particles():
    def __init__(self):
        self.particles = []
    
    def emit(self):
        if self.particles:
            self.remove_particles()
            for particle in self.particles:
                particle[0][0] += particle[2][0]
                particle[0][1] += particle[2][1]
                particle[1] += shrink_vel
                pygame.draw.circle(screen, pygame.Color('White'), particle[0], int(particle[1]))

    def add_particles(self):
        pos_x, pos_y = pygame.mouse.get_pos()
        radius = 5
        (direction_x, direction_y) = (randint(-3, 3), randint(-3, 3))
        particle_circle = [[pos_x, pos_y], radius, (direction_x, direction_y)]
        self.particles.append(particle_circle)


    def remove_particles(self):
        particle_copy = [particle for particle in self.particles if particle[1] > 0]
        self.particles = particle_copy
    

vel_spawn = 10

PARTICLE_EVENT = pygame.USEREVENT + 1


particle1 = Particles()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        
        if event.type == pygame.MOUSEBUTTONDOWN:
            pygame.time.set_timer(PARTICLE_EVENT, vel_spawn)
        
        if event.type == pygame.MOUSEBUTTONUP:
            pygame.time.set_timer(PARTICLE_EVENT, 0)


        if event.type == PARTICLE_EVENT:
            particle1.add_particles()
            #Particles.add_particles()
        
        


    screen.fill((30, 30, 30))
    particle1.emit()
    pygame.display.update()
    clock.tick(120)

The problem is that sometimes, when the code is running, it just simply closes, without any error message, as if I had clicked the close button of the window. I only can associate the closing of the program with clicking fast with the mouse, but I'm not sure why does that happens or if it has really something to do with that. Can somebody help me?


Solution

  • Pygame crashes when the coordinates used to draw an object exceed a certain limit. Therefore I recommend to check if the particle is still in the window:

    def remove_particles(self):
        screen_rect = screen.get_rect()
        self.particles = [particle for particle in self.particles if 
                          (screen_rect.collidepoint(particle[0]) and particle[1] > 0)]