So we have our image changing, but all the squares are the same color. Let’s switch that up!
If your friend was going to get you a soda, you might say – get me Cherry Coke if they have it, if not I’ll have a Dr Pepper.
The way we do that is by using if-statements. So it’s like,
if(cherrycoke) { buy(cherrycoke); } else { buy(drpepper); }
We can compare numbers using these operators:
a < b
a is less than b
a <= b
a is less than or equal to b
a > b
a is greater than b
a >= b
a is greater than or equal to b
a == b
a is equal to b
So how about we change our code to fill the applet with squares, alternating in color.
stroke(140, 9, 214); if (y%2 == 0) { if (x%2 == 0) { fill(255, 126, 0); } else { fill(238); } } else { if (x%2 == 0) { fill(238); } else { fill(255, 126, 0); } }
Using x%2 takes “mod 2″ of x. Wikipedia has a full explanation, but here we’re using it to determine whether x is even or odd.
So we’ve set the color. Now, we need to draw the square and update x and y. So:
rect(x*s, y*s, s, s); x++; if (x >= width/s) { y++; x = 0; }
And now, it update until it looks like this:
Finally, add the lines below: can you work out what they do?
if (y >= width/s) { noLoop(); }
This says we’ve come to the end of our program, so we don’t need to call draw() again.
Pingback: Processing » Archive » Pacman,