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()
请帮帮我。
解决方案
添加到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)))
并且不要忘记导入数学:),任何地方都没有其他变化..
推荐阅读
- c - Shift + Enter 与控制台中的 Enter
- ios - 使用正确的导航项返回 ViewController 时 iOS13 崩溃
- c# - 从 C# Task 调用 COM 函数会阻塞调用者线程
- java - 如何结合 DefaultTyping 仅忽略 @JsonSerialize 注释
- android - 当我使用 findfindViewById 定义两个浮动按钮时,为什么我的应用程序会崩溃?
- javascript - 如何通过 id 存储在变量中来渲染组件?
- php - PHP - 上传视频转换 mp4 并上传到 Amazon S3
- ruby - 如何在 Ruby 中编写递归阶乘函数?
- api - 我们如何根据字段值查询潜在客户?
- c# - WPF TextBlock 从字符串属性格式化粗体