a tutorial for Processing (Java and P5.js)

table of content:

introduction
Step 1: Hard coded toggle button
Step 2: Using a function to make multiple buttons
Step 3: Combining arrays and functions
Step 4: Combining arrays and class
Step 5: Screens or states
Step 6: Loading variable data from extra CSV file
Step 7: arranging code using extra JS file
Step 8: combine all to make a game
Step 9: add some detail work

introduction:

I’m an active member on the Processing forum where I like to help people with their coding questions and problems. Some topics –such as buttons, grids, and classes– are noticeably more troubling for them to get the hang of. Understandable, because these are broad and complicated topics to master. Based on the questions and problems I’ve seen on the forum I put together this tutorial. If you want to get more familiar with coding buttons in Processing (either Java or P5), then you’re at the right place.
By button I mean a screen area you can click (or touch) and something happens. We’ll start with a simple button, and step-by-step we’ll work towards a more complex quiz system that has many clickable options. I’m going to show you how to code buttons in different ways through examples, and explain why one approach is preferred over the other.
The tutorial is divided in 9 steps. Each is provided with an online P5 example which can be viewed in your browser. If you prefer to follow this tutorial with Java examples, you can download the .pde files for all here. here. Steps 1 till 4 are intended for beginners and those with average coding experience. It shows and explains different ways to code buttons. Once you understand these, steps 5 till 9 might be interesting for you. This part of the tutorial is more focused on how you could implement buttons in a complex sketch.

Step 1: Hard coded toggle button

Let’s start by coding a button that can we can toggle. By that I mean a button which we can click to turn something on or off, similar to a light switch. In this coded example we’ll use the button to toggle its own color.
Because this sketch only contains a single button, hard coding it will suffice. By hard coding I mean that we can place nearly all the code about the button inside the draw loop, instead of neatly organizing it in functions or classes that are placed outside the draw loop (which we’ll do in later steps). For a small sketch such as this one it’s okay– there’s no need to over complicate the code.

toggle button hard coded (p5.js)
toggle button hard coded (JAVA)

Step 2: Multiple buttons with global variables & functions

In the previous step we used hard coded button settings. This can work for a single button, but if we need multiple buttons it’s an inefficient method. For each button we would have to type out similar lines of code, resulting in a larger sketch. The code for each button is practically the same, aside from minor things like the x and y positions.

Whenever you notice that your sketch has similar pieces of code, it’s good practice to find alternatives for these repetitive parts. Take the width of each button for instance. It’s the same throughout the entire sketch (in this case 80 pixels). So instead of repeating ‘80’ multiple times in your sketch, it’s easier to type it just once at the beginning and refer to this value afterwards. This is where global variables come in handy.

The same principle can be applied with functionality. Rather than repeating similar lines of code to construct a button, we can write a single function for it. In this function we include all the necessary lines of code to make our button.
For each button that we want to add to our sketch, we simply refer to this function.

Using a function to make multiple buttons (p5.js)
Using a function to make multiple buttons (JAVA)


Step 3: Combining arrays and functions

Let’s kick it up a notch. Instead of adding a few buttons, we’ll add around 30. These should neatly align on our screen, and it would be a nice if we could easily change the amount of buttons afterwards. Preferably without going through too much trouble of rewriting our sketch.
Because we’re working with a lot more buttons now, the approach used in step 2 isn’t optimal. For starters we don’t want to manually type out the values for each button. Another problem is that each button in step 2 has its own variable name (such as x1, y1, and text1), meaning we’d end up with lots of variables.
These problems can be solved by combining arrays and functions. We could write a function that calculates the values for each button, and then save these values in an array (if you’re unfamiliar with arrays, Casey Reas and Ben Fry wrote a great tutorial a it). For instance, we could save the y-coordinates for 30 buttons in a single array instead of having 30 loose variables (y1, y2, y3, and so forth).
Combining arrays with functions can be tricky to grasp, but it will save you incredibly much time and trouble in the future.

Combining arrays and functions (p5.js)


Step 4: Combining arrays and class

In the former step we combined arrays with functions which helped to neatly organize the code. Keeping it manageable is important, especially in growing sketches. Doing so will make it easier for us to adjust and extend it. At the same time, when an error presents itself, it’s less problematic to pinpoint where it’s being caused (and how to solve it without influencing another part of the code).
A way to keep your sketch more manageable is by reducing the amount of functions and (global) variables. For example, it’s not necessary that the coordinates, colors, and sizes of each button are directly accessible throughout the entire sketch. At the same time, functions such as button toggling and hover effects are probably only used by the buttons itself, and not by anything else within the sketch.
It’s moments like these that classes come in handy. One of its benefits is that we can ‘categorize’ certain parts of the sketch. In this case we could combine all data and functions (that are only used by the buttons) within a class that we’ll call Button. This way we’ve created a noticeable split between the ‘main sketch’ and a category within it.
There’s more to classes than I explained in this text, and it’s crucial to understand it if you want to become a skilled coder. In case you’re not that familiar with this topic yet I suggest the tutorial Objects by Daniel Shiffman. He also posted some great videos on his YouTube channel called The Coding Train.

Combining arrays and class (p5.js)
simple Class example (JAVA)
Array Of Class example (JAVA)
complex registered class example (JAVA)

Building a complex quiz system

From this point onward we’re going to build a complex quiz system. It might be good to take a quick peak at the sketch of step 9 so you have an idea what we’re working towards.
Whenever you build a complicated sketch it’s recommended to do so one step at the time. A common pitfall is that people often try to implement all functionality straight away, and as a result they lose control over their sketch. Errors start to pop up and they wouldn’t know what’s causing it. By breaking up the entire project in smaller pieces it becomes much easier to solve the issues that arise along the way.
This is also what I did for steps 5 till 9.

Step 5: Deciding the program flow, Screens and States

Personally I like to start broad and work towards the details later. Therefore the order in which a sketch should execute is often a step I begin with. For the quiz system I have the following program flow in mind:
  1. introduction screen
  2. later can select 3 game options
  3. select question
  4. now key, later button grid
  5. question screen (show the question which the user can answer)
  6. can select multiple choice [a][b][c] now key later button
  7. answer screen (show if the answer is correct)
  8. future a real game might need a SCORE counter there
At the answer screen the user should be able to restart.
While develop need to show diagnostic info to follow program flow/logic. Please disable later.

state system for this quiz game (p5.js)

Step 6: Implementing external data

Often it’s practical to combine functionality and content (such as numbers and text) into a single sketch. Once your sketch grows bigger however, it might be good to split the two. We could put all functionality in the sketch, while the data –such as the quiz questions and answers– are in another file. Through code we can instruct the sketch to load the data from that external file. For this example I’ve put the data inside a CSV file.
Splitting functionality and content might feel like an unnecessary step, but in the long run you’ll be glad you went through the trouble. If we set it up like this it becomes much easier to add several questions and answers in the future without touching the code in the sketch. A similar approach is used for big websites, so content can easily be added, removed or changed without accidentally ‘breaking’ the website.

questions... from external CSV file loaded (p5.js)


Step 7: Dividing your sketch into files

As your sketch grows bigger and bigger, it can be good to split your sketch in multiple files (or tabs if you’re working with the Processing IDE). This principle is similar to the previous step, but instead of splitting functionality and content we’re subdividing functionality.
As an example let’s say you programmed your own calculator. You added tons of mathematical equations, and a nice looking interface so that others can easily use it. If you ever want to make changes to the interface in the future however, it might be troubling to go through hundreds (or perhaps even thousands) lines of code. In this case it might have been handier if you had split the entire program in three separate files/tabs:
  1. The main sketch to control the program flow;
  2. Everything related to the interface design;
  3. The mathematical equations.
If you’re working with P5 and not making use of the Processing IDE, make sure the external JavaScript file is loaded on your HTML page. In the coded P5 example of this step you can see that I included the file myTools.js within the HTML file (in the Web Editor you can show all sketch files by clicking on the little gray arrow right beneath the red play button– the HTML file is called index.html ).
Word caution: If you’re working on your website, be careful not to overdo it with the external JavaScript files. If a user visits your website and he has to download a lot of separate files, it affects the page speed.

easy use code from extra file.js (p5.js)


+ button and sound example (p5.js)

Step 8: Putting it all together

So far we went over various topics of coding. We’ve experimented with different ways to code buttons, got familiar with the idea of setting up a program flow beforehand, and learned how to implement external (data) files. Now that we got all the little pieces to work, it’s a matter of putting them all together.
The example is provided with comments to make it easier for you to see how it’s put together. I won’t go into detail here how I put combined all the little pieces to a functioning quiz system, but there are some points which might be interesting to share:
  1. While putting it all together, I added 3 rounds. For each correct answer he would get points (money). This means a score board had to be added to the sketch.
  2. An unexpected problem occurred with the buttons. I used a class to set up my buttons and added mouse functionality to it. A downside of my interface design however was that once I pressed a button –which instantly loaded the next screen– it also activated the button of the next screen if it happened to be on the same location. This was solved by adding a boolean to the button class.
  3. After going through all rounds, some variables needed to be reset. I did so by adding a reset function which loads once … (?).
all in one (p5.js)


Step 9: add some detail work


- - finally moved the Button class to the /assets/myTools.js file
( you want know what the problem with that was?
for documentation i write a header section how to use it, inside the file say you need to
/* < script src="assets/myTools.js" >< / script > */
when i used it for the function only no problem,
when i put the class inside ?some p5.js or IS or HTML ? went crazy. )
later found if i comment js nested with comment html ok like
/* < !-- < ?? > -- > */

+ set / get $win$ from the CSV ( new column )
and show in button grid ( after selection of STATE 1,2,3 only) and WIN page.

+ prepare 3 text array for category texts.
possibly might also better be DATA ( like from other CSV file? )
but i do not know that game...

final example (p5.js)
JAVA zip all step project

Conclusion

Phew, we’ve done it. If you went through the entire thing you should be more familiar with coding buttons in Processing. Hopefully this tutorial was helpful, and it would be great if you can put this knowledge to good use someday. If you happen to have any questions about it or suggestions to improve it, please feel free to contact me.

text editing by Tiemen de Blanken