Question
Hello everyone. I am trying to code a fractal tree. I was able to successfully do it for one rule, but I need some help
Hello everyone. I am trying to code a fractal tree. I was able to successfully do it for one rule, but I need some help with doing with other rules that I need defined in the code.
Here are the rules that I need defined in the code:
1. n = 2, Grammar rule 1: F
Grammar rule 2: F -> F[+F]F[-F][F]
2. n = 2, Grammar rule 1: F
Grammar rule 2: F -> FF - [-F+F+F]+[+F-F-F]
4. n = 2, Grammar rule 1: X
Grammar rule 2: X -> F[+X]F[-X]+X
Grammar rule 3: F -> FF
5. n = 2, Grammar rule 1: X
Grammar rule 2: X -> F[+X][-X]FX
Grammar rule 3: F -> FF
6. n = 2, Grammar rule 1: X
Grammar rule 2: X -> F-[[X]+X]+F[+FX]-X
Grammar rule 3: F -> FF
Here is the JS code:
jQuery(document).ready(function () {
var angle_step = 25 / 180 * Math.PI;
function iterate(str, iteration, target) {
var tree = "";
for (var i = 0; i < str.length; i++) {
var char = str.substr(i, 1);
if (char == "F") {
tree += "F[+F]F[-F]F";
} else {
tree += char;
}
}
if (iteration < target) {
tree = iterate(tree, iteration + 1, target);
}
return tree;
}
function draw (x, iterations) {
var tree = iterate("F", 0, iterations);
var y = 400;
var len = 1;
var a = 0;
var stack = [];
var ctx = $('canvas')[0].getContext('2d');
for (var i = 0; i < tree.length; i++) {
ctx.beginPath();
ctx.moveTo(x, y);
var char = tree.substr(i, 1);
if (char == "F") {
x += len * Math.sin(a);
y -= len * Math.cos(a);
ctx.lineTo(x, y);
} else if (char == "-") {
if (Math.random() < 0.1) {
a += angle_step;
} else {
a -= angle_step;
}
} else if (char == "+") {
if (Math.random() < 0.1) {
a -= angle_step;
} else {
a += angle_step;
}
} else if (char == "[") {
stack.push([x, y, a]);
} else if (char == "]") {
var coords = stack.pop();
x = coords[0];
y = coords[1];
a = coords[2];
ctx.moveTo(x, y);
}
ctx.stroke();
}
}
for (var z = 4; z < 7; z++) {
draw( 15 * z*z - 50, z);
}
});
HTML:
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started