Last week, I made this Sol LeWitt wall-drawing-builder.
It totally does the job, but with very free-spirited, non-compartmentalized code. I have only one function, “randomLines(),” holding the whole thing together. (see above)
Looking at this, it’s not immediately clear what’s going on. Thank god for past Kathy’s comments! And yet still it would be such an undertaking if I wanted to change the way it behaves at all.
This week, we were tasked with rewriting our programs with functions. I’ve worked with functions before so I thought it would be a breeze to simplify my code this way. It wasn’t difficult per se, but definitely I hit a few crossroads in the process.
I need something to randomly draw lines, and I need it to do that in a quadrant that I click.
Seems simple enough! But I realized that I had a number of options.
- I can randomly draw lines, but what kind of lines?
- Do I need to tell p5 how to make a horizontal line every time I draw?
- Do I make the lines random when I draw, or make them random before I draw?
- I can figure out what quadrant, but is it when I click? Or is it all the time?
I did some pseudocode to figure it all out…
I made separate functions for “checking,” and “executing.” For example, checking what quadrant I was in was separate from drawing in that quadrant. This felt cleaner and less error-prone.
I organized the 4 types of lines in their own functions as well. With this flexibility, I can change things so that some lines are drawn randomly and some are not.
There are 9 new custom functions, where there used to be just one.
- checks mouse position against quadrant bounds, returns quadrant #
- draws a random line pattern using (x,y) to determine location
- (x,y) are provided by input from “mousePressed()” and “findMouse()”
- generates a number between 1-5, assigns to global variable “r”
- draws 1 of 4 line types based on variable “r,” determined by randomNumber();
- draws lines starting from top left
- draws lines starting from top right
You can check out the improved code here.