CCA Programming for Art and Design, Fall 2015

SCIMA-200-16 (2758) Programming for Art & Design
Fall 2015
Tuesday 7:15 PM – 10:15 PM
Graduate Center Complex Bldg 1, Room GC7

Jump to current homework assignment

Instructor: Michael Shiloh
mshiloh@cca.edu
Office hours: By appointment. Email me to set up an appointment
Support:
Programming coaches are available from the Learning Resources Center.

Class blog (this document, in case you have a paper copy): http://teachmetomake.com/wordpress/cca-programming-for-art-and-design-fall-2015

Course Description:
SCIMA-200 courses provide students with foundational knowledge of major scientific/mathematical ideas and applications. They seek to communicate-especially to practicing artists and designers-the scope, power, limitations and appeal of math and science.

Section Description:
This course will provide students with the opportunity to learn programming principles through the creation of procedural and interactive works. Students will experiment with a variety of programming concepts while building an understanding of programming as an artistic/design tool. Upon completing the course, students will have both the understanding of core concepts and the practical experience needed to begin incorporating programming into their personal practice.

Requirements:

  • Prior programming experience is not required
  • High school level algebra is required
  • A laptop is required

Learning Outcomes:

  • Understand basic programming concepts such as:
    • variables and data types
    • conditional statements and loops
    • functions and objects
    • events
    • arrays and data streams
    • libraries and APIs
  • Understand relevant math concepts including:
    • geometry (Cartesian coordinates, vectors, circles, rectangles)
    • trigonometry (Pythagorean theorem and law of sines)
    • statistics (basic probability and random numbers)
    • discrete math (basic logic, boolean and basic algebra)
  • Create interactive media (i.e. games, visualizations, interactive art, nonlinear narratives, etc)
  • Understand and modify other people’s code to make it work for you
  • Understand how to debug programs including:
    • how to look at the difference(s) between the desired behavior and the observed behavior, and to use this information to find the error(s)
    • how to observe variables and other internal information from a program
    • how to deduce which variables and other internal information, and at what point in the program, will be helpful in exposing the error(s)
    • How to reduce an error to the least amount of code needed to reproduce it
  • Collaborate and share ideas easily with programmers in your field by writing clear and well documented programs
  • How to best take advantage of the many libraries, programs, and examples available on the internet, and how to “pay forward” this generosity by documenting your work so it might be useful to others

Syllabus: The syllabus for this class consists of this blog and this generic part

Homework: All homework assignments will be posted on this blog page.

Week 1 Tuesday, September 1

Lecture

  • Review syllabus
  • Where are you
    • programming
    • math
  • Intro to Processing
    • Examples
      • planets
      • http://processing.org/examples/
        • form -> star
        • basics -> transform -> arm
        • structures -> createGraphics
      • Explore; What did you find that was cool?
    • Intro to programming
      • Analogy: washing hair
      • Processing:
        • sketch_001:
          void setup() {
            // parameters are x coordinate, 
            //    y coordinate, 
            //    x size, 
            //    y size
            ellipse( 15, 15, 30, 30);
          }
        • sketch_002 change size of canvas:
          void setup() {
          
            // size of canvas (x, y)
            size(1024, 768);
          
            ellipse( 100, 200, 30, 30);
            // can change location and size
            // can also make multiple objects
          }
        • sketch_003 mouse variables, draw function:
          void setup() {
            size(1024, 768);
          } 
          
          // draw() is like making a drawing on a new
          // page in a flip book
          void draw(){
          
            // draw circle wherever the mouse is
            ellipse( mouseX, mouseY, 30, 30);
          }
        • sketch_004 our own variable that varies with every frame:
          void setup() {
            size(1024, 768);
          } 
          
          int myX = 0; // Create a variable and put 0 in it
          
          void draw(){
            // draw circle 
            ellipse( myX, 300, 30, 30);
          
            // change the x coordinate so that 
            // on the next frame 
            // it will be in a different place; 
            // this makes it appear to move
            myX = myX + 1;
          }
        • sketch_005 change color of pen; erase behind us:
          void setup() {
            size(1024, 768);
            // change color of pen
            stroke(255,0,0);
          } 
          
          int myX = 0;
          
          void draw(){  
            // clear the background 
            // before drawing each frame
            background(255);
          
            // draw circle 
            ellipse( myX, 300, 100, 100);
          
            // change the x number so next frame 
            // it will be in a different place
            myX = myX + 1;
          }

 

Homework 1 due Tuesday, September 8, at beginning of class

  1. (4 points) Create an online presence in any form that allows uploading text, images, videos, and code (programs). Options include but are not limited to WordPress, Instructables, Medium. Things I’ve heard might be good but have never tried include Tackk and Tumblr. All of your homework is to be presented here.
    1. Introduce yourself, and briefly describe your interests and projects (Grading rubric: Did it? One point. Didn’t do it? Zero points.)
    2. Upload one of the sketches we did in class. Make sure it is formatted correctly. (Grading rubric: Formatted correctly: 3 points. Uploaded but not formatted correctly: 1 point. No sketch: no points.)
    3. Send me a link to your online presence
  2. Install Processing on your laptop. Describe any problems you had, and how you overcame them.
  3. (12 points) Read and do the following tutorials. For each tutorial, note
    1) Three things that you feel are important (1 point per tutorial)
    2) Two questions (1 point per tutorial)
    3) One thing that you’d like to learn more about (1 point per tutorial)

    1. Hello Processing
    2. Getting Started
    3. Coordinate System and Shapes
    4. Color
  4. (20 points) Write a processing program which will create a simple drawing using lines, ellipses, and rectangles, and whatever else you want.
  5. Optional: If you know how to program I encourage you to add the following features:
    1. Some of your picture should change depending on mouse position and/or button clicks, like example sketch_003 I showed in class
    2. Some of your picture should change with every frame, like example sketch_004 or sketch_005 I showed in class

    The change can be to position, size, shape, etc. of any of the objects in your picture

  6. (5 points) Make sure your name is in your program

Week 2 Tuesday, September 8

Intro

  • Review homework
    • Online presence
    • Uploading of sketch
    • 1-2-3 for each tutorial
    • Run drawing program
    • Verify name is in the program

Lecture

  • Review variables
  •  Functions
    • Built-in functions like ellipse(), size(), and stroke()
    • Functions you define like setup(), and draw()
    • Functions might take one or more parameters like size(), and stroke(), or they may take no arguments
    • When you define a function, the variables that represent the values that will be passed to it for processing are called parameters. For example, the following function definition has one parameter called number:
      int doubleIt(int number) {
        int answer;
        answer = number + number;
        return answer;
      }

      However, when you use a function, the value you pass to it is called an argument. So, in the following case, price is passed as the argument to doubleIt():

      void setup() {
        int price = 50; 
        int inflated_price = doubleIt(price);  // 100
        println (inflated_price);
      }
    • Don’t worry too much about the names. I get them mixed up all the time. The important thing is to understand the difference: One refers to information you provide to a function when you use it; the other refers to the variables that contain that information within a function, so that you can use that information before knowing what it will be.

Homework 2 due Tuesday, September 15, at beginning of class

Review

Consider this program:

void setup() {
  size(500, 500);
}

void draw() {
  // draw a square
  rect(100, 100, 100, 100);
  
  // put a circle in the square
  ellipse( 150, 150, 80, 80);
}

Suppose you wanted to make 4 of these in different places. The brute force approach is to use rect() and ellipse() 4 times:

void setup() {
  size(500, 500);
}

void draw() {
  // draw a square
  rect(100, 100, 100, 100);
  
  // put a circle in the square
  ellipse( 150, 150, 80, 80);

  // draw a square
  rect(100, 200, 100, 100);
  
  // put a circle in the square
  ellipse( 150, 250, 80, 80);
  
  // draw a square
  rect(200, 100, 100, 100);
  
  // put a circle in the square
  ellipse( 250, 150, 80, 80);  
  
  // draw a square
  rect(200, 200, 100, 100);
  
  // put a circle in the square
  ellipse( 250, 250, 80, 80);
}

