-
Need help with recursion
I am trying to draw a fractal tree using turtle graphics
Java Graphics Turtle com.lrdev.turtle
The algorithm is supposed to be:
Draw the trunk
Turn left x degrees
Draw the left branch
recurse ... draw the trunk ...
Backup down the left branch to the trunk
Turn right x+x degrees (to counter the left turn you have to turn double)
Draw the right branch
recurse ... draw the trunk ...
Backup down the right branch to the trunk
Backup down the trunk
The recursive method is supposed to keep track of the recursivedepth
I can't seem to figure out how to implement the algorithm into my code. Please help
Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import com.lrdev.turtle.Turtle;
public class Tree extends JPanel{
public Tree() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(this));
f.setSize(600, 600);
f.setLocation(200, 200);
f.setVisible(true);
}
private void drawone (Turtle turtle, int x, int y, int deg, int steps){
turtle.penup();
turtle.setXY(x,y);
turtle.pendown();
turtle.left(90);
drawtwo(turtle, deg, steps);
}
// this is the recursive method, I need help writing this
private void drawtwo (Turtle turtle, double degx, int stepsx){
if(stepsx == 0) { return; }
turtle.forward(50);
turtle.left(degx);
turtle.forward(50);
drawtwo(turtle, degx/1.5, stepsx-1);
turtle.back(50);
turtle.right(2*degx);
turtle.forward(50);
turtle.back(50);
drawtwo(turtle, degx/1.5, stepsx-1);
}
protected void paintComponent(Graphics g) {
Turtle turtle = new Turtle((Graphics2D) g, getBounds());
turtle.setHeadingMode(Turtle.DEGREE);
drawone(turtle, 0, -200, 15, 2);
}
public static void main(String[] args) {
Tree test = new Tree();
}
}
-
well to keep track you need to hold a reference of some sort between each running of your method. I would pass this as a parameter to the recursive method itself and while the depth doesn't reach the threshold you want let the recursive call continue. Once that point or depth has reached, obviously stop :)
-
I know that I need to keep track of the depth. I don't know how to make it so it will draw a fractal tree. I can't figure out how to implement the algorithm into my code