23. September 2013
We had to program a forest. On the basis of the exercise about recursive functions I added a trunk to the tree and a grid system to place them. You can control parameters with certain keys. For example "." and "," to influence the density of the forest.
/*
Some controls:
Keys:
'.' more trees
',' less trees
'1' slimmer trees
'2' wider trees
'3' shorter trees
'4' higher trees
Mouse:
'click' create a new forest
*/
int x;
int y;
int density = 150; // set how many trees you want
int treeWidth = 50;
int treeHeight = 60;
void setup() {
size(800, 800);
background(255);
smooth();
noLoop();
randomSeed(millis()); // seed randomly
strokeWeight(5);
stroke(0, 0, 0, 150);
}
void draw() {
background(255);
println(density);
//create a grid
for (int x = density; x <= width - density; x += density) {
for (int y = density; y <= height - density; y += density) {
pushMatrix();
translate(x, y);
zeichnen();
popMatrix();
}
}
}
void zeichnen()
{
pushMatrix();
float baumStamm = random(-30, -50);
line(0, 0, 0, -baumStamm); //add a trunk first
translate(0, baumStamm);
popMatrix();
baum(3);
}
void baum(int tiefe) {
if (tiefe <= 0) // teste ob das ende erreicht worden ist
{
// zeichen blueten
pushStyle();
x = (int)random(-treeWidth, treeWidth);
y = -(int)random(treeHeight*0.1, treeHeight);
int clr = (int)random(100, 255);
stroke(0, clr, 0, 190);
fill(0, clr, 0, 190);
ellipse(0, 0, 50, 50);
popStyle();
return;
}
// zeichne zweige
int count = (int)random(2, 5);
for (int i = 0; i < count;i++)
{
line(0, 0, x, y);
pushMatrix();
translate(x, y);
scale(random(.3, .95));
baum(tiefe-1);
popMatrix();
}
}
void mousePressed()
{
redraw();
}
void keyPressed() {
switch (key) {
case '.':
density-=10;
redraw();
break;
case ',':
density+=10;
redraw();
break;
case '1':
treeWidth-=5;
redraw();
break;
case '2':
treeWidth+=5;
redraw();
break;
case '3':
treeHeight-=5;
redraw();
break;
case '4':
treeHeight+=5;
redraw();
break;
}
}