我需要使用海龟模块绘制一个给定中心点的方格。
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)
def main():
import turtle
mad=turtle.Turtle()
wn=mad.getscreen()
print(drawCentSq(mad,(0,0),50))
main()
我很难让我的乌龟走向正确的起点。
答案 0 :(得分:1)
你需要:
xPt-=int(side/2.0)
yPt+=int(side/2.0)
因为它只是+ =和 - = 1。
答案 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()
请注意,此解决方案会返回一个标记ID,您可以将其传递给yertle
的{{1}}方法,以便在需要时从屏幕上删除方框。