83 lines
2.7 KiB
Python
83 lines
2.7 KiB
Python
# Set the width and height of the window
|
|
width, height = 1100, 600
|
|
|
|
# Define the region of the complex plane to visualize
|
|
xmin, xmax = -2, 1
|
|
ymin, ymax = -1, 1
|
|
|
|
# Set the maximum number of iterations for the Mandelbrot calculation
|
|
max_iterations = 1000
|
|
|
|
import pygame
|
|
|
|
pygame.init()
|
|
|
|
# Create a window
|
|
screen = pygame.display.set_mode((width, height))
|
|
pygame.display.set_caption("Mandelbrot Set")
|
|
|
|
def mandelbrot(c):
|
|
z = 0
|
|
for i in range(max_iterations):
|
|
z = z**2 + c
|
|
if abs(z) > 2:
|
|
return i
|
|
return max_iterations
|
|
|
|
def update_display():
|
|
for x in range(width):
|
|
for y in range(height):
|
|
# Map pixel coordinates to complex plane coordinates
|
|
real = xmin + (x / width) * (xmax - xmin)
|
|
imag = ymin + (y / height) * (ymax - ymin)
|
|
|
|
# Create a complex number from the coordinates
|
|
c = complex(real, imag)
|
|
|
|
# Calculate Mandelbrot value for the complex number
|
|
iterations = mandelbrot(c)
|
|
|
|
# Set pixel color based on the number of iterations
|
|
color = (iterations % 256, iterations % 256, iterations % 256)
|
|
screen.set_at((x, y), color)
|
|
|
|
pygame.display.flip()
|
|
|
|
# Run the Pygame event loop
|
|
running = True
|
|
zoomed = False # Variable to track whether a zoom has occurred
|
|
|
|
while running:
|
|
for event in pygame.event.get():
|
|
if event.type == pygame.QUIT:
|
|
running = False
|
|
elif event.type == pygame.MOUSEBUTTONDOWN:
|
|
if event.button == 1: # Left mouse button
|
|
# Get the coordinates of the mouse click
|
|
click_x, click_y = event.pos
|
|
|
|
# Calculate the new region based on the clicked point
|
|
click_complex = complex(
|
|
xmin + (click_x / width) * (xmax - xmin),
|
|
ymin + (click_y / height) * (ymax - ymin)
|
|
)
|
|
|
|
# Define a zoom factor
|
|
zoom_factor = 0.5 # You can adjust this value for different zoom levels
|
|
|
|
# Update the region to zoom in on the clicked point
|
|
xmin = click_complex.real - (xmax - xmin) * zoom_factor / 2
|
|
xmax = click_complex.real + (xmax - xmin) * zoom_factor / 2
|
|
ymin = click_complex.imag - (ymax - ymin) * zoom_factor / 2
|
|
ymax = click_complex.imag + (ymax - ymin) * zoom_factor / 2
|
|
|
|
# Set the zoomed variable to True
|
|
zoomed = True
|
|
|
|
# Only update the display if a zoom has occurred
|
|
if zoomed:
|
|
update_display()
|
|
zoomed = False # Reset the variable
|
|
|
|
# Quit Pygame
|
|
pygame.quit()
|