.利用 random与turtle库绘制若干朵雪花
时间: 2024-10-26 20:16:07 浏览: 67
使用Python的random和turtle库可以创建有趣的艺术效果,比如绘制雪花。以下是简要步骤:
首先,你需要导入所需的库:
```python
import turtle
import random
```
然后,定义绘制雪花的基本形状函数,如三角形:
```python
def draw_triangle(size):
for _ in range(3):
turtle.forward(size)
turtle.right(120)
```
接着,创建一个函数来生成随机大小的雪花:
```python
def draw_snowflake():
size = random.randint(5, 30) # 随机选择大小范围
turtle.color(random.choice(['white', 'lightblue'])) # 随机颜色
turtle.begin_fill()
draw_triangle(size)
turtle.end_fill()
# 创建一个循环,不断绘制雪花
for _ in range(10): # 可以设置更多的雪花数量
draw_snowflake()
turtle.penup() # 移动到下一个位置绘制
x = turtle.xcor()
y = turtle.ycor()
dx = random.uniform(-100, 100)
dy = random.uniform(-100, 100)
turtle.goto(x + dx, y + dy)
turtle.pendown()
```
最后,记得在程序结束前关闭turtle窗口:
```python
turtle.done()
```
阅读全文
相关推荐


















