You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python基于turtle实现递归正方形分形图案开发求助

递归正方形分形实现代码

你的现有代码已经完成了单层的正方形嵌套逻辑,我们只需要补充递归终止条件、角度复位逻辑,以及多层递归调用即可,完整实现如下:

from turtle import Turtle, Screen
import math

t = Turtle()
s = Screen()
t.speed(0)
t.penup() # 避免移动到起始坐标时留下多余线条

def square(x, y, side):
    t.setpos(x,y)
    t.pendown()
    for i in range(4):
        t.forward(side)
        t.right(90)
    t.penup() # 画完后抬笔,避免多余线条

def tiltsquare(x, y, side):
    t.left(45)
    square(x, y, side)
    t.right(45) # 画完倾斜正方形后复位角度,避免后续计算偏移

def recursive_square_fractal(x, y, side, depth):
    # 递归终止条件:深度为0时不再继续绘制
    if depth <= 0:
        return
    # 绘制当前层的嵌套正方形
    square(x, y, side)
    half = side / 2
    # 计算内层倾斜正方形的边长
    inner_side = math.sqrt(half**2 + half**2)
    tiltsquare(x, y - half, inner_side)
    # 计算下一层四个角的起始坐标,边长缩小为原来的1/2,深度减1
    next_side = side / 2
    # 左上角
    recursive_square_fractal(x - half, y + half, next_side, depth - 1)
    # 右上角
    recursive_square_fractal(x + half, y + half, next_side, depth - 1)
    # 左下角
    recursive_square_fractal(x - half, y - half, next_side, depth - 1)
    # 右下角
    recursive_square_fractal(x + half, y - half, next_side, depth - 1)

# 调用示例:初始坐标(0,0),初始边长200,递归深度3
recursive_square_fractal(0, 0, 200, 3)

s.exitonclick()

参数调整说明

  • 你可以修改调用recursive_square_fractal时的最后一个参数调整递归深度,深度越大绘制的分形层级越多,建议不要超过5避免绘制时间过长
  • 调整第三个参数可以修改初始正方形的大小,适配屏幕展示范围

内容的提问来源于stack exchange,提问作者iamjr15

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 15:48:04