Conditional statements to select actions.
(The program below is a modified version of one of the examples
Processing, File, Examples, Basics, Control, Embedediteration.)
Copy the program below into a new Processing window and run it.
‘Iteration’ – a ‘for’ loop to do something many times e.g. a column of dots (and lines).
‘Embedded iteration’ – one ‘for’ loop inside another, repeat the columns of dots.
//--------------------------------------
/**
* Embedding Iteration.
* Embedding "for" structures allows repetition in two dimensions.
*/
void setup()
{
size(640, 360);
background(0);
frameRate(20);
}
void draw()
{
int gridSize = 40;
int count_x;
int count_y;
int grid_x;
int grid_y;
for (count_x = 1; count_x <= (width / gridSize) - 1; count_x++)
{
grid_x = count_x * gridSize;
for (count_y = 1; count_y <= (height / gridSize) - 1; count_y++)
{
grid_y = count_y * gridSize;
noStroke();
fill(255);
// colour condtions go here
rect(grid_x - 8, grid_y - 8, 16, 16);
stroke(255, 50);
if (frameCount < 2)
{
line(grid_x, grid_y, width/2, height/2);
}
}
}
}
//--------------------------------------
Use conditions to select colours:
Copy each of the lines below into the program, after the ‘fill(255)’
Run the program, see the colour change.
(Logic symbols: == means ‘is equal to’, && means ‘and’, || means ‘or’.)
if (count_x == 3){fill(0, 255, 0);}
if (count_y == 5){fill(0, 0, 255);}
if (count_x == count_y +3) {fill(255, 0, 255);}
if (count_x >8 && count_x <= 12) {fill(255, 100, 0);}
if (count_x >8 && count_y >= 6) {fill(0, 100, 100);}
if (count_y ==3 || count_y == 6) {fill(100, 50, 50);}
if (count_x == frameCount % 16 {fill(150, 150, 50);}
You can have more than one of those lines in the program at the same time, as many as you like, but understand what each does. Any later one may override what a previous one has done.
Try some yourself, different conditions and colours.
How could you make every other row coloured? Every 3rd column?
----------------------------