A nice way to do this is to create a function, but how do you tell the function
where to draw the square and circle? Let’s first modify the program above a little bit. Pay careful attention to how this is done:

void setup() {
  size(500, 500);
}

void draw() {
  
  int x, y;
  
  x = 100;
  y = 100;
  // draw a square
  rect(x, y, 100, 100);
  // put a circle in the square
  ellipse( x + 50, y + 50, 80, 80);

  x = 100;
  y = 200;
  // draw a square
  rect(x, y, 100, 100);
  // put a circle in the square
  ellipse( x + 50, y + 50, 80, 80);
  
  x = 200;
  y = 100;
  // draw a square
  rect(x, y, 100, 100);
  // put a circle in the square
  ellipse( x + 50, y + 50, 80, 80);
  
  x = 200;
  y = 200;
  // draw a square
  rect(x, y, 100, 100);
  // put a circle in the square
  ellipse( x + 50, y + 50, 80, 80);
}

Can you spot the difference? If not, look again very very carefully. Run the program to convince yourself that it draws the same picture.

Notice that some lines are identical for each segment:

 // draw a square
  rect(x, y, 100, 100);
  // put a circle in the square
  ellipse( x + 50, y + 50, 80, 80);

These lines are an excellent candidate for a function:

// draw a circle in a square
void circleInSquare(int x, int y) {
  // draw a square
  rect(x, y, 100, 100);
  // put a circle in the square
  ellipse( x + 50, y + 50, 80, 80);
}

And we use the function like this:

void setup() {
  size(500, 500);
}

void draw() {
  
  int x, y;
  
  x = 100;
  y = 100;
  circleInSquare(x, y);

  x = 100;
  y = 200;
  circleInSquare(x, y);
  
  x = 200;
  y = 100;
  circleInSquare(x, y);
  
  x = 200;
  y = 200;
  circleInSquare(x, y);
}
  
// draw a circle in a square
void circleInSquare(int x, int y) {
  // draw a square
  rect(x, y, 100, 100);
  // put a circle in the square
  ellipse( x + 50, y + 50, 80, 80);
}
  1. Using the above review as a model:
    1. (10 points) Write a short program that draws a simple triangle using 3 lines
    2. (10 points) Modify your short program so that it draws 5 triangles in different places, using the brute force method.
    3. (10 points) Modify your program to use variables, so that each triangle looks something like this:
        line(x, y, x, y+50);
        line(x, y+50, x+50, y+50);
        line(x+50, y+50, x, y);
    4. (20 points) Finally, create a function from the common lines and use this function to draw your 5 triangles

Announcement

On Friday September 11 I will hold my office hours in the Architecture studio on the second floor of the main SF building at the corner of 8th Street and Irwin. This is opposite computer lab A, which you can find on this map.

Week 3 Tuesday, September 15

Intro

  • Review homework
    • A, B, C, and D above

Lecture

  • Functions
    • Review
      • Functions that take arguments
        (homework examples)
      • Functions that take no arguments
        void makeBackgroundRed() {
          background(255,0,0);
        }
        
        void draw() {
          makeBackgroundRed();
        }
        
    • Functions that return something
      int doubleIt(int number) {
        int answer;
        answer = number + number;
        return answer;
      }
      
      void setup() {
        int price = 50; 
        int inflated_price = doubleIt(price);  // 100
        println (inflated_price);
      }
  • What is the meaning of void setup() and void draw()?
  • Variable types
  • Loops
    • Short lab: Write a simple Processing sketch that will draw 3 lines starting at the same point but ending at different points
    • Imagine now that you want to draw 100 such lines. It’s possible but very tedious. Wouldn’t it be nice if the Processing program could automate that for you somehow?
    • Introducing the for() loop
      • Relational Operators e.g. >=
    • Short lab: Make a drawing using two (or more) loops
      faceUsingTwoProcessingLoops

Homework 3 due Tuesday, September 22, at beginning of class

  1. Read Daniel Shiffman’s Objects tutorial
  2. Read and run the examples from this simple Processing class example.
    1. Try to understand the examples. Make a list of questions you have regarding the examples.
    2. (10 points) Modify the last examples to draw cubes instead of circles
    3. (10 points) Add a third ball (or cube) to the example
    4. (10 points) Remember to document on your online thing any questions or problems

Week 4 Tuesday, September 22

Announcement

I am changing the location of my office hours. From now on I will hold my office hours in the Architecture studio on the second floor of the main SF building at the corner of 8th Street and Irwin. This is opposite computer lab A, which you can find on this map.

Review

  • Review homework
    • Comments
    • Note similarity and differences of e.g. Valerie vs. Adriana
    • Questions?
    • Review Daniel Shiffman’s Objects tutorial
    • Review my simple Processing class example
    • A cookie cutter makes cookies, but it is not a cookie itself. The cookie cutter is the class, the cookies are the objects.

Lecture

  • Do all of the following along with me:
  • Install Minim :
    • Open Sketch -> Import Library -> Add Library
    • Scroll down to Minim; click Minim; the click Install
  • Example 1: Open a new sketch and add this:
    /**
      from http://code.compartmental.net/minim/examples/AudioOutput/SineWaveSignal/SineWaveSignal.pde
      */
    import ddf.minim.*;
    import ddf.minim.signals.*;
    
    Minim minim;     // the Minim library
    AudioOutput out; // the audio output of my laptop
    SineWave sine;   // a function to generate the values 
                     // of a sine wave
    
    void setup(){    
      minim = new Minim(this);
      
      // Connect the output of Minim to the audio output 
      // of my laptop
      out = minim.getLineOut(Minim.STEREO);  
    
      // create a sine wave oscillator
      // Frequency = 440 Hz
      // Amplitude = 0.5
      // Use the same sample rate as my output  
      sine = new SineWave(440, 0.5, out.sampleRate()); 
    
      //connect the sine wave generator to my audio output
      out.addSignal(sine);
    }
    
    void draw(){
    }
  • Example 2: Here is how you use your mouse to control the frequency:
    /**
      from http://code.compartmental.net/minim/examples/AudioOutput/SineWaveSignal/SineWaveSignal.pde
      */
    
    import ddf.minim.*;
    import ddf.minim.signals.*;
    
    Minim minim;
    AudioOutput out;
    SineWave sine;
    
    void setup()
    {
      size(512, 200);
      
      minim = new Minim(this);
      out = minim.getLineOut(Minim.STEREO);
      sine = new SineWave(440, 0.5, out.sampleRate());
      
      // makes the frequency change smoothly
      // try commenting out this line 
      // and see what happens
      sine.portamento(200);
    
      out.addSignal(sine);
    }
    
    void draw()
    {
    
    }
    
    void mouseMoved()
    {
      float freq = map(mouseY, 0, height, 1500, 60);
      sine.setFreq(freq);  
    }
    
    void stop()
    {
      out.close();
      minim.stop();
      super.stop();
    }
  • Example 3: You can add sine waves:
    /**
      from http://code.compartmental.net/minim/examples/AudioOutput/SineWaveSignal/SineWaveSignal.pde
      */
    
    import ddf.minim.*;
    import ddf.minim.signals.*;
    
    Minim minim;
    AudioOutput out;
    SineWave sine, sine2;
    
    void setup()
    {  
      minim = new Minim(this);
      
      out = minim.getLineOut(Minim.STEREO);
    
      sine = new SineWave(440, 0.5, out.sampleRate());
      out.addSignal(sine);
      
      sine2 = new SineWave(900, 0.5, out.sampleRate());
      out.addSignal(sine2);
    }
    
    void draw()
    {
    }
  • Example 4: You can use a for() loop to create a siren:
    /**
      from http://code.compartmental.net/minim/examples/AudioOutput/SineWaveSignal/SineWaveSignal.pde
      */
     
    import ddf.minim.*;
    import ddf.minim.signals.*;
     
    Minim minim;
    AudioOutput out;
    SineWave sine;
     
    void setup()
    {
      size(512, 200);
      
      minim = new Minim(this);
     
      out = minim.getLineOut(Minim.STEREO);
     
      sine = new SineWave(440, 0.5, out.sampleRate());
      
      // makes the frequency change smoothly
      // try commenting out this line 
      // and see what happens
      sine.portamento(200);
     
      out.addSignal(sine);
    }
     
    void draw()
    {
      for (float freq = 1500; freq > 60; freq --) {
          sine.setFreq(freq);  
          delay(1);
      }
    }
     
    void stop()
    {
      out.close();
      minim.stop();
      
      super.stop();
    }
  • Example 5: You can “program” a “melody”:
    void draw()
    {
      sine.setFreq(400);  
      delay(100);
      sine.setFreq(800);  
      delay(100);
      sine.setFreq(400);  
      delay(100);
      sine.setFreq(1200);  
      delay(100);
    }
  • Example 6: You can combine sine waves to make your own instrument, or you can use one of the built-in instruments:
    /**
      from http://code.compartmental.net/minim/examples/AudioOutput/SineWaveSignal/SineWaveSignal.pde
      */
    
    import ddf.minim.*;
    import ddf.minim.signals.*;
    
    Minim minim;
    AudioOutput out;
    
    void setup()
    {
      
      minim = new Minim(this);
    
      out = minim.getLineOut(Minim.STEREO);
    
      // given start time, duration, and note name  
      out.playNote( 2.0, 2.9, "C3" );
      out.playNote( 3.0, 1.9, "E3" );
      out.playNote( 4.0, 0.9, "G3" );
    }
    
    void draw()
    {
    }
    
    void stop()
    {
      out.close();
      minim.stop();
      super.stop();
    }

Exercise 1

Look at some of the examples in File -> Examples -> Contributed Libraries -> Minim -> Synthesis (e.g. defaultInstrumentExample). Find something cool to share with the class

Michael: VocoderExample, moogFilterExample
Tito: PitchNameExample
Adriana: MaxInstrumentExample
Valerie: TickRateExample
Yichen: DelayExample
Lily: WaveShaperExample
Karina: BitCrushBeatExample (kick instrument tab)
Analoud: NotchFilterExample
Nate: FrequencyModulation

Lecture

Look at File -> Examples -> Contributed Libraries -> Minim -> AudioPlayer -> loop. Notice that you can control the Processing program using your keyboard

Example 7:
Write a simple Processing program that will let you play 4 different notes by pressing one of four different keys

/**
  from http://code.compartmental.net/minim/examples/AudioOutput/SineWaveSignal/SineWaveSignal.pde
  */

import ddf.minim.*;
import ddf.minim.signals.*;

Minim minim;
AudioOutput out;

void setup()
{
  
  minim = new Minim(this);

  out = minim.getLineOut(Minim.STEREO);
}

void draw()
{
}

void keyPressed()
{
  if ( key == 'a' ) {  
    out.playNote( 0, .1, "C3" );
  }
  if ( key == 's' ) {  
    out.playNote( 0, 2, "E3" );
  }
  if ( key == 'd' ) {  
    out.playNote( 0, 1, "G3" );
  }
}

Example 8:
Add a sound to your homework assignment so that the ball makes a sound when it bumps into the wall

/**
  from http://code.compartmental.net/minim/examples/AudioOutput/SineWaveSignal/SineWaveSignal.pde
  */
 
import ddf.minim.*;
import ddf.minim.signals.*;
 
Minim minim;
AudioOutput out;
 
 
/* 
 example of creating an Object
 based on http://www.openprocessing.org/sketch/48960
 */
 
int XSPEED = 4;
int YSPEED = 7;
int CIRCLESIZE = 15;
 
MovingCircle myCircle; 
MovingCircle myOtherCircle; 
 
void setup() {
  size(400, 400);
  smooth();  
  myCircle= new MovingCircle(50,50);
  delay(100);
  myOtherCircle= new MovingCircle(100,100);
  
  minim = new Minim(this);
  out = minim.getLineOut(Minim.STEREO);
}
 
 
void draw() {
 
  // Always erase the screen first
  background(0);
 
  // update the position of the circle
  myCircle.update();
  myOtherCircle.update();
 
  // check for collisions with the walls
  myCircle.checkCollisions();
  myOtherCircle.checkCollisions();
 
  // and finally draw the circle
  myCircle.drawCircle();
  myOtherCircle.drawCircle();
}
 
// this is the definition for our custom MovingCircle class,
// start with the name of the class
 
class MovingCircle {
 
  // any variable declared here will be properties of
  // objects of this type 
  float x;
  float y;
  float xSpeed;
  float ySpeed; 
 
  // Now the functions that are part of this object
 
  // this special function declaration has the same name
  // as the class (MovingCircle) and it has no return type. This
  // is known as the constructor and it's run when an 
  // object of this type is created.
 
  MovingCircle(float xpos, float ypos) {
    x = xpos;
    y = ypos;  
    xSpeed = XSPEED;
    ySpeed = YSPEED;   
  }
 
  // Now come the functions (methods) of the object that 
  // can be called. These functions describe what the 
  // object can do:
 
  // update adds the speed to the position, making
  // our circle move around.
  void update() {
    x += xSpeed;
    y += ySpeed; 
  }
 
  // this function checks to see if our circle has gone off
  // the edge of the screen, and if so reverses the speed   
  void checkCollisions() {     
    float r = CIRCLESIZE/2;
 
    if (x<r) {
      xSpeed = -xSpeed;
      out.playNote( 0, 1, "C3" );
    } 
    
    if ( x>width-r) {
      xSpeed = -xSpeed;
      out.playNote( 0, 1, "C5" );
    } 
 
    if( y<r) {
      ySpeed = -ySpeed; 
      out.playNote( 0, 1, "F5" );
    }  
    
    if(y>height-r) {
      ySpeed = -ySpeed; 
      out.playNote( 0, 1, "F3" );
    }     
  }
 
  // This function finally draws the circle
  void drawCircle() {     
    fill(255);
    ellipse(x, y, CIRCLESIZE, CIRCLESIZE);     
  }
 
} // End of the MovingCircle class

Homework 4 due Tuesday, September 29, at beginning of class

  1. (8 points) Review all the examples we did in class. Come up with at least one question for each example.
  2. Study File -> Examples -> Contributed Libraries -> Minim -> Basics -> SynthesizeSounds. Look at how the different keys are recognized using “switch”  and “case”  statements. This is an alternate to lots of if() statements. You can use either method.
  3. (20 points) Write a program which will automatically display 8 different shapes on the screen in different colors, and will play a different sound for each shape. Display each shape and play the sound for a short interval of time, and then proceed to the next. Since you already know how to draw shapes, it might be easiest to start with one of our examples above and add the shape drawing to it. (Grading rubric: Attempted but not quite working: +2 points. Displaying shapes or making sounds, but not both: +2 points. Shapes and sounds: +4 points. Working but less than 8: +2 points. Well commented: +5 points. All 8 shapes and sounds: +5
  4. (20 points) Write a program which will display 8 different shapes on the screen in different colors, and will play a different sound for each shape, when you press 8 different keys. Look at the example above which plays different sounds for different keys. Displaying shapes or making sounds, but not both: +3 points. All shapes and sounds: +8 points. Working but less than 8: +3 points. All 8: +8 points. Well commented: +4 points.

Week 5 Tuesday, September 29

Arrays

Let’s take a look at a slight modification to Example 7 from last week:

Example 1:

/**
  from http://code.compartmental.net/minim/examples/AudioOutput/SineWaveSignal/SineWaveSignal.pde
  */
 
import ddf.minim.*;
import ddf.minim.signals.*;
 
Minim minim;
AudioOutput out;
 
void setup()
{
  
  minim = new Minim(this);
 
  out = minim.getLineOut(Minim.STEREO);
}
 
void draw()
{
}
 
void keyPressed()
{
  if ( key == '1' ) {  
    out.playNote( 0, .1, "C3" );
  }
  if ( key == '2' ) {  
    out.playNote( 0, .1, "D3" );
  }
  if ( key == '3' ) {  
    out.playNote( 0, .1, "E3" );
  }
  if ( key == '4' ) {  
    out.playNote( 0, .1, "F3" );
  }
  if ( key == '5' ) {  
    out.playNote( 0, .1, "G3" );
  }
  if ( key == '6' ) {  
    out.playNote( 0, .1, "A3" );
  }
  if ( key == '7' ) {  
    out.playNote( 0, .1, "B3" );
  }
  if ( key == '8' ) {  
    out.playNote( 0, .1, "C4" );
  }
}

The only thing that changes is the key number and the note. Isn’t there some way to simplify this?

Suppose you made a table. You can think of this as a simple spreadsheet:

Key pressed Note Note Frequency
1 C4 261.63
2 D4 293.66
3 E4 329.63
4 F4 349.23
5 G4 392.00
6 A4 440.00
7 B4 493.88
8 C5 523.25

Note that the key is simply an index into the table of notes. This is what programmers call an array:

float notes[] = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};

