簡體   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