There are a few strategies you can take, but I wouldn't hardcode the points, especially if you're just getting them by trial and error. That sort of works for one shape, but it also forfeits the opportunity to understand and encode the nature of the shapes you're drawing. We should be able to draw in a way that makes it easy to scale, rotate and generalize the shape to create different patterns.
As with any problem, find a simpler problem and start formulating a strategy. Can you draw a single triangle? If not, perhaps start with a square. These are sub-components of the larger drawing, so if you can figure out how to draw these, you can probably figure out the next step of putting them together to complete the pattern.
Drawing a 45-45-90 degree triangle is a bit tricky, but you can look up the formula:
import turtle
length = 100
side_length = 2 ** 0.5 * length
t = turtle.Turtle()
t.forward(length)
t.left(135)
t.forward(side_length)
t.left(135)
t.forward(length)
turtle.exitonclick()
That's one sub-step. Another shape that might be handy is the "hat", which we can derive from the above shape by experimenting and observing that the side (hypotenuse) length is half of what it is in the 45-45-90 triangle.
length = 100
side_length = 2 ** 0.5 * length # same as above
t = turtle.Turtle()
t.left(45)
t.forward(side_length / 2)
t.left(90)
t.forward(side_length / 2)
t.left(135)
t.forward(length)
With this shape, we can build the final result. The usual way to repeat things in programming is with loops. If we use a plain for _ in range(3):
, we can repeat the drawing 3 times, but it'll just write over itself again and agin.
To achieve the desired result, we'll need to add some code to position the turtle so that it's primed to draw the next shape when it finishes the current loop.
# same initialization as above ...
for _ in range(3):
t.left(45)
t.forward(side_length / 2)
t.left(90)
t.forward(side_length / 2)
t.left(135)
t.forward(length)
# prepare for the next triangle
t.left(90)
t.forward(length)
t.left(90)
turtle.exitonclick()
This is not the most elegant approach as lines are drawn multiple times, but the point is that we've broken the problem down, come up with a general strategy based on simpler shapes and built up to a full solution. Unlike a points-based approach, all we need to do is change length
to draw houses of different sizes, position the turtle at a different start point to translate the house, or start with a different turtle heading to draw houses at different angles.
I'll leave adding the hat and figuring out a strategy for drawing the house without overlapping as exercises. You can combine the hat with the full 45-45-90 triangle hypotenuse and a plain square to do so.