写出代码绘制矩形分形几何图形
时间: 2023-07-23 16:09:28 浏览: 112
当然可以!下面是一个使用Python绘制矩形分形几何图形的示例代码:
```python
import turtle
def draw_rectangle(x, y, width, height):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
for _ in range(2):
turtle.forward(width)
turtle.right(90)
turtle.forward(height)
turtle.right(90)
def draw_fractal(x, y, width, height, depth):
draw_rectangle(x, y, width, height)
if depth > 1:
new_width = width / 3
new_height = height / 3
draw_fractal(x - new_width, y + new_height, new_width, new_height, depth - 1)
draw_fractal(x + new_width * 2, y + new_height, new_width, new_height, depth - 1)
draw_fractal(x - new_width, y - new_height * 2, new_width, new_height, depth - 1)
draw_fractal(x + new_width * 2, y - new_height * 2, new_width, new_height, depth - 1)
# 初始化画布和画笔
turtle.setup(width=800, height=600)
turtle.speed(0)
turtle.hideturtle()
# 绘制矩形分形图形
draw_fractal(0, 0, 300, 200, 4)
# 等待用户关闭窗口
turtle.done()
```
这段代码使用了Python的turtle模块来绘制图形。`draw_rectangle`函数用于绘制一个矩形,`draw_fractal`函数则递归地绘制矩形分形图形。你可以根据需要调整矩形的位置、大小和深度。运行代码后,会弹出一个窗口显示绘制的矩形分形图形。