The user wants me to create a program that visualizes fractals using recursive algorithms. I'll create a comprehensive fractal visualization tool with multiple famous fractals, all rendered using recursive drawing methods.
I'll include:
- Sierpinski Triangle - A classic recursive fractal
- Koch Snowflake - Created by recursively adding triangular bumps
- Fractal Tree - A natural-looking recursive tree
- Dragon Curve - A complex recursive pattern
- Cantor Set - A simple but elegant recursive pattern
- Hilbert Curve - A space-filling curve
I'll use Pygame for real-time rendering with interactive controls to:
- Switch between different fractals
- Adjust recursion depth
- Zoom in/out
- Change colors
- See real-time rendering of the recursive process
Let me create a comprehensive, well-structured program:
import pygame
import math
import sys
from dataclasses import dataclass
from typing import List, Tuple, Callable
from enum import Enum
import colorsys
# Initialize Pygame
pygame.init()
# Screen settings
WIDTH, HEIGHT = 1200, 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Fractal Visualization - Recursive Algorithms")
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (50, 50, 50)
class FractalType(Enum):
SIERPINSKI_TRIANGLE = 0
KOCH_SNOWFLAKE = 1
FRACTAL_TREE = 2
DRAGON_CURVE = 3
CANTOR_SET = 4
HILBERT_CURVE = 5
SIERPINSKI_CARPET = 6
PYTHAGORAS_TREE = 7
@dataclass
class FractalConfig:
name: str
max_depth: int
default_depth: int
FRACTAL_CONFIGS = {
FractalType.SIERPINSKI_TRIANGLE: FractalConfig("Sierpinski Triangle", 10, 6),
FractalType.KOCH_SNOWFLAKE: FractalConfig("Koch Snowflake", 7, 4),
FractalType.FRACTAL_TREE: FractalConfig("Fractal Tree", 15, 10),
FractalType.DRAGON_CURVE: FractalConfig("Dragon Curve", 18, 12),
FractalType.CANTOR_SET: FractalConfig("Cantor Set", 10, 6),
FractalType.HILBERT_CURVE: FractalConfig("Hilbert Curve", 8, 5),
FractalType.SIERPINSKI_CARPET: FractalConfig("Sierpinski Carpet", 6, 3),
FractalType.PYTHAGORAS_TREE: FractalConfig("Pythagoras Tree", 12, 8),
}
class FractalRenderer:
def __init__(self):
self.depth = 5
self.color_mode = 0 # 0: single color, 1: depth-based, 2: rainbow
self.base_hue = 0.6 # Blue
self.show_animation = True
self.render_delay = 0 # ms between draws
self.points_drawn = 0
def get_color(self, depth: int, max_depth: int) -> Tuple[int, int, int]:
"""Get color based on current color mode and depth"""
if self.color_mode == 0:
# Single color
hue = self.base_hue
saturation = 0.8
value = 0.9
elif self.color_mode == 1:
# Depth-based gradient
ratio = depth / max_depth
hue = self.base_hue + ratio * 0.3
saturation = 0.8
value = 0.5 + ratio * 0.5
else:
# Rainbow based on depth
hue = (depth / max_depth + self.base_hue) % 1.0
saturation = 0.9
value = 0.9
r, g, b = colorsys.hsv_to_rgb(hue % 1.0, saturation, value)
return (int(r * 255), int(g * 255), int(b * 255))
def draw_line(self, surface, start: Tuple[float, float], end: Tuple[float, float],
color: Tuple[int, int, int], width: int = 1):
pygame.draw.line(surface, color, start, end, width)
self.points_drawn += 1
def draw_triangle(self, surface, points: List[Tuple[float, float]],
color: Tuple[int, int, int]):
pygame.draw.polygon(surface, color, points)
self.points_drawn += 1
def draw_rect(self, surface, rect: pygame.Rect, color: Tuple[int, int, int]):
pygame.draw.rect(surface, color, rect)
self.points_drawn += 1
# Sierpinski Triangle
def sierpinski_triangle(self, surface, p1: Tuple[float, float],
p2: Tuple[float, float], p3: Tuple[float, float],
depth: int, max_depth: int):
if depth == 0:
color = self.get_color(max_depth - depth, max_depth)
self.draw_triangle(surface, [p1, p2, p3], color)
return
# Find midpoints
mid1 = ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)
mid2 = ((p2[0] + p3[0]) / 2, (p2[1] + p3[1]) / 2)
mid3 = ((p3[0] + p1[0]) / 2, (p3[1] + p1[1]) / 2)
# Recursively draw three corner triangles
self.sierpinski_triangle(surface, p1, mid1, mid3, depth - 1, max_depth)
self.sierpinski_triangle(surface, mid1, p2, mid2, depth - 1, max_depth)
self.sierpinski_triangle(surface, mid3, mid2, p3, depth - 1, max_depth)
# Koch Snowflake
def koch_snowflake(self, surface, start: Tuple[float, float],
end: Tuple[float, float], depth: int, max_depth: int):
if depth == 0:
color = self.get_color(0, max_depth)
self.draw_line(surface, start, end, color, 2)
return
# Calculate the four segments
dx = end[0] - start[0]
dy = end[1] - start[1]
p1 = (start[0] + dx / 3, start[1] + dy / 3)
p2 = (start[0] + 2 * dx / 3, start[1] + 2 * dy / 3)
# Peak point
angle = math.atan2(dy, dx) - math.pi / 3
length = math.sqrt(dx**2 + dy**2) / 3
peak = (p1[0] + length * math.cos(angle), p1[1] + length * math.sin(angle))
self.koch_snowflake(surface, start, p1, depth - 1, max_depth)
self.koch_snowflake(surface, p1, peak, depth - 1, max_depth)
self.koch_snowflake(surface, peak, p2, depth - 1, max_depth)
self.koch_snowflake(surface, p2, end, depth - 1, max_depth)
def draw_koch_snowflake(self, surface, center: Tuple[float, float],
size: float, depth: int):
# Create equilateral triangle
angle_offset = -math.pi / 2
points = []
for i in range(3):
angle = angle_offset + i * 2 * math.pi / 3
x = center[0] + size * math.cos(angle)
y = center[1] + size * math.sin(angle)
points.append((x, y))
self.koch_snowflake(surface, points[0], points[1], depth, depth)
self.koch_snowflake(surface, points[1], points[2], depth, depth)
self.koch_snowflake(surface, points[2], points[0], depth, depth)
# Fractal Tree
def fractal_tree(self, surface, start: Tuple[float, float],
angle: float, length: float, depth: int, max_depth: int):
if depth == 0 or length < 2:
return
color = self.get_color(max_depth - depth, max_depth)
width = max(1, depth // 2)
end = (start[0] + length * math.cos(angle),
start[1] + length * math.sin(angle))
self.draw_line(surface, start, end, color, width)
# Branch out
branch_angle = 0.4 + 0.1 * (depth / max_depth)
length_factor = 0.67 + 0.1 * (depth / max_depth)
self.fractal_tree(surface, end, angle - branch_angle, length * length_factor,
depth - 1, max_depth)
self.fractal_tree(surface, end, angle + branch_angle, length * length_factor,
depth - 1, max_depth)
# Dragon Curve
def dragon_curve(self, surface, depth: int, size: float,
center: Tuple[float, float]):
def dragon_sequence(n: int) -> List[int]:
if n == 0:
return [1]
seq = dragon_sequence(n - 1)
new_seq = seq + [1]
for i, val in enumerate(reversed(seq)):
new_seq.append(1 if val == -1 else -1)
return new_seq
sequence = dragon_sequence(depth)
# Starting direction
direction = 0 # 0=right, 1=down, 2=left, 3=up
x, y = center[0] - size * len(sequence) / 4, center[1]
step = size / (2 ** (depth / 2))
points = [(x, y)]
for turn in sequence:
direction = (direction + turn) % 4
if direction == 0:
x += step
elif direction == 1:
y += step
elif direction == 2:
x -= step
else:
y -= step
points.append((x, y))
# Draw the curve
for i in range(len(points) - 1):
color = self.get_color(i % (depth + 1), depth)
self.draw_line(surface, points[i], points[i + 1], color, 2)
# Cantor Set
def cantor_set(self, surface, x: float, y: float, length: float,
depth: int, max_depth: int):
if depth == 0 or length < 2:
return
color = self.get_color(max_depth - depth, max_depth)
height = 20
rect = pygame.Rect(int(x), int(y), int(length), height)
self.draw_rect(surface, rect, color)
# Recursively draw two smaller bars
gap = 30
new_length = length / 3
self.cantor_set(surface, x, y + height + gap, new_length, depth - 1, max_depth)
self.cantor_set(surface, x + 2 * new_length, y + height + gap, new_length,
depth - 1, max_depth)
# Hilbert Curve
def hilbert_curve(self, surface, depth: int, size: float,
center: Tuple[float, float]):
def hilbert_points(n: int, x: float, y: float, xi: float, xj: float,
yi: float, yj: float) -> List[Tuple[float, float]]:
if n <= 0:
return [(x + (xi + yi) / 2, y + (xj + yj) / 2)]
points = []
points.extend(hilbert_points(n - 1, x, y, yi / 2, yj / 2, xi / 2, xj / 2))
points.extend(hilbert_points(n - 1, x + xi / 2, y + xj / 2, xi / 2, xj / 2,
yi / 2, yj / 2))
points.extend(hilbert_points(n - 1, x + xi / 2 + yi / 2, y + xj / 2 + yj / 2,
xi / 2, xj / 2, yi / 2, yj / 2))
points.extend(hilbert_points(n - 1, x + xi / 2 + yi, y + xj / 2 + yj,
-yi / 2, -yj / 2, -xi / 2, -xj / 2))
return points
points = hilbert_points(depth, center[0] - size / 2, center[1] - size / 2,
size, 0, 0, size)
# Draw the curve
for i in range(len(points) - 1):
color = self.get_color(i % (depth + 1), depth + 1)
self.draw_line(surface, points[i], points[i + 1], color, 2)
# Sierpinski Carpet
def sierpinski_carpet(self, surface, x: float, y: float,
size: float, depth: int, max_depth: int):
if depth == 0:
color = self.get_color(0, max_depth)
rect = pygame.Rect(int(x), int(y), int(size) + 1, int(size) + 1)
self.draw_rect(surface, rect, color)
return
new_size = size / 3
for i in range(3):
for j in range(3):
if i == 1 and j == 1:
# Leave center empty
continue
self.sierpinski_carpet(surface, x + i * new_size, y + j * new_size,
new_size, depth - 1, max_depth)
# Pythagoras Tree
def pythagoras_tree(self, surface, p1: Tuple[float, float],
p2: Tuple[float, float], depth: int, max_depth: int):
if depth == 0:
return
color = self.get_color(max_depth - depth, max_depth)
# Calculate the square points
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
p3 = (p2[0] - dy, p2[1] + dx)
p4 = (p1[0] - dy, p1[1] + dx)
# Draw square
pygame.draw.polygon(surface, color, [p1, p2, p3, p4])
# Calculate the triangle peak
p5 = ((p3[0] + p4[0]) / 2 - dy / 2, (p3[1] + p4[1]) / 2 + dx / 2)
# Recursively draw two smaller trees
self.pythagoras_tree(surface, p4, p5, depth - 1, max_depth)
self.pythagoras_tree(surface, p5, p3, depth - 1, max_depth)
class FractalApp:
def __init__(self):
self.renderer = FractalRenderer()
self.current_fractal = FractalType.SIERPINSKI_TRIANGLE
self.running = True
self.clock = pygame.time.Clock()
self.font = pygame.font.Font(None, 28)
self.small_font = pygame.font.Font(None, 22)
self.needs_redraw = True
self.zoom = 1.0
self.offset_x = 0
self.offset_y = 0
self.dragging = False
self.last_mouse_pos = (0, 0)
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
config = FRACTAL_CONFIGS[self.current_fractal]
if event.key == pygame.K_LEFT:
self.current_fractal = FractalType((self.current_fractal.value - 1) % len(FractalType))
self.needs_redraw = True
self.reset_view()
elif event.key == pygame.K_RIGHT:
self.current_fractal = FractalType((self.current_fractal.value + 1) % len(FractalType))
self.needs_redraw = True
self.reset_view()
elif event.key == pygame.K_UP:
if self.renderer.depth < config.max_depth:
self.renderer.depth += 1
self.needs_redraw = True
elif event.key == pygame.K_DOWN:
if self.renderer.depth > 1:
self.renderer.depth -= 1
self.needs_redraw = True
elif event.key == pygame.K_c:
self.renderer.color_mode = (self.renderer.color_mode + 1) % 3
self.needs_redraw = True
elif event.key == pygame.K_r:
self.reset_view()
self.needs_redraw = True
elif event.key == pygame.K_ESCAPE:
self.running = False
elif event.type == pygame.MOUSEWHEEL:
# Zoom in/out
old_zoom = self.zoom
self.zoom *= 1.1 if event.y > 0 else 0.9
self.zoom = max(0.1, min(10, self.zoom))
self.needs_redraw = True
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
self.dragging = True
self.last_mouse_pos = event.pos
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
self.dragging = False
elif event.type == pygame.MOUSEMOTION:
if self.dragging:
dx = event.pos[0] - self.last_mouse_pos[0]
dy = event.pos[1] - self.last_mouse_pos[1]
self.offset_x += dx
self.offset_y += dy
self.last_mouse_pos = event.pos
self.needs_redraw = True
def reset_view(self):
self.zoom = 1.0
self.offset_x = 0
self.offset_y = 0
config = FRACTAL_CONFIGS[self.current_fractal]
self.renderer.depth = config.default_depth
def draw_fractal(self, surface):
self.renderer.points_drawn = 0
center_x = WIDTH / 2 + self.offset_x
center_y = HEIGHT / 2 + self.offset_y
if self.current_fractal == FractalType.SIERPINSKI_TRIANGLE:
size = 400 * self.zoom
height = size * math.sqrt(3) / 2
p1 = (center_x, center_y - height * 2/3)
p2 = (center_x - size/2, center_y + height/3)
p3 = (center_x + size/2, center_y + height/3)
self.renderer.sierpinski_triangle(surface, p1, p2, p3,
self.renderer.depth, self.renderer.depth)
elif self.current_fractal == FractalType.KOCH_SNOWFLAKE:
self.renderer.draw_koch_snowflake(surface, (center_x, center_y),
300 * self.zoom, self.renderer.depth)
elif self.current_fractal == FractalType.FRACTAL_TREE:
start = (center_x, center_y + 250)
self.renderer.fractal_tree(surface, start, -math.pi/2, 120 * self.zoom,
self.renderer.depth, self.renderer.depth)
elif self.current_fractal == FractalType.DRAGON_CURVE:
self.renderer.dragon_curve(surface, self.renderer.depth,
200 * self.zoom, (center_x, center_y))
elif self.current_fractal == FractalType.CANTOR_SET:
start_x = center_x - 400 * self.zoom
start_y = center_y - 200
self.renderer.cantor_set(surface, start_x, start_y,
800 * self.zoom, self.renderer.depth,
self.renderer.depth)
elif self.current_fractal == FractalType.HILBERT_CURVE:
self.renderer.hilbert_curve(surface, self.renderer.depth,
500 * self.zoom, (center_x, center_y))
elif self.current_fractal == FractalType.SIERPINSKI_CARPET:
size = 400 * self.zoom
self.renderer.sierpinski_carpet(surface, center_x - size/2, center_y - size/2,
size, self.renderer.depth, self.renderer.depth)
elif self.current_fractal == FractalType.PYTHAGORAS_TREE:
p1 = (center_x - 50 * self.zoom, center_y + 150)
p2 = (center_x + 50 * self.zoom, center_y + 150)
self.renderer.pythagoras_tree(surface, p1, p2,
self.renderer.depth, self.renderer.depth)
def draw_ui(self, surface):
# Semi-transparent panel
panel = pygame.Surface((300, 250), pygame.SRCALPHA)
panel.fill((30, 30, 30, 200))
surface.blit(panel, (10, 10))
config = FRACTAL_CONFIGS[self.current_fractal]
# Title
title = self.font.render(config.name, True, WHITE)
surface.blit(title, (20, 20))
# Info
info_lines = [
f"Depth: {self.renderer.depth} / {config.max_depth}",
f"Zoom: {self.zoom:.2f}x",
f"Elements: {self.renderer.points_drawn:,}",
"",
"Controls:",
"←/→: Change fractal",
"↑/↓: Change depth",
"C: Change colors",
"R: Reset view",
"Scroll: Zoom",
"Drag: Pan",
"ESC: Exit"
]
y = 50
for line in info_lines:
text = self.small_font.render(line, True, (200, 200, 200))
surface.blit(text, (20, y))
y += 20
# Color mode indicator
color_modes = ["Single Color", "Depth Gradient", "Rainbow"]
mode_text = self.small_font.render(f"Color: {color_modes[self.renderer.color_mode]}",
True, (150, 200, 255))
surface.blit(mode_text, (20, y + 10))
# Fractal counter
counter = self.font.render(f"{self.current_fractal.value + 1}/{len(FractalType)}",
True, (150, 150, 150))
surface.blit(counter, (WIDTH - 60, 20))
def run(self):
while self.running:
self.handle_events()
if self.needs_redraw:
screen.fill(BLACK)
self.draw_fractal(screen)
self.draw_ui(screen)
pygame.display.flip()
self.needs_redraw = False
self.clock.tick(60)
pygame.quit()
sys.exit()
def main():
app = FractalApp()
app.run()
if __name__ == "__main__":
main()
This is a comprehensive fractal visualization program. Let me make sure it's complete and well-structured.
Fractal Visualization with Recursive Algorithms
Here's a comprehensive Python program that visualizes multiple classic fractals using recursive algorithms with an interactive interface.
Installation
pip install pygame
Complete Code
"""
Fractal Visualization using Recursive Algorithms
================================================
An interactive application showcasing various fractals generated through recursion.
Features:
- 8 different fractals (Sierpinski, Koch, Tree, Dragon, Cantor, Hilbert, Carpet, Pythagoras)
- Adjustable recursion depth
- Multiple color modes
- Pan and zoom controls
- Real-time rendering statistics
Controls:
- LEFT/RIGHT arrows: Switch between fractals
- UP/DOWN arrows: Increase/decrease recursion depth
- C: Cycle through color modes
- R: Reset view
- Mouse wheel: Zoom in/out
- Mouse drag: Pan the view
- ESC: Exit
"""
import pygame
import math
import sys
from dataclasses import dataclass
from typing import List, Tuple
from enum import Enum
import colorsys
# Initialize Pygame
pygame.init()
# Screen settings
WIDTH, HEIGHT = 1200, 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Fractal Visualization - Recursive Algorithms")
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
DARK_GRAY = (30, 30, 30)
class FractalType(Enum):
"""Enumeration of available fractal types"""
SIERPINSKI_TRIANGLE = 0
KOCH_SNOWFLAKE = 1
FRACTAL_TREE = 2
DRAGON_CURVE = 3
CANTOR_SET = 4
HILBERT_CURVE = 5
SIERPINSKI_CARPET = 6
PYTHAGORAS_TREE = 7
@dataclass
class FractalConfig:
"""Configuration for each fractal type"""
name: str
max_depth: int
default_depth: int
description: str
# Configuration for each fractal
FRACTAL_CONFIGS = {
FractalType.SIERPINSKI_TRIANGLE: FractalConfig(
"Sierpinski Triangle", 10, 6,
"A triangular fractal created by recursively removing the middle triangle"
),
FractalType.KOCH_SNOWFLAKE: FractalConfig(
"Koch Snowflake", 7, 4,
"A fractal curve formed by adding triangular bumps to each side"
),
FractalType.FRACTAL_TREE: FractalConfig(
"Fractal Tree", 15, 10,
"A natural-looking tree created by recursive branching"
),
FractalType.DRAGON_CURVE: FractalConfig(
"Dragon Curve", 18, 12,
"A self-similar fractal discovered by NASA physicists"
),
FractalType.CANTOR_SET: FractalConfig(
"Cantor Set", 8, 5,
"A classic fractal created by removing middle thirds"
),
FractalType.HILBERT_CURVE: FractalConfig(
"Hilbert Curve", 7, 5,
"A space-filling curve that visits every point in a square"
),
FractalType.SIERPINSKI_CARPET: FractalConfig(
"Sierpinski Carpet", 6, 3,
"A square version of the Sierpinski triangle"
),
FractalType.PYTHAGORAS_TREE: FractalConfig(
"Pythagoras Tree", 14, 9,
"A fractal composed of squares, resembling a tree"
),
}
class FractalRenderer:
"""
Handles the recursive rendering of various fractals.
Uses different color modes for visual variety.
"""
def __init__(self):
self.depth = 5
self.color_mode = 0 # 0: single color, 1: depth-based, 2: rainbow
self.base_hue = 0.55 # Cyan-blue base
self.elements_drawn = 0
def get_color(self, current_depth: int, max_depth: int,
index: int = 0) -> Tuple[int, int, int]:
"""
Calculate color based on the current color mode.
Args:
current_depth: Current recursion depth
max_depth: Maximum recursion depth
index: Optional index for variation
Returns:
RGB color tuple
"""
if self.color_mode == 0:
# Single color with slight depth variation
hue = self.base_hue
saturation = 0.8
value = 0.7 + 0.3 * (current_depth / max_depth) if max_depth > 0 else 0.9
elif self.color_mode == 1:
# Depth-based gradient
ratio = current_depth / max_depth if max_depth > 0 else 1
hue = (self.base_hue + ratio * 0.4) % 1.0
saturation = 0.9
value = 0.6 + ratio * 0.4
else:
# Rainbow mode - color cycles with depth and position
hue = (current_depth / (max_depth + 1) + index * 0.01 + self.base_hue) % 1.0
saturation = 0.85
value = 0.9
r, g, b = colorsys.hsv_to_rgb(hue, saturation, value)
return (int(r * 255), int(g * 255), int(b * 255))
# ============================================================
# SIERPINSKI TRIANGLE
# ============================================================
def sierpinski_triangle(self, surface: pygame.Surface,
p1: Tuple[float, float],
p2: Tuple[float, float],
p3: Tuple[float, float],
depth: int, max_depth: int) -> None:
"""
Recursively draw the Sierpinski Triangle.
Algorithm:
1. If at base case, draw the triangle
2. Otherwise, find midpoints of each side
3. Recursively draw three smaller triangles at the corners
"""
if depth == 0:
color = self.get_color(max_depth - depth, max_depth)
pygame.draw.polygon(surface, color, [p1, p2, p3])
self.elements_drawn += 1
return
# Find midpoints of each side
mid1 = ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)
mid2 = ((p2[0] + p3[0]) / 2, (p2[1] + p3[1]) / 2)
mid3 = ((p3[0] + p1[0]) / 2, (p3[1] + p1[1]) / 2)
# Recursively draw three corner triangles
self.sierpinski_triangle(surface, p1, mid1, mid3, depth - 1, max_depth)
self.sierpinski_triangle(surface, mid1, p2, mid2, depth - 1, max_depth)
self.sierpinski_triangle(surface, mid3, mid2, p3, depth - 1, max_depth)
# ============================================================
# KOCH SNOWFLAKE
# ============================================================
def koch_line(self, surface: pygame.Surface,
start: Tuple[float, float],
end: Tuple[float, float],
depth: int, max_depth: int) -> None:
"""
Recursively draw a single Koch line segment.
Algorithm:
1. Divide line into thirds
2. Create an equilateral triangle bump on the middle third
3. Recursively apply to each of the four new segments
"""
if depth == 0:
color = self.get_color(0, max_depth)
pygame.draw.line(surface, color, start, end, 2)
self.elements_drawn += 1
return
# Calculate segment divisions
dx = end[0] - start[0]
dy = end[1] - start[1]
# Points at 1/3 and 2/3
p1 = (start[0] + dx / 3, start[1] + dy / 3)
p2 = (start[0] + 2 * dx / 3, start[1] + 2 * dy / 3)
# Peak point of the triangle bump
angle = math.atan2(dy, dx) - math.pi / 3
length = math.sqrt(dx**2 + dy**2) / 3
peak = (p1[0] + length * math.cos(angle),
p1[1] + length * math.sin(angle))
# Recursively draw four segments
self.koch_line(surface, start, p1, depth - 1, max_depth)
self.koch_line(surface, p1, peak, depth - 1, max_depth)
self.koch_line(surface, peak, p2, depth - 1, max_depth)
self.koch_line(surface, p2, end, depth - 1, max_depth)
def koch_snowflake(self, surface: pygame.Surface,
center: Tuple[float, float],
size: float, depth: int) -> None:
"""Draw the complete Koch Snowflake from an equilateral triangle"""
# Create vertices of the initial equilateral triangle
angle_offset = -math.pi / 2 # Point up
points = []
for i in range(3):
angle = angle_offset + i * 2 * math.pi / 3
x = center[0] + size * math.cos(angle)
y = center[1] + size * math.sin(angle)
points.append((x, y))
# Draw Koch curve on each side
self.koch_line(surface, points[0], points[1], depth, depth)
self.koch_line(surface, points[1], points[2], depth, depth)
self.koch_line(surface, points[2], points[0], depth, depth)
# ============================================================
# FRACTAL TREE
# ============================================================
def fractal_tree(self, surface: pygame.Surface,
start: Tuple[float, float],
angle: float, length: float,
depth: int, max_depth: int,
branch_index: int = 0) -> None:
"""
Recursively draw a fractal tree.
Algorithm:
1. Draw trunk from start point
2. At end, branch into two at angles
3. Recursively draw each branch with reduced length
"""
if depth == 0 or length < 1:
return
# Calculate end point
end = (start[0] + length * math.cos(angle),
start[1] + length * math.sin(angle))
# Color and line width based on depth
color = self.get_color(max_depth - depth, max_depth, branch_index)
width = max(1, int(depth * 1.5))
pygame.draw.line(surface, color, start, end, width)
self.elements_drawn += 1
# Branch parameters - slight randomness for natural look
branch_angle = 0.4 + 0.05 * math.sin(branch_index)
length_factor = 0.67
# Left and right branches
self.fractal_tree(surface, end, angle - branch_angle,
length * length_factor, depth - 1, max_depth,
branch_index * 2)
self.fractal_tree(surface, end, angle + branch_angle,
length * length_factor, depth - 1, max_depth,
branch_index * 2 + 1)
# ============================================================
# DRAGON CURVE
# ============================================================
def dragon_curve(self, surface: pygame.Surface,
depth: int, size: float,
center: Tuple[float, float]) -> None:
"""
Draw the Dragon Curve using recursive sequence generation.
Algorithm:
1. Generate turn sequence: each iteration adds a right turn,
then the reverse of the previous sequence with inverted turns
2. Follow the turns to draw the curve
"""
def generate_sequence(n: int) -> List[int]:
"""Generate the turn sequence (1 = right, -1 = left)"""
if n == 0:
return []
seq = generate_sequence(n - 1)
# Add right turn, then reversed and inverted copy
return seq + [1] + [-x for x in reversed(seq)]
sequence = generate_sequence(depth)
# Calculate step size based on depth for consistent sizing
step = size / (2 ** (depth / 2))
# Starting position and direction
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] # Right, Down, Left, Up
direction = 0
# Calculate starting position to center the curve
x, y = 0, 0
points = [(x, y)]
for turn in sequence:
direction = (direction + turn) % 4
dx, dy = directions[direction]
x += dx * step
y += dy * step
points.append((x, y))
# Center the curve
if points:
min_x = min(p[0] for p in points)
max_x = max(p[0] for p in points)
min_y = min(p[1] for p in points)
max_y = max(p[1] for p in points)
offset_x = center[0] - (min_x + max_x) / 2
offset_y = center[1] - (min_y + max_y) / 2
points = [(p[0] + offset_x, p[1] + offset_y) for p in points]
# Draw the curve with color gradient
for i in range(len(points) - 1):
color = self.get_color(i % (depth + 1), depth + 1, i)
pygame.draw.line(surface, color, points[i], points[i + 1], 2)
self.elements_drawn += 1
# ============================================================
# CANTOR SET
# ============================================================
def cantor_set(self, surface: pygame.Surface,
x: float, y: float, length: float,
depth: int, max_depth: int) -> None:
"""
Draw the Cantor Set.
Algorithm:
1. Draw a horizontal line
2. Recursively draw two lines at 1/3 and 2/3 positions
3. The middle third is removed (not drawn)
"""
if depth == 0 or length < 1:
return
# Draw current segment
color = self.get_color(max_depth - depth, max_depth)
height = 15 + (max_depth - depth) * 2
rect = pygame.Rect(int(x), int(y), int(length), height)
pygame.draw.rect(surface, color, rect)
self.elements_drawn += 1
# Recursively draw left and right thirds
gap = 30
new_length = length / 3
self.cantor_set(surface, x, y + height + gap, new_length,
depth - 1, max_depth)
self.cantor_set(surface, x + 2 * new_length, y + height + gap,
new_length, depth - 1, max_depth)
# ============================================================
# HILBERT CURVE
# ============================================================
def hilbert_curve(self, surface: pygame.Surface,
depth: int, size: float,
center: Tuple[float, float]) -> None:
"""
Draw the Hilbert Curve - a space-filling fractal curve.
Algorithm:
Uses recursive Lindermayer system (L-system) style generation
where each level connects four smaller copies of the curve.
"""
def hilbert_points(n: int, x: float, y: float,
xi: float, xj: float, yi: float,
yj: float) -> List[Tuple[float, float]]:
"""Recursively generate Hilbert curve points"""
if n <= 0:
return [(x + (xi + yi) / 2, y + (xj + yj) / 2)]
points = []
# Four recursive calls with transformed coordinate systems
points.extend(hilbert_points(n - 1, x, y,
yi / 2, yj / 2, xi / 2, xj / 2))
points.extend(hilbert_points(n - 1, x + xi / 2, y + xj / 2,
xi / 2, xj / 2, yi / 2, yj / 2))
points.extend(hilbert_points(n - 1, x + xi / 2 + yi / 2,
y + xj / 2 + yj / 2,
xi / 2, xj / 2, yi / 2, yj / 2))
points.extend(hilbert_points(n - 1, x + xi / 2 + yi,
y + xj / 2 + yj,
-yi / 2, -yj / 2, -xi / 2, -xj / 2))
return points
points = hilbert_points(depth, center[0] - size / 2, center[1] - size / 2,
size, 0, 0, size)
# Draw the curve with color gradient
for i in range(len(points) - 1):
color = self.get_color(i % (depth + 2), depth + 2, i)
pygame.draw.line(surface, color, points[i], points[i + 1], 2)
self.elements_drawn += 1
# ============================================================
# SIERPINSKI CARPET
# ============================================================
def sierpinski_carpet(self, surface: pygame.Surface,
x: float, y: float, size: float,
depth: int, max_depth: int) -> None:
"""
Draw the Sierpinski Carpet.
Algorithm:
1. Divide square into 3x3 grid
2. Remove the center square
3. Recursively apply to remaining 8 squares
"""
if depth == 0:
color = self.get_color(0, max_depth)
rect = pygame.Rect(int(x), int(y), int(size) + 1, int(size) + 1)
pygame.draw.rect(surface, color, rect)
self.elements_drawn += 1
return
new_size = size / 3
for i in range(3):
for j in range(3):
# Skip center square
if i == 1 and j == 1:
continue
self.sierpinski_carpet(surface,
x + i * new_size,
y + j * new_size,
new_size, depth - 1, max_depth)
# ============================================================
# PYTHAGORAS TREE
# ============================================================
def pythagoras_tree(self, surface: pygame.Surface,
p1: Tuple[float, float],
p2: Tuple[float, float],
depth: int, max_depth: int,
angle_variation: float = 0) -> None:
"""
Draw the Pythagoras Tree fractal.
Algorithm:
1. Draw a square
2. On top, draw two smaller squares rotated 45°
3. Recursively continue building the tree
"""
if depth == 0:
return
color = self.get_color(max_depth - depth, max_depth)
# Calculate square vertices
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
# Other two corners of the square
p3 = (p2[0] - dy, p2[1] + dx)
p4 = (p1[0] - dy, p1[1] + dx)
# Draw the square
pygame.draw.polygon(surface, color, [p1, p2, p3, p4])
self.elements_drawn += 1
# Calculate the peak of the triangle on top
# (for the two smaller squares)
base_angle = math.atan2(dy, dx)
# Add slight variation for more natural look
left_angle = base_angle + math.pi / 4 + angle_variation * 0.1
right_angle = base_angle - math.pi / 4 - angle_variation * 0.1
side_length = math.sqrt(dx**2 + dy**2) / math.sqrt(2)
# Left branch peak
p5 = (p4[0] + side_length * math.cos(left_angle - math.pi/2),
p4[1] + side_length * math.sin(left_angle - math.pi/2))
# Right branch starts at p5, ends at p3
# Recursively draw branches
self.pythagoras_tree(surface, p4, p5, depth - 1, max_depth,
angle_variation + 0.1)
self.pythagoras_tree(surface, p5, p3, depth - 1, max_depth,
angle_variation - 0.1)
class FractalApplication:
"""
Main application class handling user interaction and rendering.
"""
def __init__(self):
self.renderer = FractalRenderer()
self.current_fractal = FractalType.SIERPINSKI_TRIANGLE
self.running = True
self.clock = pygame.time.Clock()
# Fonts
self.title_font = pygame.font.Font(None, 36)
self.info_font = pygame.font.Font(None, 24)
self.small_font = pygame.font.Font(None, 20)
# View controls
self.zoom = 1.0
self.offset_x = 0
self.offset_y = 0
self.dragging = False
self.last_mouse_pos = (0, 0)
# Render state
self.needs_redraw = True
self.fps = 60
# Set initial depth from config
self.reset_depth()
def reset_depth(self) -> None:
"""Reset depth to default for current fractal"""
config = FRACTAL_CONFIGS[self.current_fractal]
self.renderer.depth = config.default_depth
def reset_view(self) -> None:
"""Reset zoom and position"""
self.zoom = 1.0
self.offset_x = 0
self.offset_y = 0
self.reset_depth()
self.needs_redraw = True
def handle_events(self) -> None:
"""Process user input events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
self.handle_key_press(event.key)
elif event.type == pygame.MOUSEWHEEL:
self.handle_mouse_wheel(event.y)
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # Left click
self.dragging = True
self.last_mouse_pos = event.pos
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
self.dragging = False
elif event.type == pygame.MOUSEMOTION:
if self.dragging:
self.handle_mouse_drag(event.pos)
def handle_key_press(self, key) -> None:
"""Handle keyboard input"""
config = FRACTAL_CONFIGS[self.current_fractal]
if key == pygame.K_LEFT or key == pygame.K_a:
# Previous fractal
new_value = (self.current_fractal.value - 1) % len(FractalType)
self.current_fractal = FractalType(new_value)
self.reset_view()
elif key == pygame.K_RIGHT or key == pygame.K_d:
# Next fractal
new_value = (self.current_fractal.value + 1) % len(FractalType)
self.current_fractal = FractalType(new_value)
self.reset_view()
elif key == pygame.K_UP or key == pygame.K_w:
# Increase depth
if self.renderer.depth < config.max_depth:
self.renderer.depth += 1
self.needs_redraw = True
elif key == pygame.K_DOWN or key == pygame.K_s:
# Decrease depth
if self.renderer.depth > 1:
self.renderer.depth -= 1
self.needs_redraw = True
elif key == pygame.K_c:
# Cycle color mode
self.renderer.color_mode = (self.renderer.color_mode + 1) % 3
self.needs_redraw = True
elif key == pygame.K_r:
# Reset view
self.reset_view()
elif key == pygame.K_SPACE:
# Change base hue
self.renderer.base_hue = (self.renderer.base_hue + 0.15) % 1.0
self.needs_redraw = True
elif key == pygame.K_ESCAPE or key == pygame.K_q:
self.running = False
def handle_mouse_wheel(self, direction: int) -> None:
"""Handle mouse wheel zoom"""
zoom_factor = 1.15
if direction > 0:
self.zoom *= zoom_factor
else:
self.zoom /= zoom_factor
self.zoom = max(0.1, min(20.0, self.zoom))
self.needs_redraw = True
def handle_mouse_drag(self, pos: Tuple[int, int]) -> None:
"""Handle mouse drag for panning"""
dx = pos[0] - self.last_mouse_pos[0]
dy = pos[1] - self.last_mouse_pos[1]
self.offset_x += dx
self.offset_y += dy
self.last_mouse_pos = pos
self.needs_redraw = True
def draw_current_fractal(self, surface: pygame.Surface) -> None:
"""Render the currently selected fractal"""
self.renderer.elements_drawn = 0
# Calculate center with offsets
center_x = WIDTH / 2 + self.offset_x
center_y = HEIGHT / 2 + self.offset_y
fractal = self.current_fractal
depth = self.renderer.depth
if fractal == FractalType.SIERPINSKI_TRIANGLE:
size = 380 * self.zoom
height = size * math.sqrt(3) / 2
p1 = (center_x, center_y - height * 0.6)
p2 = (center_x - size / 2, center_y + height * 0.4)
p3 = (center_x + size / 2, center_y + height * 0.4)
self.renderer.sierpinski_triangle(surface, p1, p2, p3, depth, depth)
elif fractal == FractalType.KOCH_SNOWFLAKE:
self.renderer.koch_snowflake(surface, (center_x, center_y),
280 * self.zoom, depth)
elif fractal == FractalType.FRACTAL_TREE:
start = (center_x, center_y + 280 * self.zoom)
self.renderer.fractal_tree(surface, start, -math.pi / 2,
100 * self.zoom, depth, depth)
elif fractal == FractalType.DRAGON_CURVE:
self.renderer.dragon_curve(surface, depth, 180 * self.zoom,
(center_x, center_y))
elif fractal == FractalType.CANTOR_SET:
bar_width = 700 * self.zoom
self.renderer.cantor_set(surface, center_x - bar_width / 2,
center_y - 200, bar_width, depth, depth)
elif fractal == FractalType.HILBERT_CURVE:
self.renderer.hilbert_curve(surface, depth, 450 * self.zoom,
(center_x, center_y))
elif fractal == FractalType.SIERPINSKI_CARPET:
size = 400 * self.zoom
self.renderer.sierpinski_carpet(surface,
center_x - size / 2,
center_y - size / 2,
size, depth, depth)
elif fractal == FractalType.PYTHAGORAS_TREE:
half_width = 40 * self.zoom
p1 = (center_x - half_width, center_y + 200)
p2 = (center_x + half_width, center_y + 200)
self.renderer.pythagoras_tree(surface, p1, p2, depth, depth)
def draw_ui(self, surface: pygame.Surface) -> None:
"""Draw the user interface overlay"""
config = FRACTAL_CONFIGS[self.current_fractal]
# Semi-transparent background panel
panel_width = 320
panel_height = 320
panel = pygame.Surface((panel_width, panel_height), pygame.SRCALPHA)
panel.fill((20, 20, 30, 220))
pygame.draw.rect(panel, (80, 80, 100), (0, 0, panel_width, panel_height), 2)
surface.blit(panel, (15, 15))
# Title
title = self.title_font.render(config.name, True, WHITE)
surface.blit(title, (25, 25))
# Description (word wrap)
words = config.description.split()
lines = []
current_line = []
for word in words:
current_line.append(word)
test_text = " ".join(current_line)
if self.small_font.size(test_text)[0] > panel_width - 30:
current_line.pop()
lines.append(" ".join(current_line))
current_line = [word]
if current_line:
lines.append(" ".join(current_line))
y = 60
for line in lines:
desc_text = self.small_font.render(line, True, (180, 180, 200))
surface.blit(desc_text, (25, y))
y += 18
# Statistics
y += 15
stats = [
f"Recursion Depth: {self.renderer.depth} / {config.max_depth}",
f"Zoom Level: {self.zoom:.2f}x",
f"Elements Drawn: {self.renderer.elements_drawn:,}",
f"Color Mode: {['Single', 'Gradient', 'Rainbow'][self.renderer.color_mode]}"
]
for stat in stats:
text = self.info_font.render(stat, True, (150, 200, 255))
surface.blit(text, (25, y))
y += 25
# Controls
y += 10
pygame.draw.line(surface, (80, 80, 100), (25, y), (panel_width - 5, y), 1)
y += 15
controls = [
"←/→ or A/D: Change fractal",
"↑/↓ or W/S: Adjust depth",
"C: Cycle colors | SPACE: Change hue",
"R: Reset view | Scroll: Zoom",
"Drag: Pan | ESC/Q: Quit"
]
for control in controls:
text = self.small_font.render(control, True, (140, 140, 160))
surface.blit(text, (25, y))
y += 20
# Fractal counter (top right)
counter_text = f"{self.current_fractal.value + 1} / {len(FractalType)}"
counter = self.info_font.render(counter_text, True, (100, 100, 120))
surface.blit(counter, (WIDTH - 70, 25))
# FPS counter
fps_text = self.small_font.render(f"FPS: {int(self.clock.get_fps())}",
True, (80, 80, 100))
surface.blit(fps_text, (WIDTH - 80, HEIGHT - 30))
def run(self) -> None:
"""Main application loop"""
while self.running:
self.handle_events()
if self.needs_redraw:
# Clear screen
screen.fill(BLACK)
# Draw fractal
self.draw_current_fractal(screen)
# Draw UI overlay
self.draw_ui(screen)
# Update display
pygame.display.flip()
self.needs_redraw = False
self.clock.tick(self.fps)
pygame.quit()
sys.exit()
def main():
"""Entry point"""
print("=" * 60)
print("Fractal Visualization - Recursive Algorithms")
print("=" * 60)
print("\nStarting application...")
print("Use arrow keys to navigate, mouse to pan/zoom\n")
app = FractalApplication()
app.run()
if __name__ == "__main__":
main()
Features
8 Different Fractals:
| Fractal | Description | Max Depth |
|---|
| Sierpinski Triangle | Classic recursive triangle subdivision | 10 |
| Koch Snowflake | Infinitely complex snowflake curve | 7 |
| Fractal Tree | Natural branching tree structure | 15 |
| Dragon Curve | Self-similar space-filling curve | 18 |
| Cantor Set | Classic middle-third removal | 8 |
| Hilbert Curve | Space-filling square traversal | 7 |
| Sierpinski Carpet | 2D square version of Sierpinski | 6 |
| Pythagoras Tree | Squares forming a tree structure | 14 |
Controls:
- ←/→ or A/D: Switch between fractals
- ↑/↓ or W/S: Adjust recursion depth
- C: Cycle through 3 color modes (Single, Gradient, Rainbow)
- SPACE: Change base color hue
- R: Reset view to default
- Mouse Wheel: Zoom in/out
- Mouse Drag: Pan the view
- ESC/Q: Exit
Key Recursive Algorithms Explained:
Sierpinski Triangle:
┌─────────────────────────────────────┐
│ draw_triangle(points, depth): │
│ if depth == 0: │
│ fill triangle at points │
│ else: │
│ find midpoints of each side │
│ draw_triangle(corner1, d-1) │
│ draw_triangle(corner2, d-1) │
│ draw_triangle(corner3, d-1) │
└─────────────────────────────────────┘
Koch Snowflake:
┌─────────────────────────────────────┐
│ koch_line(start, end, depth): │
│ if depth == 0: │
│ draw line from start to end │
│ else: │
│ divide line into thirds │
│ create peak (equilateral bump) │
│ koch_line(4 new segments) │
└─────────────────────────────────────┘
Run the program and explore the beautiful world of mathematical fractals!