尝试用Turtle在python中制作同心方块。这是我的尝试:
import turtle
def draw_square(t, size):
for i in range(4):
t.forward(size)
t.left(90)
wn = turtle.Screen()
dan = turtle.Turtle()
sizevar = 1
for i in range(10):
draw_square(dan,sizevar)
sizevar += 20
dan.penup()
dan.backward(sizevar/ 2)
dan.right(90)
dan.forward(sizevar / 2)
dan.left(90)
dan.pendown()
我不确定为什么他们不是同心的,我的dan.backward(sizevar/2)
和
dan.forward(sizevar/2)
行似乎将广场向下移动到左侧太多了?
答案 0 :(得分:1)
应该是这样的:
import turtle
def draw_square(t, size):
for i in range(4):
t.forward(size)
t.left(90)
wn = turtle.Screen()
dan = turtle.Turtle()
sizevar = 1
for i in range(10):
draw_square(dan, sizevar)
sizevar += 20
dan.penup()
dan.backward(10)
dan.right(90)
dan.forward(10)
dan.left(90)
dan.pendown()
每个方格仅比前一个方格宽10个像素。
答案 1 :(得分:1)
同心方块要求使用递归算法(而不是迭代):
import turtle
def draw_square(t, size):
for i in range(4):
t.forward(size)
t.left(90)
def recursive_draw(t, x, y, size):
if (size < 200):
t.penup()
t.goto(x, y)
t.pendown()
draw_square(t, size)
x -= 10
y = x
size += 20
recursive_draw(t, x, y, size)
wn = turtle.Screen()
dan = turtle.Turtle()
recursive_draw(dan, 0, 0, 1)
以这种方式解释代码似乎更容易:
基本情况:尺寸不得超过200 接近策略:将规模增加20倍