Digital and Analog

Document Sample
Digital and Analog Powered By Docstoc
					           Introduction to Programming

•   Instead of emphasizing the details of a particular programming language, this
    course will teach how to approach a problem in a way that makes it easy to
    solve using programming.

•   The most difficult part of learning to program is learning how to analyze and
    break down a problem, and that’s what we intend to focus on. This is to
    provide tools to make your vision a reality.
        The Four Steps of Programming

Programming is just a process of logical problem-solving - something that anyone can learn
and most people do all the time.
The two big challenges are learning syntax and applying your logical problem-solving skills to
an unfamiliar domain.
There are four important things that will help you do this.

1. Code Reading

2. Pseudo-Code

3. Writing Code

4. Debugging
        The Four Steps of Programming
1.   Code – Reading

     To be able to program is being able to look at the code and figure out what it does.

•    What a particular line of code is doing – understanding the syntax and control flow of
     program. i.e. When the program executes a line of code, what is the line of code that it
     will execute next?

•    Knowing how to read a line of code, and knowing what order to read those lines in, will
     give you the tools to understand programs and other people have written.

•    Code–sharing – borrowing a code from existing programs that already does what you’re
     trying to do: if you can’t read their code, you can not know which parts are relevant to
     your project.

•    Additionally, if you work on a code project together with somebody else, it will be
     helpful if you can each read what the other one is doing.

•    Finally, code-reading is very important for debugging your code.
         The Four Steps of Programming

2. Pseudo-Code

•   The second step of programming is programming pseudo-code.

•   This is where you do a lot of thinking and not very much writing code!

•   Most projects start with a vague idea or an text description, this step helps turn the
    project into something that is approachable as program.

•   It forces you to define and explain what you’re trying to do very precisely.

•   This is also the step where you think about the best way to solve problems that you’re
    going to run into during the project, figuring out what solutions to try before you start
    writing random code.
        The Four Steps of Programming

3. Writing Code

•   This is the most-hyped step of programming.

•   This can be very intimidating process to express what you’re trying to do with unfamilar
    syntax of a programming language.

•   However, if you have done a good job in pseudo-code, this should be in some ways the
    simplest step: just performing a transformation from the precise and clear concepts.

•   As you write the code, you’ll figure out issues that your original design and pseudo-code
    didn’t address. You will improvise, double-back, and sometimes change your entire
    design.
         The Four Steps of Programming

4. Debugging

•   Debugging means testing and fixing the problems in a program that you’ve already
    written.

•   Unfortunately, this is the step that will generally take most of your time.

•   Sometimes your program will not work or do something unexpected. That’s why learning
    actual techniques for figuring out what’s wrong is so important.

•   There are a wide variety of ways to debug effectively, but not all work for you.

•   The key way to being a good debugger is to be able to make intelligent hypotheses
    about what might be going wrong, then to come up with ways to test those hypotheses.
                     Data and Algorithms

•   Data and algorithms are the two key concepts of programming.

•   Data is “stuff” – information that the program stores, things that the program knows
    about, material that the program operates on.

•   An algorithm is “action” – what the program is doing and in what order and why.

•   If data is noun, then algorithms are the verbs.

•   An algorithm is a set of instructions that tells you how to solve a problem. It must be
    precise – clear and unambiguous, without relying on human judgment or interpretation,
    so that the computer knows exactly what it is supposed to do when it comes time to
    create a program. It must be finite – it must always have an ending, even if that ending
    simply states, “I could not solve this problem.
Working with Processing
                Processing Environment

Processing is Open Source Software.

Processing is a programming language, development environment, and online community
that since 2001 has promoted software literacy within the visual arts.

Processing was founded by Ben Fry and Casey Reas in 2001 while both were
John Maeda's students at the MIT Media Lab.

The Processing software runs on the Mac, Windows, and GNU/Linux platforms.
With the click of a button, it exports applets for the Web or standalone applications for Mac,
Windows, and GNU/Linux. Graphics from Processing programs may also be exported as
PDF, DXF, or TIFF files and many other file formats. Future Processing releases will focus on
faster 3D graphics, better video playback and capture, and enhancing the development
environment. Some experimental versions of Processing have been adapted to other
languages such as JavaScript, ActionScript, Ruby, Python, and Scala; other adaptations
bring Processing to platforms like the OpenMoko, iPhone, and OLPC XO-1.


http://processing.org/download/
http://www.learningprocessing.com/
                Processing Environment
Processing is a "sketching" tool

Processing is a simple programming environment that was created to make it easier to
develop visually oriented applications with an emphasis on animation and providing users
with instant feedback through interaction.

The developers wanted a means to “sketch” ideas in code.
As its capabilities have expanded over the past six years, Processing has come to be used for
more advanced production-level work in addition to its sketching role.

