简体   繁体   English

Python Turtle如何编程使其自动关闭?

[英]Python Turtle How to program it to go down automatically?

I have to program a function that draws triangles. 我必须编写一个绘制三角形的函数。 I managed to draw triangles next to each other quite well, but I can't program it in such a way that the triangles stand one under the other. 我设法很好地画出了彼此相邻的三角形,但是我不能对它们进行编程,以使三角形彼此之间直立。 Or at least not that it goes automatically. 或至少不是它会自动运行。
I did it like that: 我是那样做的:

import turtle
otto = turtle.Turtle()

def triangle(t, l): 
    t.color("cadetblue")
    t.begin_fill() 
    for i in range(3):
        t.fd(l)
        t.lt(360/3)
    t.end_fill() 

def pile_triangle (t,l):
    for i in range(1):
        triangle(t, l)
        t.penup()
        t.goto(0,-70)
        t.pendown()
    for i in range(1):  
        triangle(t, l) 
        t.penup()
        t.goto(0,-140)
        t.pendown()
    for i in range(1): 
        triangle(t, l) 
        t.penup()
        t.goto(0,-210)
        t.pendown()
    for i in range(1):  
        triangle(t, l) 


otto = turtle.Turtle()
pile_triangle(otto, 80)


turtle.mainloop()
turtle.bye()

So, as you can see, when the value of l increases, there are gaps or triangles overlap. 因此,如您所见,当l的值增加时,将出现间隙或三角形重叠。 Can it be done differently? 可以做不同的事情吗? So that it draws four triangles and matches the length l? 这样就可以绘制四个三角形并匹配长度l?

Is this what you want? 这是你想要的吗?

import turtle
def triangle(t,l): 
    t.color("cadetblue")
    t.begin_fill() 
    t.lt(360/6)
    for i in range(3):
        t.lt(-360/3)
        t.fd(l)
    t.end_fill()
    t.penup()
    t.lt(-360/3)
    t.fd(l)
    t.lt(-360/3)
    t.fd(l/2)
    t.lt(180)
otto = turtle.Turtle()
for i in range(3):
    triangle(otto,50)

Your original code is pretty close, you only need a couple of things: Thing 1 is to turn your repeated code pattern into a loop. 您的原始代码非常接近,您只需要做几件事:第一件事情就是将重复的代码模式变成一个循环。 Thing 2 is to calculate the amount to move (the triangle's height) rather than use a fixed value. 第二件事是计算移动量(三角形的高度),而不是使用固定值。 From trigonometry you recall that the height of an equilateral triangle is: 通过三角函数,您还记得等边三角形的高度是:

side_length * sqrt(3) / 2

Here's a rework of your code with these two changes: 这是对您的代码进行的以下两个更改:

import turtle

def triangle(t, length):
    t.begin_fill()

    for i in range(3):
        t.forward(length)
        t.left(360 / 3)

    t.end_fill()

def pile_triangle(t, length):
    height = length * 3 ** 0.5 / 2  # height of triangle given a side

    for i in range(1, -3, -1):  # center stack vertically on screen
        t.penup()
        t.goto(-length / 2, i * height)  # center stack horizontally on screen
        t.pendown()

        triangle(t, length)

otto = turtle.Turtle()
otto.color("cadetblue")

pile_triangle(otto, 100)

turtle.mainloop()
turtle.bye()

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

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