It would be nice to simply say “play the note that corresponds to the number of the key that was pressed” without needing 8 if() statements.

Fortunately, that’s exactly how you access an array: by the index

import ddf.minim.*;
import ddf.minim.signals.*;

Minim minim;
AudioOutput out;

void setup()
{
  minim = new Minim(this);
  out = minim.getLineOut(Minim.STEREO);
}

void draw()
{
}

void keyPressed()
{
  float notes[] = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};

  out.playNote( 0, .1, notes[ key ] );
}

Problem 1: Why doesn’t that work?

It turns out that the variable key contains a special code indicating which key was pressed, not the numerical value of the key, so we need to convert it to a numerical value:

int keyNumber = (int) key;

Problem 2: Why does it still not work?

(int) key gives us the numerical value of the code, but not the key. Use a println() to see the value of keyNumber.

  print(keyNumber + "\t");
  keyNumber = keyNumber - 49;
  println(keyNumber);

Observe that the code for the 10 digits are sequential, so if we subtract 49 we’ll end up with the right index:

import ddf.minim.*;
import ddf.minim.signals.*;

Minim minim;
AudioOutput out;

void setup()
{
  minim = new Minim(this);
  out = minim.getLineOut(Minim.STEREO);
}

void draw()
{
}

void keyPressed()
{
  float notes[] = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};
  int keyNumber = (int) key;
  keyNumber = keyNumber - 49;

  out.playNote( 0, .1, notes[ keyNumber ] );
}

What are the rules of an array?

  1. An array must be declared
  2. An array can be filled either at the same time it’s being declared (see above) or later. If later, the array must be constructed with the new keyword, indicating the size of the array:
    void setup() {
      int myArray[];
      myArray = new int[5];
    
      myArray[0] = 60;
      myArray[1] = 510;
      myArray[2] = 140;
      myArray[3] = -6;
      myArray[4] = 3/2;
      
      println (myArray[0]);
      println (myArray[1]);
      println (myArray[2]);
      println (myArray[3]);
      println (myArray[4]);
    }
    
  3. Any array can be any data type (e.g. int, float) or objects, either built-in or ones you’ve made
  4. Arrays and for() loops work well together:
    void setup() {
      float myArray[];
      myArray = new float[5];
    
      myArray[0] = 60;
      myArray[1] = 510;
      myArray[2] = 140;
      myArray[3] = -6;
      myArray[4] = 3/2;
      
      for ( int i = 0; i < 5; i++ ) {
        println (myArray[i]);
      }
    }

    (Why did 3/2 still come out as an integer?)

The random() function

size (500,500);

for (int y = 0; y < 500; y++) {
  float l = random(500); // random() returns a float
  line(0, y, l, y);
}

Look at the random() reference. Note that it can take either one or two arguments.

Study the last example. It’s a little tricky. You might want to break it apart a bit and play with it to understand. Notice a new data type, a String. It’s actually not new, we saw it briefly earlier. A String is simply a collection of characters. It can be of any length and can include spaces and other characters.

Exercise 1

Write a program which creates an array of 5 “fortunes” (e.g. “you will find good luck this week”), and then every time you press the letter ‘f’ (for “fortune”) you get a random fortune from this list. You will need to combine the last example from the random() reference with the keyPressed() function we used with the musical instruments.

Solution:

// needed even if it's empty
void draw() { 
}

void keyPressed()
{
  // An array of Strings
  String[] fortunes = { "you will get rich", 
                   "you will get a flat tire", 
                   "you will enjoy dinner", 
                   "you will travel far" }; 
  if ( key == 'f' ) {  
    // choose a random element of the array 
    int index = int(random(fortunes.length));
    // print it
    println(fortunes[index]);  
  }
}

Exercise 2

Write a program which plays random sounds.

One possible solution:

import ddf.minim.*;
import ddf.minim.signals.*;

Minim minim;
AudioOutput out;

void setup()
{
  minim = new Minim(this);
  out = minim.getLineOut(Minim.STEREO);
}

void draw()
{
  out.playNote( 0, .1, random(1000) ) ;
  delay(100);
}

Arrays of objects

We can modify the MovingCircles example to use an array, and make 100 circles instead of just two:

int XSPEED = 4;
int YSPEED = 7;
int CIRCLESIZE = 15;

MovingCircle myCircles[]; // declare an array of the MovingCircle class
 
void setup() {
  size(400, 400);
  smooth(); 
    myCircles = new MovingCircle[100]; 
    // Create each MovingCircle using a for() loop
    for (int i = 0; i < 100; i++ ) {  
      // use random() to place each circle in a different place
      myCircles [i] = new MovingCircle( (int) random(400), (int) random(400));
  }
}
 
void draw() {
 
  // Always erase the screen first
  background(0);
 
  // update the position of each circle
  for (int i = 0; i < 100; i++ ) {
    myCircles [i].update();
    myCircles [i].checkCollisions();
    myCircles [i].drawCircle();
  }
}

(The definition of the MovingCircle class remains unchanged. I left it off to save space. To run this example, get the class definition from the last example here)

Exercise 3

Modify the example above so that the X and Y speeds of each circle are random as well

Concepts learned this week

  1. Arrays
    1. How to create
    2. How to initialize
    3. How to use with classes
    4. The built-in variable (array name).length which gives the number of elements in an array
    5. Manipulating arrays and individual elements in an array
  2. How to use print() and println()
  3. How to use ‘+‘ and ‘\t‘ when printing
  4. Converting key codes to numbers using (int) and subtracting 49
  5. The random() function
  6. The draw() function is sometimes needed even if there is nothing in it!
  7. The String class
  8. Commenting out lines of your program by selecting them and pressing <CTRL> /

