Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*; // for graphics
- import javax.swing.*; // for JFrame
- public class FractalTriangles {
- /**
- * Program: FractalTriangles.java
- * Purpose: Draw Sierpinski Triangle using recursive algorithm.
- * Creator: Chris Clarke
- * Created: 03.04.2012
- * Modified: 11.07.2013 larger size JFrame
- */
- public static void main(String[] args) {
- FractalTrianglesJFrame frame = new FractalTrianglesJFrame();
- frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
- frame.setVisible(true);
- }
- }
- class FractalTrianglesJFrame extends JFrame {
- public FractalTrianglesJFrame() {
- setTitle("Fractal Triangles by Chris Clarke");
- // Set to maximum size.
- setSize(MAX_X, MAX_Y);
- }
- public void drawTriangle(Graphics g,int x0,int y0) {
- // draw filled-in triangle whose apex is at (x0, y0)
- for (int i=x0; i<=x0+2*TRI_HALF_BASE; i++)
- g.drawLine(i, y0+TRI_HEIGHT, x0+TRI_HALF_BASE, y0);
- // relatively long or short pause depending on value of DELAY
- for (int i=0; i<DELAY; i++);
- }
- public void draw3Triangles(Graphics g,int x0,int y0, int size) {
- // draw fractal using recursion
- size/=2;
- if (size==1) {
- // left corner
- drawTriangle(g, x0-TRI_HALF_BASE, y0+TRI_HEIGHT);
- // right corner
- drawTriangle(g, x0+TRI_HALF_BASE, y0+TRI_HEIGHT);
- // apex
- drawTriangle(g, x0, y0);
- } else { // recursive method call
- // left corner
- draw3Triangles(g, x0-size*TRI_HALF_BASE, y0+size*TRI_HEIGHT, size);
- // right corner
- draw3Triangles(g, x0+size*TRI_HALF_BASE, y0+size*TRI_HEIGHT, size);
- // apex
- draw3Triangles(g, x0, y0, size);
- }
- }
- public void paint(Graphics g) {
- // draw background
- g.setColor(new Color(100, 138, 255));
- g.fillRect(0,0,MAX_X,MAX_Y);
- // draw black triangles
- g.setColor(Color.BLACK);
- draw3Triangles(g, START_X, START_Y, SIZE);
- }
- public static final int MAX_X=1280; // maximum width = width of screen
- public static final int MAX_Y=800; // maximum height = height of screen
- public static final int START_X=MAX_X/2;
- public static final int START_Y=100;
- public static final int TRI_HEIGHT = 2; // size in pixels of black triangle
- public static final int TRI_HALF_BASE = 2; // size in pixels of black triangle
- public static final int DELAY=5000000; // many iterations to slow down construction
- public static final int SIZE=256; // size in pixels of base of largest triangle
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement