Okay, this is a fun one! We'll create a Game of Life simulation with Pygame, focusing on those vibrant special effects.
Here's the plan:
- Core Game of Life Logic: Standard rules, grid update.
- Pygame Setup: Screen, event loop, drawing.
- Grid Rendering: Drawing cells and grid lines.
- Mouse Interaction: Left-click to make alive, right-click to kill.
- Particle System for Effects:
- When a cell is born: A burst of expanding, fading, colorful particles.
- When a cell dies: A different set of imploding/fading particles.
- Visual Polish: Good color choices, smooth animations.
Let's get started!
import pygame
import random
import math
# --- Constants ---
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
CELL_SIZE = 10
GRID_WIDTH = SCREEN_WIDTH // CELL_SIZE
GRID_HEIGHT = SCREEN_HEIGHT // CELL_SIZE
# Colors
COLOR_BLACK = (0, 0, 0)
COLOR_WHITE = (255, 255, 255)
COLOR_GRID = (40, 40, 40)
COLOR_ALIVE_BASE = (0, 255, 128) # A vibrant green/cyan
COLOR_EFFECT_PALETTE_BIRTH = [
(255, 255, 0), (255, 128, 0), (0, 255, 255),
(128, 255, 0), (255, 0, 255)
]
COLOR_EFFECT_PALETTE_DEATH = [
(100, 100, 255), (150, 50, 200), (200, 100, 100),
(50, 50, 150)
]
FPS = 30 # For simulation updates
ANIMATION_FPS = 60 # For smoother particle animations
# --- Particle Class for Special Effects ---
class Particle:
def __init__(self, x, y, type="birth"):
self.x = x
self.y = y
self.type = type
self.lifespan = random.randint(15, 30) # Frames for particle to live
if self.type == "birth":
self.base_color = random.choice(COLOR_EFFECT_PALETTE_BIRTH)
self.radius = random.uniform(1, 3)
self.max_radius = random.uniform(CELL_SIZE * 0.4, CELL_SIZE * 0.8)
self.expand_speed = (self.max_radius - self.radius) / self.lifespan
angle = random.uniform(0, 2 * math.pi)
speed = random.uniform(0.5, 2)
self.dx = math.cos(angle) * speed
self.dy = math.sin(angle) * speed
elif self.type == "death":
self.base_color = random.choice(COLOR_EFFECT_PALETTE_DEATH)
self.radius = random.uniform(CELL_SIZE * 0.3, CELL_SIZE * 0.6)
self.shrink_speed = self.radius / self.lifespan
# Death particles can just fade or move slightly inwards
angle = random.uniform(0, 2 * math.pi)
speed = random.uniform(0.1, 0.5)
self.dx = math.cos(angle) * speed * -0.5 # Move slightly inwards
self.dy = math.sin(angle) * speed * -0.5
def update(self):
self.lifespan -= 1
self.x += self.dx
self.y += self.dy
if self.type == "birth":
self.radius += self.expand_speed
self.radius = min(self.radius, self.max_radius)
elif self.type == "death":
self.radius -= self.shrink_speed
self.radius = max(0, self.radius)
return self.lifespan > 0 and self.radius > 0
def draw(self, surface):
if self.lifespan <= 0 or self.radius <= 0:
return
alpha = int(255 * (self.lifespan / 30)) # Fade out
alpha = max(0, min(255, alpha))
# Create a temporary surface for alpha blending if needed, or use per-pixel alpha if available
# For simplicity, we'll draw solid circles that shrink/grow and fade
# Pygame's draw.circle doesn't directly support alpha.
# A common trick is to use a surface with set_alpha.
particle_surf = pygame.Surface((int(self.radius * 2), int(self.radius * 2)), pygame.SRCALPHA)
current_color = (*self.base_color, alpha) # Add alpha to the color tuple
# Draw on the temporary surface
pygame.draw.circle(particle_surf, current_color, (int(self.radius), int(self.radius)), int(self.radius))
# Blit the temporary surface onto the main screen
# Using BLEND_RGBA_ADD can create a nice glow effect
surface.blit(particle_surf, (int(self.x - self.radius), int(self.y - self.radius)), special_flags=pygame.BLEND_RGBA_ADD)
# --- Game Logic Functions ---
def create_grid(rows, cols, randomize=False):
grid = [[0 for _ in range(cols)] for _ in range(rows)]
if randomize:
for r in range(rows):
for c in range(cols):
if random.random() < 0.2: # 20% chance of being alive
grid[r][c] = 1
return grid
def count_neighbors(grid, r, c):
count = 0
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
nr, nc = r + i, c + j
# Wrap around boundaries
nr = nr % GRID_HEIGHT
nc = nc % GRID_WIDTH
count += grid[nr][nc]
return count
def update_grid(current_grid, particles_list):
new_grid = [row[:] for row in current_grid] # Create a deep copy
changes = [] # To store (r, c, type) for effects
for r in range(GRID_HEIGHT):
for c in range(GRID_WIDTH):
neighbors = count_neighbors(current_grid, r, c)
cell_state = current_grid[r][c]
if cell_state == 1: # Alive cell
if neighbors < 2 or neighbors > 3:
new_grid[r][c] = 0
changes.append((r, c, "death"))
else: # Dead cell
if neighbors == 3:
new_grid[r][c] = 1
changes.append((r, c, "birth"))
# Spawn particles based on changes
for r, c, change_type in changes:
cell_center_x = c * CELL_SIZE + CELL_SIZE // 2
cell_center_y = r * CELL_SIZE + CELL_SIZE // 2
num_particles = random.randint(5, 10) if change_type == "birth" else random.randint(3, 7)
for _ in range(num_particles):
particles_list.append(Particle(cell_center_x, cell_center_y, change_type))
return new_grid
# --- Drawing Functions ---
def draw_grid_lines(surface):
for x in range(0, SCREEN_WIDTH, CELL_SIZE):
pygame.draw.line(surface, COLOR_GRID, (x, 0), (x, SCREEN_HEIGHT))
for y in range(0, SCREEN_HEIGHT, CELL_SIZE):
pygame.draw.line(surface, COLOR_GRID, (0, y), (SCREEN_WIDTH, y))
def draw_cells(surface, grid, particles_list):
for r in range(GRID_HEIGHT):
for c in range(GRID_WIDTH):
if grid[r][c] == 1:
# Base cell color
pygame.draw.rect(surface, COLOR_ALIVE_BASE,
(c * CELL_SIZE, r * CELL_SIZE, CELL_SIZE, CELL_SIZE))
# Add a slightly brighter inner rect for depth
inner_brightness_factor = 1.2
inner_color = tuple(min(255, int(ch * inner_brightness_factor)) for ch in COLOR_ALIVE_BASE)
pygame.draw.rect(surface, inner_color,
(c * CELL_SIZE + 2, r * CELL_SIZE + 2, CELL_SIZE - 4, CELL_SIZE - 4))
def draw_particles(surface, particles_list):
for particle in particles_list:
particle.draw(surface)
def draw_hud(surface, font, paused, generation):
pause_text = "PAUSED (Space)" if paused else "RUNNING (Space)"
text_surface = font.render(pause_text, True, COLOR_WHITE)
surface.blit(text_surface, (10, 10))
gen_text = f"Generation: {generation}"
text_surface_gen = font.render(gen_text, True, COLOR_WHITE)
gen_rect = text_surface_gen.get_rect(topright=(SCREEN_WIDTH - 10, 10))
surface.blit(text_surface_gen, gen_rect)
help_text_lines = [
"Left Click: Revive Cell",
"Right Click: Kill Cell",
"C: Clear Grid",
"R: Randomize Grid",
"Q: Quit"
]
for i, line in enumerate(help_text_lines):
help_surface = font.render(line, True, (180,180,180))
surface.blit(help_surface, (10, 30 + i * 20))
# --- Main Game ---
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Game of Life with Special Effects")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 28) # Default font, size 28
grid = create_grid(GRID_HEIGHT, GRID_WIDTH)
particles = []
running = True
paused = True
generation = 0
# Timer for simulation updates (slower than animation FPS)
time_since_last_update = 0
simulation_interval = 1000 / FPS # milliseconds
while running:
dt = clock.tick(ANIMATION_FPS) # Delta time for smooth animations
time_since_last_update += dt
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
paused = not paused
if event.key == pygame.K_c:
grid = create_grid(GRID_HEIGHT, GRID_WIDTH)
particles.clear()
generation = 0
paused = True
if event.key == pygame.K_r:
grid = create_grid(GRID_HEIGHT, GRID_WIDTH, randomize=True)
particles.clear()
generation = 0
paused = True # Start paused after randomizing
if event.key == pygame.K_q:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
mx, my = pygame.mouse.get_pos()
col = mx // CELL_SIZE
row = my // CELL_SIZE
if 0 <= col < GRID_WIDTH and 0 <= row < GRID_HEIGHT:
cell_center_x = col * CELL_SIZE + CELL_SIZE // 2
cell_center_y = row * CELL_SIZE + CELL_SIZE // 2
if event.button == 1: # Left click - bring to life
if grid[row][col] == 0:
grid[row][col] = 1
for _ in range(random.randint(8, 15)): # More particles for manual birth
particles.append(Particle(cell_center_x, cell_center_y, "birth"))
elif event.button == 3: # Right click - kill
if grid[row][col] == 1:
grid[row][col] = 0
for _ in range(random.randint(5, 10)): # More particles for manual death
particles.append(Particle(cell_center_x, cell_center_y, "death"))
# --- Update ---
if not paused and time_since_last_update >= simulation_interval:
grid = update_grid(grid, particles)
generation += 1
time_since_last_update = 0 # Reset timer
# Update particles
particles = [p for p in particles if p.update()]
# --- Draw ---
screen.fill(COLOR_BLACK)
draw_grid_lines(screen)
draw_cells(screen, grid, particles) # Pass particles for potential cell-specific effects (not used yet)
draw_particles(screen, particles)
draw_hud(screen, font, paused, generation)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
Key Features and Explanations:
-
Particle Class:
- Manages individual effect particles (position, color, lifespan, movement, size).
type: "birth" or "death" determines color palette, expansion/shrink behavior.
update(): Moves the particle, changes its size, and reduces lifespan. Returns False if dead.
draw(): Draws the particle. It uses a temporary surface (particle_surf) with SRCALPHA to handle transparency correctly. BLEND_RGBA_ADD is used for a nice additive blending (glow) effect.
-
update_grid modified for effects:
- It now takes
particles_list as an argument.
- When a cell's state changes, it records these changes.
- After checking all cells, it iterates through the
changes list and spawns a burst of Particle objects at the location of the change, adding them to the main particles list.
-
Mouse Interaction:
- Left-click sets
grid[row][col] = 1 and spawns "birth" particles if the cell was dead.
- Right-click sets
grid[row][col] = 0 and spawns "death" particles if the cell was alive.
- Particles are spawned immediately on click for instant feedback.
-
Dual FPS:
FPS (e.g., 10-30): Controls how often the Game of Life simulation updates.
ANIMATION_FPS (e.g., 60): Controls the main game loop and particle animation smoothness. This allows particles to animate smoothly even if the simulation itself runs slower.
-
Visuals:
- Alive Cells: A base vibrant color with a slightly brighter inner rectangle to give a subtle 3D/glowing feel.
- Birth Particles: Expand outwards, use a bright color palette (yellows, oranges, cyans), and fade.
- Death Particles: Shrink or fade, use a cooler/muted color palette (blues, purples), and fade.
- Additive Blending:
special_flags=pygame.BLEND_RGBA_ADD for drawing particles makes overlapping bright particles appear even brighter, creating a nice glow.
-
Controls:
- Space: Pause/Resume simulation.
To Run This:
- Make sure you have Pygame installed:
pip install pygame
- Save the code as a
.py file (e.g., game_of_life_effects.py).
- Run it from your terminal:
python game_of_life_effects.py
This implementation should give you a visually engaging Game of Life with distinct and colorful effects for cell births and deaths! You can tweak the particle parameters (lifespan, speed, colors, number of particles) to achieve different looks.