首页 > 解决方案 > 以python海龟为中心绘制多边形

问题描述

我想在屏幕的中心绘制一个多边形,并且我希望多边形的中心为 0、0。我该怎么做?(有很多输入和其他东西。我已将方向指向 45,这是一个意外(但八角形是我想象的测试)

import turtle

# THIS IS ALSO POSSIBLE WITH A FUNCTION AND ARGUMENTS, I WAS TOO BORED TO DO THAT

# initiate turtle, make a turtle
polygon_turtle = turtle.Turtle('turtle')

# inputs sides, length, edgecolor, fillcolor, show/hide artist, thickness of sides
sides = int(input('How many sides do you want on this regular polygon: '))
length = int(input('How long do you want each side to be: '))
edgecolor = input('What\'s the color for the sides of your polygon? ')
iffill = input('Do you want your polygon to be colored in? [Y/N]: ')
thickness = int(input('What do you want the width of the outline to be? '))
visibility = input('Do you want to see the artist that draws the polygon? [Y/N]: ')

# setup artist
polygon_turtle.pencolor(edgecolor)
polygon_turtle.pensize(thickness)
if iffill == 'Y':
    fillcolor = input('What do you want your fill color to be? ')
    polygon_turtle.fillcolor(fillcolor)
if visibility == 'N':
    polygon_turtle.hideturtle()

# center the polygon
polygon_turtle.penup()
polygon_turtle.goto(?????)
polygon_turtle.setheading(45)
polygon_turtle.pendown()

# draw polygon
polygon_turtle.begin_fill()
for i in range(sides):
    # use length as forward parameters, 360/sides as turn right parameters
    polygon_turtle.forward(length)
    polygon_turtle.right(360 / sides)
polygon_turtle.end_fill()

turtle.done()

请帮帮我。

标签: pythonpython-3.xpython-turtle

解决方案


添加到Arne的答案,您只需要使用

polygon_turtle.goto(x coordinate that you want, y coordinate that you want)

在这里,您说“我希望多边形的中心为 0”,所以使用这样的东西,因为原点位于屏幕的中心:

polygon_turtle.goto(0, 0)

休息是Arne 的回答的后续行动,有一点变化,乌龟向右移动而不是向左移动(否则它不会居中)。因此,使多边形居中的完整代码将是:

# center the polygon
polygon_turtle.goto(0,0)
R = length / (2 * math.sin(math.pi / sides))
polygon_turtle.forward(R)
polygon_turtle.right(90+(360 / (2 * sides)))

并且不要忘记导入数学:),任何地方都没有其他变化..


推荐阅读