Skip to content

Instantly share code, notes, and snippets.

@dfockler
Created May 22, 2016 16:45
Show Gist options
  • Save dfockler/0037a06a358074e38af2ef6df59b816f to your computer and use it in GitHub Desktop.
Save dfockler/0037a06a358074e38af2ef6df59b816f to your computer and use it in GitHub Desktop.
Random Tree Generator in Processing
Node root;
int level_max = 5;
int branch_max_x = 200;
int branch_min_x = 0;
int branch_max_y = 200;
int branch_min_y = 0;
int children_max = 4;
void setup() {
size(1000, 800);
root = new Node(new PVector(10, 20), new PVector(50, 50), get_color(0));
build_tree(root, 0);
}
void draw() {
background(255);
draw_tree(root);
}
void mouseClicked() {
clear_tree();
build_tree(root, 0);
draw_tree(root);
}
color get_color(int level) {
float colorLevel = map(level, 0, level_max, 0.0, 1.0);
return lerpColor(color(255, 0, 0), color(0, 255, 255), colorLevel);
//return random_color();
}
color random_color() {
return color((int)random(0, 255), (int)random(0, 255), (int)random(0, 255));
}
void clear_tree() {
root = new Node(new PVector(10, 20), new PVector(50, 50), get_color(0));
}
void build_tree(Node node, int level) {
int children = (int)random(1, children_max+1);
int[] x_vals = new int[children];
int[] y_vals = new int[children];
level++;
for (int i = 0; i < children; i++) {
x_vals[i] = (int)random(node.end.x + branch_min_x, node.end.x + branch_max_x);
y_vals[i] = (int)random(node.end.y + branch_min_y, node.end.y + branch_max_y);
}
sort(x_vals);
sort(y_vals);
for (int i = 0; i < children; i++) {
Node child = new Node(node.end, new PVector(x_vals[i], y_vals[i]), get_color(level));
node.add(child);
if (level < level_max) {
build_tree(child, level);
}
}
}
void draw_tree(Node node) {
node.draw();
for (int i = 0; i < node.children.size(); i++) {
draw_tree(node.children.get(i));
}
}
class Node {
public ArrayList<Node> children;
public PVector start;
public PVector end;
public color c;
Node(PVector start, PVector end, color c) {
this.children = new ArrayList<Node>();
this.start = start;
this.end = end;
this.c = c;
}
void add(Node child) {
this.children.add(child);
}
void draw() {
stroke(c);
line(start.x, start.y, end.x, end.y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment