in pygame, make me a visualization of fractals that zoom in infinitely.
- User
in pygame, make me a visualization of fractals that zoom in infinitely.
- Assistant
in pygame, make me a visualization of fractals that zoom in infinitely.
Creating an infinite zoom visualization of a fractal, such as the Mandelbrot set, is a fascinating project. Below is a Python script using Pygame that continuously zooms into the Mandelbrot set. This script utilizes numpy for efficient numerical operations and pygame for rendering the visualization.
Key Features:
numpy arrays and vectorized operations for faster computations.Prerequisites:
Before running the script, ensure you have pygame and numpy installed. You can install them using pip:
pip install pygame numpy
Complete Script:
import pygame
import numpy as np
import sys
import time
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Infinite Mandelbrot Zoom")
# Parameters for Mandelbrot
MAX_ITER = 256
# Initial zoom parameters
zoom = 1.0
zoom_speed = 1.02 # Zoom factor per frame
center_x, center_y = -0.743643887037151, 0.13182590420533 # Interesting point in Mandelbrot set
# Function to compute Mandelbrot set
def mandelbrot_set(width, height, center_x, center_y, zoom, max_iter):
# Calculate the range of x and y values
aspect_ratio = width / height
scale = 1.5 / zoom
x_min = center_x - scale * aspect_ratio
x_max = center_x + scale * aspect_ratio
y_min = center_y - scale
y_max = center_y + scale
# Create a 2D array of complex numbers representing the complex plane
x = np.linspace(x_min, x_max, width).reshape((1, width))
y = np.linspace(y_min, y_max, height).reshape((height, 1))
C = x + 1j * y
# Initialize Z to zero
Z = np.zeros(C.shape, dtype=complex)
# Initialize the iteration count to zero
M = np.full(C.shape, True, dtype=bool)
N = np.zeros(C.shape, dtype=int)
for i in range(max_iter):
Z[M] = Z[M] * Z[M] + C[M]
escaped = np.abs(Z) > 2
N[escaped & M] = i
M[escaped] = False
if not M.any():
break
# Normalize the iteration counts for coloring
N = N / N.max()
return N
# Function to map iteration counts to colors
def create_color_map(iter_counts):
# Create a color gradient (you can customize this)
colors = np.zeros((WIDTH, HEIGHT, 3), dtype=np.uint8)
colors[..., 0] = (iter_counts * 255).astype(np.uint8) # Red channel
colors[..., 1] = (iter_counts * 255).astype(np.uint8) # Green channel
colors[..., 2] = 255 - (iter_counts * 255).astype(np.uint8) # Blue channel
return colors
def main():
global zoom, center_x, center_y
clock = pygame.time.Clock()
# Precompute the initial Mandelbrot set
print("Computing initial Mandelbrot set...")
iteration_counts = mandelbrot_set(WIDTH, HEIGHT, center_x, center_y, zoom, MAX_ITER)
color_map = create_color_map(iteration_counts)
fractal_surface = pygame.surfarray.make_surface(color_map.transpose((1, 0, 2)))
running = True
while running:
start_time = time.time()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update zoom
zoom *= zoom_speed
# Recompute Mandelbrot set with updated zoom
iteration_counts = mandelbrot_set(WIDTH, HEIGHT, center_x, center_y, zoom, MAX_ITER)
color_map = create_color_map(iteration_counts)
fractal_surface = pygame.surfarray.make_surface(color_map.transpose((1, 0, 2)))
# Draw the fractal
screen.blit(fractal_surface, (0, 0))
pygame.display.flip()
# Cap the frame rate
clock.tick(5) # Adjust to control zoom speed and performance
end_time = time.time()
# Optional: Print frame computation time
# print(f"Frame computed in {end_time - start_time:.2f} seconds")
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Explanation of the Script:
Initialization:
-0.743643887037151, 0.13182590420533) is known for its intriguing fractal structures.Mandelbrot Set Calculation (mandelbrot_set Function):
numpy to create a grid of complex numbers representing the points in the complex plane.Color Mapping (create_color_map Function):
numpy array that represents the color of each pixel based on the iteration counts.Main Loop (main Function):
zoom_speed factor.Customization Options:
Zoom Speed: Adjust the zoom_speed variable to control how fast the zoom progresses. A value slightly above 1.0 ensures a smooth zoom.
Center Coordinates: Changing center_x and center_y will shift the zoom focus to different parts of the Mandelbrot set.
Color Gradient: Modify the create_color_map function to implement different color schemes and gradients for more vibrant or varied visuals.
Frame Rate: Adjust clock.tick(5) to a higher or lower value to change how many frames per second are rendered. Keep in mind that higher frame rates require more computational power.
Performance Considerations:
Computational Load: Continuously recomputing the Mandelbrot set is computationally intensive. The current setup balances performance by limiting the resolution and frame rate.
Optimizations:
WIDTH and HEIGHT will speed up computations but reduce visual clarity.MAX_ITER can increase performance at the cost of less detailed fractal rendering.numba for just-in-time compilation or leveraging GPU acceleration with libraries such as PyOpenGL.Running the Script:
Save the script to a file, for example, infinite_mandelbrot_zoom.py, and run it using Python:
python infinite_mandelbrot_zoom.py
A window will open displaying the Mandelbrot set, and it will begin to zoom into the specified point infinitely. You can exit the visualization by closing the window.
Final Notes:
This script provides a foundational infinite zoom visualization. For deeper exploration, you can implement features like:
Dynamic Center Shifting: Allow the center point to change dynamically based on user input or an algorithmic path to explore different regions.
Higher Precision Arithmetic: For deeper zoom levels beyond floating-point precision, consider using libraries that support arbitrary-precision arithmetic, though this will significantly impact performance.
Interactive Controls: Add keyboard and mouse controls to manipulate the zoom, center point, and coloring in real-time.
Enjoy exploring the mesmerizing depths of the Mandelbrot set!
Not yet included in a published release.