2016-11-02 88 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