Originally built as a domain-specific extension to Java targeted towards artists and designers,
Processing has evolved into a full-blown design and prototyping tool used for large-scale
installation work, motion graphics, and complex data visualization.

Processing covers basic drawing, exporting, saving files, rendering to different contexts
(2D, 3D, PDF).

Download porcessing (free)
http://processing.org/download/
                 Processing Environment
Processing is based on Java, but because program elements in Processing are fairly simple,
you can learn to use it even if you don't know any Java.

If you're familiar with Java, it's best to forget that Processing has anything to do with Java
for a while, until you get the hang of how the API works.

Processing consists of:

  * The Processing Development Environment (PDE).
    The PDE is an Integrated Development Environment (IDE) with a minimalist set of
    features designed as a simple introduction to programming or for testing one-off ideas.

  * A collection of functions (also referred to as commands or methods) that make up
    the “core” programming interface, or API, as well as several libraries that support
    more advanced features such as drawing with OpenGL, reading XML files, and saving
    complex imagery in PDF format.

  * A language syntax, identical to Java but with a few modifications.
               Sketching with Processing

A Processing program is called a sketch.
The idea is to make Java-style programming feel more like scripting, and adopt the process of
scripting to quickly write code. Sketches are stored in the sketchbook, a folder that's used as
 the default location for saving all of your projects. When you first run Processing, the sketch
last used will automatically open. If this is the first time Processing is used (or if the sketch
is no longer available), a new sketch will open.

Sketches that are stored in the sketchbook can be accessed from File → Sketchbook.
Alternatively, File → Open... can be used to open a sketch from elsewhere on the system.

Advanced programmers need not use the PDE, and may instead choose to use its libraries
with the Java environment of choice.
However, if you're just getting started, it's recommended
that you use the PDE for your first few projects to gain familiarity with the way things are done.

While Processing is based on Java, it was never meant to be a Java IDE with training wheels.
To better address our target audience, the conceptual model (how programs work,
how interfaces are built, and how files are handled) is somewhat different from Java.
     Processing Tutorials




http://processing.org/learning/basics/index.html
 Processing Tutorials




http://processing.org/learning/basics/index.html
    Processing Tutorials




http://processing.org/learning/tutorials/index.html
Processing Environment
            Processing Environment




Run button is an icon that looks like the Play button from any audio or video device.
If you have a code, a new window with a gray background will be appeared.
       Exporting and distributing your work

• Select File → Export to package your current sketch as an
  applet. This will create a folder named applet inside your
  sketch folder. Opening the index.html file inside that folder
  will open your sketch in a browser.

• File → Export Application to bundle your sketch as an
  application for Windows, Mac OS X, and Linux
         Creating images from your work
• saveFrame("output.png");

• To do the same for a numbered sequence, use # (hash marks) where the
  numbers should be placed:

   saveFrame("output-####.png");

• For high quality output, you can write geometry to PDF files instead of the
  screen, as described in the later section about the size() function.
              Libraries add new features
                    http://processing.org/reference/libraries/



• Sketch → Import Library → PDF Export

   import processing.pdf.*;
   beginRecord(PDF, "line.pdf");


• Other libraries provide features such as writing movie files,
  reading images from a camera, sending and receiving MIDI
  and OSC commands, sophisticated 3D camera control, and
  access to MySQL databases.
               Loading and displaying data

• To add a file to the data folder of a Processing sketch,
    Sketch → Add File
• To view the contents of the sketch folder
    Sketch → Show Sketch Folder
loadStrings()
loadImage()
// Examples of loading a text file and a JPEG image
// from the data folder of a sketch.
String[] lines = loadStrings("something.txt");
PImage image = loadImage("picture.jpg");
                                 Hello World!
About size()
•    size(400, 400);
    // The wrong way to specify the middle of the screen ellipse(200, 200, 50, 50);
    // Always the middle, no matter how the size() line changes ellipse(width/2, height/2, 50, 50);

•    Java2D : default, high-quality 2D vector graphics, low speed,
           size(400, 400, JAVA2D);
•    Processing 2D : simpler graphics and fast pixel operations, to draw thousands of simple
                     shapes or directly manipulate pixels of an image or video
          size(400, 400, P2D);
•    Processing 3D : speed and pixel operations, 3D graphics inside a web browser, Image quality is poorer
     (the smooth() function is disabled, and image accuracy is low) but you can draw thousands of triangles
     very quickly
           size(400, 400, P3D);
•    OpenGL : faster rendering, select Import Library, then OpenGL from the Sketch menu
          size(400, 400, OPENGL);
•    PDF : import the PDF library before using it
          size(400, 400, PDF, "output.pdf");
                             Hello World!
For example;

     line(15, 25, 70, 90);

