微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

以python乌龟为中心绘制一个多边形

如何解决以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()

请帮帮我。

解决方法

根据Wikipedia

从正多边形中心到顶点之一的外接半径 R 与边长 s 的关系为 R = s / (2 * sin(pi / n))。

如果海龟从中间开始并且您想从其中一个顶点开始绘制,那么一开始您必须走多远。翻译成 Python,使用你的变量:

import math

R = length / (2 * math.sin(math.pi / sides))

现在你可以像这样绘制多边形(从中间开始):

  1. 向任何方向前进 R 的距离,不要画画。
  2. 左转(比如说)90 + 360 / (2 * sides) 度。
  3. 开始绘图。
  4. sides 次:
    • 向前走 length
    • 左转 360 / sides 度。
,

Circles can be used to draw polygons,带有可选的“步骤”参数。

如果你想一次性绘制整个对象,那就是:

turtle .circle( radius,steps = sides )

如果你想让你的乌龟并排画出来,那就是:

for i in range( sides ):
    turtle .circle( radius,extent = 360 /sides,steps = sides )
    turtle .left( 360 /sides )

如果您真的愿意,您可以通过缩小“范围”值来进一步划分每个线段;但它需要一个嵌套循环来完成:

segments_per_side = 5
for i in range( sides ):
    for j in range( line_segments_per_side ):
        turtle .circle( radius,extent = 360 /sides /segments_per_side,steps = sides )
    turtle .left( 360 /sides )
,

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

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

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

polygon_turtle.goto(0,0)

其余的是 Arne's 答案的后续,稍有变化,乌龟向右移动而不是向左移动(否则它将不会居中)。 因此,使多边形居中的完整代码将是:

# 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)))

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。