improving drawing pythagoras tree
Posted
by sasquatch90
on Stack Overflow
See other posts from Stack Overflow
or by sasquatch90
Published on 2010-05-07T17:16:57Z
Indexed on
2010/05/07
17:18 UTC
Read the original article
Hit count: 237
Hello. I have written program for drawing pythagoras tree fractal. Can anybody see any way of improving it ? Now it is 120 LOc. I was hoping to shorten it to ~100...
import javax.swing.*;
import java.util.Scanner;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JComponent;
public class Main extends JFrame {;
public Main(int n) {
setSize(900, 900);
setTitle("Pythagoras tree");
Draw d = new Draw(n);
add(d);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private int pow(int n){
int pow = 2;
for(int i = 1; i < n; i++){
if(n==0){
pow = 1;
}
pow = pow*2;
}
return pow;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Give amount of steps: ");
int steps = sc.nextInt();
new Main(steps);
}
}
class Draw extends JComponent {
private int height;
private int width;
private int steps;
public Draw(int n) {
height = 800;
width = 800;
steps = n;
Dimension d = new Dimension(width, height);
setMinimumSize(d);
setPreferredSize(new Dimension(d));
setMaximumSize(d);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
g.setColor(Color.black);
int w = width;
int h = height;
int x1, x2, x3, x4, x5, y1, y2, y3, y4, y5;
int base = w/7;
x1 = (w/2)-(base/2);
x2 = x1;
x3 = (w/2)+(base/2);
x4 = x3;
x5 = w/2;
y1 = (h-(h/15))-base;
y2 = h-(h/15);
y3 = y2;
y4 = y1;
y5 = (h-(h/15))-(base+(base/2));
//paint
g.drawLine(x1, y1, x2, y2);
g.drawLine(x2, y2, x3, y3);
g.drawLine(x3, y3, x4, y4);
g.drawLine(x1, y1, x4, y4);
int n1 = steps;
n1--;
if(n1>0){
g.drawLine(x1, y1, x5, y5);
g.drawLine(x4, y4, x5, y5);
paintMore(n1, g, x1, x5, x4, y1, y5, y4);
paintMore(n1, g, x4, x5, x1, y4, y5, y1);
}
}
public void paintMore(int n1, Graphics g, double x1_1, double x2_1, double x3_1, double y1_1, double y2_1, double y3_1){
double x1, x2, x3, x4, x5, y1, y2, y3, y4, y5;
//counting
x1 = x1_1 + (x2_1-x3_1);
x2 = x1_1;
x3 = x2_1;
x4 = x2_1 + (x2_1-x3_1);
x5 = ((x2_1 + (x2_1-x3_1)) + ((x2_1-x3_1)/2)) + ((x1_1-x2_1)/2);
y1 = y1_1 + (y2_1-y3_1);
y2 = y1_1;
y3 = y2_1;
y4 = y2_1 + (y2_1-y3_1);
y5 = ((y1_1 + (y2_1-y3_1)) + ((y2_1-y1_1)/2)) + ((y2_1-y3_1)/2);
//paint
g.setColor(Color.green);
g.drawLine((int)x1, (int)y1, (int)x2, (int)y2);
g.drawLine((int)x3, (int)y3, (int)x4, (int)y4);
g.drawLine((int)x1, (int)y1, (int)x4, (int)y4);
n1--;
if(n1>0){
g.drawLine((int)x1, (int)y1, (int)x5, (int)y5);
g.drawLine((int)x4, (int)y4, (int)x5, (int)y5);
paintMore(n1, g, x1, x5, x4, y1, y5, y4);
paintMore(n1, g, x4, x5, x1, y4, y5, y1);
}
}
}
© Stack Overflow or respective owner