2

I'm working on writing a recursive function to draw nested squares around a central point using turtle. What I have so far draws nested squares but around a corner point not the center of the square.

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()

Any suggestions or corrections?

4

2 回答 2

3

You have to calculate the top left corner (starting point) each time from the center point and the size of the square (and I am not sure what direction is +x, -x, +y, and -y in Turtle but you should get the point).

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)
于 2013-07-18T20:08:43.127 回答
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()
于 2013-07-24T09:00:32.967 回答