Monday, March 26, 2012

Lab 19: Sierpinsky Triangle

For this lab you will implement a recursive method that draws the Sierpinsky Triangle to various levels. You will start out with the following code:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * Triangle.java
 * @author Jose M Vidal 
 * Created on Mar 19, 2012
 * 
 */

public class Triangle extends JPanel {

  public void drawTriangle(Graphics2D g, int x1, int y1, int x2, int y2, int x3, int y3){
    g.drawLine(x1, y1, x2, y2);
    g.drawLine(x2, y2, x3, y3);
    g.drawLine(x3, y3, x1, y1);
  }
 
  public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.black);
    drawTriangle(g2,1,640, 320,0, 640,640);
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame("Window"); //frame is the window
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Triangle panel = new Triangle(); //panel is the graphics area where we can draw

    frame.add(panel); //put the panel inside the window
    frame.setSize(650,680); //set the window size to 640x640 pixels
    frame.setVisible(true); 
   }
}


which simply draws a triangle and change it so that it draws the Sierpinsky triangle to any desired level.

That is, change the drawTriangle method so that it takes as argument another variable, the level. If the level is 0 it will draw the triangle exactly as it does now.

But, if the level is 1 it will instead draw the 3 triangles, as shown in the first figure. In other words, it will draw three Sierpinsky level 0 triangles: one on the bottom left, one on the top, and one on the bottom right. Note that we do not draw the upside-down triangle in the middle, that one is just a side-effect from drawing the three other triangles. Similarly, if the level is 2 we draw 3 Sierpinsky level 2 triangles: one on the bottom left, one on the top, and one on the bottom right, and so on.

The program should work for all levels but, I note that running it for levels greater than 12 will take significant amounts of time, and will not change the look of the triangle because you have already reached the limits of the resolution (640 by 640 pixels)

As always, turn this in on the dropbox.cse.sc.edu.

Oh, and, how might this be related to exponential functions as discussed in class? Vihart explains:

No comments: