while and for loop example

//int x = 0;

void setup() {
  fill(0);
  size(400,400);
}

void draw() {
 background(255,255,255);
 
 /*
 x = 0;
 while(x < width && mouseX > 0) {
   rect(x,0,mouseX/2,height);
   x = x + mouseX;
   println(x);
 } 
 */
 
 for (int x = 0; x < width && mouseX > 0; x = x+mouseX) {
     rect(x,0,mouseX/2,height);
 }
}

Bouncing Code – Start


int rectWidthHeight;

int rectX;
int rectY;

int direction = 10;

void setup() {
 
  println("setup");
  println("width " + width);
  println("height " + height);
  //frameRate(1);
  
  //rectMode(CENTER);
  
  rectWidthHeight = 50;
  
  rectX = mouseX;
  rectY = mouseY;
  
}

void draw() {
  background(120,120,120);

  rectWidthHeight = mouseX;
  
  rect((width/2)-(rectWidthHeight/2),(height/2)-rectWidthHeight/2,rectWidthHeight,rectWidthHeight);

  //println("draw");
  
  if (mousePressed) {
    rectX = mouseX;
    rectY = mouseY; 
  }
  
  if (rectX < 0 || rectY < 0) {
   direction = direction * -1; 
  } 
    
  if (rectX > width) {
       direction = direction * -1; 

  }

  if (rectY > height) {
    
       direction = direction * -1; 
  }
  
  rectX = rectX + direction;
  rectY = rectY + direction;
  
  rect(rectX,rectY,50,50);
  
}

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.

Conditionals

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

If Statement:

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

If Else Statement:

            int anint = 1;
            if (anint >= 0)
            {
                // Excute some code
            } 
            else
            {
                // Execute some other code
            }   

If, Else If, Else:

            int anint = 1;
            if (anint >= 0)
            {
                // Execute some code
            }
            else if (anint < -1)
            {
                // Execute some other code
            }
            else
            {
                // Execute this code if none of the other conditions are true
            }

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
            }        

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);

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

Logical Operators: boolean logic
|| (logical OR)
&& (logical AND)
! (logical NOT)

Truth tables:

Or True False
True true true
False true false
And True False
True true false
False false false

Built-In Variables

mouseX and mouseY:
Define where the mouse (finger) is in relation to the window or screen.
Follow the cursor around:

        void setup()
        {
            size(500,500);
            fill(255,0,0);
            frameRate(10);
        }
        
        void draw()
        {
            rect(mouseX,mouseY,50,50);        
        }

width and height:
Contain the width and height of the sketch window. They are only set after size() is called (in the standard version, with Android it may be set already).

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

More information about the screen dimensions and other built-in variables available on Android can be found on the Processing Android Wiki Page

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).

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 someint = 5;

boolean – True or False. Often the result of an expression.

boolean somebool = true;

float – A number with a decimal point. 1.5, 3.987 and so on.

float somefloat = 99.76;

byte – An 8 bit value. Ranges from -127 to 128 in value.

byte mybyte = -90;

char – A single character.

char mychar = 'A';

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; 

VARIABLE SCOPE

You may have noticed the integer is declared outside of the setup() method we wrote here. This is due to something called variable scope. The concept is that variables are only accessible to the block of code they are defined in.

For instance, if we declared a variable in the setup function, we would not be able to access that variable in the draw function.

Blocks of code are defined by “{” and “}”. 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
        }

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. Local to that block.

A global and a local variable:

        int myint = 90;  // Global
        
        void setup()
        {
            int myotherint = 100; // Local to the setup function
        }

Setup and Draw

Setup and Draw

So far, we have just been writing code without placing that code into any methods.  This is a great way for us to get started but in order to move forward we need to take the next step.

Processing has two special methods that we can define in our sketches.

Setup()
The setup method is run once, at the beginning of the execution of any processing sketch. It is typically used to set things like background, size and other static items.

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

Draw()
The draw method 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():

        int myint = 0;  // Notice this is outside of setup().  You can declare and assign variables outside of setup but you can not call methods or issue other commands outside of a method.

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

Here is a simple draw() which includes some variable usage (see the int myint = 0 line above):

        void draw()
        {
            rect(myint,myint,50,50);  
            myint = myint + 1;
        }

If we copy these lines of code into Processing we will see a rectangle move from the top left of the screen down to the bottom right. 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.

Hello Processing

Processing

Processing is a free and Open Source Java based IDE and an API.

Java is at the lower end of high level languages, it is equally good at many tasks and is easy to understand if you have a background in lower level languages like C as well as for those with higher level language skills (JavaScript, Perl, PHP and so on).

Processing takes this one step further and makes Java useful to those with no or minimal programming experience while leaving in place the full functionality of Java for those with experience.

Download and Install it: http://www.processing.org/

Unless you work on the lab machines only (which have Processing installed already) you will need to download it. (If you are downloading it for Windows, make sure you get the version with Java, not the version without Java.)

IDE stands for Integrated Development Environment. It is the editor you write a program in and the means to compile and test. The Processing IDE is very simple and easy to understand.

Open up Processing and go through the IDE

Try out the commands under the File menu: New, Save, Sketchbook Examples, Export

Try out the commands under the Sketch menu: Run, Stop

Your best friend will be the Help menu: Reference

