【问题标题】:How to make the center point the center of my square?如何使中心点成为我方的中心?
【发布时间】:2021-05-27 00:22:49
【问题描述】:

如何使中心点成为我方格的中心?现在它变成了角落:

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

【问题讨论】:

    标签: python drawing turtle-graphics python-turtle


    【解决方案1】:

    解决方案是简单的几何,不涉及正弦或割线。只需计算一半的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()
    

    【讨论】:

      猜你喜欢
      • 2012-04-15
      • 2014-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      • 2015-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多