Use recursion to generate a
fractal snowflake. This snowflake is an example of a fractal
computation, but we don't need to know anything about fractals to solve
it.There are several ways to describe a fractal snowflake. The best way
for this assignment is to first draw an equilateral triangle like this:
____________________
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
Then draw a second one on top of this, the same size, but rotated 180 degrees
(thus generating the Star of David):
/ \
/
\
/
\
_____/________\_____
\ / \ /
\ / \ /
/ \ / \
/___\__________/___\
\ /
\ /
\ /
\ /
This figure is roughly drawn -- the triangles are supposed to be
equilateral, having the same center point, and the six smaller triangles that
this forms should also be equilateral of the same size. Note that three
of the smaller triangles are oriented like the first large triangle, and three
are oriented like the second. Indeed, the
point now is to repeat this process for each of the corner triangles, and
repeat again and again, until a suitably small triangle is reached.
Draw your snowflake on a Form. Experiment with sizes to get it to
look nice (hint: make the form large!). You may want to experiment
with filled versus unfilled triangles and different colors for the
successively smaller layers.
Hint: The hardest thing about this assignment is figuring
out the coordinates of the various images. I suggest that you start with the
smallest version, and then scale it up suitably. There are two things to
figure out from a given center: the new centers, and the vertices of the two
triangles. If we map this out on a 6-by-6 grid, the centers are given by:
(3,1)
(1,2) (5,2)
(3,3)
(1,4) (5,4)
(3,5)
and the vertices by:
(3,0)
(0,1.5) (6,1.5)
(3,3)
(0,4.5) (6,4.5)
(3,6)
If this doesn't make sense to you, draw a 6x6 grid on paper, and map out
the above coordinates.
Additional hints:
Define a method:
public
void
DrawTri(Graphics g, int
x, int y,
int m,
int c,
bool o)
This method should draw a triangle on g that is centered at (x,y) and has
side-length 6*m. The parameter o determines the orientation -- if o is
true, the horizontal side is on top, and if false the horizontal side is on
the bottom. The parameter c determines the color of the triangle, and is
optional (I used it to index into an array of colors so that I could change
the color at each level of the recursion).
Then define a method:
public
void Flake(Graphics g,
int x,
int y,
int m,
int c,
bool o)
This method is the heart of the program, and should be recursive. It
should first draw a triangle using DrawTri, and then recursively call itself
at each of the six smaller triangles.
Final hint: the
OnPaint method should
make one call to DrawTri, and then one call to Flake.
Solution.