Coding a Calculator in P5.js
by The_Tech_Lab in Circuits > Computers
1310 Views, 1 Favorites, 0 Comments
Coding a Calculator in P5.js
Calculator is a really handy and easy tool. They are even easier to code on your website, whether you have an e-commerce website or just a portfolio website, calculators are a great way to start the skill showcase. In this tutorial, you will learn how to code a fully functional p5.js calculator. Let’s get right down to work!
User Interface
Normally on a day to day basis everyone uses a basic calculator. For keeping track of ledgers and other business transactions, you need something more advanced than the normal calculator. Scientific calculator is the best friend of the mathematics whiz and the engineering students. But, our calculator is the normal basic calculator one will find in phones which resembles the iOS calculators pretty accurately.
We chose this as our calculator because this is a widely known UI and very easy to code for beginners. If someone wants to make it more advanced they can follow our guidelines and go from there. Look for the suggestions below. The user interface is very easy to your eyes. Nothing fancy and crazy going on in the calculator. The UI is very easy to code and very beginner-friendly. This is good for practice and for use on websites. You can also improve the code to suit your needs. The UI is simple and clean and it resembles the calculator in iOS. If you have always wanted to make the calculator in Apple products, this would be the perfect guide since it is very much like that one. The tutorial is easy to follow and you can easily make your own version of the calculator.
Coding Environment
As we were working on a team with members from different places around the country, we needed a virtual coding environment where anyone could work at any time. We picked Repl.it
Repl.it lets us code on the same project as a team and has easy access to many programming languages, all while being virtual. We don’t even need a powerful computer to run the codes as it all happens on cloud. For the programming language, we wanted to go with JavaScript to build a nice looking UI with ease. It might have been a little hard with ordinary JS but with the p5.js library, making the UI became much easier.
The Main Code
The code for this project is much easier than one would imagine. You could take a look at our code on repl.it here. If you want to understand the code better, follow us along as we explain all the functions.
Functions:
The key functions in this program are as follows:
- keyPressed: Detects keyboard key presses. Our calculator works with both mouse and keyboard and this function detects all the key presses i.e. numbers, operators, backspace and equal key etc. We detect the keys with the keyIsDown() function of the p5.js library. We used Keycode to find the keycode for each key that we were going to use.
-
mousePressed: Detects mouse clicks on the user interface. The user can click on any button to use it’s function. This function also enables touch interface for touch screen devices. It consists of a whole bunch of if statements to check where the location of the cursor is when the mouse is clicked, then does the certain function of the button underneath the cursor.
-
Calculate: This is where all the magic happens. All the calculations take place here once the user clicks the equal sign. The program takes the input String, splits it where the operators are, and puts them into an array called "value". After that, the function uses a switch case statement to do the calculation for each operator.
-
checkMultipleOpt: This function checks if the user has used multiple operators before pressing the equal button. If you check your phone calculator, you will notice (well, at least for most of the iPhones and Androids) that when you use multiple operators in a single input, it calculates the first operator's output and uses it as the input of the second operator. This is exactly what this function in our code does. It simplifies using multiple operators and we don’t need to use any calculating tricks like BODMAS or PEMDAS.
-
drawCalculator: As the name says, this function draws the calculator UI. It works with two for loops, one for the horizontal lines and one for the vertical ones, paired with some fill and line functions.
-
drawButtons: Again, as the name suggests, this function draws the buttons on the UI. It draws the button texts to be exact. The texts are stored in the "buttons" array at the beginning of the code.
-
updateDisplay: This is just what runs in our draw loop. Here we update the input and output string on the display of our calculator.
Obstacles and Tips
If you think this tutorial took us just a few hours to do then you are completely wrong. We just like you are beginners and so have faced our fair share of problems. Below are some problems we faced while making this tutorial:
Finding the center and line coordinates took a lot of trial and error. Recommendation: Try to map it out the numbers on a piece of paper before writing in the actual code. Using percentages scales itself to window size.
Fingering out the mouse coordinates is something we struggled to find. We averted the problem with multiple if statements but this method is not efficient.
No built-in button feature in p5.js library, like the general HTML+JS add button function.
We have an auto zero which isn't a problem but technically a bug. The input was given as zero that is why this automatic zero.
Finding the operator in the inputString was a challenge. We thought of multiple ways including going through all the characters with for loop, using substring function etc. In the end using .split() seemed to work the best.
Fetching the input variables from a string. We forgot to mention which substring it was we were trying to remove(while scrolling). Recommendation: write comments for every section of the code.
Some other common problems:
For loop TypeError. X had to be reset to 0.
Same name variable caused error (can be fixed).
Had to add space after 0 for a wide button.
Detecting shift key.
Possible Improvements - Hacks and Mods
Now, as you can see you have a calculator which very much resembles what we made - if you followed our tutorial carefully. But, as always you can flaunt your skills even more by making some slight changes to the calculator.
Some possible suggestions are given below. Do check them out.
Sound effects can be added to the calculator to make a click sound while you type or click. This can surely make the experience pleasant.
You can add more functions to the calculator making it more scientific from basic by adding trigonometric values, logarithmic functions, binomial, permutations and if you are bold enough differential functions such as integration and differentiation. Play around to see what you can do and what suits your needs.
You can change the color and make it absolutely unique from the others. Custom colors are really easy to give just play around with the color codes.
You can add animation to enhance the user experience. For eg; when you hover over the keys use a mouse to give a special effect before being clicked. Just think outside the box.
You can fiddle around with the code to make it efficient. As beginners ourselves, some of the code is not efficient. See what you can do to reduce the line of codes. Being able to reduce lines of code, showcases talent and your skills. Hence, if you use it in a portfolio it will surely make an impression on the visitor.
Thank You for Reading
This marks the end of the tutorial. Hope you had fun making the calculator as much as we did. The best way to learn programming is to understand codes and to learn to modify them. We encourage you to go ahead and start tinkering with our code.
Do check us out on your socials below and check out the official website to see what we are doing next for you. Stay with us for more amazing tutorials we have yet to come, till then keep coding.
Written by Iqbal Samin Prithul, Nourin Siddique Ananna and Addittya Saha under Apprenticeship Programme at The Tech lab.
The Tech Lab is an EdTech startup helping kids and teens by making engineering fun for them, unraveling their interest in robotics, game development and 3D design. For more information, visit the website or contact us through Facebook.
Website - www.thetechlab.website
Facebook Page - www.facebook.com/thetechlab