科赫雪花多个不一样python代码
时间: 2023-11-13 13:27:32 浏览: 104
以下是三个不同的 Python 代码实现科赫雪花:
1. 使用 Turtle 库绘制科赫雪花:
```python
import turtle
def koch(length, depth):
if depth == 0:
turtle.forward(length)
else:
for angle in [60, -120, 60, 0]:
koch(length / 3, depth - 1)
turtle.left(angle)
def snowflake(length, depth):
for _ in range(3):
koch(length, depth)
turtle.right(120)
turtle.speed(0)
snowflake(300, 4)
turtle.done()
```
2. 使用 Pygame 库绘制科赫雪花:
```python
import pygame, math
def koch_snowflake(surface, color, length, depth, x, y):
if depth == 0:
end_x = x + length * math.cos(math.radians(0))
end_y = y + length * math.sin(math.radians(0))
pygame.draw.line(surface, color, (x, y), (end_x, end_y), 3)
else:
angle = 60
new_length = length / 3
koch_snowflake(surface, color, new_length, depth - 1, x, y)
x, y = x + new_length * math.cos(math.radians(0)), y + new_length * math.sin(math.radians(0))
koch_snowflake(surface, color, new_length, depth - 1, x, y)
x, y = x + new_length * math.cos(math.radians(-angle)), y + new_length * math.sin(math.radians(-angle))
koch_snowflake(surface, color, new_length, depth - 1, x, y)
x, y = x + new_length * math.cos(math.radians(2 * angle)), y + new_length * math.sin(math.radians(2 * angle))
koch_snowflake(surface, color, new_length, depth - 1, x, y)
x, y = x + new_length * math.cos(math.radians(-angle)), y + new_length * math.sin(math.radians(-angle))
koch_snowflake(surface, color, new_length, depth - 1, x, y)
pygame.init()
screen = pygame.display.set_mode((600, 600))
screen.fill((255, 255, 255))
koch_snowflake(screen, (0, 0, 0), 400, 5, 100, 100)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
```
3. 使用 matplotlib 库绘制科赫雪花:
```python
import matplotlib.pyplot as plt
def koch_snowflake(points, depth):
if depth == 0:
return points
else:
new_points = []
for i in range(len(points) - 1):
x1, y1 = points[i]
x2, y2 = points[i + 1]
length = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
new_length = length / 3
angle = math.atan2(y2 - y1, x2 - x1)
x3, y3 = x1 + new_length * math.cos(angle), y1 + new_length * math.sin(angle)
x4, y4 = x3 + new_length * math.cos(angle - math.pi / 3), y3 + new_length * math.sin(angle - math.pi / 3)
x5, y5 = x4 + new_length * math.cos(angle + math.pi / 3), y4 + new_length * math.sin(angle + math.pi / 3)
new_points.extend([(x1, y1), (x3, y3), (x4, y4), (x5, y5)])
new_points.append(points[-1])
return koch_snowflake(new_points, depth - 1)
points = [(0, 0), (1, 0)]
for i in range(5):
points = koch_snowflake(points, 1)
x, y = zip(*points)
plt.plot(x, y)
plt.show()
```
阅读全文