Skip to content

Instantly share code, notes, and snippets.

@connlark
Created April 12, 2016 15:12
Show Gist options
  • Save connlark/18d15e5daa73111671da3c6e050c868b to your computer and use it in GitHub Desktop.
Save connlark/18d15e5daa73111671da3c6e050c868b to your computer and use it in GitHub Desktop.
import java.awt.*;
public class Tree {
private double fractionLength;
private int smallestBranch;
private double branchAngle;
private int trunkStartX, trunkStartY, trunkEndX, trunkEndY;
public Tree() {
fractionLength = .8;
smallestBranch = 10;
branchAngle = .2;
trunkStartX = 400;
trunkStartY = 700;
trunkEndX = 400;
trunkEndY = 600;
}
public void drawTree(Graphics g) {
g.setColor(Color.red);
/**
* Draw the trunk of the tree using the Graphic's class
* drawLine method
*/
g.drawLine(trunkStartX,trunkStartY,trunkEndX,trunkEndY);
/**
* Call the drawBranch method below. Send in the graphics parameter
* the length of the trunk, the starting point of the first branch, and the
* angle 3pi/2.
*/
drawBranch(g,100,trunkEndX,trunkEndY,(3.0*Math.PI)/2.0);
}
public void drawBranch(Graphics g,double currentLength, int startX, int startY, double currentAngle) {
currentLength = currentLength*fractionLength;
/**
* Calculate the angles of both branches
*/
double angle1 = currentAngle+branchAngle, angle2 = currentAngle-branchAngle;
/**
* Calculate the end points of both branches
*/
int endX1 = (int)(currentLength * Math.cos(angle1) + startX);
int endY1 = (int) (startY + (currentLength*Math.sin(angle1)));
int endX2 = (int) (startX + currentLength*Math.cos(angle2));
int endY2 = (int) (startY + (currentLength*Math.sin(angle2)));
/**
* Draw the branches using Graphics's class drawLine method
*/
g.drawLine(startX,startY,endX1,endY1);
g.drawLine(startX,startY,endX2,endY2);
/**
* Now check and see if we should recursively call
* drawBranch. If so, recursively call drawBranch with
* appropriate parameters.
*/
if (currentLength > smallestBranch){
drawBranch(g,currentLength,endX1,endY1,angle1);
drawBranch(g,currentLength,endX2,endY2,angle2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment