Imagen Escrita: Árbol
De Casiopea
Título | Árbol con función recursiva |
---|---|
Tipo de Proyecto | Proyecto de Curso |
Asignatura | Imagen Escrita |
void setup() { size(700, 500); smooth(); noLoop(); } float margen, spX, spY; int numX, numY; void draw() { background(255); arbol(width/2, height, 200, 4); } boolean unoEn(int n) { boolean p = false; int x = round(random(n)); if (x <= 1) { p = true; } else { p = false; } return p; } void keyPressed() { redraw(); if (key == 's') { saveFrame("arbol-de-ejemplo.jpg"); } } void rama(float x, float y, float tam) { noStroke(); fill(0); pushMatrix(); { translate(x, y); beginShape(); vertex(-tam * 0.1, tam * 0.05); vertex(-tam * 0.05, -tam); vertex( tam * 0.05, -tam); vertex( tam * 0.1, tam * 0.05); endShape(); } popMatrix(); } void arbol(float x, float y, float tam, int levels) { rama(x, y, tam); // construya la rama if (levels > 0) { int ramas = round(random(2, 10)); // número aleatorio de ramas for (int i = 0; i < ramas; i++) { float ang = random(PI/8, PI/4); if (unoEn(2) == true) { ang *= -1; // puede crecer para la izq o a la der } float h = random(tam * 0.3, tam * 0.9); // altura de la nueva rama pushMatrix(); translate(x, y-h); rotate(ang); arbol(0, 0, tam/1.6, levels - 1); popMatrix(); } } }