NotesWeek2
Search:
Syllabus / NotesWeek2

Introduction To Computational Media: Week 2

The Fundamentals of Programming

(modified from Shawn Van Every's ICM notes)

Processing Constructs

Processing provides two empty functions that you may define in order to accomplish special things in your program.

Setup() The setup function is run once, at the beginning of the execution of any processing applet. It is typically used to set things like background, size and other items that don't change.

        void setup()
        {
            // YOUR CODE IS RUN ONCE
        }

Draw()

 The draw function is executed in a loop. It is run continuously throughout the execution of the processing applet.

        void draw()
        {
            // YOUR CODE IS RUN OVER AND OVER AGAIN
        }

Here is a common use of setup():

        void setup() {
            size(500,500);
            background(255);  //white bg
            frameRate(30);  // Defines how many times per second draw() will run
            fill(255,0,0);  //red fill
            stroke(0,0,0);  //black stroke
            strokeWeight(10);  //thick stroke
        }


        void draw() {
        	background(255);
            rect(mouseX, mouseY,50,50);  
        }

If we copy these lines of code into Processing we will see a rectangle follow our cursor around the screen. The obvious analogy here is that of animation. The setup function sets up our window and the draw function runs every 15 seconds and gives us the appearance of movement. Processing will attempt to draw the screen at 60 frames/ second unless you define a different frame rate.

Blocks of code are defined by "{" and "}". They allow you, the programmer, to establish a set of instructions as a defined group. Any code that is within the brackets is considered in the same block. Therefore, setup and draw have their own blocks of code.

A code block:

        {
            // Some code
            // Some more code
        }

Printing Text Output println(): println() allows you to print text to the console- the black area at the bottom of the processing application. println() is very useful for debugging and learning the value of a variable.

println(50); Prints out "50".

int someNumber = 10; println(someNumber); Prints out the value of someNumber, or "10".

println("The value of someNumber is: " + someNumber); Concatinates the string specified in "" with the value of someNumber.

Can you guess what this would output to the console?

 void setup() {
  frameRate(5);
  println("a");
  println("b");
  println("c");
  println("done with setup!!");
 }

void draw() {

  println("d");
  println("e");
  println("f");
  println("done with draw.  Looping back!");

}

look up print() on the reference for another console printing option.

Variables

Variables are containers for data. Essentially a variable is something that can hold a value and that value can be changed (They can vary).

We get a few variables for free from Processing. These are referred to as system variables. Here's some of the most common:

 mouseX - the horizontal position of the mouse cursor
 mouseY - the vertical position of the mouse cursor
 width- the width of your window (defined in size())
 height- the height of your window (defined in size())
 key- the most recent key pressed on the keyboard
 mousePressed- true or false?  what the mouse pressed?
 keyPressed- true or false?  was a key pressed?

Data Types: Variables in Processing (and other strictly typed languages) must be defined or declared with their type.

The different (primitive) types that Processing/Java support are as follows:

  • int - An integer. Whole numbers only. int zipcode = 90210;
  • boolean - True (1) or False (0). boolean someBoolean = true;
  • float - A number with a decimal point. 1.5, 3.987 and so on. float temperature = 92.76;
  • byte - An 8 bit value. Ranges from -127 to 128 in value. byte myByte = -90;
  • char - A single character. char myInitial = 'C';

Declaration: Variables must be declared with their type as shown (in the examples above as well as) here:

 int myInteger;
 float yourFloat;
 boolean myBool;

Assignement: Once they are declared, you are free to assign values to them and subsequently use them in operations:

 myInteger = 5;
 myInteger = 5 + 5;
 myInteger = myInteger - 5;
 yourFloat = 5.5;

Of course, as shown in the examples above, you can take a shortcut and do both declaration and assignement in one step:

int someInt = 89;

Random Numbers A great way to make things feel less calculated is by introducing randomness into your code. Processing's random() function will give you a float between 0 and 1 by default. Adding a value to the function, like random(10), will give a float value between 0 and that value. random(-20,15) will give a float value between -20 and 15.

random() example another random() example

generally, random values are used like this: float aRandomValue = random(20); //declares a float called "aRandomValue" and assigns a random number between 0-20

If you declare a variable outside of a block of code- in the main processing code section- it is a global variable. If you declare it inside of a block of code, it is a local variable to that block. It will be erased when it reaches the end of the code block that it was declared in. If you want a variable to be available to other unrelated code blocks, then make it a global variable.

A global and a local variable:

        int myInt = 90;  // Global

        void setup()
        {
            int myOtherInt = 100; // Local to the setup function     
        }

        void draw(){
        	println("myInt is global- "+myInt);
        	//THIS WILL CAUSE AN ERROR!
        	//Because myOtherInt was local in setup(), draw() has no idea
        	//what it is.
        	println("myOtherInt is local- "+myotherInt);
        }

More Built-in Variables mouseX and mouseY: Define where the mouse is in relation to the applet window. Follow the cursor around:

        void setup()
        {
            size(500,500);
            fill(255,0,0);
            framerate(30);
        }

        void draw()
        {
            rect(mouseX,mouseY,50,50);        
        }

width and height: Contain the width and height of the applet window. They are only set after size() is called.

        void setup()
        {
            size(400,200);
            println("The width is: " + width);
            println("The height is: " + height);
        }

Indentataion: Notice above how I indent code that is within the blocks. This is purely for readability and understanding. Do it, you will thank me later. Processing will auto indent for you- select all of your code and choose "auto format" from the tools menu.

Operators: Assignment: =

Mathematical Operators: +, -, /, * (addition, subtraction, division and multiplication)

Example:

        int aNumber = 0;
        aNumber = aNumber + 1;
        println("aNumber = " + aNumber);
        aNumber = aNumber + aNumber;
        println("aNumber = " + aNumber);
        aNumber = aNumber/2;
        println("aNumber = " + aNumber);
        aNumber = 7 * 8;
        println("aNumber = " + aNumber);

        anumber++;  // Short-cut for adding one, called "increment"
        println("anumber = " + anumber);
        anumber--; // Short-cut for subtracting one, called "decrement"
        println("anumber = " + anumber);

Conditionals Execute a block of code based on the result of an expresssion that utilizes relational or logical (boolean) operators

Relational Operators: >= (greater than or equal to) <= (less than or equal to) == (equality) != (inequality)

Logical Operators: Sometime called boolean logic

&& (logical AND) ! (logical NOT)

If Statement:

            int anInt = 1;
            if (anint >= 0)
            {
                println("anInt is greater than or equal to 0");
            }

If Else Statement:

            int anInt = 1;
            if (anInt >= 0)
            {
                 println("anInt is greater than or equal to 0");
            } 
            else
            {
                 println("anInt is less than 0");
            }   

If, Else If, Else:

            int anInt = 1;
            if (anInt >= 0)
            {
                 println("anInt is greater than or equal to 0");
            }
            else if (anInt < -10)
            {
                 println("anInt is less 0 and greater than -10");
            }
            else
            {
                println("anInt is greater than or equal to 0");
            }

You can use the boolean operations to use boolean logic on multiple expressions.

            int anint = 1;
            int anotherint = 2;
            if (anint > 0 && anotherint <= 2)
            {
                // Execute some code
            }        

look at roll over demo and ball bouncing demo source code for some examples on variables and conditionals.

Loops

While: Just as with our conditional (if / else) statements a while loop employs boolean test that must evaluate to true in order for the instructions enclosed in the curly brackets to be executed. The difference is that the instructions continue to be executed until the test condition becomes false.

            int x = 0;
            while (x < 10) 
            {
                println("x is less than 10.");
                x++;
            }

Consider doing a striped background. You could do the following:

	void setup()
	{
	  size(400,400);
	  background(128);
	  stroke(255,0,0);
	  strokeWeight(5);
	}

	void draw()
	{
	 line(0,0,0,height);
	 line(20,0,20,height);
	 line(40,0,40,height);
	 // and so on..

	 // or you could use a variable:
	 int x = 60;
	 line(x,0,x,height);
	 x = x + 20;
	 line(x,0,x,height);
	}	

but that would get very tedious.

With a "while" loop we could do it much more quickly and easily:

	void setup()
	{
	  size(400,400);
	  background(128);
	  stroke(255,0,0);
	  strokeWeight(5);
	}

	void draw()
	{
	 int x = 0;
	 while (x <= width)
	 {
	   line(x,0,x,height);
	   x = x + 20;
	 }
	}

For Loop Since this is a common use of a loop (creating a variable, checking it's value and incrementing by a certain amount) there exists an even quicker way to do the above, all in one step.

          for (int x = 0; x <= width; x = x + 20)
          {
             line(x,0,x,height);
          }

You can read this as, create variable x and set it to 0, while x is less than or equal to the width, do the following. Increment x by 20 at the end. Exactly what we are doing in the while loop but in one quick step.

Search
  Page last modified on September 10, 2007, at 02:54 PM