It has buttons for quick access to: Run, Stop, Export

API stands for Application Programming Interface. It is the code or statements that the language supports. Processing has it’s own language for programming that is based upon Java (actually it is simplified Java). Processing also supports normal Java but we will get to that later.

Modes:

Processing has 3 modes of operation, basic (the mode we will start in), continuous (the mode we will work in most of the time) and Java (the mode we will introduce later in the semester).

In basic mode, you can simply start inserting Processing commands or functions.

Coordinate System:

All programming languages that allow you to draw to the screen use coordinate systems in one form or another. Generally these coordinate systems reference pixels (picture elements).

Processing (and most other languages) reference the 0 point of the window (both x and y axis) as the top left corner and work from there. Going down increases the value of the y axis and going to the right increases the value of the x axis. Therefore the point (10,15) in the form (x,y) would be 10 pixels to the right and 15 pixels down from the top left corner of the window.

Commands:

Make this reference your best friend.

We are going to start with the very basics that you will need to get your homework done.

point(x,y) As the name implies, this draws a point on the screen at the specific x and y coordinates. This is a pixel (picture element).

To write this command in Processing, simply type: point(10,10); and click run. If you squint you can probably a black dot 10 pixels from the top and 10 pixels from the left. Point Reference

You will notice that all commands end with a semicolon. This is a Java standard and consistent through many programming languages.

line(x1,y1,x2,y2) Draws a line from (x1,y1) to (x2,y2). As an example: line(10,15,30,30); draws a line from the point 10 pixels to the left, 15 pixels down to the point 30 pixels from the left and 30 pixels down. Line Reference

size(width, height) Sets the size of the canvas that you are drawing on. size(100,100); would make the canvas 100 pixels wide by 100 pixels tall. Size Reference

background(grayvalue) Sets the background color of the canvas to the specified grayscale value. A gray value of 0 means black whereas a value of 255 means white. background(127); would fill the background with a medium gray color.

background(redvalue, greenvalue, bluevalue) Sets the background color of the canvas to the specified value. Processing (and most other color representations on the computer) use an additive color space. Think of it like the sun, the absense of the sun makes it dark or black whereas full sun light would be white. Colors are mixed out of the additive primaries of red, green and blue. Again, as with the gray scale values, these go from 0 to 255 (which is 8 bits per channel).

You may have noticed that there are two background() functions listed. This means that background() is overloaded. Processing (Java) considers a function to be the total of it’s signature, that is, for our purposes it’s name and the number of it’s arguments. background() with one argument is the first function and background with 3 arguments is the second. We couldn’t have another background that only takes one value but does something other than the the first one.

fill(grayvalue) or fill(redvalue,greenvalue,bluevalue) An overloaded function (like background()) that specifies the fill color for any shape that is to draw on the screen.

noFill() turns off the fill for any shape that is to draw on the screen. The shape will be transparent.

stroke(grayvalue) or stroke(redvalue,greenvalue,bluevalue) Specifies the color to be used for drawing anything to the screen (line, point, shapes).

noStroke() Turns off the stroke color for shapes, effectively making their outline transparent.

rect(x, y, width, height) Draws a rectangle with the specified width and height at the specified x and y position.

rectMode(MODE) MODE can be: CORNERS or CENTER. Changes the mode for drawing a rectagle. CORNERS means that the x and y coordinates specified will be the top left corner or the rectangle. CENTER means that the x and y coordinates specified will be the center point of the rectangle.

At this point, you should be comfortable enough with the reference material to look the following commands up on your own:

ellipse() Ellipse Reference

ellipseMode() EllipseMode Reference

triangle()

Comments

Comments are very important to programming. They allow you and others to understand your code. You should immediately get into the habit of commenting everything you do in Processing.

To create a comment, in your code, simply prepend the line with a double slash “//”.

     // This is a comment

If you are entering multiple lines for a comment, you can start the comment with a slash and asterisk and end with an asterisk and a slash.

     /* Enter comments Here

     More comments */

Errors

At this point you will have undoubtly run upon an error in your code. Processing puts error messages down the red bar between the output window and code window.

Unfortunately, Processing’s error reporting isn’t the greatest in the world and it takes some getting used to to be able to identify the exact error.

For instance: I opened up Processing and typed “test” into the code window and hit run. Processing reported: “unexpected token: test” in the red bar. In other words, Processing didn’t understand “test” as it is not a command in the language.

For another example: I typed “line(10,10,50,50)” leaving out the semicolon.

Processing reported: “unexpected token: null” Meaning: Processing was looking for something but found nothing (null). In this case it was looking for the “;” semicolon.

Processing for Android

Wiki Page http://wiki.processing.org/w/Android

Hello App Inventor

App Inventor

Developed at Google Labs – Donated to MIT with a grant to fund Center for Mobile Learning

Open Sourced: http://code.google.com/p/app-inventor-releases/

What is App Inventor: http://appinventoredu.mit.edu/what-is-app-inventor

2 parts – 1 in browser app designer (google app engine) – 1 blocks editor where you program (amazon build server)

Our own instance: http://nyuadmobilemedia.appspot.com/

Setup

First we have to setup the machine:  http://nyuadmobilemedia.appspot.com/learn/

http://nyuadmobilemedia.appspot.com/learn/setup/index.html

Hello World

We’ll interactively go through a Hello World example