Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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:

Fractal trees demo

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Beginning Databases With PostgreSQL From Novice To Professional

Authors: Richard Stones, Neil Matthew

2nd Edition

1590594789, 978-1590594780

More Books

Students also viewed these Databases questions