[Rod Stephens Books]
Index Books Python Examples About Rod Contact
[Mastodon] [Bluesky]
[Build Your Own Ray Tracer With Python]

[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

Title: Draw a Koch snowflake fractal with Python

[A Koch curve fractal drawn with Python]

The example Draw a Koch curve fractal with Python shows how to draw a fractal Koch curve. You can put three of them together to build the Koch snowflake.
To make the snowflake, the three thick blue lines in the following picture are replaced with Koch curves of the desired depth.

[A depth 3 Koch snowflake fractal drawn with Python]

Drawing the snowflake is just a matter of figuring out how to use the previous example's draw_koch_curve to draw the snowflake's three sides.

The following draw_snowflake method draws Koch curves to connect the points in the endpoints list.

def draw_snowflake(endpoints, depth): '''Draw the complete snowflake.''' # Draw the snowflake. points = [endpoints[0]] for i in range(1, len(endpoints)): p1 = endpoints[i - 1] p2 = endpoints[i] length = math.dist(p1, p2) dx = p2[0] - p1[0] dy = p2[1] - p1[1] theta = math.atan2(dy, dx) p1 = draw_koch_curve(points, depth, p1, theta, length) return points

This method loops through the endpoints. For adjacent pairs of endpoints, it calculates the distance and angle between the pair and calls draw_koch_curve to draw a Koch curve between them.

The following code shows how the main program calls draw_snowflake.

# Find the three corners. wid = self.canvas.winfo_width() hgt = self.canvas.winfo_height() height = 0.75 * min(wid, hgt) - 20 width = height / math.sqrt(3.0) * 2 y3 = hgt - 10 y1 = y3 - height x3 = hgt / 2 x1 = x3 - width / 2 x2 = x1 + width endpoints = [ (x1, y1), (x2, y1), (x3, y3), (x1, y1), ] # Get the points. points = draw_snowflake(endpoints, depth) # Draw the polygon. self.canvas.create_polygon(points, fill='light blue') self.canvas.create_line(points, width=1, fill='black')

This code finds three reasonable points to use as corners for the snowflake so it will fit nicely on the canvas. It then calls draw_snowflake, passing it those endpoints. After the call returns, the program fills the snowflake with light blue and then outlines it.

Download the example to see additional details.

© 2024 Rocky Mountain Computer Consulting, Inc. All rights reserved.