3. Variables and conditionals

Variables

In Processing, to create a variable you need to define what kind of information that variable is going to hold. The most common are int (integer) float (a number with a decimal) String (text), boolean (true or false) and color (red, green, blue, alpha).

int x = 5; //integer (whole number) called x
 
float var1 = 5.3; //float (decimal) variable called var1
 
String hi = "hello world"; //string variable called hi and containing the phrase "hello world". Note the capital 'S'.
 
color blue = color(0,0,255); //color variable called blue containing the RGB color values for blue
 
boolean finished = true; //this boolean variable is called finished and is set to true.

Declaring and using a Variable

In the example below we create an int called x (it could be anything we want), and give it a value of 200. Then when we make our circle we use the variable instead of a number. Declaring the variable before the setup area means the variable is “global” and accessible throughout the entire sketch. You can also declare a variable within a section, these variables are local. For example, if you declared a variable within setup you would not be able to access it in the draw section.

int x = 200; // "x" is the variable name.
void setup() {
  size(400, 150);
}
void draw() {
  background(255);
  ellipse(x, height/2, 100, 100); //height is an in built variable that automatically updates to the height of the canvas
}

Whup-de-doo right? Well the power of variables is we can change it each time the program cycles through the draw routine.

Add this line inside the draw area and play the sketch.

x = x + 1;

There is a shortcut way of writing the line which is

x++;

The ++ adds 1 to the value of var1 each time through the program. (So when they came out with C++ it was a clever programmer joke – as a rule programmers are hi-fricking-larious.)
To make the ball go faster try

x += 5; // adds 5 to the variable x each time.

If Statements

But how do we get our ball back? We need an “if” statement.

int x = 200;
void setup() {
  size(400, 150);
}
void draw() {
  background(255);
  x++;
  ellipse(x, height/2, 100, 100);
  if (x == width) { // the test
  x = 0; // send the ball back to zero
  }
}

Inside the parenthesis are the conditions of the if statement, the test for if it is true or not. If it is true, the code within the curly brackets will run. You can have more than one test, and more than one result of the test.
Notice the double “==” sign? One = means we are assigning the variable to a new value and a double == means we are comparing one side to the other. This is one of the most common mistakes you will make. When this happens you will get an error message that says something like “you cannot convert from int to boolean” – meaning the program thinks you are using the = to set something to something else and it doesn’t like it.

In the following code we are checking the condition of the variable x with two tests. The && means “and” (called a “logical and”) so that in order for the statement to be true x has to be greater than 1 AND less than 20. Both tests need to be true. If they are then the fill will be red and the stroke will be yellow.

if(x>1&&x<20){
  fill(255, 0, 0); //if both tests are true, run this code
  stroke(0, 0, 200);
}else{
  fill(255, 255, 0); //if one or more is not true, run this
  stroke(0, 255, 0);
}

When an else statement follows an if statement, the block of code following else, (the code in the curly brackets) will run when the if statement is not true. If you say it in your head,

if (this is true) {
do this!
}else{
do this instead!
}

In the above code, instead of test1 && test2 we could have written test1 || test2. The two upright slashes are the symbol for “or” (it is not a letter l). So if test1 OR test 2 is true, run the code in the following brackets.

These symbols allowing us to use two if statements are called logical operators. They are:

