Sierpinski Triangle

We're going to use what we've been learning to draw a famous fractal: the Sierpinski triangle. You'll need to implement the following steps:

  1. Make certain that your application specifies a WIDTH of 1024 and a HEIGHT of 768 for the Canvas.
  2. Create six variables to represent three vertices: (512,109), (146,654), and (876,654). I recommend storing these as (x1,y1), (x2,y2), and (x3,y3).
  3. Create another pair of variables which will store the "current" point. You should really call them x and y. Start x at 512, and start y at 382.
  4. Then, in a loop that repeats 50,000 times:
  5. (optional) Once the loop ends, draw the string "Sierpinski Triangle" at (462,484) or so.

Here is a working example version:

For those who want to know where the random points above come from:

There's nothing particularly special about these points, but they form the vertices of a nice-looking equilateral triangle that pretty much fills the screen. But the fractal would still come out pretty much no matter which starting values you use for the vertices.

The starting (x,y) could actually be any point inside the triangle. I chose (512,382) because it's smack-dab in the middle of the triangle and usually gets overwritten by the others. If you move it somewhere else, the output will still turn out almost identically.

The Sierpinski triangle is named after Waclaw Sierpinski, who described it in 1915.




©2013–2015 Graham Mitchell

This assignment is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License.
Creative Commons License