import pygame
import math
import random
import time
import colorsys
from pygame import gfxdraw
# --- Utility functions ---
def lerp(a, b, t):
return a + (b - a) * t
def ease_in_out(t):
return t * t * (3 - 2 * t)
def hsv_to_rgb(h, s, v):
return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(h, s, v))
def distance(p1, p2):
return math.hypot(p1[0] - p2[0], p1[1] - p2[1])
# --- Perlin noise implementation for smooth particle motion ---
class PerlinNoise1D:
def __init__(self, seed=None):
self.gradients = {}
self.seed = seed or random.randint(0, 10000)
def gradient(self, x):
if x not in self.gradients:
random.seed(x + self.seed)
self.gradients[x] = random.uniform(-1, 1)
return self.gradients[x]
def lerp(self, a, b, t):
return a + t * (b - a)
def fade(self, t):
# 6t^5 - 15t^4 + 10t^3
return t * t * t * (t * (t * 6 - 15) + 10)
def noise(self, x):
x0 = int(math.floor(x))
x1 = x0 + 1
sx = x - x0
n0 = self.gradient(x0) * (x - x0)
n1 = self.gradient(x1) * (x - x1)
u = self.fade(sx)
return self.lerp(n0, n1, u)
# --- Particle class ---
class Particle:
def __init__(self, pos, color, size=2):
self.pos = pygame.Vector2(pos)
self.target = pygame.Vector2(pos)
self.color = color
self.size = size
self.glow = 0.0
self.velocity = pygame.Vector2(0, 0)
self.noise_offset = random.uniform(0, 1000)
def update(self, dt, noise, time_sec):
# Smoothly move towards target with noise-based perturbation
direction = self.target - self.pos
dist = direction.length()
if dist > 0.1:
direction.scale_to_length(min(dist, 100 * dt))
self.velocity += direction * 5 * dt
self.velocity *= 0.85 # friction
# Add Perlin noise for natural flow
noise_val_x = noise.noise(time_sec + self.noise_offset)
noise_val_y = noise.noise(time_sec + 1000 + self.noise_offset)
noise_vec = pygame.Vector2(noise_val_x - 0.5, noise_val_y - 0.5) * 20
self.velocity += noise_vec * dt
self.pos += self.velocity * dt
def draw(self, surface):
# Draw glowing particle with anti-aliasing
glow_radius = int(self.size * 3 * self.glow)
base_radius = self.size
x, y = int(self.pos.x), int(self.pos.y)
# Glow layers
for i in range(glow_radius, 0, -1):
alpha = int(20 * (1 - i / glow_radius))
if alpha > 0:
s = pygame.Surface((i * 2, i * 2), pygame.SRCALPHA)
pygame.draw.circle(s, (*self.color, alpha), (i, i), i)
surface.blit(s, (x - i, y - i))
# Core particle
pygame.gfxdraw.filled_circle(surface, x, y, base_radius, self.color)
pygame.gfxdraw.aacircle(surface, x, y, base_radius, self.color)
# --- Sand Art Figures ---
def generate_tree_points(center, scale, count):
# Generate points forming a stylized tree silhouette
points = []
cx, cy = center
for i in range(count):
# Trunk: bottom center rectangle
if i < count * 0.2:
x = cx + random.uniform(-scale * 0.05, scale * 0.05)
y = cy + scale * 0.4 + random.uniform(0, scale * 0.1)
else:
# Leaves: triangle shape above trunk
angle = random.uniform(-math.pi / 3, math.pi / 3)
radius = random.uniform(scale * 0.1, scale * 0.4)
x = cx + radius * math.sin(angle)
y = cy + scale * 0.4 - radius * math.cos(angle)
points.append((x, y))
return points
def generate_bird_points(center, scale, count):
# Generate points forming a flying bird silhouette (side view)
points = []
cx, cy = center
for i in range(count):
t = i / count
# Wing shape: two arcs
if t < 0.5:
x = cx - scale * (0.5 - t) * 2
y = cy - scale * math.sin(t * math.pi) * 0.5
else:
x = cx + scale * (t - 0.5) * 2
y = cy - scale * math.sin((1 - t) * math.pi) * 0.5
# Add some noise
x += random.uniform(-scale * 0.02, scale * 0.02)
y += random.uniform(-scale * 0.02, scale * 0.02)
points.append((x, y))
return points
def generate_human_points(center, scale, count):
# Generate points forming a human silhouette (standing figure)
points = []
cx, cy = center
for i in range(count):
t = i / count
# Body: ellipse
angle = random.uniform(0, 2 * math.pi)
r_x = scale * 0.15
r_y = scale * 0.4
x = cx + r_x * math.cos(angle) * random.uniform(0.7, 1.0)
y = cy + r_y * math.sin(angle) * random.uniform(0.7, 1.0)
# Head: circle on top
if random.random() < 0.15:
x = cx + random.uniform(-r_x * 0.3, r_x * 0.3)
y = cy - r_y * 0.6 + random.uniform(-r_y * 0.1, r_y * 0.1)
points.append((x, y))
return points
# --- Text rendering with glow ---
def render_glowing_text(text, font, glow_color, base_color, glow_radius=8):
# Render text with glow by layering blurred text surfaces
base_surf = font.render(text, True, base_color)
size = base_surf.get_size()
glow_surf = pygame.Surface((size[0] + glow_radius * 2, size[1] + glow_radius * 2), pygame.SRCALPHA)
# Draw glow layers
for i in range(glow_radius, 0, -1):
alpha = int(20 * (1 - i / glow_radius))
glow_layer = font.render(text, True, (*glow_color, alpha))
glow_layer = pygame.transform.smoothscale(glow_layer, (size[0] + i, size[1] + i))
glow_surf.blit(glow_layer, (glow_radius - i // 2, glow_radius - i // 2), special_flags=pygame.BLEND_ADD)
glow_surf.blit(base_surf, (glow_radius, glow_radius))
return glow_surf
# --- Main Story and Animation Controller ---
class SandArtStory:
def __init__(self, screen, width, height):
self.screen = screen
self.width = width
self.height = height
self.font = pygame.font.SysFont("serif", 48, bold=True)
self.small_font = pygame.font.SysFont("serif", 28, italic=True)
self.noise = PerlinNoise1D()
self.particles = []
self.max_particles = 1200
self.story = [
"In the beginning, the grains of time drifted silently across the void,",
"each a whisper of moments yet to be born,",
"forming the roots of a tree that would cradle the sky.",
"From the branches, a bird took flight,",
"its wings painting the air with the colors of dawn,",
"carrying the dreams of countless souls beyond the horizon.",
"Beneath the endless expanse, a figure stood still,",
"woven from the sands of memory and light,",
"a testament to the fragile beauty of existence.",
"And as the story unfolded, the particles danced,",
"transforming, glowing, becoming the very essence of life itself."
]
self.current_sentence = 0
self.text_alpha = 0
self.text_fade_in = True
self.text_fade_out = False
self.text_display_time = 0
self.text_duration = 8.0 # seconds per sentence
self.text_fade_duration = 2.0
self.start_time = time.time()
self.particle_targets = []
self.particle_colors = []
self.state = "fade_in" # fade_in, display, fade_out, transition
self.sentence_start_time = time.time()
self.glow_color = (255, 180, 100)
self.base_text_color = (255, 230, 200)
self.prepare_particles()
self.text_surface = None
self.text_pos = (self.width // 2, 60)
self.text_progress = 0.0 # for gradual reveal
self.text_full = self.story[self.current_sentence]
self.text_rendered = ""
self.text_char_index = 0
self.text_char_delay = 0.05 # seconds per char
self.last_char_time = time.time()
self.fade_out_started = False
def prepare_particles(self):
# Initialize particles randomly on screen
self.particles.clear()
for _ in range(self.max_particles):
x = random.uniform(0, self.width)
y = random.uniform(0, self.height)
color = (100, 100, 100)
p = Particle((x, y), color, size=2)
p.glow = 0.0
self.particles.append(p)
def set_targets_for_sentence(self, sentence_index):
# Define particle target shapes and colors per sentence
center = (self.width // 2, self.height // 2 + 50)
scale = min(self.width, self.height) * 0.3
count = self.max_particles
if sentence_index == 0:
# drifting grains of time - random slow drift, dim gray-blue
for p in self.particles:
p.target = pygame.Vector2(random.uniform(0, self.width), random.uniform(0, self.height))
p.color = (80, 90, 120)
p.glow = 0.1
elif sentence_index == 1:
# whispers of moments - particles swirl gently, soft cyan glow
angle_base = random.uniform(0, 2 * math.pi)
for i, p in enumerate(self.particles):
angle = angle_base + (i / count) * 2 * math.pi
radius = scale * 0.4 + math.sin(i * 0.1) * 20
x = center[0] + radius * math.cos(angle)
y = center[1] + radius * math.sin(angle)
p.target = pygame.Vector2(x, y)
p.color = (100, 200, 220)
p.glow = 0.3
elif sentence_index == 2:
# roots of a tree - particles form a tree silhouette, warm earth tones
points = generate_tree_points(center, scale, count)
for i, p in enumerate(self.particles):
p.target = pygame.Vector2(points[i])
# Color gradient from brown trunk to green leaves
if i < count * 0.2:
p.color = (120, 70, 30)
else:
p.color = (30, 120, 40)
p.glow = 0.4
elif sentence_index == 3:
# bird took flight - particles form bird shape, bright orange-yellow
points = generate_bird_points(center, scale, count)
for i, p in enumerate(self.particles):
p.target = pygame.Vector2(points[i])
p.color = (255, 180, 50)
p.glow = 0.6
elif sentence_index == 4:
# wings painting air - particles spread out in arcs, pastel colors
for i, p in enumerate(self.particles):
angle = (i / count) * math.pi * 2
radius = scale * 0.5 + math.sin(i * 0.3) * 30
x = center[0] + radius * math.cos(angle)
y = center[1] - scale * 0.2 + radius * math.sin(angle)
p.target = pygame.Vector2(x, y)
h = 0.1 + 0.1 * math.sin(i * 0.1)
p.color = hsv_to_rgb(h, 0.5, 1.0)
p.glow = 0.5
elif sentence_index == 5:
# carrying dreams - particles flow rightward with trailing glow, warm pinks
for i, p in enumerate(self.particles):
x = (i / count) * self.width * 1.2 - self.width * 0.1
y = center[1] + math.sin(i * 0.1) * scale * 0.2
p.target = pygame.Vector2(x, y)
p.color = (255, 100 + int(155 * (i / count)), 150)
p.glow = 0.7
elif sentence_index == 6:
# figure stood still - particles form human silhouette, soft white-blue
points = generate_human_points(center, scale, count)
for i, p in enumerate(self.particles):
p.target = pygame.Vector2(points[i])
p.color = (180, 210, 255)
p.glow = 0.5
elif sentence_index == 7:
# woven from sands - particles cluster tighter, golden hues
for i, p in enumerate(self.particles):
angle = (i / count) * 2 * math.pi
radius = scale * 0.3 * (1 - (i / count))
x = center[0] + radius * math.cos(angle)
y = center[1] + radius * math.sin(angle)
p.target = pygame.Vector2(x, y)
p.color = (255, 215, 100)
p.glow = 0.8
elif sentence_index == 8:
# testament to beauty - particles pulse gently, shifting blues and purples
for i, p in enumerate(self.particles):
angle = (i / count) * 2 * math.pi
radius = scale * 0.35
x = center[0] + radius * math.cos(angle)
y = center[1] + radius * math.sin(angle)
p.target = pygame.Vector2(x, y)
h = 0.6 + 0.1 * math.sin(time.time() + i)
p.color = hsv_to_rgb(h, 0.7, 0.9)
p.glow = 0.6
elif sentence_index == 9:
# particles danced - particles scatter and swirl, multicolor glow
for i, p in enumerate(self.particles):
angle = (i / count) * 4 * math.pi
radius = scale * 0.5 + 50 * math.sin(i * 0.3)
x = center[0] + radius * math.cos(angle)
y = center[1] + radius * math.sin(angle)
p.target = pygame.Vector2(x, y)
h = (i / count + time.time() * 0.2) % 1.0
p.color = hsv_to_rgb(h, 0.8, 1.0)
p.glow = 1.0
elif sentence_index == 10:
# transforming, glowing, essence of life - particles swirl into a glowing orb
orb_center = pygame.Vector2(center[0], center[1])
for i, p in enumerate(self.particles):
angle = (i / count) * 2 * math.pi * 5 + time.time()
radius = scale * 0.15 + 20 * math.sin(i * 0.5 + time.time())
x = orb_center.x + radius * math.cos(angle)
y = orb_center.y + radius * math.sin(angle)
p.target = pygame.Vector2(x, y)
h = (time.time() * 0.1 + i / count) % 1.0
p.color = hsv_to_rgb(h, 1.0, 1.0)
p.glow = 1.0
else:
# default: random scatter
for p in self.particles:
p.target = pygame.Vector2(random.uniform(0, self.width), random.uniform(0, self.height))
p.color = (100, 100, 100)
p.glow = 0.1
def update_text(self):
now = time.time()
# Gradual reveal of characters
if self.text_char_index < len(self.text_full):
if now - self.last_char_time > self.text_char_delay:
self.text_char_index += 1
self.text_rendered = self.text_full[:self.text_char_index]
self.last_char_time = now
else:
# Full text revealed, hold for display time
if not self.fade_out_started and now - self.sentence_start_time > self.text_duration:
self.fade_out_started = True
self.state = "fade_out"
self.fade_start_time = now
# Handle fade in/out alpha
if self.state == "fade_in":
elapsed = now - self.sentence_start_time
self.text_alpha = min(255, int(255 * (elapsed / self.text_fade_duration)))
if self.text_alpha >= 255:
self.state = "display"
elif self.state == "display":
self.text_alpha = 255
elif self.state == "fade_out":
elapsed = now - self.fade_start_time
self.text_alpha = max(0, int(255 * (1 - elapsed / self.text_fade_duration)))
if self.text_alpha <= 0:
self.state = "transition"
self.current_sentence += 1
if self.current_sentence >= len(self.story):
self.current_sentence = 0 # Loop story
self.text_full = self.story[self.current_sentence]
self.text_char_index = 0
self.text_rendered = ""
self.sentence_start_time = now
self.fade_out_started = False
self.state = "fade_in"
self.set_targets_for_sentence(self.current_sentence)
def update_particles(self, dt):
t = time.time()
for p in self.particles:
p.update(dt, self.noise, t)
def draw_text(self):
if self.text_rendered:
# Render glowing text surface
glow_surf = render_glowing_text(self.text_rendered, self.font, self.glow_color, self.base_text_color, glow_radius=10)
glow_surf.set_alpha(self.text_alpha)
rect = glow_surf.get_rect(center=self.text_pos)
self.screen.blit(glow_surf, rect)
def draw_particles(self):
for p in self.particles:
p.draw(self.screen)
def run_frame(self, dt):
self.update_text()
self.update_particles(dt)
self.screen.fill((0, 0, 0))
self.draw_particles()
self.draw_text()
# --- Main program ---
def main():
pygame.init()
width, height = 1280, 720
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Sand Art Story - Particle Narrative")
clock = pygame.time.Clock()
story = SandArtStory(screen, width, height)
story.set_targets_for_sentence(0)
running = True
while running:
dt = clock.tick(60) / 1000.0 # seconds elapsed since last frame
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
story.run_frame(dt)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()