import pygame
import math
import random
import time
import sys
# Initialize Pygame
pygame.init()
pygame.font.init()
# Screen setup
WIDTH, HEIGHT = 1280, 720
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Sand Art Narrative - Particle Symphony")
# Clock for FPS control
clock = pygame.time.Clock()
FPS = 60
# Colors
BLACK = (0, 0, 0)
GLOW_BASE = (30, 144, 255) # Dodger Blue glow base
# Fonts
# Use a large, elegant serif font for narrative text
try:
font_path = pygame.font.match_font('serif') or pygame.font.match_font('timesnewroman') or pygame.font.match_font('georgia')
except:
font_path = None
FONT_SIZE = 48
font = pygame.font.Font(font_path, FONT_SIZE)
# Helper functions for glow effect on text
def render_glowing_text(text, font, base_color, glow_color, glow_radius=8):
"""Render text with a glowing effect by layering blurred text."""
text_surface = font.render(text, True, base_color)
size = text_surface.get_size()
glow_surface = pygame.Surface((size[0] + glow_radius*2, size[1] + glow_radius*2), pygame.SRCALPHA)
# Draw glow by blitting multiple times with offsets and alpha
for i in range(glow_radius, 0, -1):
alpha = int(255 * (i / glow_radius) ** 2 * 0.3)
glow_text = font.render(text, True, glow_color)
glow_text.set_alpha(alpha)
for dx, dy in [(-i, 0), (i, 0), (0, -i), (0, i), (-i//1.5, -i//1.5), (i//1.5, i//1.5), (-i//1.5, i//1.5), (i//1.5, -i//1.5)]:
glow_surface.blit(glow_text, (dx + glow_radius, dy + glow_radius))
glow_surface.blit(text_surface, (glow_radius, glow_radius))
return glow_surface
# Particle class
class Particle:
def __init__(self, x, y, color, radius=2):
self.pos = pygame.Vector2(x, y)
self.vel = pygame.Vector2(random.uniform(-1, 1), random.uniform(-1, 1))
self.acc = pygame.Vector2(0, 0)
self.color = color
self.radius = radius
self.target = None # Target position for morphing
self.glow_intensity = 0.0 # 0 to 1 for glow effect
self.base_color = color
self.current_color = color
def update(self, dt):
# If target is set, move towards it with easing
if self.target:
direction = self.target - self.pos
dist = direction.length()
if dist > 0.5:
# Smooth approach with easing
self.acc = direction * 5.0
else:
self.acc = pygame.Vector2(0, 0)
self.pos = self.target # Snap to target when close
else:
# Free floating with some noise
self.acc = pygame.Vector2(random.uniform(-0.1, 0.1), random.uniform(-0.1, 0.1))
# Update velocity and position
self.vel += self.acc * dt
# Damping for smooth motion
self.vel *= 0.85
self.pos += self.vel * dt
# Keep particles inside screen bounds softly
margin = 50
if self.pos.x < margin:
self.vel.x += (margin - self.pos.x) * 0.1
elif self.pos.x > WIDTH - margin:
self.vel.x -= (self.pos.x - (WIDTH - margin)) * 0.1
if self.pos.y < margin:
self.vel.y += (margin - self.pos.y) * 0.1
elif self.pos.y > HEIGHT - margin:
self.vel.y -= (self.pos.y - (HEIGHT - margin)) * 0.1
# Update glow intensity smoothly
self.glow_intensity = max(0.0, min(1.0, self.glow_intensity + (random.uniform(-0.05, 0.05))))
# Color shift example: oscillate hue slightly
self.current_color = shift_color(self.base_color, math.sin(pygame.time.get_ticks() * 0.002 + self.pos.x * 0.01) * 20)
def draw(self, surface):
# Draw glow by drawing multiple circles with increasing radius and decreasing alpha
glow_strength = int(150 * self.glow_intensity)
for i in range(3, 0, -1):
alpha = glow_strength // i
glow_color = (*self.current_color[:3], alpha)
glow_surf = pygame.Surface((self.radius*6, self.radius*6), pygame.SRCALPHA)
pygame.draw.circle(glow_surf, glow_color, (self.radius*3, self.radius*3), self.radius*i*1.5)
surface.blit(glow_surf, (self.pos.x - self.radius*3, self.pos.y - self.radius*3), special_flags=pygame.BLEND_ADD)
# Draw main particle
pygame.draw.circle(surface, self.current_color, (int(self.pos.x), int(self.pos.y)), self.radius)
def shift_color(color, hue_shift):
"""Shift the hue of an RGB color by hue_shift degrees."""
import colorsys
r, g, b = [c / 255.0 for c in color[:3]]
h, l, s = colorsys.rgb_to_hls(r, g, b)
h = (h + hue_shift / 360.0) % 1.0
r, g, b = colorsys.hls_to_rgb(h, l, s)
return (int(r * 255), int(g * 255), int(b * 255))
# Shape definitions for morphing particles into figures
def shape_heart(center_x, center_y, scale=1.0, points=200):
"""Generate points forming a heart shape."""
pts = []
for t in range(points):
angle = (t / points) * 2 * math.pi
x = 16 * math.sin(angle) ** 3
y = 13 * math.cos(angle) - 5 * math.cos(2 * angle) - 2 * math.cos(3 * angle) - math.cos(4 * angle)
pts.append(pygame.Vector2(center_x + x * scale, center_y - y * scale))
return pts
def shape_bird(center_x, center_y, scale=1.0, points=150):
"""Generate points forming a stylized bird shape."""
pts = []
for t in range(points):
angle = (t / points) * 2 * math.pi
# Parametric bird-like shape (abstract)
x = scale * (math.sin(angle) * (1 + 0.5 * math.cos(3 * angle)))
y = scale * (math.cos(angle) * (1 + 0.5 * math.sin(3 * angle)))
# Add wing tip
if 0.3 < t / points < 0.5:
y -= scale * 0.5 * math.sin(5 * angle)
pts.append(pygame.Vector2(center_x + x * 100, center_y + y * 60))
return pts
def shape_tree(center_x, center_y, scale=1.0, points=250):
"""Generate points forming a stylized tree shape."""
pts = []
# Trunk rectangle
trunk_width = 20 * scale
trunk_height = 60 * scale
for i in range(points // 5):
x = random.uniform(center_x - trunk_width / 2, center_x + trunk_width / 2)
y = random.uniform(center_y + 40 * scale, center_y + 40 * scale + trunk_height)
pts.append(pygame.Vector2(x, y))
# Leaves (circle cluster)
leaf_radius = 80 * scale
for i in range(points - len(pts)):
angle = random.uniform(0, 2 * math.pi)
r = random.uniform(0, leaf_radius)
x = center_x + r * math.cos(angle)
y = center_y - r * math.sin(angle)
pts.append(pygame.Vector2(x, y))
return pts
def shape_person(center_x, center_y, scale=1.0, points=300):
"""Generate points forming a stylized person figure."""
pts = []
# Head (circle)
head_center = pygame.Vector2(center_x, center_y - 80 * scale)
head_radius = 30 * scale
for i in range(points // 6):
angle = random.uniform(0, 2 * math.pi)
r = random.uniform(0, head_radius)
x = head_center.x + r * math.cos(angle)
y = head_center.y + r * math.sin(angle)
pts.append(pygame.Vector2(x, y))
# Body (ellipse)
body_center = pygame.Vector2(center_x, center_y)
body_width = 60 * scale
body_height = 120 * scale
for i in range(points - len(pts)):
angle = random.uniform(0, 2 * math.pi)
r = random.uniform(0, 1)
x = body_center.x + r * body_width * math.cos(angle)
y = body_center.y + r * body_height * math.sin(angle)
pts.append(pygame.Vector2(x, y))
return pts
# Story sentences and corresponding particle shapes and colors
story = [
{
"text": "In the quiet dawn, where shadows dance with light, a single grain of sand begins its journey.",
"shape": None,
"color": (200, 180, 150),
"glow": (255, 220, 180),
"count": 400,
"motion": "drift"
},
{
"text": "From scattered whispers, the grains gather, weaving the silhouette of a solitary figure — a dreamer.",
"shape": shape_person,
"color": (180, 220, 255),
"glow": (100, 180, 255),
"count": 350,
"motion": "morph"
},
{
"text": "Her eyes, pools of endless night, reflect the boundless sky where a bird takes flight.",
"shape": shape_bird,
"color": (255, 255, 180),
"glow": (255, 255, 100),
"count": 300,
"motion": "fly"
},
{
"text": "Beneath her feet, the earth breathes life — a tree of hope, its branches reaching for the stars.",
"shape": shape_tree,
"color": (100, 255, 100),
"glow": (180, 255, 180),
"count": 400,
"motion": "grow"
},
{
"text": "And in her heart, a glowing ember, a love that blooms eternal — a radiant heart of sand and light.",
"shape": shape_heart,
"color": (255, 100, 100),
"glow": (255, 180, 180),
"count": 250,
"motion": "pulse"
},
{
"text": "Together, they dance — the dreamer, the bird, the tree, and the heart — a symphony of grains, forever intertwined.",
"shape": None,
"color": (255, 255, 255),
"glow": (255, 255, 255),
"count": 500,
"motion": "dance"
}
]
# Text display parameters
TEXT_Y = 40
TEXT_X = WIDTH // 2
TEXT_FADE_TIME = 2.0 # seconds to fade out
TEXT_TYPE_SPEED = 40 # characters per second
# Particle system
class ParticleSystem:
def __init__(self, count, base_color, glow_color):
self.particles = []
self.base_color = base_color
self.glow_color = glow_color
for _ in range(count):
x = random.uniform(0, WIDTH)
y = random.uniform(HEIGHT * 0.3, HEIGHT * 0.9)
p = Particle(x, y, base_color)
p.glow_intensity = random.uniform(0.3, 0.7)
self.particles.append(p)
def morph_to_shape(self, shape_points):
# Assign targets to particles, cycling if fewer points than particles
for i, p in enumerate(self.particles):
target = shape_points[i % len(shape_points)]
p.target = target
def disperse(self):
# Remove targets to let particles drift freely
for p in self.particles:
p.target = None
def update(self, dt, motion_type=None):
# Update particles with different motion patterns
for i, p in enumerate(self.particles):
if motion_type == "fly":
# Bird flying: particles move in a gentle wave pattern
p.pos.x += math.sin(p.pos.y * 0.05 + pygame.time.get_ticks() * 0.005) * 0.5
p.pos.y -= 0.3
if p.pos.y < -10:
p.pos.y = HEIGHT + 10
p.pos.x = random.uniform(WIDTH * 0.3, WIDTH * 0.7)
elif motion_type == "grow":
# Tree growing: particles slowly move upward and settle
if p.target:
p.pos += (p.target - p.pos) * 0.02
else:
p.pos.y -= 0.1
elif motion_type == "pulse":
# Heart pulsing: particles oscillate radius and glow
pulse = 0.5 + 0.5 * math.sin(pygame.time.get_ticks() * 0.01 + i)
p.radius = 2 + pulse * 2
p.glow_intensity = pulse
elif motion_type == "dance":
# Dance: particles move in circular orbits around their target or random points
if p.target:
angle = pygame.time.get_ticks() * 0.002 + i
radius = 10 + 5 * math.sin(pygame.time.get_ticks() * 0.005 + i)
offset = pygame.Vector2(math.cos(angle), math.sin(angle)) * radius
p.pos = p.target + offset
else:
p.pos += pygame.Vector2(math.sin(i), math.cos(i)) * 0.1
elif motion_type == "morph":
# Morph: particles smoothly approach targets
if p.target:
p.pos += (p.target - p.pos) * 0.1
elif motion_type == "drift":
# Drift: slow random movement
p.pos += pygame.Vector2(random.uniform(-0.3, 0.3), random.uniform(-0.1, 0.1))
else:
# Default update
p.update(dt)
# Clamp positions inside screen
p.pos.x = max(0, min(WIDTH, p.pos.x))
p.pos.y = max(0, min(HEIGHT, p.pos.y))
def draw(self, surface):
for p in self.particles:
p.draw(surface)
# Text display manager
class TextDisplay:
def __init__(self, font, width, x_center, y_top):
self.font = font
self.width = width
self.x_center = x_center
self.y_top = y_top
self.current_text = ""
self.displayed_text = ""
self.char_index = 0
self.start_time = 0
self.typing = False
self.fade_alpha = 255
self.fading_out = False
def start(self, text):
self.current_text = text
self.displayed_text = ""
self.char_index = 0
self.start_time = pygame.time.get_ticks()
self.typing = True
self.fade_alpha = 255
self.fading_out = False
def update(self):
if self.typing:
elapsed = (pygame.time.get_ticks() - self.start_time) / 1000
chars_to_show = int(elapsed * TEXT_TYPE_SPEED)
if chars_to_show > len(self.current_text):
chars_to_show = len(self.current_text)
self.typing = False
self.fading_out = True
self.fade_start = pygame.time.get_ticks()
self.displayed_text = self.current_text[:chars_to_show]
elif self.fading_out:
fade_elapsed = (pygame.time.get_ticks() - self.fade_start) / 1000
self.fade_alpha = max(0, 255 - int(255 * (fade_elapsed / TEXT_FADE_TIME)))
if self.fade_alpha == 0:
self.fading_out = False
def is_done(self):
return not self.typing and not self.fading_out
def draw(self, surface):
if not self.displayed_text:
return
# Render glowing text centered at top
glow_surf = render_glowing_text(self.displayed_text, self.font, (255, 255, 255), GLOW_BASE, glow_radius=10)
glow_surf.set_alpha(self.fade_alpha)
rect = glow_surf.get_rect(center=(self.x_center, self.y_top))
surface.blit(glow_surf, rect)
# Main loop and orchestration
def main():
running = True
current_scene = 0
particle_system = None
text_display = TextDisplay(font, WIDTH, TEXT_X, TEXT_Y)
scene_start_time = 0
scene_duration = 12 # seconds per scene approx
# Initialize first scene
def init_scene(index):
nonlocal particle_system, text_display, scene_start_time
scene = story[index]
particle_system = ParticleSystem(scene["count"], scene["color"], scene["glow"])
if scene["shape"]:
shape_points = scene["shape"](WIDTH // 2, HEIGHT // 2 + 50, scale=1.5)
particle_system.morph_to_shape(shape_points)
else:
particle_system.disperse()
text_display.start(scene["text"])
scene_start_time = pygame.time.get_ticks()
init_scene(current_scene)
while running:
dt = clock.tick(FPS) / 1000.0 # Delta time in seconds
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update text
text_display.update()
# Update particles with motion type
motion = story[current_scene]["motion"]
particle_system.update(dt, motion_type=motion)
# Clear screen
screen.fill(BLACK)
# Draw particles
particle_system.draw(screen)
# Draw text
text_display.draw(screen)
pygame.display.flip()
# Scene transition logic
elapsed_scene = (pygame.time.get_ticks() - scene_start_time) / 1000
if elapsed_scene > scene_duration and text_display.is_done():
current_scene += 1
if current_scene >= len(story):
# End gracefully
running = False
else:
init_scene(current_scene)
# Fade out before exit
fade_out(screen, clock)
pygame.quit()
sys.exit()
def fade_out(surface, clock, duration=3):
fade_surface = pygame.Surface((WIDTH, HEIGHT))
fade_surface.fill(BLACK)
for alpha in range(0, 255, 5):
fade_surface.set_alpha(alpha)
surface.blit(fade_surface, (0, 0))
pygame.display.flip()
clock.tick(60)
if __name__ == "__main__":
main()