# -*- coding: utf-8 -*-
import pygame
import random
import math
import time
import sys
from typing import List, Tuple, Optional, Dict, Any
# --- Configuration Constants ---
WIDTH, HEIGHT = 1280, 720
FPS = 60
BLACK = (0, 0, 0)
FONT_NAME = None # Use default Pygame font
# Try "Garamond", "Georgia", "Times New Roman" or a specific .ttf if available
# FONT_NAME = "georgia" # Example: if Georgia font is installed
TEXT_COLOR_BASE = (220, 220, 180) # Warm off-white/gold
TEXT_FONT_SIZE = 48
TEXT_TOP_MARGIN = 70
TEXT_FADE_DURATION = 1.5 # seconds for fade in/out
TEXT_READ_DURATION = 5.0 # seconds sentence stays fully visible
PARTICLE_COUNT = 1500
PARTICLE_SIZE_BASE = 1.5
PARTICLE_SIZE_VARIATION = 1.0
PARTICLE_WANDER_SPEED = 0.8
PARTICLE_TARGET_SPEED = 4.0
PARTICLE_DAMPING = 0.97 # friction/drag
PARTICLE_GLOW_RADIUS_FACTOR = 3.5 # How much bigger the glow circle is
PARTICLE_GLOW_ALPHA = 40 # Transparency of the glow
# --- Story Definition ---
# Each element is a tuple: (sentence, animation_config)
# animation_config is a dictionary specifying particle behavior
STORY = [
(
"From the silent void, where darkness reigned absolute...",
{
"type": "disperse",
"color_palette": [(50, 50, 80), (70, 70, 100), (30, 30, 60)], # Deep blues/purples
"glow_color": (100, 100, 150),
"duration": TEXT_READ_DURATION + TEXT_FADE_DURATION * 2,
}
),
(
"...a thought flickered, hesitant, like the first spark.",
{
"type": "form_shape",
"shape": "spark",
"center": (WIDTH // 2, HEIGHT // 2),
"size": 20,
"color_palette": [(255, 255, 200), (255, 230, 150), (255, 200, 100)], # Bright yellows/whites
"glow_color": (255, 255, 220),
"duration": TEXT_READ_DURATION + TEXT_FADE_DURATION,
"hold": 1.0 # Hold shape briefly after text fades
}
),
(
"It gathered substance, swirling dust coalescing into memory.",
{
"type": "transition",
"from": "spark", # Implied previous state
"to": "swirl",
"center": (WIDTH // 2, HEIGHT // 2 + 50),
"size": 200,
"color_palette": [(180, 150, 100), (150, 120, 80), (200, 180, 150)], # Earthy sand tones
"glow_color": (200, 180, 160),
"duration": TEXT_READ_DURATION + TEXT_FADE_DURATION * 1.5,
}
),
(
"A face emerged, etched in ephemeral light, soft and familiar.",
{
"type": "form_shape",
"shape": "face_outline",
"center": (WIDTH // 2, HEIGHT // 2),
"size": 250,
"color_palette": [(220, 220, 200), (200, 200, 180), (240, 240, 220)], # Soft whites/creams
"glow_color": (230, 230, 230),
"duration": TEXT_READ_DURATION + TEXT_FADE_DURATION,
"hold": 2.0
}
),
(
"Laughter, bright motes dancing, filled the nascent mindscape.",
{
"type": "multi_burst",
"origins": [
(WIDTH * 0.4, HEIGHT * 0.6),
(WIDTH * 0.6, HEIGHT * 0.55),
(WIDTH * 0.5, HEIGHT * 0.65),
],
"color_palette": [(255, 215, 0), (255, 230, 80), (255, 190, 0)], # Gold/yellow hues
"glow_color": (255, 220, 50),
"burst_speed": 5,
"duration": TEXT_READ_DURATION + TEXT_FADE_DURATION * 0.5,
}
),
(
"Then, a sigh... a gentle breeze scattering the golden motes.",
{
"type": "disperse",
"color_palette": [(150, 150, 120), (180, 180, 150), (120, 120, 90)], # Fading gold/grey
"glow_color": (160, 160, 130),
"duration": TEXT_READ_DURATION + TEXT_FADE_DURATION,
"force": (0, -0.5) # Gentle upward drift
}
),
(
"Time, the relentless sculptor, began to smooth the edges.",
{
"type": "form_shape",
"shape": "hourglass",
"center": (WIDTH // 2, HEIGHT // 2 + 50),
"size": 300,
"color_palette": [(100, 120, 140), (120, 140, 160), (80, 100, 120)], # Cool greys/blues
"glow_color": (110, 130, 150),
"duration": TEXT_READ_DURATION + TEXT_FADE_DURATION,
"hold": 1.5
}
),
(
"Colors bled, vibrancy fading into washes of muted grey.",
{
"type": "color_fade",
"target_palette": [(90, 90, 90), (110, 110, 110), (70, 70, 70)],
"target_glow": (100, 100, 100),
"duration": TEXT_READ_DURATION + TEXT_FADE_DURATION * 1.5,
# Keep the hourglass shape while colors fade
"keep_shape": True,
"shape_config": { # Redefine shape slightly if needed, or use previous implicitly
"type": "form_shape",
"shape": "hourglass",
"center": (WIDTH // 2, HEIGHT // 2 + 50),
"size": 300,
}
}
),
(
"The image fractured, sharp lines dissolving like sand through fingers.",
{
"type": "shatter",
"center": (WIDTH // 2, HEIGHT // 2 + 50), # Center of previous shape
"strength": 1.5,
"color_palette": [(90, 90, 90), (110, 110, 110), (70, 70, 70)], # Keep faded colors
"glow_color": (100, 100, 100),
"duration": TEXT_READ_DURATION + TEXT_FADE_DURATION,
}
),
(
"Returning to the quiet dust, a canvas wiped clean.",
{
"type": "disperse",
"color_palette": [(60, 60, 60), (80, 80, 80), (40, 40, 40)], # Darker greys
"glow_color": (70, 70, 70),
"duration": TEXT_READ_DURATION + TEXT_FADE_DURATION * 2,
"force": (0, 0.3) # Gentle downward drift
}
),
(
"Yet, within the void, an echo remained... a single, persistent warmth.",
{
"type": "form_shape",
"shape": "single_pulse",
"center": (WIDTH // 2, HEIGHT * 0.6),
"size": 15,
"color_palette": [(255, 100, 100), (230, 80, 80), (200, 60, 60)], # Warm red/ember
"glow_color": (255, 120, 120),
"duration": TEXT_READ_DURATION + TEXT_FADE_DURATION * 3, # Linger longer
"hold": 10.0 # Hold significantly longer at the end
}
),
(
"", # End scene - allow final animation to play out
{
"type": "linger",
"duration": 5.0, # Keep the pulse lingering
}
)
]
# --- Helper Functions ---
def lerp(a, b, t):
"""Linear interpolation"""
return a + (b - a) * t
def lerp_color(c1, c2, t):
"""Linear interpolation for colors"""
return tuple(int(lerp(a, b, t)) for a, b in zip(c1, c2))
def get_random_color(palette: List[Tuple[int, int, int]]) -> Tuple[int, int, int]:
"""Chooses a random color from the palette."""
return random.choice(palette) if palette else (255, 255, 255)
def clamp(value, min_val, max_val):
"""Clamps a value between min and max"""
return max(min_val, min(value, max_val))
# --- Shape Generation Functions ---
def get_shape_points(config: Dict[str, Any], num_points: int) -> List[pygame.Vector2]:
"""Generates target points for particles based on shape config."""
shape_type = config.get("shape", "random")
center = pygame.Vector2(config.get("center", (WIDTH / 2, HEIGHT / 2)))
size = config.get("size", 100)
points = []
if shape_type == "spark":
# Small, dense cluster
for _ in range(num_points):
radius = random.gauss(0, size * 0.3) # Gaussian distribution around center
angle = random.uniform(0, 2 * math.pi)
points.append(center + pygame.Vector2(radius * math.cos(angle), radius * math.sin(angle)))
elif shape_type == "swirl":
# Archimedean spiral
a = 0
b = size / (2 * math.pi * 4) # Controls distance between arms, 4 turns
for i in range(num_points):
angle = math.sqrt(i / num_points) * 8 * math.pi # Spread points along the spiral
radius = a + b * angle
offset = pygame.Vector2(radius * math.cos(angle), radius * math.sin(angle)) * random.uniform(0.8, 1.2)
points.append(center + offset)
elif shape_type == "face_outline":
# Simplified face shape using parametric equations or key points
# Approximate oval for head
w, h = size * 0.8, size
chin_depth = h * 0.2
for i in range(num_points):
angle = (i / num_points) * 2 * math.pi
x = center.x + w * math.cos(angle)
y = center.y + h * math.sin(angle)
# Add a slight chin dip
if math.pi * 0.8 < angle < math.pi * 1.2:
y += chin_depth * (1 - abs(angle - math.pi) / (math.pi * 0.2))**2
# Add some noise/texture
x += random.uniform(-size * 0.03, size * 0.03)
y += random.uniform(-size * 0.03, size * 0.03)
points.append(pygame.Vector2(x, y))
elif shape_type == "hourglass":
w, h = size * 0.5, size
waist_factor = 0.15
num_per_section = num_points // 2 # Approx half top, half bottom
curve_intensity = 3 # Higher = sharper curve to waist
for i in range(num_points):
is_top = (i < num_per_section)
py = (i % num_per_section) / num_per_section # Progress 0 to 1 within section
if is_top:
y = center.y - h / 2 * py # Linear y position in top
current_h = h / 2 * py
else:
y = center.y + h / 2 * py # Linear y position in bottom
current_h = h / 2 * (1 - py) # Inverted height from center
# Calculate width based on height from center (creating the curve)
width_ratio = waist_factor + (1 - waist_factor) * (current_h / (h / 2))**curve_intensity
current_w = w * width_ratio
# Add random side and depth
side = random.choice([-1, 1])
x = center.x + side * current_w / 2 * random.uniform(0.8, 1.2)
y += random.uniform(-h * 0.02, h * 0.02) # Small y jitter
points.append(pygame.Vector2(x,y))
elif shape_type == "single_pulse":
# Concentrated point, particles oscillate around it
# Target points are very close to the center
for _ in range(num_points):
points.append(center + pygame.Vector2(random.gauss(0, size * 0.1), random.gauss(0, size * 0.1)))
else: # Default: random points within a rectangular area
rect_w, rect_h = size * 2, size * 1.5
for _ in range(num_points):
points.append(center + pygame.Vector2(random.uniform(-rect_w/2, rect_w/2),
random.uniform(-rect_h/2, rect_h/2)))
# Ensure we have exactly num_points (can happen if logic generates slightly fewer/more)
while len(points) < num_points:
points.append(random.choice(points) + pygame.Vector2(random.uniform(-5, 5), random.uniform(-5, 5))) # Add near existing
return points[:num_points]
# --- Particle Class ---
class Particle:
def __init__(self, x: float, y: float, color_palette: List[Tuple[int, int, int]]):
self.pos = pygame.Vector2(x, y)
self.vel = pygame.Vector2(random.uniform(-1, 1), random.uniform(-1, 1)).normalize() * PARTICLE_WANDER_SPEED
self.acc = pygame.Vector2(0, 0)
self.target_pos: Optional[pygame.Vector2] = None
self.current_color = get_random_color(color_palette)
self.target_color = self.current_color
self.target_glow_color = self.current_color # Initial glow matches particle
self.current_glow_color = self.target_glow_color
self.base_size = PARTICLE_SIZE_BASE + random.uniform(-PARTICLE_SIZE_VARIATION / 2, PARTICLE_SIZE_VARIATION / 2)
self.size = self.base_size
self.alpha = 255
self.target_alpha = 255
self.color_lerp_speed = random.uniform(0.02, 0.05)
self.size_oscillation = random.uniform(0, math.pi * 2) # For pulsing effect
self.size_oscillation_speed = random.uniform(0.05, 0.15)
self.state = "wander" # wander, move_to_target, pulsing
def apply_force(self, force: pygame.Vector2):
self.acc += force
def set_target(self, target_pos: pygame.Vector2, target_color: Tuple[int, int, int], target_glow: Tuple[int, int, int]):
self.target_pos = target_pos
self.target_color = target_color
self.target_glow_color = target_glow
self.state = "move_to_target"
def release(self):
self.target_pos = None
# Give a little outward push when released
# self.vel += pygame.Vector2(random.uniform(-0.5, 0.5), random.uniform(-0.5, 0.5))
self.state = "wander"
def update(self, dt: float, general_force: pygame.Vector2, scene_config: Dict[str, Any]):
self.size_oscillation += self.size_oscillation_speed * dt * 60 # Keep speed consistent regardless of FPS
self.size = self.base_size + math.sin(self.size_oscillation) * self.base_size * 0.3
if self.state == "move_to_target" and self.target_pos:
direction = self.target_pos - self.pos
dist = direction.length()
if dist > 1: # Avoid division by zero and jittering at target
# Move faster when further away, slower when closer
speed = lerp(PARTICLE_TARGET_SPEED * 0.1, PARTICLE_TARGET_SPEED, clamp(dist / 150.0, 0, 1))
direction.normalize_ip()
seek_force = direction * speed - self.vel
self.apply_force(seek_force * 0.1) # Steering force
else:
# Close enough to target, maybe switch state or just hover
self.vel *= 0.8 # Strongly damp velocity when close
if scene_config.get("shape") == "single_pulse":
self.state = "pulsing"
elif self.state == "wander":
# Apply gentle random steering force
wander_force = pygame.Vector2(random.uniform(-1, 1), random.uniform(-1, 1)).normalize() * 0.1
self.apply_force(wander_force)
# Gradually move towards center if too far out (gentle pull)
center_dir = pygame.Vector2(WIDTH/2, HEIGHT/2) - self.pos
dist_from_center = center_dir.length()
if dist_from_center > min(WIDTH, HEIGHT) * 0.6:
self.apply_force(center_dir.normalize() * 0.02)
elif self.state == "pulsing":
# Specific behavior for the final pulse - oscillate around target
direction = self.target_pos - self.pos
dist = direction.length()
spring_force = direction * 0.05 # Pull towards center
self.apply_force(spring_force)
# Add small random jitter
self.apply_force(pygame.Vector2(random.uniform(-0.1, 0.1), random.uniform(-0.1, 0.1)))
# Apply general forces (like wind/gravity from scene)
self.apply_force(general_force)
# Update velocity and position
self.vel += self.acc * dt * 60 # Adjust force effect by dt
self.vel *= PARTICLE_DAMPING # Apply friction
# Speed limit for wandering particles
if self.state == "wander" and self.vel.length_squared() > PARTICLE_WANDER_SPEED**2:
self.vel.scale_to_length(PARTICLE_WANDER_SPEED)
self.pos += self.vel * dt * 60 # Adjust movement by dt
# Reset acceleration for next frame
self.acc = pygame.Vector2(0, 0)
# Keep particles on screen (wrap around)
if self.pos.x < 0: self.pos.x = WIDTH
if self.pos.x > WIDTH: self.pos.x = 0
if self.pos.y < 0: self.pos.y = HEIGHT
if self.pos.y > HEIGHT: self.pos.y = 0
# Update color and alpha towards target
self.current_color = lerp_color(self.current_color, self.target_color, self.color_lerp_speed)
self.current_glow_color = lerp_color(self.current_glow_color, self.target_glow_color, self.color_lerp_speed)
# Alpha update would go here if needed (e.g., fading out particles)
# self.alpha = lerp(self.alpha, self.target_alpha, 0.05)
def draw(self, surface: pygame.Surface):
if self.alpha <= 0: return
# Draw glow first (larger, semi-transparent circle)
glow_radius = int(self.size * PARTICLE_GLOW_RADIUS_FACTOR)
if glow_radius >= 1:
# Create a temporary surface for the glow to handle alpha correctly
glow_surf = pygame.Surface((glow_radius * 2, glow_radius * 2), pygame.SRCALPHA)
glow_color_with_alpha = self.current_glow_color + (int(PARTICLE_GLOW_ALPHA * (self.alpha / 255.0)),)
pygame.draw.circle(glow_surf, glow_color_with_alpha, (glow_radius, glow_radius), glow_radius)
# Use BLEND_RGBA_ADD for a brighter, more intense glow effect
surface.blit(glow_surf, (int(self.pos.x - glow_radius), int(self.pos.y - glow_radius)), special_flags=pygame.BLEND_RGBA_ADD)
# Draw the main particle
# Use integer positions for drawing, prevents anti-aliasing issues with tiny circles
px, py = int(self.pos.x), int(self.pos.y)
particle_radius = int(self.size)
if particle_radius < 1: particle_radius = 1
color_with_alpha = self.current_color # Alpha handled by glow surface blend
# color_with_alpha = self.current_color + (int(self.alpha),) # If not using blend flags
# Use simple circle drawing
pygame.draw.circle(surface, color_with_alpha, (px, py), particle_radius)
# --- Main Application Class ---
class SandArtNarrative:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ephemeral Echoes - A Sand Art Narrative")
self.clock = pygame.time.Clock()
self.font = pygame.font.Font(FONT_NAME, TEXT_FONT_SIZE)
self.is_running = True
self.particles: List[Particle] = []
self.current_scene_index = -1
self.current_sentence = ""
self.current_animation_config: Dict[str, Any] = {}
self.target_points: List[pygame.Vector2] = []
self.text_alpha = 0
self.text_state = "idle" # idle, fading_in, visible, fading_out
self.scene_timer = 0.0
self.text_timer = 0.0
self._initialize_particles()
self._next_scene()
def _initialize_particles(self):
"""Create the initial set of particles."""
# Start with the color palette of the first scene
initial_palette = STORY[0][1].get("color_palette", [(255, 255, 255)])
self.particles = [
Particle(random.uniform(0, WIDTH), random.uniform(0, HEIGHT), initial_palette)
for _ in range(PARTICLE_COUNT)
]
# Set initial target colors/glow based on the first scene
initial_glow = STORY[0][1].get("glow_color", initial_palette[0])
for p in self.particles:
p.target_color = get_random_color(initial_palette)
p.target_glow_color = initial_glow
def _next_scene(self):
"""Advances to the next sentence and animation configuration."""
self.current_scene_index += 1
if self.current_scene_index >= len(STORY):
# End of story - maybe fade out or loop? For now, just stop major updates.
self.current_sentence = ""
self.text_state = "idle"
# Could add a final fade out of particles here
print("End of narrative.")
# Let the last animation linger based on its config, then potentially exit
# We handle the linger/exit in the main loop based on the last scene's config.
return
self.current_sentence, self.current_animation_config = STORY[self.current_scene_index]
print(f"Scene {self.current_scene_index}: {self.current_sentence}") # Debugging
# Reset timers and text state
self.scene_timer = 0.0
self.text_timer = 0.0
self.text_alpha = 0
if self.current_sentence:
self.text_state = "fading_in"
else:
self.text_state = "idle" # No text for this scene (e.g., final linger)
# --- Configure Particles Based on Scene ---
anim_type = self.current_animation_config.get("type", "disperse")
color_palette = self.current_animation_config.get("color_palette", [(200, 200, 200)])
glow_color = self.current_animation_config.get("glow_color", color_palette[0] if color_palette else (255, 255, 255))
duration = self.current_animation_config.get("duration", TEXT_READ_DURATION + TEXT_FADE_DURATION * 2)
self.current_animation_config["effective_duration"] = duration # Store for timing
if anim_type == "form_shape" or anim_type == "transition":
if anim_type == "transition":
# Transition implies we keep previous target points briefly? Or generate new ones immediately?
# Let's generate new ones for the target shape.
shape_name = self.current_animation_config.get("to", "random")
self.current_animation_config["shape"] = shape_name # Ensure shape key exists
self.target_points = get_shape_points(self.current_animation_config, PARTICLE_COUNT)
random.shuffle(self.target_points) # Shuffle to assign randomly
for i, p in enumerate(self.particles):
target_p = self.target_points[i % len(self.target_points)]
target_c = get_random_color(color_palette)
p.set_target(target_p, target_c, glow_color)
elif anim_type == "disperse" or anim_type == "linger":
self.target_points = [] # Clear specific targets
for p in self.particles:
p.release()
p.target_color = get_random_color(color_palette)
p.target_glow_color = glow_color
elif anim_type == "multi_burst":
self.target_points = [] # No fixed shape target
origins = self.current_animation_config.get("origins", [(WIDTH/2, HEIGHT/2)])
burst_speed = self.current_animation_config.get("burst_speed", 5)
num_origins = len(origins)
for i, p in enumerate(self.particles):
p.release() # Go into wander state first
p.target_color = get_random_color(color_palette)
p.target_glow_color = glow_color
# Give an initial velocity burst outwards from a random origin
origin = pygame.Vector2(origins[i % num_origins])
direction = (p.pos - origin).normalize() if (p.pos - origin).length() > 0 else pygame.Vector2(random.uniform(-1,1), random.uniform(-1,1)).normalize()
p.vel = direction * burst_speed * random.uniform(0.5, 1.5)
elif anim_type == "shatter":
self.target_points = [] # No fixed target
center = pygame.Vector2(self.current_animation_config.get("center", (WIDTH/2, HEIGHT/2)))
strength = self.current_animation_config.get("strength", 1.5)
for p in self.particles:
p.release()
p.target_color = get_random_color(color_palette) # Update colors if needed
p.target_glow_color = glow_color
# Apply outward force based on position relative to center
direction = (p.pos - center).normalize() if (p.pos - center).length() > 0 else pygame.Vector2(random.uniform(-1,1), random.uniform(-1,1)).normalize()
p.vel += direction * strength * random.uniform(0.8, 1.2) * (1.0 - clamp((p.pos-center).length() / (WIDTH*0.3) , 0, 1) ) # Less force further away
elif anim_type == "color_fade":
# Only change target colors, keep existing state (wander or target)
target_palette = self.current_animation_config.get("target_palette", color_palette)
target_glow = self.current_animation_config.get("target_glow", glow_color)
keep_shape = self.current_animation_config.get("keep_shape", False)
if keep_shape and not self.target_points:
# Need to recalculate target points if we were dispersed before
shape_config = self.current_animation_config.get("shape_config", {})
if shape_config:
self.target_points = get_shape_points(shape_config, PARTICLE_COUNT)
random.shuffle(self.target_points)
for i, p in enumerate(self.particles):
p.target_color = get_random_color(target_palette)
p.target_glow_color = target_glow
# If keeping shape, re-apply target position and state
if keep_shape and self.target_points:
target_p = self.target_points[i % len(self.target_points)]
p.set_target(target_p, p.target_color, p.target_glow_color) # Use new color targets
# If not keep_shape, particle state (wander/move) remains as it was
def _handle_events(self):
"""Handles user input and window events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.is_running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.is_running = False
if event.key == pygame.K_RIGHT: # Manual scene advance (for debugging)
self._next_scene()
def _update(self, dt: float):
"""Update game state."""
self.scene_timer += dt
# --- Update Text ---
if self.text_state == "fading_in":
self.text_timer += dt
self.text_alpha = clamp(lerp(0, 255, self.text_timer / TEXT_FADE_DURATION), 0, 255)
if self.text_timer >= TEXT_FADE_DURATION:
self.text_state = "visible"
self.text_timer = 0.0
elif self.text_state == "visible":
self.text_timer += dt
if self.text_timer >= TEXT_READ_DURATION:
self.text_state = "fading_out"
self.text_timer = 0.0
elif self.text_state == "fading_out":
self.text_timer += dt
self.text_alpha = clamp(lerp(255, 0, self.text_timer / TEXT_FADE_DURATION), 0, 255)
if self.text_timer >= TEXT_FADE_DURATION:
self.text_state = "idle"
# Don't advance scene immediately, let animation play out
# --- Update Particles ---
general_force = pygame.Vector2(self.current_animation_config.get("force", (0, 0)))
for p in self.particles:
p.update(dt, general_force, self.current_animation_config)
# --- Scene Transition Logic ---
scene_duration = self.current_animation_config.get("effective_duration", 5.0)
hold_duration = self.current_animation_config.get("hold", 0.0)
# Advance scene when the current scene's animation + hold time is mostly done
# But ensure text fade-out has also completed if text was present
ready_for_next_scene = (self.scene_timer >= scene_duration + hold_duration)
# For scenes with text, only advance *after* text has faded out
text_done = (not self.current_sentence) or (self.text_state == "idle" and self.text_timer >= TEXT_FADE_DURATION)
# Special case: last scene linger
is_last_scene = (self.current_scene_index == len(STORY) - 1)
if not is_last_scene and ready_for_next_scene and text_done:
self._next_scene()
elif is_last_scene and self.scene_timer > scene_duration + hold_duration + 2.0: # Extra buffer after last scene linger
print("Narrative complete. Closing.")
self.is_running = False # Auto-close after the final scene
def _draw(self):
"""Render the scene."""
self.screen.fill(BLACK)
# Draw particles
# Using SRCALPHA surface might be slightly slower but gives better blending control
# particle_surface = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
for p in self.particles:
p.draw(self.screen) # Draw directly or onto particle_surface
# self.screen.blit(particle_surface, (0,0))
# Draw text if visible
if self.text_alpha > 0 and self.current_sentence:
try:
text_surface = self.font.render(self.current_sentence, True, TEXT_COLOR_BASE)
text_surface.set_alpha(int(self.text_alpha))
text_rect = text_surface.get_rect(center=(WIDTH // 2, TEXT_TOP_MARGIN))
self.screen.blit(text_surface, text_rect)
except pygame.error as e:
print(f"Error rendering font: {e}")
# Fallback: draw simple text if font fails
fallback_font = pygame.font.Font(None, 30) # Default fallback
text_surface = fallback_font.render("Font error - " + self.current_sentence, True, (255,0,0))
text_surface.set_alpha(int(self.text_alpha))
text_rect = text_surface.get_rect(center=(WIDTH // 2, TEXT_TOP_MARGIN))
self.screen.blit(text_surface, text_rect)
pygame.display.flip()
def run(self):
"""Main application loop."""
while self.is_running:
dt = self.clock.tick(FPS) / 1000.0 # Delta time in seconds
# Prevent large dt jumps if debugging or pausing
dt = min(dt, 0.1)
self._handle_events()
self._update(dt)
self._draw()
pygame.quit()
sys.exit()
# --- Entry Point ---
if __name__ == "__main__":
if not pygame.font.get_init():
print("Warning: Pygame font module not initialized.")
try:
app = SandArtNarrative()
app.run()
except Exception as e:
print(f"\n--- An error occurred ---")
print(f"Error Type: {type(e).__name__}")
print(f"Details: {e}")
import traceback
traceback.print_exc()
pygame.quit()
sys.exit("Exiting due to error.")