2016-08-09 54 views
3

我想画一个瓷砖等边三角形,看起来像这样如何画一个三角形的瓷砖与Python乌龟

enter image description here

使用Python的乌龟。我希望能够有16,25,36,49或64个三角形。

我最初的尝试很笨拙,因为我还没有想出如何将龟从一个三角形整齐地移动到下一个三角形。

这是我的(部分正确)的代码

def draw_triangle(this_turtle, size,flip):  
    """Draw a triangle by drawing a line and turning through 120 degrees 3 times""" 
    this_turtle.pendown() 
    this_turtle.fill(True) 
    for _ in range(3): 
     if flip: 
      this_turtle.left(120) 
     this_turtle.forward(size) 
     if not flip: 
      this_turtle.right(120) 
    this_turtle.penup() 

myturtle.goto(250,0) 
for i in range(4): 
    for j in range(4): 
     draw_triangle(myturtle, square_size,(j%2 ==0)) 
     # move to start of next triangle 
     myturtle.left(120) 
     #myturtle.forward(square_size) 

    myturtle.goto(-250,(i+1)*square_size) 

必须有这样的一个优雅的方式?

回答

1

我发现这是一个有趣的问题,如果修改,以便乌龟必须通过移动和没有跳跃画图。

我找到了解决办法是丑陋的,但它可以是一个起点......

def n_tri(t, size, n): 
    for k in range(n): 
     for i in range(k-1): 
      t.left(60) 
      t.forward(size) 
      t.left(120) 
      t.forward(size) 
      t.right(180) 
     t.left(60) 
     t.forward(size) 
     t.right(120) 
     t.forward(k * size) 
     t.left(60) 
    t.right(180) 
    t.forward(n * size) 
    t.right(180) 

你可以看到图案的外观here

+0

好主意。我没有想过这样做。 – user2175783