简体   繁体   中英

nested triangle in python with turtle

My goal is to produce a simple graphical representation of a set of nested triangles, as shown in Figure 1. The output should consist of 4 equilateral triangles (equal sides, inside angles of 60 degrees). The triangles should have sides of length 20, 40, 60 and 80, respectively. Use a distance of 7 between the bottom horizontal lines of adjacent triangles.

I've seen a post about this on here but the answers were too complicated, as you can see by my code, this is one of my first programs.

from turtle import *
number_of_shapes = 2

for shape in range(1, number_of_shapes + 1):
    # Draw A Triangle
    for sides in range(1, 4):
        forward(10 + shape * 10 )
        left(120)
right(90)
forward(7 + shape)

My question is: how do I simply align my triangles inside each other?

Without the promised illustration, I'm going to assume you're trying to draw nested triangles. Starting at the corner as you are makes it more difficult so I suggest you rearrange your code to start in the middle of the bottom of the triangle and draw from there. This requires drawing the bottom in two steps but it's easier to adjust our positioning if we work from the center:

from turtle import *

number_of_shapes = 4

for shape in range(1, number_of_shapes + 1):
    # Draw A Triangle
    forward(shape * 10)
    for _ in range(2):
        left(120)
        forward(shape * 20)
    left(120)
    forward(shape * 10)

    right(90)
    penup()
    forward(7)
    pendown()
    left(90)

done()

在此处输入图片说明

Though the spacing isn't perfect as the bottoms should closer to 6px away from each other rather than 7px as specified. But we can eliminate this calculation altogether, and simplify the code greatly, by using stamping instead of drawing :

from turtle import *

number_of_shapes = 4

shape('triangle')
fillcolor('white')
right(30)

for size in range(number_of_shapes, 0, -1):
    shapesize(size)
    stamp()

done()

在此处输入图片说明

Using stamping, we're working from the center of the triangle instead of it's edge. Since the default cursor size is 20, the resizing falls out for free.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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