2016-11-02 31 views
0

我在尋找最佳的方式來自動找到新的海龜繪圖的起始位置,以便它將以圖形窗口爲中心,而不管它的大小和形狀如何。海龜繪圖自動對中

到目前爲止,我已經開發了一個函數,用於檢查每個繪製元素的烏龜位置,以便爲左,右,上和下找到極端值,並且以這種方式查找圖片大小,並且可以在釋放我之前使用它來調整起始位置碼。這是例如簡單的形狀,與我的圖片尺寸檢測繪製的說:

from turtle import * 

Lt=0 
Rt=0 
Top=0 
Bottom=0 

def chkPosition(): 
    global Lt 
    global Rt 
    global Top 
    global Bottom 

    pos = position() 
    if(Lt>pos[0]): 
     Lt = pos[0] 
    if(Rt<pos[0]): 
     Rt= pos[0] 
    if(Top<pos[1]): 
     Top = pos[1] 
    if(Bottom>pos[1]): 
     Bottom = pos[1] 

def drawShape(len,angles): 
    for i in range(angles): 
     chkPosition() 
     forward(len) 
     left(360/angles) 


drawShape(80,12) 
print(Lt,Rt,Top,Bottom) 
print(Rt-Lt,Top-Bottom) 

但是這一方法的工作看起來很笨拙的我,所以我想問更多的經驗龜程序員有沒有更好的辦法找到啓動烏龜圖紙的位置,使他們居中?

問候

+0

使用幾何找到起始位置。 – furas

回答

1

沒有到中心各種形狀(你畫它,並找到所有你的最大值,最小值點之前)的通用方法。

對於你的形狀(「幾乎」圓形),可以使用幾何來計算起點。

enter image description here

alpha + alpha + 360/repeat = 180 

所以

alpha = (180 - 360/repeat)/2 

,但我需要180-alpha向右移動(後來到左移動)

beta = 180 - aplha = 180 - (180 - 360/repeat)/2 

現在width

cos(alpha) = (lengt/2)/width 

所以

width = (lengt/2)/cos(alpha) 

因爲Python使用cos()radians所以我需要

width = (length/2)/math.cos(math.radians(alpha)) 

現在我有betawidth,所以我可以移動的起點和形狀將居中。

from turtle import * 
import math 

# --- functions --- 

def draw_shape(length, repeat): 

    angle = 360/repeat 

    # move start point 

    alpha = (180-angle)/2 
    beta = 180 - alpha 

    width = (length/2)/math.cos(math.radians(alpha)) 

    #color('red') 
    penup() 

    right(beta) 
    forward(width) 
    left(beta) 

    pendown() 
    #color('black') 

    # draw "almost" circle 

    for i in range(repeat): 
     forward(length) 
     left(angle) 

# --- main --- 

draw_shape(80, 12) 

penup() 
goto(0,0) 
pendown() 

draw_shape(50, 36) 

penup() 
goto(0,0) 
pendown() 

draw_shape(70, 5) 

penup() 
goto(0,0) 
pendown() 

exitonclick() 

我在圖像上留下了紅色width

enter image description here

0

我佩服@furas'的解釋和代碼,但是我逃避數學。爲了說明總有另一種方式去了解一個問題,這裏有一個免費的數學解決方案,產生相同的同心多邊形:

from turtle import Turtle, Screen 

def draw_shape(turtle, radius, sides): 

    # move start point 

    turtle.penup() 

    turtle.sety(-radius) 

    turtle.pendown() 

    # draw "almost" circle 

    turtle.circle(radius, steps=sides) 

turtle = Turtle() 

shapes = [(155, 12), (275, 36), (50, 5)] 

for shape in shapes: 
    draw_shape(turtle, *shape) 
    turtle.penup() 
    turtle.home() 
    turtle.pendown() 

screen = Screen() 
screen.exitonclick() 

enter image description here