Skip to content

Instantly share code, notes, and snippets.

@taka2
Created October 5, 2008 12:55
Show Gist options
  • Save taka2/14882 to your computer and use it in GitHub Desktop.
Save taka2/14882 to your computer and use it in GitHub Desktop.
import java.awt.*;
import java.awt.geom.*;
import java.util.Stack;
import javax.swing.*;
// キモい再帰的なツリーを描くプログラム
public class drawtree extends JPanel
{
private static final int DEGREE = 12;
private static final int BRUNCH_LENGTH = 40;
private static final int DRAW_LEVEL = 8;
public static void main(String[] args)
{
drawtree dt = new drawtree();
JFrame jf = new JFrame();
jf.setSize(200, 200);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(new BorderLayout());
jf.add(dt, BorderLayout.CENTER);
}
public drawtree()
{
this.currentDegree = 90;
this.positionStack = new Stack<Point2D>();
positionStack.push(new Point2D.Double(100, 150));
}
private int currentDegree;
private Stack<Point2D> positionStack;
public void drawtree(Graphics g, int n)
{
if(n == 0)
{
// 何もしない
}
else
{
left();
forward(g, n);
drawtree(g, n-1);
back(n);
right();
right();
forward(g, n);
drawtree(g, n-1);
back(n);
left();
}
}
public void left()
{
this.currentDegree -= DEGREE;
}
public void right()
{
this.currentDegree += DEGREE;
}
public void forward(Graphics g, int n)
{
int brunchLength = BRUNCH_LENGTH - ((DRAW_LEVEL - n) * 2);
Graphics2D g2d = (Graphics2D)g;
Point2D currentPosition = (Point2D)positionStack.peek();
// debug
//System.out.println("CURRENT:" + currentPosition.getX() + "," + currentPosition.getY());
Point2D moveTo = null;
if(currentDegree <= 90)
{
double moveX = Math.sin((90 - (currentDegree - DEGREE)) / 180.0) * brunchLength;
double moveY = Math.sin((currentDegree - DEGREE) / 180.0) * brunchLength;
moveTo = new Point2D.Double(currentPosition.getX() - moveX, currentPosition.getY() - moveY);
}
else
{
int targetDegree = 180 - currentDegree;
double moveX = Math.sin((90 - (targetDegree - DEGREE)) / 180.0) * brunchLength;
double moveY = Math.sin((targetDegree - DEGREE) / 180.0) * brunchLength;
moveTo = new Point2D.Double(currentPosition.getX() + moveX, currentPosition.getY() - moveY);
}
// debug
//System.out.println("MOVE:" + moveTo.getX() + "," + moveTo.getY());
g.setColor(Color.black);
Line2D.Double line2d = new Line2D.Double(currentPosition.getX(), currentPosition.getY(), moveTo.getX(), moveTo.getY());
g2d.draw(line2d);
positionStack.push(moveTo);
}
public void back(int n)
{
positionStack.pop();
}
public void paint(Graphics g)
{
drawtree(g, DRAW_LEVEL);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment