我正在编写一个递归函数,使用turtle在中心点周围绘制嵌套方块。到目前为止我所绘制的是嵌套的正方形,但是在角点附近而不是正方形的中心。
def drawCentSq(t, center,side):
xPt=center[0]
yPt=center[1]
t.up()
t.goto(xPt,yPt)
xPt-=20
yPt+=20
t.up()
t.goto(xPt,yPt)
t.down()
for i in range(4):
t.forward(side)
t.right(90)
def drawNestSqCent(t, center, side):
if side<1:
return
else:
drawCentSq(t,center,side)
drawNestSqCent(t,center,side-10)
def main():
import turtle
import random
mad=turtle.Turtle()
wn=mad.getscreen()
print(drawNestSqCent(mad,(0,0),100))
main()
有任何建议或更正吗?
答案 0 :(得分:3)
你必须每次从中心点和正方形的大小计算左上角(起点)(我不知道Turtle中的+ x,-x,+ y和-y是什么方向但你应该明白这一点。
import turtle
import random
def drawCentSq(t, center,side):
## calculate top left corner
xPt=center[0]-side/2
yPt=center[1]+side/2
t.up()
t.goto(xPt, yPt)
t.down()
for i in range(4):
t.forward(side)
t.right(90)
def drawNestSqCent(t, center, side):
if side<1:
return
## else: not necessary as long as the return comes first
drawCentSq(t,center,side)
drawNestSqCent(t,center,side-10)
mad=turtle.Turtle()
wn=mad.getscreen()
drawNestSqCent(mad,[0,0],100)
答案 1 :(得分:0)
这是一个有效的脚本。
def drawSquare(cx,cy,turtle,side):
for i in range(4):
turtle.forward(side)
turtle.right(90)
turtle.forward(5)
turtle.right(90)
turtle.up()
turtle.forward(5)
turtle.down()
turtle.left(90)
def drawNestedSquare(cx,cy,turtle,side):
if side >= 1:
drawSquare(cx,cy,turtle,side)
drawNestedSquare(cx,cy,turtle,side-10)
def drawsTheSquares(cx,cy,turtle,side):
turtle.up()
turtle.goto(cx,cy)
turtle.forward(side/2)
turtle.right(90)
turtle.forward(side/2)
turtle.right(90)
turtle.down()
drawNestedSquare(cx,cy,turtle,side)
def main():
import turtle
artem = turtle.Turtle()
drawsTheSquares(150,10,artem,75)
main()