This challenge is all about triangles. So far we've mostly created Rectangles (which might be Squares), whick require two Points representing the opposite corners of the Rectangle.
There is no graphics.py command for a "Triangle()". Instead we use the Polygon() function, which can be use to create any straight-sided polygon (including Rectangles). Rectangles can be defined with only two points because they follow strict rules about parallel sides of equal length, but Polygons don't have any similar rules so we have to define all points.
For example, here's the code for a right triangle:
p1 = Point(10,10)
p2 = Point(10,90)
p3 = Point(70,90)
t = Polygon( p1, p2, p3 )
As always, this could also be written in one line:
t = Polygon( Point(10,10), Point(10,90), Point(70,90) )
Question: how do we know this would make a right triangle?
- To warm up, write code to make a triangle with three random points. Try to do it without any hard-coded values. (Hint: create your GraphWin using variables not numbers.)
- Write code to make an equilateral triangle. The first two points are easy...how do you know where the third point goes? (You might want to do some sketches. You could use trigonometry to figure out the answer, but you can do this with Pythagorean Theorem, too.)
This is really a math & logic puzzle, not a coding puzzle.
- Modify your code, if it doesn't do this already, so that you give it two points with the same y value and Python figures out where the third point is, assuming that the equilateral triangle points downward:
p1 = Point(10,10)
p2 = Point(100,10)
p3 = # ???? This is where you need to do some math
t = Polygon(p1, p2, p3)
To do this you'll need to take what you did in the last step and turn it into a general rule.
- Ok, let's up the ante: can you make your code work even if the points have different x and y values? That is, make an equilateral triangle from a sloped line? Again, you might want to do some sketching first. Notice that from any line segment you could create two equilateral triangles, one facing each way. How do you decide which one to make? (We would love to see photos of your sketches posted in Slack...)
- Read up on Python functions. We've used functions to print variables, create shapes, draw shapes, generate random numbers, and so on. Now it's time to learn to write functions. See if you can write a function that creates and returns a random triangle. Give your function two parameters, the width and height of your window, and have it return a random triangle within those bounds.
- Now try to write a function that, given two points, returns an equilateral triangle. So the same logic as two steps ago, but inside a function.
- Finally: given a line segment, can you write a function that returns an equilateral triangle using only the middle third of the segment. That is, just like in our Koch Triangle.