Intro to Processing

Intro to Programming Logic COMP-1029

Red River College

Introduction

Path

“The journey of a thousand miles begins with one step.” – Lao Tzu

Here begins your journey into the Java programming language by way of Processing, an open source programming language and environment for people who want to program images, animation, and sound.

“Focus on the journey, not the destination.

Joy is found not in finishing an activity but in doing it.” – Greg Anderson

Objectives

Upon completion of this module, you should be able to:

What is Source Code?

Source-code

Source code is a special kind of written document through which a programmer can control a computer.

Most source code is simply text made of letters, numbers and symbols. It can therefore be viewed and edited using any text-editor. However it is sometimes helpful to use an Integrated Development Environment (IDE), a program that allows you to both edit and run your source.

Processing programs are called sketches and are composed of one or more source code files. We can run and edit these sketches using the Processing IDE called the PDE (Processing Development Environment).

Conventions

All source code in these notes will be syntax highlighted like so:

smooth();
ellipse(50, 40, 60, 60);
ellipse(31, 40, 16, 32); 
ellipse(69, 40, 16, 32); 

Creating Processing Sketches

Processing comes bundled with an IDE for editing and running your sketches. It also comes with a large number of example sketches that you can read through and run.

When you launch Processing you are presented with a blank unnamed sketch. You can save the sketch using the file menu or by pressing CTRL-S.

The first time you save a sketch the IDE may ask you where you wish all your sketches to be saved. I recommend saving your sketches to a folder within your “My Documents” folder.

Open Processing and save the empty sketch as “first sketch”.

Commenting Code

Comments are lines of source code that are ignored by the computer but are important for people.

Comments let us write notes to ourselves and to any others who may read our code. These notes allow us to document our design decisions and to explain complex portions of our source.

Source documents often begin with a collection of comments explaining the purpose and functionality of the code. These comments may also show who created the code, when it was created, when it was modified and by whom.

Single and Multi-Line Comments

Single lines of text can be flagged as comments by place two forward slashes at the start of the line. There must not be any spaces between the slashes.

// This is a single-line comment.

A forward slash followed by an asterisk allows a comment to continue across multiple lines until the comment is “closed” using an asterisk and a forward slash.

/* This is a multi-line comment.
   As you can see the comment does
   indeed span multiple lines. */

Adding Comments

Let’s add a multi-line comment block to the top of our first sketch.

/**************************************************
 * Description: This is my first sketch.          *
 * Created By: Kyle Geske                         *
 * Created On: November 9th, 2009                 *
 * Modified On: ---- by ----                      *
 **************************************************/

Note: All but two of those asterisks are required. Which ones?

Using Built-In Functions

Add the following to your first sketch:

ellipse(50, 40, 60, 60);

Run your program and you will see that we are providing Processing with a command to draw an ellipse. We will refer to commands in Processing as functions. Functions are the verbs of computer programming, they do things. When use a function we are said to be “calling the function.”

Some functions require that we specify arguments that control how the command will be executed. The ellipse function above requires four arguments. Can you figure out what each argument means?

Statements - Sentences in Code

Add the following to your sketch:

line(20, 10, 80, 70);

If this function is to be seen as a verb then the entire line of source code can be seen as a sentence.

All sentences in Processing must end in a semicolon. As we will soon see, there are different kinds of Processing sentences beyond function calls. We will refers to sentences in Processing as statements.

Try running a sketch with one of the semicolons missing.

Expressions - Phrases in Code

In human language a number of phrases can be combined to form a sentence. The Processing equivalent of phrases are called expressions.

Expressions are often combinations of operators such as +, *, and / along with values on which to operate. An expression always has a value, determined by evaluating its contents.

ExpressionValue
1212
7 * 7 - 742
(3+2) * -10)-50

Boolean Expressions

Expressions can also be used to compare values using comparison operators that return Boolean values.

ExpressionValue
8 > 2true
89 < 4false
23 == 23true
23 == 24false
23 != 24true

Note: The double equals signs test for numeric equivalence. The exclamation mark equals tests for non-equivalence.

White Space

In many programming languages, Processing included, the amount of whitespace between elements of a program can be arbitrary.

Currently your sketch contains the following code:

ellipse(50, 40, 60, 60);
line(20, 10, 80, 70);

The program would run the same way had we typed:

ellipse
(    50,40    ,60,      60)             ;
line   (20,10,      80, 70)
;

Of course, we want our source code to be as readable as possible, so try not to get too fancy with your whitespace.

Variables Hold Data

Processing allows us to remember specific data using variables. We can think of variables as containers for storing data. Before we can use a variable we need to assign it a name along with a type. The type specifies what kind of data a particular variable can store.

Here are some common variable types:

NameSizeValue Range
boolean1 bittrue or false
byte8 bits-128 to 127
char16 bits0 to 65535
int32 bits-2,147,483,648 to 2,147,483,647
float32 bit-3.40282347E+38 to 3.40282347E+38
color32 bit16,777,216 colours

Variable Creation

A variable needs to be declared before it can be used. The declaration specifies the variable’s name and type.

int x;   // Declares a variable named x of type int
float y; // Declares a variable named y of type float
x = 50;  // Assigns the value of 50 to the variable x
y = 2.5; // Assigns the value of 2.5 to the variable y

Once a variable is declared we can assign it a value using a single equals sign.

Note: Both the declaration and assignment of variables are statements and therefore need to end with semi-colons.

Variables can also be assigned values at the same time as they are declared:

int x = 50;
int y = 2.5;

Be Careful: A common novice programming error is to confuse the double equals operator that tests for equality with the single equals assignment operator.

Variable Naming

Variable names should be chosen so that they accurately describe their content. This makes our programs easier to read by humans.

