RecursiveFractals

advertisement
The code below is complete and works as is. Run it
in BlueJ and try to figure out what is going on. Then
use it as an example to complete the Sierpinski carpet
program on the next page.
/*** A Cool Circle Fractal - using recursion ***/
import java.awt.*;
import java.applet.*;
public class Circles extends Applet {
Graphics g;
/**
* recursive method to draws 1 big circle then 5 circles 1/3 the size
* inside the big circle.
*/
public void drawCircle(int x, int y, int s) {
if (s <= 2)
{
return; // base case - draw circles until size<2
}
else
{
/** --- this for loop does nothing ---* it is here just to act as a time delay between recursive call so
* that you can see the order in which the circles are being drawn
*/
for (int i=0; i<10000000; i++) {
// do nothing
}
/**
* draw circle at position x, y, dimension s by s
*/
g.drawOval(x,y,s,s);
/**
* reduce the size to 1/3 and make recursive calls to draw
* 5 circles within the big circle
*/
s = s / 3;
drawCircle(x+s, y, s);
drawCircle(x, y+s, s);
drawCircle(x+s+s, y+s, s);
drawCircle(x+s, y+s+s, s);
drawCircle(x+s, y+s, s);
}
}
public void paint(Graphics gr) {
g = gr;
setVisible(true);
g.setColor(Color.red);
drawCircle(0, 0, 500);
}
}
Your assignment is to complete the code to draw the Sierpinski carpet (SEE NEXT
PAGE). Use the Cool Circle Fractal as a template to help you with this program. The
Sierpinski carpet is a plane fractal first described by Wacław Sierpiński in 1916 - wow!
/**
* Complete the Applet below which draws the Sierpinski Carpet
* This fractal is formed by drawing a "big" square at position x,y
* with length = s, width = s, with 8 smaller squares inside it.
*
* >>> Use the command: g.drawRect(x,y,s,s) to draw a square.
*
* >>> Then make recursive calls to draw 8 smaller squares in
* the big square each with size s/3
*/
import java.awt.*;
import java.applet.*;
public class Carpet extends Applet {
Graphics g;
public void drawBoxes(int x, int y, int s) {
// complete the code
}
public void paint(Graphics gr) {
g = gr;
setVisible(true);
g.setColor(Color.red);
drawBoxes(0, 0, 800);
}
}
Download