如何使中心点成为我的正方形的中心?现在它变成了角落:
def draw_square(t, center_x, center_y, side_length):
"""
Function draw_square draws a square
Parameters:
t = reference to turtle
center_x = x coordinate of the center of square
center_y = y coordinate of the center of square
side_length = the length of each side
Returns:
Nothing
"""
t.up() #picks up tail of turtle
t.goto(center_x, center_y) #tells turtle to go to center of command
t.down() #puts tail down
for sides in range(4): #creates loop to repeat 4 times
t.left(90) #turns left 90 degrees
t.forward(side_length) #move forward the length given
def main(): #defines main function
import turtle #imports turtle module
t = turtle.Turtle() #attaches turtle to t
draw_square(t, 100, 100, 75) #uses the value to make square
main() #calls function
解决方案是简单的几何,不涉及正弦和正割。只需计算一半的side_length
,然后将其添加到X坐标,并从Y坐标中减去它:
from turtle import Screen, Turtle # import turtle module
def draw_square(t, center_x, center_y, side_length):
"""
Function draw_square draws a square
Parameters:
t = reference to turtle
center_x = x coordinate of the center of square
center_y = y coordinate of the center of square
side_length = the length of each side
Returns:
None
"""
offset = side_length/2
t.penup() # picks up pen of turtle
t.goto(center_x, center_y) # tell turtle to go to center of drawing
t.dot() # visualize center of square (for debugging)
t.goto(center_x + offset, center_y - offset) # adjust for drawing from corner
t.pendown() # put pen down
for _ in range(4): # create loop to repeat 4 times
t.left(90) # turn left 90 degrees
t.forward(side_length) # move forward the length given
def main(): # define main function
t = Turtle() # attach turtle to t
draw_square(t, 100, 100, 75) # use the values to make a square
screen = Screen()
main() # call function
screen.exitonclick()