//LOGICAL OPERATORS ALLOW US TO USE TWO TESTS
if(test1 && test2) {   //AND - both have to be true
if(test1 || test2)  {  //OR - either test one or two have to be true

Bouncing Ball

If we want our ball to ‘bounce’. We have to find a way to reverse its direction to move it back the other way. That is instead of adding 1 to the x position each time, we need to also be able to minus 1 each time.
So in this line, the 1 is defining the speed of the ball.

x=x+1;  //remember we can shorten this to x++ too

If we want to be able to change the speed from 1 to -1 we need to make this a variable called speed

x=x+speed;

Then later in the code, when the ball hits the edge of the screen, when x==width, we need to change speed from 1 to -1 so that it goes back the other way. Remember we can do this by multiplying the speed by negative 1, to make it negative.

speed = speed*-1;   //new speed = old speed multiplied by -1
//CONDITIONALS AND VARIABLES
//Declare and assign an initial value to our variables
float x = 0;
float speed = 2;
 
void setup(){
  size(400,150);
  smooth();
  //set the fill to red
  fill(255,0,0);
}
 
void draw(){
  //refresh the background
  background(255);
  // Increase the x position by speed for each loop of draw
  x = x+speed;
  //check if the ball has moved outside of the screen with an if statement
  //this means if((TEST1)OR(TEST2)){ 
  // the || means OR and the && means AND
  if((x==width)||(x==0)){
 //if it is we will change the speed to send it back the other direction
 // we do this by multiplying speed by negative one to change it's directino.
    speed = speed * -1;
  } //close the if statement
 
  //Use the variable to draw the ball to a new position
  ellipse(x,75,20,20); 
}

Exercise: Introduce an y variable to this code to change the vertical motion of the ball. Change the y variable so that the ball moves in the vertical direction too.

Can you write conditional statements for the vertical dimension to keep the ball on the screen?

More tutorials on conditionals are:

System Variables

We have already been using variable like mouseX and mouseY. Processing has a set of convenient system variables freely available. These are commonly needed pieces of data associated with all sketches (such as the width of the window, the key pressed on the keyboard, etc.). When naming your own variables, it is best to avoid system variable names, however, if you inadvertently use one, your variable will become primary and override the system one. Here is a list of commonly used system variables (there are more, which you can find in the Processing reference).

  • width—Width (in pixels) of sketch window.
  • height—Height (in pixels) of sketch window.
  • mouseX – X mouse position
  • mouseY – Y mouse position
  • frameCount—Number of frames processed.
  • frameRate—Rate that frames are processed (per second).
  • screen.width—Width (in pixels) of entire screen.
  • screen.height—Height (in pixels) of entire screen.
  • key—Most recent key pressed on the keyboard.
  • keyCode—Numeric code for key pressed on keyboard.
  • keyPressed—True or false? Is a key pressed?
  • mousePressed—True or false? Is the mouse pressed
  • mouseButton—Which button is pressed? Left, right, or center?

 

Printing

keeping track of your variables can be tricky. fortunately you can easily “print” your variables as the sketch runs. Add the line

println(x);

to your sketch and the value will be printed out at the bottom of the programing window. You can write a a phrase by putting it in quotes

println("joe is good");

or you can combine variables and phrases with the “+”

println("the value is" + var1);

Random

Random will return a random(ish) value as a float.

float randomX;
 
void setup() {
  size(400, 400);
}
 
void draw() {
  background(255);
  randomX = random(400); // creates a random number between 0 and 400
  println(randomX);
  ellipse(randomX, 250, 100, 100);
}

If you want to turn the results into an int (whole number) you need to convert the float to an int. To do this put the float value inside an int() argument – here’s an example.

float randomX;
int num;
 
void setup() {
  size(400, 400);
}
 
void draw() {
  randomX = random(5, 10);
 
  num = int(randomX);
  println(num);
}

Notice that the number is between 5 and 9 – this is because converting to an int rounds DOWN the float. So a float that is 9.9999 will be 9 when converted to an int.

Video tutorial on random here.

Using Booleans

A boolean is a variable that has only two states, true or false. Unless you declare a boolean to be true, the default will be false.

color RanColor;
boolean goCrazy;
 
void setup() {
  size(300, 300);
  RanColor = color(200, 10, 189);
}
 
void draw() {
  background (RanColor);
  if (goCrazy == true) {
  RanColor = color(random(255), random(255),   random(255));
  }
 
if(mousePressed){
  goCrazy = true;
  }else{
  goCrazy = false;
  }
}

Color variable

There is a special variable just for color.

color pinkcolor = color(255, 50, 100);
void setup() {
  size(400, 400);
}
void draw() {
  background(255);
  fill(pinkcolor);
  ellipse(200, 250, 100, 100);
}

you can extract just the red green or blue colors from the color variable with red(), green() and blue().

color pinkcolor = color(255, 50, 100);
void setup() {
  size(400, 400);
}
void draw() {
  background(255);
  fill(pinkcolor);
  ellipse(200, 250, 100, 100);
  float r = red(pinkcolor);
  println(r);
}