2013-07-18 70 views
1

我需要使用turtle模塊繪製一個給定中心點的正方形。Python Turtle draw centered square

def drawCentSq(t,center,side): 
    xPt=center[0] 
    yPt=center[1] 
    xPt-=int(side/side) 
    yPt+=int(side/side) 
    t.up() 
    t.goto(xPt,yPt) 
    t.down() 
    for i in range(4): 
     t.forward(side) 
     t.right(90) 

高清的main():

import turtle   
mad=turtle.Turtle() 
wn=mad.getscreen() 
print(drawCentSq(mad,(0,0),50)) 
main() 

我有一個很難讓我的烏龜去正確的出發點。

回答

1

您需要:

xPt-=int(side/2.0) 
yPt+=int(side/2.0) 

由於這是你只是+ =和 - = 1

0

我需要繪製給出了使用龜模塊中心點的正方形。

由於@seth筆記,你可以在你的代碼固定的中心計算做到這一點:

from turtle import Turtle, Screen 

def drawCentSq(turtle, center, side): 

    """ A square is a series of perpendicular sides """ 

    xPt, yPt = center 

    xPt -= side/2 
    yPt += side/2 

    turtle.up() 
    turtle.goto(xPt, yPt) 
    turtle.down() 

    for _ in range(4): 
     turtle.forward(side) 
     turtle.right(90) 

yertle = Turtle() 

drawCentSq(yertle, (0, 0), 50) 

screen = Screen() 
screen.exitonclick() 

但是,讓我們退一步考慮,我們還能如何在一個給定的點繪製一個正方形給定的大小。這裏是一個完全不同的解決方案:

def drawCentSq(turtle, center, side): 

    """ A square is a circle drawn at a rough approximation """ 

    xPt, yPt = center 

    xPt -= side/2 
    yPt -= side/2 

    turtle.up() 
    turtle.goto(xPt, yPt) 
    turtle.right(45) 
    turtle.down() 

    turtle.circle(2**0.5 * side/2, steps=4) 

    turtle.left(45) # return cursor to original orientation 

和這裏的另一個:

STAMP_UNIT = 20 

def drawCentSq(turtle, center, side): 

    """ A square can be stamped directly from a square cursor """ 

    mock = turtle.clone() # clone turtle to avoid cleaning up changes 
    mock.hideturtle() 
    mock.shape("square") 
    mock.fillcolor("white") 
    mock.shapesize(side/STAMP_UNIT) 

    mock.up() 
    mock.goto(center) 

    return mock.stamp() 

請注意,此解決方案返回可以傳遞給yertleclearstamp()方法郵票ID從屏幕上去掉方如果/當你想。