We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Help!!!!
Doing a project for uni, want to have 5x5 squares which have a random colour assigned - squares need to be in a grid formation with no gaps and no overlaps!!
I can manually do it but need a faster way to repeat the shape.
void setup(){ size(400, 200, P2D); background(255);
frameRate(10); noLoop(); }
void draw(){
noStroke();
fill(random(255), random(255), random(255));
rect(0, 0, 5, 5);
noStroke();
fill(random(255), random(255), random(255));
rect(5, 0, 5, 5);
noStroke();
fill(random(255), random(255), random(255));
rect(10, 0, 5, 5);
}
Answers
You need to use... A LOOP. And then you need... ANOTHER LOOP. Don't freak out. Let's start with something simple. Something you already have working. One square.
As you can see, this draws one red square. Where is there square? It is there, at (0,0), because that's where we drew it.
What if I want to draw it somewhere else?
Now it is somewhere else. What if I want to draw it at a position determined by some variables?
Notice that the square is now drawn at a position determined by the values of x and y. If we were to use a loop, and each time that loop executes, we draw the square at a different place, then we will draw several squares.
Here is a loop:
As you can see, it prints out the numbers 0 to 4. Why? Well a for loop consists of three parts. First is the initialization. This instruction happens once when the loop starts. For this loop, this sets the variable i up with the value 0. Next is the condition. If this condition is true, the body of the loop runs. The condition here is i < 5. Since 0 is less than 5, the loop runs, and the value of i (which is 0) is printed. After the loop's body has run, the third part, the step, happens. In this loop, the step is i++, which adds increments i, turning it from 0 to 1.
Then the condition is checked again. Since 1 is less than 5, the loop body runs and prints 1. And so on.
Once i gets up to a value of 5, the condition is false, and the loop ends.
How does this help us with our squares? Well using a loop allows use to change the X variable. For example:
Now all you need to do is add a loop that changes the value of the Y variable too! Try doing this yourself first, and post your attempt at it for more help.
Amazing!
This has all squares as same colour, is it possible to have each individual square as a different colour (can be any random colour)?
@natcarr89 -- that is because you are picking a random fill color once per draw.
If you want to pick a random color once per row in the outer loop, move your
fill
line into the firstfor
loop.If you want to pick a random color once per rect in the inner loop, move your
fill
line into the secondfor
loop, just aboverect
.Thanks Guys