On a gray background, this code generate a black line from coordinate (15, 25) to (70, 90).
The (0, 0) coordinate is the upper left-hand corner of the display window.
                            Hello World!
This program is to change the size of the display window and set the background color.
                            Hello World!
Building on this program to change the size of the display window and set the background
color, type in the code below:
                            Hello World!

Stroke()
•   stroke(255); // sets the stroke color to white
•   stroke(255, 255, 255); // identical to the line above
•   stroke(255, 128, 0); // bright orange (red 255, green 128, blue 0)
•   stroke(#FF8000); // bright orange as a web color
•   stroke(255, 128, 0, 128); // bright orange with 50% transparency
                                    Points

•   Drawing Point Syntax:
    point(x, y);

•   Parameters:
    x     int or float: x-coordinate of the
    point
    y     int or float: y-coordinate of the
    point
                                      Points

•   Drawing Point Syntax:

        point(x, y);

        point(x, y, z);

•   Parameters:

    x        int or float: x-coordinate of the point
    y        int or float: y-coordinate of the point
    z        int or float: z-coordinate of the point
•   Drawing Line
                                           Lines
•   Syntax:
     line(x1, y1, x2, y2);

•   Parameters:
    x1    int or float: x-coordinate of the first point
    y1    int or float: y-coordinate of the first point
    x2    int or float: x-coordinate of the second point
    y2    int or float: y-coordinate of the second point
                                         Lines

•   Drawing Line

•   Syntax:

     line(x1, y1, x2, y2);

     line(x1, y1, z1, x2, y2, z2);
•   Parameters:
    x1    int or float: x-coordinate of the first point
    y1    int or float: y-coordinate of the first point
    z1    int or float: z-coordinate of the first point
    x2    int or float: x-coordinate of the second point
    y2    int or float: y-coordinate of the second point
    z2    int or float: z-coordinate of the second point
                      Points and Lines
•   Constructing a simple dimensional form with lines and rectangles.
Shapes
         Syntax:

         rect(x, y, width, height);

         ellipse(x, y, width, height);

         triangle(x1, y1, x2, y2, x3, y3);

         quad(x1, y1, x2, y2, x3, y3, x4, y4);

         stroke (255);
         stroke (255, 255, 255);
         stroke (125, 250, 112);
         noStroke();

         fill (226);
         fill (226, 226, 226)
         fill (125, 250, 112);
         noFill();

         smooth();
         noSmooth();

         Processing is Case Sensitive!
smooth()
                           Modes for Shapes
Modifies the location from which rectangles draw.

The default mode is rectMode(CORNER), which specifies the location to be the upper left corner of
the shape and uses the third and fourth parameters of rect() to specify the width and height.

The syntax rectMode(CORNERSuses the first and second parameters of rect() to set the location of
one corner and uses the third and fourth parameters to set the opposite corner.

The syntax rectMode(CENTER) draws the image from its center point and uses the third and forth
parameters of rect() to specify the image's width and height.

Syntax:

rectMode(MODE)
                                     Vertices

•   The beginShape() function begins
    recording vertices for a shape and
    endShape() stops recording.

•   A vertex is a location in space
    specified by X, Y and sometimes Z
    coordinates.

•   After calling the beginShape()
    function, a series of vertex()
    functions must follow.

•   To stop drawing the shape, call the
    endShape() functions.
                                     Variables

•   Constructing a simple dimensional
    form with lines and rectangles.

•    Changing the value of the variable
    'd' scales the image.

•    The four variables set the positions
    based on the value of 'd'.
                             Colors
Grayscale Color




         background(255); // Setting the background to white
         stroke(0); // Setting the outline (stroke) to black
         fill(150); // Setting the interior of a shape (fill) to grey
         rect(50,50,75,100); // Drawing the rectangle
Colors

    Red + Green = Yellow
    Red + Blue = Purple
    Green + Blue = Cyan (blue-green)
    Red + Green + Blue = White
    no colors = Black
                        Colors

                        TOOLS (from the menu bar) → COLOR SELECTOR
background(255);
noStroke();

// Bright red
fill(255,0,0);
ellipse(20,20,16,16);
// Dark red
fill(127,0,0);
ellipse(40,20,16,16);
// Pink (pale red)
fill(255,200,200);
ellipse(60,20,16,16);
                   Color Transparency
•   Alpha values also range from 0 to 255, with 0   background(0);
    being completely transparent (i.e., 0%          noStroke();
    opaque) and 255 completely opaque (i.e.,
                                                    // No fourth argument means 100% opacity.
    100% opaque).
                                                    fill(0,0,255);
                                                    rect(0,0,100,200);

                                                    // 255 means 100% opacity.
                                                    fill(255,0,0,255);
                                                    rect(0,0,200,40);

                                                    // 75% opacity.
                                                    fill(255,0,0,191);
                                                    rect(0,50,200,40);

                                                    // 55% opacity.
                                                    fill(255,0,0,127);
                                                    rect(0,100,200,40);

                                                    // 25% opacity.
                                                    fill(255,0,0,63);
                                                    rect(0,150,200,40);
Color Range
colorMode()




• RGB

• HSB
(hue, saturation, and brightness)
•   Hue - The color type, ranges from 0 to 360 by default (think of 360 degrees on a color
    "wheel").
•   Saturation - The vibrancy of the color, 0 to 100 by default.
•   Brightness - The, well, brightness of the color, 0 to 100 by default.
                                  Variables

•   A variable is a way of helping the computer remember a particular piece of information.

•   By default, the computer is stupid: it can only remember things for one line at a time.

•   Returning to the idea of control flow, each time the computer moves from on line of
    code to the next, the program forgets everything that happened on the last line and only
    thinks about the lines it’s currently processing.

•   What variable can do is give a name to a piece of information, so that the computer can
    remember that piece of information whenever in the program the name is called.
    For example, the variable is like a bucket labeled that the computer can store
    information in.

•   From a technical standpoint, what putting a piece of information into a variable does is
    give that information a place in memory.
                                         Variables
•   To set a variable value, you simply use the “ = “ sign.

•   i.e.
      speed = 10

    Now if you want to find out what the speed is later on in our program, we can simply say:

     print speed

    That will print the current value of speed to the message window.
    There are lots of other ways we could use the retrieved value, like making it part of the comparison
    in an if statement.

     if speed > 5 then
                print “Too fast!”
     end if

•       Scope
•       VOID : if you didn’t set or create the variable in advance and call it later.
                                  Variables

How to name your variables?

•   All variable names must be one word, contain no spaces, and begin with a letter.
•   They can also include numbers, but they can’t start with one.

•   1 Speed / Speed_1 / Speed1

•   Also, variable name should be meaningful.

How to recognize a variable?

•   Reserved words appear in color.
              Data - Integers and Floats
Integers and Floats
• Integers and floats are two different kinds of numerical data.
• An integer (more commonly called an int) is a number without a decimal point.
• A float is a floating-point number, which means it is a number that has a decimal place.
    Floats are used when more precision is needed.
Variables
                      Interactive Program

•   A program written as a list of statements (like the previous examples) is called a static
    mode sketch. In static mode, a series of functions are used to perform tasks or create a
    single image without any animation or interaction.
•   Interactive programs are drawn as a series of frames, which you can create by adding
    functions titled setup() and draw() as shown in the code below. These are built-in
    functions that are called automatically.

     void setup() {
          size(400, 400);
          stroke(255);
          background(192, 64, 0);
       }

       void draw() {
          line(150, 25, mouseX, mouseY);
       }
                                void setup()

•   The setup() block runs once.
•   As such, setup() can be used for any initialization; in this case, setting the screen size,
    making the background orange, and setting the stroke color to white.
•   The size() function must always be the first line inside setup().

     void setup() {
          size(400, 400);
          stroke(255);
          background(192, 64, 0);
       }
                               Void draw()

•   While the setup() block runs once, and the draw() block runs repeatedly.
•   The draw() block is used to handle animation.

     void setup() {
          size(400, 400);
          stroke(255);
          background(192, 64, 0);
       }

       void draw() {
          line(150, 25, mouseX, mouseY);
       }
                                 Void draw()

•   Because the background() function is used only once, the screen will fill with lines as the
    mouse is moved.
•   To draw just a single line that follows the mouse, move the background() function to the
    draw() function, which will clear the display window (filling it with orange) each time
    draw() runs.

     void setup() {
          size(400, 400);
          stroke(255);
       }

       void draw() {
          background(192, 64, 0);
          line(150, 25, mouseX, mouseY);
       }
                       Interactive Program
•   Static mode programs are most commonly used for extremely simple examples, or for
    scripts that run in a linear fashion and then exit.

•   Most programs will employ active mode, which use the setup() and draw() blocks. More
    advanced mouse handling can also be introduced; for instance, the mousePressed()
    function will be called whenever the mouse is pressed. So in the following example,
    when the mouse is pressed, the screen is cleared via the background() function:

      void setup() {
     size(400, 400);
     stroke(255);
      }

      void draw() {
          line(150, 25, mouseX, mouseY);
      }

      void mousePressed() {
          background(192, 64, 0);
      }
                     Mouse Actions

•   Mouse Movement
•   mouseX, mouseY
Mouse Actions - Movement
Mouse Actions – Movement + Pressed
Mouse Actions
Mouse Actions
               Keyboard Actions – Key

The system variable key always contains the
value of the most recent key on the keyboard
that was used (either pressed or released).

For non-ASCII keys, use the keyCode variable.
The keys included in the ASCII specification
(BACKSPACE, TAB, ENTER, RETURN, ESC, and
DELETE) do not require checking to see if they
key is coded, and you should simply use the
key variable instead of keyCode If you're
making cross-platform projects, note that the
ENTER key is commonly used on PCs and Unix
and the RETURN key is used instead on
Macintosh. Check for both ENTER and RETURN
to make sure your program will work for all
platforms.
            Keyboard Actions – KeyCode

The variable keyCode is used to detect special keys
such as the UP, DOWN, LEFT, RIGHT arrow keys
and ALT, CONTROL, SHIFT. When checking for
these keys, it's first necessary to check and see if
the key is coded. This is done with the conditional
"if (key == CODED)" as shown in the example.

The keys included in the ASCII specification
(BACKSPACE, TAB, ENTER, RETURN, ESC, and
DELETE) do not require checking to see if they key
is coded, and you should simply use the key
variable instead of keyCode If you're making cross-
platform projects, note that the ENTER key is
commonly used on PCs and Unix and the RETURN
key is used instead on Macintosh. Check for both
ENTER and RETURN to make sure your program will
work for all platforms.
                             Variable Scope

Scoping

•   A variable which doesn’t need any special declaration is called local variable.

•   What this means is that this kind of variable is only temporary storage for the
    information they contain. Local variables always disappear when the control flow of
    program arrives at the word end.

•   To make a variable that the program can remember for longer, you need to declare the
    variable as a global one. Global variables are the ones that get remembered as long as
    the program is running: They can be modified over and over again but will never be
    forgotten. They can also be used by multiple different scripts, which is something that w
    use multiple scripts at once.

•   i.e.) global gSpeed
                            Variable Scope

Scoping in Processing

•   Variables may either have a global or local "scope". For example, variables declared
    within either the setup() or loop() functions may be only used in these functions.
•   Global variables, variables declared outside of setup() and loop(), may be used anywhere
    within the program.
•   If a local variable is declared with the same name as a global variable, the program will
    use the local variable to make its calculations within the current scope. Variables may be
    localized within classes, functions, and iterative statements.
Variable Scope
                                  Variables

Summary

•   Variables are flexible.
    You can change one number (for example, what you initialize the variable to) and have
    the changes happen thought your whole program.

•   Variables are dynamic.
    They change over time depending on how your program affects them.

•   Variables are long-term.
    Even if you don’t use them for a while, they are stored and can be ready to be used any
    time later on.

•   Variables allow you to communicate between handlers.
     Multiple pieces of your program can operate on the same piece of information,
    changing it in much more sophisticated ways.
              Data - Integers and Floats
Integers and Floats
• Integers and floats are two different kinds of numerical data.
• An integer (more commonly called an int) is a number without a decimal point.
• A float is a floating-point number, which means it is a number that has a decimal place.
    Floats are used when more precision is needed.
             Data – Characters & Strings
Characters
• Characters are typographic symbols such as A, d, and %.
• The character datatype, abbreviated as char, stores letters andsymbols in the Unicode
   format, a coding system developed to support a variety of world languages.
• Characters are distinguished from other symbols by putting them between single quotes
   ('P').

Strings
• A string is a sequence of characters. A string is noted by surrounding a group of letters
    with double quotes ("Processing").
• Chars and strings are most often used with the keyboard methods, to display text to the
    screen, and to load images or files.
                         Data - Characters
Characters & Strings
• Click on the image to give it focus and then type letters to shift the location of the image.
                            Data - Boolean
Boolean
• Boolean data is one bit of information. True or false. It is common to use Booleans with
   control statements to determine the flow of a program.
                      Datatype Conversion
•   It is sometimes beneficial to convert a value from one type of data to another.
•   Each of the conversion functions converts its parameter to an equivalent representation
    within its datatype.
•   The conversion functions include int(), float(), char(), byte(), and others.




                               Put “print (f);” for debugging


                               http://www.asciitable.com/
                                Operators
Logical Operators
• The logical operators for AND (&&) and OR (||) are used to combine simple relational
   statements into more complex expressions.
• The NOT (!) operator is used to negate a boolean statement.
                       Operators

-= (subtract assign)
+ (addition)
/= (divide assign)
- (minus)
*= (multiply assign)
% (modulo)
+= (add assign)
/ (divide)
* (multiply)
++ (increment)
-- (decrement)
Operators
Writing "a++" is equivalent to "a = a + 1".
Writing "a--" is equivalent to "a = a - 1".
                                  For Loops

•   Iteration with a "for" structure constructs repetitive forms.

    int k;
    int num = 12;

    for (int i=0; i < num/3; i++) {
               rect(25, k, 155, 5);
               k+=10;
    }
For Loops
                                 Conditionals

Conditionals 1. “IF” statement

 Conditions are like questions.
 They allow a program to decide to take one action if the answer to a question is true or to
   do another action if the answer to the question is false.
The questions asked within a program are always logical or relational statements. For
   example, if the variable 'i' is equal to zero then draw a line.
                               Conditionals

Conditionals 2. “IF” “Else” statement

We extend the language of conditionals by adding the keyword "else".
This allows conditionals to ask two or more sequential questions, each with a different action.
                                      Arrays
What is an Array?
•   Like a variable, an array is a way of helping the computer remember information from
    one moment to the next.
•   Like a variable, it give a name to whatever information it stores so that the computer can
    retrieve it from memory at a later time, instead of just losing track of that information
    and never being able to get it back.

Arrays are but more powerful!
•   Where a variable can only hold one piece of information, an array can hold a whole
    bunch pieces of information.
•   Not only that it can preserve them in order, so that you can give a logical ordering to the
    pieces of information while still keeping them filed under one name.
•   Each piece of information within the array can change independently, without changing
    any other.
•   Pieces of information can be moved around within the array, and the array can grow and
    shrink in length.
                                         Arrays
Why use an array?
•   After all the syntax is a lot complicated, but good reason to use an array!
•   Related information
    Arrays are really good ways of storing different pieces of information together. For
    example, if you were trying to animate a flower that had ten different petals, you could
    create variables called petal1 through petal10. Unfortunately that would mean that each
    petal would be stored in a different place, and you would have to remember how many
    petals you had, and you would have to develop a naming scheme ... It gets messy very
    quickly. With an array, you could simply store all ten petals sprites in a single list called
    petals and retrieve them one at a time.
•   Adjacency ( Sequentially ordered pieces of information)
    A sense of which variables within them are next to each other. The first item in an array
    is conceptually next to the second item. The tenth item is next to the eleventh and ninth
    items. This means arrays are a great way to store information that has spatial
    component.
•   Variable length
    Array can store as many or as few information as you need, and that number can
    change with your needs as well. For example, imagine that you want to store the name
    and password of everyone who logs into your chat room that you designed. You could
    create a hundred variable for names and a hundred for passwords. Then hope that no
    more than a hundred users ever log in – since you only have a hundred places to store
    their information. Or you could store the information in an array (or two) and never
    have to worry about running out of room .. At least until the computer run out of
    memory.
                                         Arrays

•   An array is a list of data, a list of variables all in a row.

•   Each if these variables is known as a cell of the array.

     myArray = [1, 2, 3, 4];

•   Each piece of data in an array is identified by an index number representing its position
    in the array. Arrays are zero based, which means that the first element in the array is [0],
    the second element is [1], and so on.
                                      Arrays

•   Arrays are similar to objects, so they must be created with the keyword new.

     int[] numbers = new int[3];
     numbers[0] = 90;
     numbers[1] = 150;
     numbers[2] = 30;

•   Every array has a variable length which is an integer value for the total number of
    elements in the array. (People are often confused by the use of length() to get the size
    of a String and length to get the size of an array. Notice the absence of the parentheses
    when working with arrays.)
Arrays
Arrays
                         Sin(), Cos(), Tan()
Sin()
• Calculates the sine of an angle.
• This function expects the values of the angle parameter to be provided in radians
• (values from 0 to 6.28).
• Values are returned in the range -1 to 1.
• Syntax:      cos(angle in radians)

Cos()
• Calculates the cosine of an angle.
• This function expects the values of the angle parameter to be provided in radians (values from
   0 to PI*2).
• Values are returned in the range -1 to 1.
• Syntax:      sin(angle in radians)

Tan()
• Calculates the ratio of the sine and cosine of an angle.
• This function expects the values of the angle parameter to be provided in radians (values from
   0 to PI*2).
• Values are returned in the range infinity to -infinity.
• Syntax:      tan(angle in radians)
                                Project 1

1. Guessing Game

    The computer picks a number between 1 and 10, and the user has to guess it.
    The computer tell the user if the number is too high, too low, or just right.
    When the game ends, the computer will pick a new number and start again.

    a. Write the pseudo-code for the guessing game.
    b. Write a code in Processing.

    Optionally, you can also show the user how many guesses it took them.
                                Project 2

1. Guessing Game

    The computer picks a number between 1 and 10, and the user has to guess it.
    The computer tell the user if the number is too high, too low, or just right.
    When the game ends, the computer will pick a new number and start again.

    a. Write the pseudo-code for the guessing game.
    b. Write a code in Processing.

    Optionally, you can also show the user how many guesses it took them.
                              Assignment 1

1-01. Draw five lines.

1-02. Draw three ellipses.

1-03. Control the position of lines with one variable.

1-04. Control the position and size of two lines with two variables.

1-05. Control the properties of two shapes with two variables.

1-06. Create a simple, regular pattern with six lines.

1-07. Program your pattern from Exercise A1-06 using while().

1-08. Draw a layered form with two new loops.

1-09. Redo Exercise A1-04 using mouseX and mouseY as the variables.
                             Assignment 1

1-10. Draw two visual elements that each move in relation to the mouse in a different way.

1-11. Draw three visual elements that each move in relation to the mouse in a different way.

1-12. Move a visual element across the screen. When it disappears off the edge, move it
   back into the frame.

1-13. Draw a visual element that moves in relation to the mouse, but with a different
   relation when the mouse is pressed.

1-14. Using if and else, make the mouse perform different actions when in different parts of
   the window.

1-15. Develop a kinetic image which responds to the mouse.
                             Assignment 2
2-01.
Using beginShape() and endShape(), create a composition with five or more vertices.
a dynamic animation using the cos() and sin() function as a generator for motion.

2-02.
Using beginShape() and endShape(), create a composition with ten or more vertices.

2-03.
Create an image different from A2-02, but using the same vertex data.

2-04.
Write a function with one parameter and demonstrate it visually.

2-05.
Write a function for drawing triangles and visually demonstrate its flexibility.

2-06.
Write a function with three or more parameters and visually demonstrate its flexibility.
                               Assignment 2
2-07.
Create a dynamic animation using the cos() function as a generator for motion.

2-08
Create a dynamic animation using the cos() and sin() function as a generator for motion.

2-09.
Move two visual elements across the screen using the random() function as a generator of
movement. Give each element a unique nonliear motion.

2-10.
Create an event that begins when the mouse is pressed and ends when the mouse is released.

2-11.
Create a responsive image that behaves differently when the mouse is moving and the mouse
is dragging.

2-12.
Create a button that changes the color of the background when it is clicked.
                              Assignment 3

3-01.
Create a subclass of PImage that implements a mosaic(int blockSize) method.
Demonstrate your new class by drawing an image with several different block sizes.



3-02.
Write a small app that demonstrates kinetic text.
Your app should allow the user to type something and move the text around in some while
    they type.
For example, the user might type text on a line, but slowly the words or letters start drifting
    apart, or perhaps the line starts bending, or the words and letters flutter to the bottom
    of the screen, etc.
Of course you shouldn't exactly copy any of the typographic in Processing or that you find
    on the web (though using such examples for inspiration, as a place to start modifying
    code, etc. is fine).
Assignment 02 - Clock
                   Assignment 02 - Clock
1. Guessing Game
             Loading and displaying data

•   One of the unique aspects of the Processing API is the way files are handled.
•   The loadImage() and loadStrings() functions each expect to find a file inside a folder
    named data, which is a subdirectory of the sketch folder.

•   File handling functions include loadStrings(), which reads a text file into an array of
    String objects, and loadImage() which reads an image into a PImage object, the
    container for image data in Processing.

     // Examples of loading a text file and a JPEG image
     // from the data folder of a sketch.
     String[] lines = loadStrings("something.txt");
     PImage image = loadImage("picture.jpg");
              Loading and displaying data
     String[] lines = loadStrings("something.txt");
     PImage image = loadImage("picture.jpg");

•   These examples may be a bit easier to read if you know the programming concepts of
    data types and classes. Each variable has to have a data type, such as String or PImage.

•   The String[] syntax means “an array of data of the class String.”
•   This array is created by the loadStrings function and is given the name lines; it will
    presumably be used later in the program under this name. The reason loadStrings
    creates an array is that it splits the something.txt file into its individual lines.

•   The following function creates a single variable of class PImage, with the name image.

•   To add a file to the data folder of a Processing sketch, use the Sketch → Add File menu
    option, or drag the file into the editor window of the PDE. The data folder will be created
    if it does not exist already.

•   To view the contents of the sketch folder, use the Sketch → Show Sketch Folder menu
    option. This opens the sketch window in your operating system's file browser.
        Creating images from your work

•   If you don't want to distribute the actual project, you might want to create images of its
    output instead. Images are saved with the saveFrame() function. Adding saveFrame() at the
    end of draw() will produce a numbered sequence of TIFF-format images of the program's
    output, named screen-0001.tif, screen-0002.tif, and so on. A new file will be saved each time
    draw() runs — watch out, this can quickly fill your sketch folder with hundreds of files. You can
    also specify your own name and file type for the file to be saved with a function like:

     saveFrame("output.png")


•   To do the same for a numbered sequence, use # (hash marks) where the numbers should be
    placed:

     saveFrame("output-####.png");


•   For high quality output, you can write geometry to PDF files instead of the screen.
                         More about size()

•   The size() function also sets the global variables width and height. For objects whose
    size is dependent on the screen, always use the width and height variables instead of a
    number. This prevents problems when the size() line is altered.

       size(400, 400);

     // The wrong way to specify the middle of the screen
        ellipse(200, 200, 50, 50);

       // Always the middle, no matter how the size() line changes
       ellipse(width/2, height/2, 50, 50);
                            More about size()
•   In the earlier examples, the size() function specified only a width and height for the
    window to be created. An optional parameter to the size() function specifies how
    graphics are rendered.
•   A renderer handles how the Processing API is implemented for a particular output
    function (whether the screen, or a screen driven by a high-end graphics card, or a PDF
    file).
•   Several renderers are included with Processing, each having a unique function. Here's a
    description of the possible drawing modes to use with Processing.

     size(400, 400, JAVA2D);

•   The Java2D renderer is used by default, so this statement is identical to size(400, 400).
    The Java2D renderer does an excellent job with high-quality 2D vector graphics, but at
    the expense of speed. In particular, working with pixels is slower compared to the P2D
    and P3D renderers.

     size(400, 400, P2D);

•   The Processing 2D renderer is intended for simpler graphics and fast pixel operations. It
    lacks niceties like stroke caps and joins on thick lines, but makes up for it when you need
    to draw thousands of simple shapes or directly manipulate pixels of an image or video.
                         More about size()

       size(400, 400, P3D);

•   Similar to P2D, the Processing 3D renderer is intended for speed and pixel operations. It
    also produces 3D graphics inside a web browser, even without the use of a library like
    Java3D. Image quality is poorer (the smooth() function is disabled, and image accuracy
    is low) but you can draw thousands of triangles very quickly.

     size(400, 400, OPENGL);

•   The OpenGL renderer uses Sun's JOGL (Java for OpenGL) library for faster rendering,
    while using Processing's simpler graphics APIs and the Processing development
    environment's easy applet and application export. To use OpenGL graphics, in addition to
    altering your size() function, you must select Import Library, then OpenGL from the
    Sketch menu. OpenGL applets also run within a web browser without additional
    modification, but a dialog box will appear asking the user whether they trust “Sun
    Microsystems, Inc.” to run Java for OpenGL on their computer. If this poses a problem,
    the P3D renderer is a simpler, if less full-featured, solution.
                         More about size()
      size(400, 400, PDF, "output.pdf");

•   The PDF renderer draws all geometry to a file instead of the screen. Like the OpenGL
    library, you must import the PDF library before using it. This is a cousin of the Java2D
    renderer, but instead writes directly to PDF files.

•   Each of the renderers has its own specific role. P2D and P3D are great for pixel-based
    work, while the JAVA2D and PDF settings will give you the highest quality 2D graphics.

•   When the Processing project first began, the P2D and P3D renderers were a single
    choice (and in fact, the only available renderer). This was an attempt to offer a unified
    mode of thinking about drawing, whether in two or three dimensions. However, this
    became too burdensome because of the number of tradeoffs that must be made
    between 2D and 3D. A very different expectation of quality exists for 2D and 3D, for
    instance, and trying to cover both sides meant doing both poorly.
Arduino Starter Kit
http://www.plughouse.co.kr/

http://www.plughouse.co.kr/shop/goods/Goods_view.php?G
_code=20082605191625
                             Repeat Loops

What is a Repeat Loop?

•   Like an if statement, a repeat loop is a control flow structure: a command that changes
    the order in which program commands are executed.

•   A repeat loop is a way to signal to the computer that you want to do something multiple
    times in a row, looping over and over the same set of commands.
•   This is what’s know as iteration.

•   Two key factor that make repeat loop’s looping quality useful.
•   1. Repeat loops don’t repeat forever: each repeat loop has a termination condition,
       a statement that defines when it will stop repeating.
    2. Some repeat loops increment a variable each time through the loop, so that you can
     know which iteration of the code you are currently involved with.
     This lets you do the same thing over and over with slight variations.
                              Repeat Loops

Repeat Loop Syntax

•   repeat while condition
     commands go there
    end repeat

When the computer sees the words “repeat while”, it immediately check if the condition that
  follows it is true. For example, if the condition were gSpeed < 5 then it would check to
  se whether gSpeed was less than 5.

If the condition is ever false, the computer immediately skips to the next line of code after
     the words “end repeat”.
                             Repeat Loops

Repeat Loop Syntax

   counter = 1
   put “This loop will repeat ten times exactly.”
   repeat while counter <= 10
    put “This is repeat number “ & counter
    counter = counter + 1
   end repeat

   counter = 1
   repeat while counter <= 10
    rectangle.locv = rectangle.locv + counter * 10
    counter = counter + 1
   end repeat

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:11
posted:7/15/2012
language:simple
pages:110