Variables names should begin with a lowercase letter. If a variable name is composed of multiple words the words should be combined with the first letter of each additional word capitalized.

sampleWeightInKilograms = 2.4;
usersAgeBeforeSpaceFlight = 32;

Rules for naming variables:

  • The first character must be a lower-case letter, not a number.
  • Remaining positions can be filled with numbers or letters and “_”
  • Variable names cannot contain spaces.
  • Variables are case-sensitive. They must be written the same way every time. (For example, the variable Pizza is not the same as pizza.)

Common Variable Errors

When working with variables there are some common errors we encounter when we attempt to:

No Variable Re-Declaration

Once a variable has been declared it may never be re-declared to change it’s type or to reset it’s value.

int x = 5;
float y;

float x; // This declaration will trigger an error.
float y; // Error: Even though the type is the same.

Incorrect Variable Type

Attempting to use a variable with data of an incompatible type will trigger an error.

int whole_number;
String a_sentence;

whole_number = "Five"; // Error: An int cannot be a string.
a_sentence = 5; // Error: A string cannot be an integer.

Numeric Truncation

Some numeric data can be shared amongst different types, but we may loose some accuracy.

int whole_number = 5;
float decimal_number = 10.12;

println(decimal_number);  // Prints 10.12
whole_number = decimal_number; // Error: Incorrect type

println(whole_number / 2); // Prints 2! Truncated.
whole_number = (int)decimal_number; // Convert the float to an int.
println(decimal_number); // Prints 10

Note: The decimal place values were truncated when we converted the float to an integer.

Built-in Variables

There are a number of variables provided by the Processing environment. These built-in variables provide access to system properties like the position of the mouse, the size of the drawing window, and the state of the keyboard.

For example:

Incrementing and Decrementing

A common occurrence in programming is the act of incrementally adding or subtracting one from a variable.

int x = 10;
int y = 10;

x = x + 1;
y = y - 1;

println(x); // Prints 11
println(y); // Prints 9

x++; // A shortcut for x = x + 1
y--; // A shortcut for y = y - 1

println(x); // Prints 12
println(y); // Prints 8

Printing to the Console

The built-in print() function can be used to print out information to the Processing console. The console is the black text area below the source code window.

The println() function is identical to the print() function but it also moves the cursor to the next line after printing.

print("The ");
print("rain ");
print("in ");
println("Spain"); // Go to a new line after printing Spain.
print("falls mainly on the plain.");

Output:

The rain in Spain
falls mainly on the plain.

Printing Variables

The print() and println() functions can also be used to print out the contents of variables.

int apples = 5;
float gravity = 9.81;
println(apples);
println("Apples: " + apples);
println("Gravity on earth is " + gravity + " m/s^2");

Output:

5
Apples: 5
Gravity on earth is 9.81m/s^2

Note: The addition operator in the last two lines in the above source-code appends the content of a variable to the quoted text. This operation is called concatenation.

Input/Output = Yin/Yang

Ying-yang

Think back to the “How Computers Work” module:

Input and output devices (I/O devices) allow data from the outside world into and out of the computer system.

We can control keyboard and monitor I/O using Processing in much the same way we did using Scratch. To do so you will need perform a bit of setup work.

I/O Additional Setup Step

Library

When you want to work with I/O you need to add an extra library to your processing sketch. Libraries are pre-written pieces of source code that add capabilities to your sketches.

To add I/O capabilities to a sketch:

  • Download this file: ask.jar (Located in Learn in the “Basic Operations module.”)
  • Create and save a new Processing sketch.
  • Drag and drop the downloaded file to the Processing Development Environment with your sketch open.

To ensure these steps have worked, check the folder where your sketch is saved. It should now contain a sub-folder named code containing a single file named ask.jar.

IMPORTANT: Every time you start a new sketch that requires keyboard based I/O you must repeat these instructions.

Asking for Strings

We can now use this Ask file to ask for input. To use this input, we must store the input to a variable. For example, here’s the code to ask for a String:

String name = Ask.forString("What is your name?");
println("Hello " + name + "! It's nice to meet you.");

If this code does not run it means you did not properly follow the steps on the previous slide. Ask your instructor or EA for assistance if you cannot get this code to run! :)

Asking for Numbers (int)

When using Ask.forString the user response is returned to us as a String.

If we wish to retrieve an integer you can use the Ask.forInt function.

int celcius = Ask.forInt(answer); 

int fahrenheit = celcius * 2 + 32;

println("It's " + fahrenheit + " in Fahrenheit.");

Asking for Numbers (double)

The previous code converted a string to an int. This next code will gather to doubles using the Ask.forDouble method.

double distance = Ask.forDouble("How far are you going? (km)");
double speedLimit = Ask.forDouble("How fast can you go? (km/hr)");  

// Calculate the lenght of the trip.
double lengthOfTrip = distance / speedLimit;

// Print out the trip length.
println("This trip will take you " + lengthOfTrip + " hours.");

Static Sketches

Capture

All the sketches we’ve seen so far have been examples of static sketches.

A static sketch is written as a series of statements. When executed, each of these statements is executed in order starting at the top of the sketch. The code displayed to the right is an example of a static sketch.

Other than requesting input using the Ask functions, static sketches are not interactive.

Interactive Sketches

Interactive sketches can be created by adding two specific sections to your code, a setup function and a draw function.

Here’s an example:

void setup() 
{
  size(640, 360);
  background(102);
  stroke(255);
}

void draw()
{
  ellipse(mouseX, mouseY, 5, 5);
}

The code within the curly braces below void setup() will run exactly once. The code with the curly braces below void draw() will run over and over, until you stop the sketch with the stop button.

What's Next?

In upcoming modules and assignments we will learn about: