繁体   English   中英

Python(长度输入以绘制中心点为 0,0 的星形)

[英]Python (Length input to draw star with a center point of 0,0)

我有一些代码是用户输入他们想要他们的星星的长度,然后它绘制出星星。 我在这里想要完成的是,每次他们进行输入时,不仅要绘制星星,还要使其保持在屏幕的中心。 所以中间点 0,0

import turtle

Length = eval(input("enter the length you want for your star: "))

turtle.penup()
turtle.goto(0,200)
turtle.pendown()
turtle.goto(0,-200)
turtle.penup()
turtle.goto(200,0)
turtle.pendown()
turtle.goto(-200,0)

turtle.penup()
turtle.goto(0,0)

turtle.showturtle
turtle.pendown()
turtle.left(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)

尝试这个

import turtle
import math

theta = 18  * math.pi / 180   # convert degrees to radians

Length = eval(input("enter the length you want for your star: "))

x = math.sin(theta) * Length
y = math.cos(theta)* Length / 2

turtle.penup()
turtle.goto(0,200)
turtle.pendown()
turtle.goto(0,-200)
turtle.penup()
turtle.goto(200,0)
turtle.pendown()
turtle.goto(-200,0)

turtle.penup()
#turtle.goto(0,0)
turtle.goto(x,-y)

turtle.showturtle
turtle.pendown()
turtle.left(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.hideturtle()

input("Press Enter to exit")

只需找出您正在绘制的星星中心的坐标,然后通过该向量平移起始位置,将中心移动到原点即可。

编辑:

如果您返回原始绘图,在 y 轴的左侧,您会看到两条线段,呈倒 V 形。 如果我们将这些线段的两个交点与 x 轴连接起来,我们就会得到一个等腰三角形,其中心是恒星的中心。 这就是我们需要找到的点。 现在,星星的每个角度都是 36 度,一半是 18。这就是 18 的来源。 为了真正找到中心,我们需要使用一些三角学,我猜你还没有研究过。 函数 sin 和 cos 是三角学中的正弦和余弦函数。 这些函数的参数通常不是以度数给出,而是以另一个称为弧度的系统给出。 碰巧 1800 度与 pi 弧度相同,所以 theta 只是一个 18 度角,以弧度为单位。

“为什么是 18 度,”我听到你问了吗? 请记住,我们试图找到等腰三角形的中心,其中两条边等于长度,斜边为 Length。 所以,我们放下一个垂直于底边的线,我们把它切成两个直角三角形,一个锐角是 18 度(另一个是 72 度)。这就是正弦和余弦的作用。在一个直角三角形中斜边长度,与锐角 theta 相对的边的长度为sin(theta)*Length ,与角 theta 相邻的边的长度为cos(theta)*Length

这是一个冗长的解释,但我不知道如何以这种格式缩短它。 您可以在此处找到带图片的说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM