我需要繪製給出了使用龜模塊中心點的正方形。
由於@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()
請注意,此解決方案返回可以傳遞給yertle
的clearstamp()
方法郵票ID從屏幕上去掉方如果/當你想。