Homework 5 due Tuesday, October 6, at beginning of class

  1. Review the Simple Processing Class Example and your class notes
  2. (40 points) Create a very simple class (e.g. MyOwnClass) that creates and displays shapes.
    Your class should have 6 private variables: the X and Y locations, the shape, and the three color variables red, green, and blue. Your class should also have the following methods which take arguments as indicated:
  1. The constructor (e.g. MyOwnClass() which takes no arguments. Don’t forget that the constructor has no return type (not even void!) (5 points)
  2. selectShape (int whichShape) which takes an integer argument (whichShape) which choses one of a few (between 5 and 10) simple shapes (anything you want e.g. square, circle, ellipse, small triangles, bigger triangles, parallelogram, etc.). START WITH JUST ONE SHAPE AND ONCE YOU GET THINGS WORKING ADD MORE (10 points)
  3. setLocation (int x, int y) where x and y are the coordinates of where to display the shape (corner, center, whatever) (10 points)
  4. setColor(int red, int green, int blue) which sets the color of the shape (stroke or fill, your choice) (10 points)
  5. displayShape() which takes no arguments and displays the shape (5 points)

 

  • (20 points) Write a simple testing program which demonstrates a very few shapes (e.g. 2 or 3) you can make with your new class, putting a few different objects in different places. Keep this part very simple while you work out all the problems
     
    int SHAPESIZE = 30;
     
     
    Shape myShape;
    Shape myOtherShape;
     
    void setup() {
      size(400, 400);
      noStroke();
      myShape= new Shape();
      myOtherShape = new Shape();
    }
     
    void draw() {
     
      // Always erase the screen first
      background(0);
     
      myShape.selectShape(3);
      myShape.setLocation(100,50);
      myShape.setColor(255,0,0);
      myShape.displayShape();
     
      myOtherShape.selectShape(2);
      myOtherShape.setLocation(50,50);
      myOtherShape.setColor(0,255,0);
      myOtherShape.displayShape();
     
    }
     
    // this is the definition ,
    // start with the name of the class
     
    class Shape {
     
      int myShape; // 1 is rect; 2 is triangle; 3 is ellipse
      int X = 50; 
      int Y = 50;
      int c1 = 43;
      int c2 = 162;
      int c3 = 255;
     
      Shape () {
      }
     
      void selectShape (int whichShape) {
        myShape = whichShape;
      }
     
      void setLocation (int tempx, int tempy) {
        X = tempx;
        Y = tempy;
      }
     
      void setColor(int red, int green, int blue) {
        c1 = red;
        c2 = green;
        c3 = blue;
      }
     
      void displayShape() {     
        fill(c1, c2, c3); 
     
        if ( myShape == 1 ) {
          rect(X, Y, SHAPESIZE, SHAPESIZE);  
        } else if ( myShape == 2 ) {
          triangle(X+50, Y+230, X+250, Y+230, X+150, Y+50); 
        } else if  ( myShape == 3 ) {
          ellipse(X+15, Y+300, SHAPESIZE+20, SHAPESIZE);
        } 
      }
     
    } // Lily
     
    [codesyntax]
     
    (20 points) Write a testing program which uses a for() loop to display each shape your class can make. Color and placement can be the same or your choice. The shapes should either be in different places or at different times so that they can be seen.
    (20 points) Write a program which uses random() to randomly chose which shape, where to put it, and what color to make it. It's enough to display just one shape each time the program is run. If you run the program multiple times you should end up with a different shape of a different color in a different location most of the time.
     
     
    Week 6 Tuesday, October 6
    Detecting when the mouse is in a region
    Take a look at this example from Daniel Shiffman's excellent book Learning Processing. Pay close attention to how the code figures out if the mouse is inside a particular rectangle or not. Look at the reference page for the rect() function to understand how rect() works.
    Exercise 1
    Modify Daniel's example so that instead of simply using two lines to divide the canvas into four quadrants, make four explicit rectangles. Make the rectangles smaller, so that there is space between rectangles and between the edges of the canvas. Change the code so that if the mouse is over one of the rectangles, it turns red. You will need to change the if() statement to be more complete.
    Suggestion: Get one rectangle to work first, then do the other three.
    Exercise 2
    With your solution to Exercise 1, write a function called isMouseOverMe() that takes as its four arguments the same four arguments as the rect() function. Your function should return a boolean, which is a new data type that has only one of two values: true or false. Your function should return true if the mouse is within its rectangle, and should return false otherwise.
    Use this function to determine whether the mouse is over a particular rectangle or not.
    Exercise 3
    Modify your solution to exercise 2, creating a class called MyRect(). The constructor to MyRect() takes the same four arguments that rect() takes. Your class should have three methods:
     
    setColor(int r, int g, int b)
    display() which actually draws the rectangle
    isMouseOverMe() which returns true or false, just as in exercise 2
     
    You will need 7 private variables: x, y, xSize, ySize, r, g, and b.
    Exercise 4
    Modify your solution to exercise 3 to use an array to store the rectangles, and use a for() loop instead of manually testing and displaying each rectangle
    Exercise 5
    Add the mousePressed() and mouseReleased() functions to your solution to exercise 4. Add a global boolean variable called mouseIsPressed, and set it to true when the mouse is pressed and false when the mouse is released.
    In your class' display() function, if the mouse is over a rectangle, AND if the mouse is pressed, change the color to green.
    Exercise 6
    In addition to changing the rectangle to green, also play a sound.
    Homework 6 due Tuesday, October 13, at beginning of class
    I will hold extra office hours on Friday 10/9 from 12-1:30 in the Hybrid Lab downstairs, and then from 2 PM - 3 PM upstairs in the architecture studio in the main building on the San Francisco campus.
     
    (30 points) Complete exercises 3-6 that we did not do in class. If you did not attend class do all 6 exercises. (5 points each exercise)
    (20 points) Consider everything we learned so far. You might want to make a list for reference. Propose a project that will take a few weeks and use at least 5 important programming techniques like loops, classes, conditionals, functions, etc. Your project may be a game, or an artistic creation (which could be either stand-alone or interactive), or something else of your imagination. Search for "Processing Projects" if you are having trouble coming up with an idea.Your assignment is to describe your project in some detail. You should consider how you are going to implement your project, and discus your ideas. Pay particular attention to areas that seem complex or frightening to you: that's what you will focus on first.
     
    Week 7 Tuesday, October 13
     
    What do you want?
    What do you want to get out of this class? How can it be relevant to your own work and/or interests? We will talk about this later.
    Transparency
    void setup(){
      size(500,500);
    }
    void draw() {
      fill(255,0,0);
      rect(30, 20, 55, 55);
      
      fill(0,255,0);
      // this rectangle will completely
      // block the one underneath
      rect(60, 50, 55, 55); 
      
      fill(0,0,255,128); // 50% transparency
      // this rectangle will only partially
      // block the one underneath
      // due to the transparency setting
      rect(90, 80, 55, 55);
    }
    Animation
    Review concept of setup(), draw(), and introduce frameCount and frameRate(). I encourage you to browse the Processing reference pages for these and other functions that interest you. Introduce modulo (%) operator.
    int x = 0;
     
    void setup(){
      size(500,500);
      
      // slow the movie down a lot so
      // we can see each frame
      frameRate(5);
    }
    void draw() {
      
      // Erase the previous picutre
      background(255);
      
      // turn off the stroke (outline)
      noStroke();
      fill(255,0,0); // red square
      rect(30, 20, 55, 55);
      
      fill(0,255,0); // green square
      // this square will completely
      // block the one underneath
      rect(x, 50, 55, 55);
      
      // increment x, which determines the position of
      // the green square, so on the next frame it will 
      // appear in a different position.
      x = x + 1;
      
      // if the square reaches the end of the screen, 
      // move it back to the begining of the screen
      if (x > width) {
        x = 0;
      }
      
      // blue square
      fill(0,0,255,240); // 50% transparency
      // this rectangle will only partially
      // block the one underneath
      // due to the transparency setting
      rect(90, 80, 55, 55);
      
      // just print the frameCount so I can
      // see how quickly frames are changing
      println(frameCount);
    }
    Translations
    We will work through this excellent tutorial by J Eisenberg.
    Here is the first translation example we developed in class:
    int x = 0;
     
    void setup() {
      size(400,400);
    }
     
    void draw() {
      
      // erase the screen!!
      background(255);
      
      // draw the house
      house(x,100);
      
      // move the house 
      x = x + 1;
      
      // make sure the house stays on the screen
      if (x > width) {
        x = 0;
      }
    }
     
    void house(int x, int y)
    {
      pushMatrix();
      translate(x, y);
      triangle(15, 0, 0, 15, 30, 15);
      rect(0, 15, 30, 30);
      rect(12, 30, 10, 15);
      popMatrix();
    }
    Here is the rotate example as we modified in class:
    void setup() {
      size(200, 200);
      background(255);
      smooth();
      noStroke();
    }
     
    void draw(){
      //if (frameCount % 10 == 0) {
        fill(frameCount * 100 % 255, frameCount * .75 % 255,
          frameCount * 7 % 255);
        pushMatrix();
        translate(100, 100);
        rotate(radians(frameCount * 2.567929838383  % 360));
        rect(0, 0, 80, 20);
        popMatrix();
      //}
    }
    Here is the same example using random numbers for everything:
    void setup() {
      size(200, 200);
      background(255);
      smooth();
      noStroke();
    }
     
    void draw(){
      
      if (frameCount % 10 == 0) {
        // instead of chosing the color based on the frame count,
        // chose the color randomly
        fill(random(0, 255), 
          random(0, 255),
          random(0, 255));
        pushMatrix();
        // instead of always translating to the middle
        // of the canvas, translate to a random place 
        // but stay on the canvas
        translate(random(0, width), random(0, height));
        
        // rotate by a random amount as well
        rotate(radians(random(0, 360)));
        
        // more randomness! make ellipses of random
        // sizes
        ellipse(0, 0, random(0,30), random(0,30));
        popMatrix();
      }
    }
    Project proposals
    Present your project proposals. Identify high risk areas.
    Individual meetings
    I'd like to meet with each of you to discuss your areas of interest as we move towards the last half of the semester. While I am doing this the rest of you can work on your projects.
    Debugging
    Time permitting, I'll briefly show you how to use the built-in debugger
    Homework 7 due Tuesday, October 20, at beginning of class
    Start your project. What this means will be different for each one of you. The project will be due on November 3, which means you have two more weeks after this coming meeting, which suggests that you should have about 1/3 of the project done by October 20. Of course you don't yet know how long the project is going to take, so it's hard to judge what 1/3 is, which means you have to be safe and achieve more than 1/3 by October 20.
    I suggest the following:
     
    Write a program that will set up the environment for your project. If your project is visual it should display the environment. If there are characters, you should have objects to display them.
    Identify the top three items that you feel are going to be the most difficult and complex, and figure out how to solve them. In some cases you can do this in a separate program, in other cases it will be integrated into the environment you created in (1) above.
    Describe, in your blog, these top three items and how you solved them.
     
    During class on October 20 you will continue to work on your project, and I will meet with each of you individually to check on your work and to help you along.
    Week 8 Tuesday, October 20
     
    Homework 8 due Tuesday, October 27, at beginning of class
    For our next meeting your project should be mostly done. You might think the last week is for finishing the project, but the truth is that you should reserve the last week for fixing problems that you don't know about yet.
    On October 27 I want to see your project functioning. It doesn't need to be complete, it might break at certain places, it might not look pretty, but it must be functioning. If you can't get the basic functionality to work then you should remove features until you can get it to work.
    Email me or meet with me if you have questions
    Week 9 Tuesday, October 27
     
    +, -, and ^
    Review your project progress:
     
    Upload your project to a page (or post) and name it "Project progress, October 27 2015"
    Make a list of what features already work in your project
    Make a list of what features do not yet work in your project
     
     
     
    Homework 9 due Tuesday, November 3, at beginning of class
    Your completed project is due!
    Your project should include:
     
    A short, well written description of what the project does. Grammar and spelling must be correct or points will be taken off. Make use of the coaches at the Learning Resources Center if you have difficulty with this. Include any necessary instructions.
    The program itself, which must be:
     
    properly formatted and indented
    any code that is not in use (e.g. commented out lines or variables that are not being used) must be removed
    properly commented i.e. meaningful, useful comments to explain what's going on
     
     
    A list of things you learned while working on this project
    A list of questions that you have after working on this project
    As always, this should all be on your blog. Call this the first project.
     
    If you are having trouble please email me, and also use online resource, which are plentiful. Here is a nice short tutorial on how to debug Processing programs
    Tuesday, November 3, at beginning of class
     
    Project presentations
     
    Homework 10 due Tuesday, November 10, at beginning of class
    I apologize for the very late assignment. For this reason your homework can be very brief and simple, but it must be complete. It should not take too long:
    For this homework assignment describe a very simple interactive concept. You are writing a homework assignment exercise for someone else:
     
    Input can be through the mouse or keyboard.
    Output can be visual or sound based, but should be very simple.
    You are encouraged to draw inspiration from the individual projects we saw last week.
    Draw one or more simple sketches describing the appearance you want.
    Describe very clearly how the program should behave. How will you judge whether the program does what you want it to do or not? Provide that information in the description.
     
    As always, put this description on your blog.
    Tuesday, November 10
    Lecture
     
    State machines:
     
    [codesyntax lang="c"]
    /* A traffic light for an intersection of a
    highway and a country road. Normally, the light
    should be green for the highway and red for the
    country road, but when traffic approaches on
    the country road, the highway gets a red light
    and the country road gets a green light.
     
    When a light turns red it transitions from green to
    red it goes through yellow, but a red light changing
    to green transitions directly to green.
     
    A mouse click represents a car approaching on
    the country road.
     
    Implement the solution with a Finite State
    Machine or FSM.
     
    Following the excellent description at
    http://hacking.majenko.co.uk/finite-state-machine
    first break down the problem into states.
     
    Identify which states are Transitional (T) and
    which are Static (S). A Static state is one in
    which the FSM is waiting for stimulus, and is
    taking no actions. A Transitional State is a
    state which causes actions, but doesn't look
    for stimulus.
     
    A Transitional State runs once and immediately
    moves on to a Static State.
     
    State 0: highway = green, country = red; (T)
    State 1: wait for car on country road (S)
    State 2: highway = yellow, make note of current time (T)
    State 3: wait for yellow time to pass (S)
    State 4: highway = red, country =  green, make note of current time (T)
    State 5: wait for highway red time to pass (S)
    State 6: country = yellow, make note of current time (T)
    state 7: wait for yellow time to pass (S) then go to 0
    */
     
    // Use names for states so it's easier to
    // understand what the code is doing
    final int S_HIGHWAYGREEN = 0;
    final int S_WAITCARCOUNTRY = 1;
    final int S_HIGHWAYYELLOW = 2;
    final int S_WAITHIGHWAYYELLOW = 3;
    final int S_HIGHWAYRED = 4;
    final int S_WAITHIGHWAYRED = 5;
    final int S_COUNTRYYELLOW = 6;
    final int S_WAITCOUNTRYYELLOW = 7;
     
    final int REDCOLOR = #FF0000;
    final int GREENCOLOR = #00FF00;
    final int YELLOWCOLOR = #FFFF00;
     
    // things to remember 
    int state; // what is our current state
    long frameCountAtLightChange;
     
    TrafficLight mainRoad;
    TrafficLight countryRoad;
     
    class TrafficLight {
      int x;
      int y;
      int r;
     
      TrafficLight (int tx, int ty, int tr) {
        x = tx;
        y = ty;
        r = tr;
      }
     
      void changeColor(int tColor) {
        fill(tColor);
        ellipse(x,y, r, r);
      }
    }  
     
    void setup()
    {  
      size(200,200);
      mainRoad = new TrafficLight(50,50, 40);
      countryRoad = new TrafficLight(160,50, 20);
      // start off with the highway getting green
      println("changing state to S_HIGHWAYGREEN");
      state = S_HIGHWAYGREEN ;
    }
     
    void draw()
    {
     
      switch (state)
      {
        case S_HIGHWAYGREEN:
     
          // Highway gets green, country road red
          mainRoad.changeColor(GREENCOLOR);
          countryRoad.changeColor(REDCOLOR);
     
          // next state is waiting for a car on the country road
          state = S_WAITCARCOUNTRY;
     
          break;
     
        case S_WAITCARCOUNTRY:
           // nothing to do; keep waiting for a car
          break;
     
        case S_HIGHWAYYELLOW:
          mainRoad.changeColor(YELLOWCOLOR);
          countryRoad.changeColor(REDCOLOR);
     
          // Remember the frame count at which we changed color
          frameCountAtLightChange = frameCount;  
     
          state = S_WAITHIGHWAYYELLOW;  // Move to the next state
     
          break;
     
        case S_WAITHIGHWAYYELLOW:
          // If two seconds have passed, then move on to the next state.
          if (frameCount > frameCountAtLightChange + 100)
          {
            state = S_HIGHWAYRED;
          }
     
          break;
     
        case S_HIGHWAYRED:
          // Highway red, country road green
          mainRoad.changeColor(REDCOLOR);
          countryRoad.changeColor(GREENCOLOR);
     
          // Remember the frame count at which we changed color
          frameCountAtLightChange = frameCount;  
     
          state = S_WAITHIGHWAYRED;
     
          break;
     
        case S_WAITHIGHWAYRED:
     
          // If five seconds have passed, then start
          // transition to a red light for the country 
          // road (start with yellow)
          if (frameCount > frameCountAtLightChange + 200)
          {
            state = S_COUNTRYYELLOW;
          }
     
          break;
     
        case S_COUNTRYYELLOW:
          mainRoad.changeColor(REDCOLOR);
          countryRoad.changeColor(YELLOWCOLOR);
     
          frameCountAtLightChange = frameCount;
     
          state = S_WAITCOUNTRYYELLOW;
     
          break;
     
        case S_WAITCOUNTRYYELLOW:
     
          // If two seconds have passed, then go
          // back to the beginning with the highway 
          // getting the green light
          if (frameCount > frameCountAtLightChange + 100)
          {
            state = S_HIGHWAYGREEN;
          }
     
          break;
     
      } // end of switch
     
      // other things could go on here, and they would not affect the timing 
      // of the traffic light
     
    } // end of draw()
     
    void mouseClicked() {
      println("detected mouse click");
      if ( state == S_WAITCARCOUNTRY ) {
        println("changing state to S_HIGHWAYYELLOW");
     
        state = S_HIGHWAYYELLOW;
      }
    }

    Time permitting:

    • Review
      • Transformations
      • Classes and objects
      • Functions
    • Analysis in depth
    • New material
      • Text
        • Tools -> Create Font
        • size(200,200);
          PFont font;
          font = loadFont("Waree-48.vlw");
          textFont(font);
          fill(0);
          text("hello", 20, 80);
      • The smooth() function
        Aliasing_a
      • Shapes and Vertices
        • size(200,200);
          noFill();
          beginShape();
          vertex(30,20);
          vertex(85,20);
          vertex(85,75);
          vertex(30,75);
          endShape();
        • Try endShape(CLOSE);
        • noStroke();
          fill(0);
          beginShape();
          vertex(40,10);
          for (int i = 20; i <= 100; i += 5) {
            vertex(20,i);
            vertex(30,i);
          }
          vertex(40,100);
          endShape();
          
        • size (1100,1000);
          noStroke();
          fill(0);
          beginShape();
          vertex(10,40);
          for (int i = 20; i <= 1000; i += 2) {
            vertex(i,20);
            vertex(i,30);
          }
          vertex(1000,40);
          endShape();
          
      • Developing software
        • Sketching on paper
        • Pseudocode
        • Using functions and classes to organize code
    class Egg {
      float x, y; // X-coordinate, y-coordinate
      float tilt; // Left and right angle offset
      float angle; // Used to define the tilt
      float scalar; // Height of the egg
     
      // Constructor
      Egg(float xpos, float ypos, float s) {
        x = xpos;
        y = ypos;
        scalar = s / 100.0;
      }
     
      void wobble() {
        tilt = cos(angle) / 8;
        angle += 0.1;
      }
     
      void display() {
        noStroke();
        fill(255);
        pushMatrix();
        translate(x, y);
        rotate(tilt);
        scale(scalar);
        beginShape();
        vertex(0, -100);
        bezierVertex(25, -100, 40, -65, 40, -40);
        bezierVertex(40, -15, 25, 0, 0, 0);
        bezierVertex(-25, 0, -40, -15, -40, -40);
        bezierVertex(-40, -65, -25, -100, 0, -100);
        endShape();
        popMatrix();
      }
    }
     
    Egg egg;
     
    void setup() {
      size(200, 200);
      // Inputs are: x,y coordinates; height
      egg = new Egg(100, 150, 80);
    }
     
    void draw() {
      background(0);
      egg.wobble();
      egg.display();
    }

    Homework 11 due Tuesday, November 17, at beginning of class

    Each of you has uploaded to your blog a description of a simple project. I have assigned each of you to a different project, and your assignment for next week is to implement that project.

    The project should be simple enough to finish in one week. If it seems to complicated to you contact me and I will simplify the project if necessary.

    • Nate does Karina's project
    • Lily does Adriana's project
    • Valerie does Lily's project
    • Karina does Valerie's project
    • Adriana does Nate's project
    • Heather, Alanoud, Yichen: I forgot to write down the assignments we discussed in class. Can you please email me?

    Tuesday, November 17

    1. Download some data e.g. from http://www.ndbc.noaa.gov/
    2. Open in Microsoft Excel (or Libreoffice Calc) and carefully select columns
    3. Save as .csv file
    4. If you open with a text editor, your file should look something like this:
      #YY,MM,DD,hh,mm,WDIR,WSPD,GDR,GST,GTIME
      2011,12,31,23,0,167,7.9,999,99,9999
      2011,12,31,23,10,168,7.9,999,99,9999
      2011,12,31,23,20,164,7.4,999,99,9999
      2011,12,31,23,30,168,7.6,999,99,9999
      2011,12,31,23,40,166,7.7,999,99,9999
      2011,12,31,23,50,166,7.9,157,10.1,2259
      2012,1,1,0,0,166,7.8,999,99,9999
      2012,1,1,0,10,162,8.1,999,99,9999
      2012,1,1,0,20,160,7.9,999,99,9999
      2012,1,1,0,30,161,8.1,999,99,9999
      2012,1,1,0,40,163,8.3,999,99,9999
      2012,1,1,0,50,167,8.8,167,10.8,41
      2012,1,1,1,0,166,8.4,999,99,9999
      2012,1,1,1,10,166,8.4,999,99,9999
      
    5. Create a processing sketch starting with this:
      	
      Table table;
      
      void setup() {
        
        // the file must be in the sketch's data folder
        // the argument "header" tells loadTable() to organize the file
        // columns according to the header line (the first line)
        table = loadTable("myfile.csv", "header"); 
      
        // how many rows did we read?
        println(table.getRowCount() + " total rows in table"); 
      
        // A new way to do a for() loop: Do each row in the table
        // The variable "row" contians one row, and the loop executes
        // once for each row in the table
        for (TableRow row : table.rows()) {
          
          int direction = row.getInt("WDIR"); // the wind direction
          float speed = row.getFloat("WSPD"); // the wind speed
          
          println("direction " + direction + "\tspeed " + speed);
        }
        
      }
      
    6. Move your .csv file into your sketch's data folder
    7. Run and experiment
    8. Useful classes and methods include:
      1. Table
      2. TableRow:  getInt(), getFloat(), getString()
    9. Useful functions include:
      1. loadTable()
    10. Now do something interesting with this data. This is known as "data visualization":
    Table table;
     
    void setup() {
     
      size(1000,1000);
     
      // the file must be in the sketch's data folder
      // the argument "header" tells loadTable() to organize the file
      // columns according to the header line (the first line)
      table = loadTable("myfile.csv", "header"); 
     
      // How many rows did we read?
      int tableRowCount = table.getRowCount();
     
      // We want to make a grid of this many squares; that means
      // that the number of rows and the number of columns
      // is the square root of the tableRowCount
     
      // By making this an int we will ignore any fractional
      // part
      int squareRowsOrColumnCount = (int) sqrt(tableRowCount);
     
      // Print these numbers to check:
      println("Total rows in table = " 
              + tableRowCount 
              + " number of squares in each row or colunn = " 
              + squareRowsOrColumnCount); 
     
      // Now calculate the square size. This will be our width divided by
      // the number of squares. Again make this an int.
      int squareSize = (int) width / squareRowsOrColumnCount;
      println("square size = " + squareSize);
     
      int squareRowNumber = 0;
      int squareColumnNumber = 0;
      for (TableRow row : table.rows()) {
     
        int direction = row.getInt("WDIR"); // the wind direction
        float speed = row.getFloat("WSPD"); // the wind speed
     
        // the wind direction will indicate the rotation of the square
        // no sense in going more than 90 degrees as we can't tell the 
        // difference (since it's a square)
        int squareAngle = (int) map( direction, 0, 360, 0, 90);
     
        // the wind speed will change the color (monochrome)
        int squareFill = (int) map(speed, 0, 15, 0, 255);
     
        // use transformations to get to the right position and angle 
        pushMatrix();
        translate(squareRowNumber*squareSize, squareColumnNumber*squareSize);
        rotate(radians(squareAngle));
     
        // Draw this square
        noStroke();
        fill(squareFill);
        rect(0,0,squareSize,squareSize);
     
        // Transform back to the origin
        popMatrix();
     
        // move to the next column
        squareColumnNumber ++;
        if (squareColumnNumber > squareRowsOrColumnCount ) {
          squareRowNumber ++;
          squareColumnNumber = 0;
        }
     
      }
     
    }

    Notes

    • No draw()!

    Debugging

    • Use println() to inspect variables
    • Use println() to know where you are in a program
    • Use fewer pieces of data
    • Use data that should give you known results

    Homework 12 due Tuesday, November 24, at beginning of class

    1. Describe your final project for this class. Requirements for the final project are described below.
    2. Create a debugging log, which is a log of the problems you run in to as you develop your project, along with how you figure out the solution. The details of the debugging log are below in the final project requirements.
    3. Create a dummy entry in your debugging log. You may make one up, or use a bug you've experienced in the past. The content doesn't matter as long as you clearly show me that you know how to use your debugging log.

    Tuesday, November 24

    • Look at proposals
    • Review good habits
    • Review debugging techniques

    To get a constant report of your mouse x and y coordinates, put this in your draw() function:

    surface.setTitle(mouseX + ", " + mouseY);

    Homework 13 due Tuesday, December 1, at beginning of class

    I am surprised that so many of you were absent last week and this week. Please remember that three unexcused absences will result in a failing grade, as discussed in the syllabus.

    I expect to see everyone next week.

    For next week I want to see your projects almost done. You can use the last week to put the finishing touches on your program and to finish your documentation, but I want to see the program mostly working.

    Final Project, due Tuesday December 8, at beginning of class

    For this project you will design and create a data visualization program. You may use any data you wish, including the examples we used in class (wind speed, wind direction, wave height, water temperature, etc. taken by a buoy in the ocean). You must visualize at least two columns of data from at least 1000 data rows.

    If you prefer (although it may be more difficult) you may make an auditory representation of the data, if your proposal receives my approval.

    You are encouraged (but not required) to draw upon your own aesthetic and practice to make the work unique and compelling; however note that artistic critique is not a goal of this class.

    In addition to your ability to program, this assignment requires you to demonstrate your ability to investigate and report on your observations. For this you will be required to provide a debugging log, described below. This is a serious bit of work, but it will help you develop very critical skills in debugging; if there is only one valuable thing you take from this class, it will be this ability. Don't skimp on it!

    Deliverables:

    • An image generated from your code
    • Your data
    • Your Processing code, which must be well structured and highly commented, demonstrating a comprehensive understanding of the code. Create your own classes and functions to keep your code modular and understandable. Variable, class, and function names must be suitable and there should not be unused elements. Pay attention to all the good habits we have discussed in class.
    • A paragraph or two description of your original plan and how you set about designing the code to implement that plan, what problems arose, and how you overcame them. If you changed your original plan, explain why you did so and how.
    • Your debugging log. Every time you run in to unexpected behavior in your project (a bug, a component that works differently than you thought, or something else), make an entry in your log. Describe the following:
      1. In a sentence, explain the behavior you expected.
      2. In a sentence, explain the observed behavior.
      3. Formulate a hypothesis about what might be causing the mismatch: what part of your code or what part of your circuit is behaving in a way you don't expect?
      4. Test your hypothesis: what action can you take you determine if your hypothesis is true?
      5. What is the result of your test?
      6. Repeat steps iii-v above until you resolve your "bug".
    • Select 5 visualization points in the image that look as different as possible, and correlate them to the appropriate rows in the data set. Follow the values through your program, and explain how those visualization points came to be displayed the way they are.

    Grading rubric:

    • D:
      • Code is poorly documented and structured, and can not be understood without deep analysis
      • Written description vague and/or difficult to understand
      • Tracing of 5 visualization points through the code is incorrect and/or lacking
    • C:
      • Code is minimally understood
      • Written description is weak. The overall plan is understandable but details remain vague
      • Tracing of 5 visualization points through the code partially correct and partially sufficient
    • B:
      • Code is mostly understood.
      • Written description is moderate. The overall plan is understandable and most details are explained.
      • Tracing of 5 visualization points through the code mostly correct and mostly sufficient
    • A:
      • Code is easily understood, program is well structured and commented, showing excellent understanding of the statements and how they contribute to the task at hand.
      • Written description is excellent. The overall plan is easily understandable and all details are explained clearly.
      • Tracing of 5 visualization points through the code entirely correct and easily understood

    Tuesday, December 1

    • Review what we've learned
    • Evaluations

    Announcement:

    Three of us faculty members who teach Programming have decided to combine our extra office hours this week to make them available to all our students. If you feel you need some assistance, I encourage you to take advantage of these hours. I highly recommend Margaretha and J.D. as excellent teachers.

    All of this will take place in the Hybrid Lab in San Francisco:

    • Wednesday 12/2 12:30-3 PM with J.D.
    • Friday 12/4 11:30 - 2:30 with Margaretha and Michael
      (although Michael arrives at 12:30)

    Processing and the Internet

    1. Network library
      1. File -> Examples -> Libraries -> Network -. HTTPClient
    2. Twitter, using Temboo
      1. Log on to Twitter and create keys
        1. Login to dev.twitter.com. At the bottom click on Manage your APIs. Click on Create a new app.
        2. Fill out the form
        3. Click on Manage keys
        4. Click on Generate access tokens
        5. copy 4 things:
          1. Consumer Key
          2. Consumer Secret
          3. Access Token
          4. Access Token Secret
      2. Get the code from Temboo
        1. Create an account at temboo.com
        2. Chories -> Twitter -> Timelines HomeTimelines
        3. Insert the keys and secrets from above
        4. Optional: Click Run
        5. Select Processing
        6. Copy the code
        7. Paste it into a Processing window
        8. in Processing, install the Temboo library (Sketch -> Import Library -> Add Library, filter for Temboo)
        9. Run!
        10. Too messy? Processing can help you parse the returned data (which is in JSON format https://temboo.com/processing/display-tweet

    Students

    Resources

    1. A nice series of slides on Processing
      1. chapter01_ProcessingPixels.pdf
      2. chapter02_Processing.pdf
      3. chapter03_ProcessingInteractionKB.pdf
    2. A list of books on Processing, curated by the creators of Processing
    3. Shiffman's list of common processing errors
    4. Datasets
      1. Time Series Data Library
      2. r-dir list of datasets
      3. Kevin Chai's list of datasets
      4. Meteorite landings dataset
      5. Behavioral and social science datasets
      6. GDELT database of human society

    Debugging Techniques

    1. Google!
    2. Ask someone
    3. Println()
    4. Change stuff and see what happens (this is unscientific and should probably be used as a last resort)
    5. Break problem into little pieces
    6. Comment out sections to make them ignored
    7. Try reducing the amount of data you are processing to 1 or 10 lines

    Good Programming Habits

    1. Proper indentation
    2. Good choice of names for variables, functions, classes
    3. Excellent comments!!
    4. Make functions and classes as necessary to encapsulate blocks of code

     

    Print Friendly
Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Leave a Reply

Your email address will not be published. Required fields are marked *