SlideShare a Scribd company logo
1 of 202
LearningProcessing
Beginning
Daniel Shiffman
Graphics from http://www.learningprocessing.com/tutorials/
Section 1
基本概念
Invitation to Computer Science, Java Version, Third Edition 2
What is an image?
Digital
Camera
Source: A. Efros
255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 20 0 255 255 255 255 255 255 255
255 255 255 75 75 75 255 255 255 255 255 255
255 255 75 95 95 75 255 255 255 255 255 255
255 255 96 127 145 175 255 255 255 255 255 255
255 255 127 145 175 175 175 255 255 255 255 255
255 255 127 145 200 200 175 175 95 255 255 255
255 255 127 145 200 200 175 175 95 47 255 255
255 255 127 145 145 175 127 127 95 47 255 255
255 255 74 127 127 127 95 95 95 47 255 255
255 255 255 74 74 74 74 74 74 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255
A Grid of Intensity Values
(commonto use one byte per value: 0 = black, 255 = white)
=
255 75 75 255 255
175 175 175 255 255
200 145 175 255 255 255
200 175 175 175 255 255
145 200 200 175 175 95
200 200 175 175 95
145 175 127 127 95
Image as Grid of Values
75
95
127
145
145
145
145
75
95
145
95
95
255
175
175
127
75
75
175
95
145
200
145
200
145
175
175
175
175
127
255
255
255
75
175
175
200
175
200
127
255
175
175
127
255
255
255
255
175
175
200
175
200
127
255
95
95
95
255
255
255
255
175
95
175
95
175
95
175
200
200
175
255
255
255
175
175
175
175
175
127
255
95
95
255
175
175
127
GraphPaper
Every point on the screen is a pixel
It has a location: (x, y)
Learning Processing: Slides by Don Smith 6
Upper left corner is 0,0
X is ‘across’ (to right as x increases)
Y is ‘down’ (down as y increases)
Learning Processing: Slides by Don Smith 7
CoordinateSystem
NOT the same as your Algebra coordinate system!
SimpleShapes
What do we need to specify a shape?
Point: x and y
Line: Two end points?
Rectangle: Two corners? Or ???
Ellipse: ????
Learning Processing: Slides by Don Smith 8
Point
Note that x (across) comes first
In Processing: point(x, y);
lower case ‘point’
two ‘parameters’ in parenthesis
Semicolon;
Learning Processing: Slides by Don Smith 9
Line
Learning Processing: Slides by Don Smith 10
 Two Points: A and B
 In Processing: line(x1, y1, x2, y2);



lower case ‘line’
four ‘parameters’ in parenthesis
Semicolon;
Rectangle1
From Corner: One Point for top left corner
In Processing: rect(x, y, width, height);
lower case ‘rect’
four ‘parameters’ in parenthesis
Semicolon;
NOTE: This is the default mode (CORNER)
Learning Processing: Slides by Don Smith 11
Rectangle2
From Center: One point, size
In Processing:
rectMode(CENTER);
rect(x, y, width, height);
Two lines of code
Learning Processing: Slides by Don Smith 12
Rectangle3
CORNERS: Top Left point, Bottom Right point
In Processing:
rectMode(CORNERS);
rect(x1, y1, x2, y2);
Two lines of code
Learning Processing: Slides by Don Smith 13
EllipseModes
Same as rectangle modes:
CENTER (x, y, width, height)
CORNER (x, y, width, height)
CORNERS (x1, y1, x2, y2)
Draws ellipse in a ‘Bounding box’
Circle is a ‘special case’ of an ellipse (width = height)
Learning Processing: Slides by Don Smith 14
SizeMatters
You can specify the size of your ‘canvas’ at the
start of a ‘script’
size(width, height);
Use 200 x 200 to get started
It matches the ‘graphPaper200x200.doc’ file
Learning Processing: Slides by Don Smith 15
Color: Grayscale
You can set the color of lines and background:
0 is black (no ‘light’)
255 is white (most ‘light’)
Some examples in processing:
background(255);
stroke(0);
fill(150);
// Sets background to white
// Sets outline to black
// Sets interior of a shape to grey
rect(50,50,75,100); // Draws shape with most recent settings
Learning Processing: Slides by Don Smith 16
GrayscaleExample
To fill or not to fill
If noFill() is set, shapes have only an outline
What are the ‘default’ grayscales of:
Background:
Stroke:
Fill:
Learning Processing: Slides by Don Smith 17
RGBColor
Color Mixing 101:
Red + Green = Yellow
Red + Blue = Purple
Green + Blue = Cyan (blue-green)
Red + Green + Blue = White
no colors = Black
Learning Processing: Slides by Don Smith 18
 RGB Values
 Each color has a value between 0 and 255


0 means NONE of that color
255 means MAX of that color
Learning Processing: Slides by Don Smith 19


Use fill(),background() or stroke() with three
parameters:
 fill(red, green, blue);
Then draw a shape!
// Bright red
// Dark red
// Pink (pale red)
ManualColors
background(255);
noStroke();
fill(255,0,0);
ellipse(20,20,16,16);
fill(127,0,0);
ellipse(40,20,16,16);
fill(255,200,200);
ellipse(60,20,16,16);
PickingColors
Learning Processing: Slides by Don Smith 20
 Processing has a color selector to aid in
choosing colors.
 Access this via TOOLS (from the menu bar)
→ COLOR SELECTOR.
There is a fourth ‘parameter’ you can use:
Called ‘Alpha’
0 means transparent
255 means opaque
No fourth parameter means ‘100% opacity’
Learning Processing: Slides by Don Smith 21
Transparency
// 50% opacity.
fill(255,0,0,127);
// 25% opacity.
fill(255,0,0,63);
rect(0,150,200,40);
NowGettoWork!
Plan a more interesting alien!
Use grayscale!
Black eyes
Gray body
Learning Processing: Slides by Don Smith 22
Section 2
开发环境
Invitation to Computer Science, Java Version, Third Edition 23
Installing
Finding the files
Website: www. processing.org – click Download
Blackboard: Files, Tools folder
Version 2.1.1 is the most current
Download (110MB) processing-2.1-windows64
If you already have Java installed:
Install the Windows (Without Java) expert version instead
processing-xxx-expert.zip - From www.processing.org
Unzip , or open and extract files
Let it choose defaults (location…)
Installs Java SDK automatically and examples
Puts Java files in a folder under Processing
Works with XP and Win7
Installs an icon on your desktop
Learning Processing: Slides by Don Smith
24
WheredoesJavafitin?
Processing provides a
simple ‘front end’ to Java.
Processing requires Java
SDK to be installed
Software Development Kit
Processing has it’s own
library for graphics
Java’s library (API) can
also be used in
Processing
Learning Processing: Slides by Don Smith 25
Processing Source code
Processing
Java Compiler
Portable Java Program
Processing
Library
Java
Library
TheJavaVirtualMachine(JVM)
Java was designed to run on embedded systems, it was
designed around a virtual machine
“Write once, run everywhere”
Called the JRE (Java Runtime Environment)
Portable Java Program
PC
Java VM
Windows
x86
Running
Java
Program
Mac
Java VM
OS X
G3/4/5
Running
Java
Program
Cell Phone
Java VM
Phone OS
CPU
Running
Java
Program
JRE
SketchMenuOptions
Processing has an ‘PDE’ called Sketch
File: New, Open, Quit, Examples!
Edit: Copy, Paste, Select, Indent, Comment…
Sketch: Run, Stop, Show Sketch folder…
Tools: Auto format, Color chooser…
Help: Getting Started, Reference, Find in Reference…
Learning Processing: Slides by Don Smith 27
PDE
28
Menu
Toolbar
Sketch Tabs
Text Editor
Message Line
Text Area
Current Line#
To run: Menu Sketch, Run, Ctrl-R or Toolbar Run button
You either get a display window (all’s well) or an error in Message Area
Learning Processing: Slides by Don Smith
Display
Window
Toolbarbuttons
Learning Processing: Slides by Don Smith 29
GettingStarted
Learning Processing: Slides by Don Smith 30
 Help, Getting Started goes to processing
website and explains:






Processing Development Environment (PDE)
 All menu options, hot keys
Sketchbook
Tabs, Multiple Files, and Classes
Coordinates
Programming Modes
Rendering Modes
SketchFilesandFolders…
The folder where you store your sketches is
called your ‘Sketchbook’
Sketch stores files under where Processing was
installed
May not be where you want.
Use File, Save As to select a folder on your flash drive
Processing remembers where you last saved
Each sketch has it’s own folder
File extension ‘PDE’ is a Processing Development Environment
file
Double click on PDE file to open Sketch for that folder
Learning Processing: Slides by Don Smith 31
Whereareyourfiles?
Choose File,
Preferences
Select new location for default
Not flash drive (not always there)
Learning Processing: Slides by Don Smith 32
YourFirstProgram
Open a new sketch
Default name is based on date/time
In the Text window, type:
// My first Program
Print(“Hello World by me”);
rect(10, 10, 50, 50);
One comment and two lines of code
Run it… If no errors,
What is in the Message/Text Area?
What is in the Display window?
Learning Processing: Slides by Don Smith 33
Errors
The brown line tells you what is wrong
Editor window: The line with the error is highlighted
RECT should be lower case (rect)
Learning Processing: Slides by Don Smith 34
 Note: Processing only shows one error at a time
Help,FindInReference
Double click key word (highlights in yellow)
Menu: Help, Find in Reference: (or Ctrl-Shift-F)
Does not work if word is mis-spelled
Normally goes directly to detailed page (local)
Usually provides an example
Learning Processing: Slides by Don Smith 35
Lab: ZoogHeadstand
Draw your alien – Upside Down!
Use grayscale
White head
Black eyes
Gray body
Add a comment with your name at the top
Add: print(“Zoog Headstand by <Your name>”);
Save your sketch
To your flash drive
Submit your sketch (pde) via Blackbloard
Learning Processing: Slides by Don Smith 36
Section 3
编程基础
Invitation to Computer Science, Java Version, Third Edition 37
Programflow
Games are written with ‘loops’
Like running a race
Prepare (put on shoes…)
Loop putting feet forward over and over
Run until the race is over
Remember that programs are made of parts:
Sequential
Conditional
Iterative
Learning Processing: Slides by Don Smith 38
Usingyourfirst‘methods’!
setup()and draw()are ‘methods’
Think of them as named ‘blocks’ of code
You get to write the code inside the ‘block’
New symbols and words! (just look for now)
void
()
//
{ }
Learning Processing: Slides by Don Smith 39
A‘block’ofcode
Parts of a program are separated into blocks
In Java, C, C++, PHP and many other languages:
Blocks are surrounded by curly braces: { ….. }
Think of blocks like an outline set of sub-steps:
1
1a
1b
2
Programmers (and editors) line up code in blocks
Usually indent the ‘statements’ inside the block
Learning Processing: Slides by Don Smith 40
setup()anddraw()methods
When your program starts,
Processing:
Calls setup() once
Continues to call draw() unti
the program ends
Learning Processing: Slides by Don Smith 41
Program Starts
Call setup()
Call draw()
Done
yet?
Yes
Program ends
No
CodeforZoogasadynamicsketch
All of your code can go into two ‘blocks’:
The‘invisible’lineofcode…
When does processing ‘paint’ the screen?
Learning Processing: Slides by Don Smith 43
TrackingtheMouse
Processing keeps track of where the mouse is:
mouseX: The current X coordinate of the mouse
mouseY: The current Y coordinate of the mouse
These are both ‘key words’ that you can use!
Their values change as the mouse moves
An example:
Learning Processing: Slides by Don Smith 44
MoreMousetracks…
Processing also keeps track of where the mouse
WAS the last time you left draw():
pmouseX: The previous X coordinate of the mouse
pmouseY: The previous Y coordinate of the mouse
Learning Processing: Slides by Don Smith 45
Ascribbleapplication
Learning Processing: Slides by Don Smith 46
 Just keep connecting the points where the
mouse was and it is now:
MouseclicksandKeypresses
Learning Processing: Slides by Don Smith 47


Two ‘methods’ that you can
write to handle events that
might happen:
Processing ‘calls’ your
method when events occur:
 mousePressed()
 keyPressed()
Processingsetup()method
Things that you may use during setup():
size(200,200);
smooth();
frameRate(30);
background(255);
// defaults to 60 frames/sec
// clear the screen
Each may be used for their own purposes
Some may also be used in draw()methods
What would this do to your drawing if the
background(255)call was in draw()?
Learning Processing: Slides by Don Smith 48
Usingbackground(255)
void setup() {
size(200,200);
background(255);
}
void draw() {
line(mouseX, mouseY, 100,100);
}
void setup() {
size(200,200);
}
void draw() {
background(255);
line(mouseX, mouseY, 100,100);
}
49

Try these
Learning Processing: Slides by Don Smith
Section 4
变量
Invitation to Computer Science, Java Version, Third Edition 50
Learning Processing: Slides by Don Smith 51
Whatisavariable?
Storage Analogies:
Different sizes
Like a bucket
Like a locker
Graph Paper/Spreadsheet
Many ‘storage’ places, all with
unique locations (x,y)
In Excel, E3 could be named ‘Billys
Score’
Billy’s score can change!
A B C D E F
1
2
3
4
5
Learning Processing: Slides by Don Smith 52
Whatisavariable?
In Algebra:
x=y*z
Named with single letters to represent some number
In Programming:
We use longer, more descriptive names
Variables refer to ‘memory locations’
Stored in ‘RAM’
Random Access Memory
Have a ‘size’
How many bytes of memory ‘wide’
Learning Processing: Slides by Don Smith 53
Variablesmustbe‘Declared’
What is a Declaration?
Programmer tells the compiler:
Type
Name
;
What is a Type?
Each type requires a specific amount of storage
‘Primitive’ types include three main categories
Integers – Whole Numbers (positive and negative), no fractions
Floating point – Numbers with fractional parts and exponents
Characters – One letter that you can type
A, B, C, a, b, c, 1, 2, 3, %, &….
Learning Processing: Slides by Don Smith 54
AllPrimitiveTypes
Integer Types
byte: A very small number (-127 to +128)
short: A small number (-32768 to +32767)
int:
long:
A large number (-2,147,483,648 to +2,147,483,647)
A huge number
Floating Point Types
float: A huge number with decimal places
double: Much more precise, for heavy math
Other Types
boolean: true or false
char: One symbol in single quotes ‘a’
55
PrimitiveTypeStorage
Integer Types
byte:
short:
int:
long:
Floating Point Types
float:
double:
Other Types
boolean:
char:
Learning Processing: Slides by Don Smith
Learning Processing: Slides by Don Smith 56
PrimitiveTypeExamples
Integer Types
byte:
short:
int:
long:
123
1984
1784523
234345456789
Floating Point Types
float:
double:
4.0
3.14159
Other Types
boolean: true
char: ‘a’
Numericversus‘Character’types
How do you decide if you need a numeric or
a character type?
If you plan on doing ‘math’ on the variable, then
you MUST use a numeric type
What is the letter ‘a’ times the letter ‘c’?
Notice the single quotes around characters
If you plan on using “Strings” (later), they are just
words made up of characters.
“Bob” and “Mary” are Strings (of characters)
Notice the double quotes around strings
What is the string “Bob” times the string “Mary”?
Learning Processing: Slides by Don Smith
57
Learning Processing: Slides by Don Smith 58
DeclaringandInitializingVariables
What is Initialization?
Setting an initial value into the contents of the variable
Pseudocode: Set NumPlayers to 5
Can be done in two ways:
During Declaration: On one line
int count = 50; // declare and initialize
After declaration: On two lines
int count;
count = 50;
// declare the variable
// initialize the value
Can also be initialized with a calculation!
int max = 100;
int min = 10;
int count = max – min; // calculation
PongVariables
What variables would be required to play?
Scores?
Paddle locations?
Ball location?
Net location
Screen Size?
Learning Processing: Slides by Don Smith
59
Learning Processing: Slides by Don Smith 60
NamingVariables
There are some ‘rules’ and some ‘best practices’
Rules
Letters, Digits and underscore ( _ ) are OK to use
Cannot start with a digit ( 0,1,…9 )
Cannot use reserved words
mouseX, int, size..
Best Practices
Use descriptive names
boolean moreToDo;
Use ‘camelHump’ notation
Start with lower case
Each new word starts with Upper Case
DeclarationandInitializationExamples
Type name (optional initialization) ;
int count = 0;
char letter = 'a';
double d = 132.32;
boolean happy = false;
float x = 4.0;
float y;
// Declare an int , initialized to 0
// Declare a char, initialized to 'a'
// Declare a double, initialized to 132.32
// Declare a boolean, initialized to false
// Declare a float, initialized to 4.0
// Declare a float (no assignment)
float z = x * y + 15.0; // Declare a float, initialize it to
// x times y plus 15.0.
After declaration Assignments:
count = 1;
letter = ‘b’;
happy = true;
y = x + 5.2; // Assign the value of x plus 5.2
Learning Processing: Slides by Don Smith 61
DeclarationandInitializationIssues
You can only initialize a variable to a value
of the same, or compatible type:
Which initializations are compatible?
int count = ‘a’;
char letter = 0;
double deposit = “Fred”;
boolean happy = 1;
float feet = 6;
int inches = feet * 12;
long giant = feet * 3.0;
Learning Processing: Slides by Don Smith 62
DeclarationandInitializationIssues
You can only initialize a variable to a value
of the same, or compatible type.
Which initializations are compatible?
int count = ‘a’;
char letter = 0;
double deposit = “Fred”;
boolean happy = 1;
float feet = 6;
int inches = feet * 12;
long giant = feet * 3.0;
Learning Processing: Slides by Don Smith 63
WheretoDeclareVariables
Remember that your code is in ‘blocks’
Variables can go inside or outside these blocks
For now, we will put them ‘outside’ (before) blocks
VaryingVariables: Example
Remember that processing calls draw()in a loop
If you want the variable to change every time:
Declare and initialize it outside of draw()!
Change it inside draw()!
Moves as circleX increases 
Callto
draw()
circleX
1 0
2 1
3 2
4 3
5 4
…
200 199
66
WhathappensinPre-example?
circleX Is initialized to 0
Used first time draw()is called
ellipse(circleX, circleY, 50,50);
Then circleX = circleX + 1;
Next time draw()is called, circleX is 1
ellipse(circleX, circleY, 50,50);
Then circleX = circleX + 1;
Next time draw()is called, circleX is 2
ellipse(circleX, circleY, 50,50);
Then circleX = circleX + 1;
.. Until circleX is over 200, and the circle just
moves off the right side of the screen, never to be
seen again!
It is often useful to make a ‘table’ of all of the
variables that are being changed every time
through a ‘loop’
Learning Processing: Slides by Don Smith
Callto
draw()
circleX circleY circleW circleH
1 0 0 50 100
2 0.5 0.5 50.5 100.5
3 1.0 1.0 51 101
10 4.5 4.5 54.5 104.5
30 14.5 14.5 64.5 114.5
100 49.5 49.5 99.5 149.5
200 99.5 99.5 149.5 199.5
UsingManyVariables
Make things more interesting using more variables!
Declare and initialize them outside of draw()!
Change them inside draw()!
Learning Processing: Slides by Don Smith 68
SystemVariables
Processing provides many ‘built-in’ variables:
These are not for you to play with, but may change!
mouseX , mouseY, pmouseX and pmouseY
width: Width (in pixels) of sketch window
height: Height (in pixels) of sketch window
frameCount: Number of frames processed
frameRate: Rate (per sec.) that frames are processed
screen.height, screen.width: Entire screen
key: Most recent key pressed on keyboard
keyCode: Numeric code for which key pressed
mousePressed: True or false (pressed or not?)
mouseButton: Which button (left, right, center)
Learning Processing: Slides by Don Smith 69
Random: Varietyisthespiceoflife
Processing (and all programming languages)
provide a way to get a random value when your
program runs.
random() is a ‘function’ that returns a float
You can assign this number to a variable and use it!
Some examples:
Whatisthat(int)and(1,100)stuff?
(int)
Since random()returns a floating point number
and w is an int, we need to change the type from
float to int.
This is called ‘casting’
random(1,100) ;
(1,100) are ‘parameters’ which tell the random
function the range of numbers to return
w will be between 1 and 99 (not quite 100)
Learning Processing: Slides by Don Smith
70
MakeZoogMove!
Use variables to make Zoog move and change!
1) Make Zoog rise from below the screen
Need variables for the Zoog’s X and Y locations
Note: Locations of ALL of Zoog’s parts need to use them
If left eye is left 30 and down 50 from the center of the head:
ellipse( zoogX – 30, zoogY + 50, 20, 30);
2) Change his eye color randomly as he moves
Need variables for Zoog’s eye color (R,G and B)
Learning Processing: Slides by Don Smith 71
Lab: MovingZoog
Use variables and random() to make a Zoog
move from upper left to lower right of the screen.
Starting point is provided (Example 4.8)
Plan!
Declare variables
Use variables
Use Random
Learning Processing: Slides by Don Smith 72
1 2 3 4 5 6 7 8 9 10
73
Whydowecare(aboutarrays)?
What if you have a whole bunch of cars (or aliens
or balls or ???) bouncing around the screen?
How do we keep track of where each one is?
int car1X, car1Y, car2X, car2Y, car3X, car3Y……
How about keeping them in a ‘table’ or a ‘grid’
CarX table:
Each ‘column’ has a number
You can refer to CarX table, column 3 for Car3…
Note that all of the values in the row must be the
same data type
Learning Processing: Slides by Don Smith
Learning Processing: Slides by Don Smith 74
WhentouseanArray
Any time a program requires multiple instances
of similar data, it might be time to use an array.
For example, an array can be used to store:
The scores of four players in a game
A selection of 10 colors in a design program
A list of fish objects in an aquarium simulation
The days per month in a scheduling program
75
Whatisanarray?
A variable is a named
location in memory.
An array is a named set
of locations in memory
A ‘list’ of variables
Each element of the list
has a number called an
‘index’
Starts at 0!
Learning Processing: Slides by Don Smith
76
Whystartat0? Whynot1?
Which of the following is why arrays start at 0?
A)
B)
C)
D)
Because programmers think that way
Because I say so
So that programmers can make ‘the big bucks’
So you can use loops easily to ‘walk’ the array
Here’s a preview of adding up all the ‘votes’:
int sumArray(int size) {
int sum = 0;
for (int c = 0; c < size; c++) {
sum = sum + votes[c]; // huh? [ ]?
}
return sum;
}
Learning Processing: Slides by Don Smith
HowtoDeclareanarray(Step1)
Create the array variable (with the name and type)
Make a named ‘list’ with the following parts:
Type Square Braces Array name semicolon
int [ ] arrayOfInts ;
You are ‘declaring’ that
There is an array named arrayOfInts
The elements inside are of type int
You have not (YET) declared how many are in inside
Other Rules:
Arrays can be declared anywhere you can declare a
variable
Do not use ‘reserved’ words or already used names
Learning Processing: Slides by Don Smith 77
HowtoCreateanarray(Step2)
Reserve memory for all of the elements in the list:
Array name Keyword Type Size semicolon
arrayOfInts = new int [42] ;
Learning Processing: Slides by Don Smith 78
You are reserving memory for:
The array named arrayOfInts
Needs storage for [42]
elements the size of type int
Now you (and the compiler) know how many are in
inside
You cannot change the size after you declare it!
arrayOfInts
[0] [1] [2] [3] [4] … [41]
int int int int int int
TwoStepsononeline:
Declare and Create at the same time:
Type Braces Array name Keyword Type Size semi
int [] arrayOfInts = new int [42] ;
You are ‘declaring’ that
There is an array named arrayOfInts
The elements inside are of type int
You are reserving memory for the array
Needs storage for [42]
elements the size of type int
Note that the size cannot be changed, so you should make
enough room when you start!
Learning Processing: Slides by Don Smith
79
Exercise: Writethedeclarationsfor:
Declare the array variable (step 1) for these:
Learning Processing: Slides by Don Smith 80
Exercise: Writethedeclarationsfor:
Declare the array variable (step 1) for these:
// type [] arrayName ;
int [] arrayOfInts;
float [] hundredFloats;
Zoog [] zoogArmy;
Learning Processing: Slides by Don Smith 81
Exercise: Writethedeclarationsfor:
Declare storage (step 2) for the following:
Learning Processing: Slides by Don Smith 82
Exercise: Writethedeclarationsfor:
Declare storage (step 2) for the following:
// arrayName = new type[size];
arrayOfInts = new int[30];
hundredFloats = new float[100];
zoogArmy = new Zoog[56];
Learning Processing: Slides by Don Smith 83
Exercise: Writethedeclarationsfor:
Both Steps 1 and 2 on the same line:
Learning Processing: Slides by Don Smith 84
Exercise: Writethedeclarationsfor:
Both Steps 1 and 2 on the same line:
// type [] arrayName = new type[size];
int [] arrayOfInts = new int[30];
float [] hundredFloats = new float[100];
Zoog [] zoogArmy = new Zoog[56];
Learning Processing: Slides by Don Smith 85
Exercise: What’swrongwiththese?
May be valid, maybe not!
Learning Processing: Slides by Don Smith 86
87
InitializinganArray
The ‘long’ way
int [] stuff = new int[3];
stuff[0] = 8;
stuff[1] = 3;
stuff[2] = 1;
The one-liner way:
int [] stuff = { 8, 3, 1 };
The compiler counts the number of elements (3)
Sets the size automatically!
Fills the contents with the values inside the { };
Values are separated by commas
Learning Processing: Slides by Don Smith
InitializingwithIteration
Rolling 5 dice (Yahtzee) Example
The ‘hard’ way
Learning Processing: Slides by Don Smith 88
int[] die = new int[5];
=
=
=
=
=
(int)random(0,6);
(int)random(0,6);
(int)random(0,6);
(int)random(0,6);
(int)random(0,6);
die[0]
die[1]
die[2]
die[3]
die[4]
Using a while loop:
int n = 0;
while (n < 5) {
die[n] = random(0,6);
n = n + 1;
}
InitializingwithIteration
Rolling 5 dice (Yahtzee) Example
The ‘hard’ way
Learning Processing: Slides by Don Smith 89
int[] die = new int[5];
die[0]
die[1]
die[2]
die[3]
die[4]
=
=
=
=
=
(int)random(0,6);
(int)random(0,6);
(int)random(0,6);
(int)random(0,6);
(int)random(0,6);
Using a for loop:
for (int n = 0; n < 5; n++ ) {
die[n] = (int)random(0,6);
}
Learning Processing: Slides by Don Smith 90
Exercise: Loop/Arrayexample:
Using a for loop to initialize an array:
float[] values = new float[6];
for (int i = 0; i < values.length; i++)
values[i] = 0;
Note the use of values.length
The array knows how long it is!
Now write code to square each entry:
int [] nums = { 5, 4, 2, 7, 6, 8, 5, 2, 6, 14 };
Learning Processing: Slides by Don Smith 91
Exercise: Loop/Arraycontinued:
int [] nums = { 5, 4, 2, 7, 6, 8, 5, 2, 6, 14 };
Learning Processing: Slides by Don Smith 92
Walkingofftheendofthearray…
A very common problem is trying to access an
element in the array that doesn’t exist:
int[] xpos = new int[10];
Remember that we start at element 0
What is the index of the last element? ______
What happens if we try to access element [10]?
for (int i = 0; i <= 10; i++ ) {
xpos[i] = 0;
}
Exception in thread "Animation Thread"
java.lang.ArrayIndexOutOfBoundsException: 10
Learning Processing: Slides by Don Smith 93
ArraysLab: PreliminarytoTheSnake
Declare and initialize two ‘global’ arrays:
int[] xpos = new int[10];
int[] ypos = new int[10];
Initialize them in setup()
for (int i = 0; i < xpos.length; i++ ) {
xpos[i] = 0;
ypos[i] = 0;
}
Each time the mouse is clicked, store the
mouseX and mouseY into the next available spot
in the array (fill from left to right)
Each time through draw, display a line between
each location saved in the array.
AdditionalProcessingArrayfeatures
Processing provides a set of functions to help
manage arrays (covered in 9.9):
shorten()
concat() -- Puts two arrays together
subset()
append()
splice()
expand() – Make an array larger in size!
sort() – Sort all the elements in the array
reverse() – Reverse the order of all elements
Learning Processing: Slides by Don Smith 94
ArraysofObjects
Using arrays to store multiple objects is a
very powerful programming feature
We will use the Car class (from Chapter 8),
and create a screen full of unique cars
Learning Processing: Slides by Don Smith 95
The‘Car’ClassRevisited
class Car { // Define a class below the rest of the program.
color c; // Variables.
float xpos, ypos, xspeed;
// Constructor with three parameters
Car(color c_, float xpos_, float ypos_, float xspeed_) {
c = c_;
xpos = xpos_;
ypos = ypos_;
xspeed = xspeed_;
}
void display() { // Function.
// The car is just a square
rectMode(CENTER);
stroke(0);
fill(c);
rect(xpos,ypos,20,10);
}
void move() { // Function.
xpos = xpos + xspeed;
if (xpos > width) {
xpos = 0;
}
}
}
Maketheparkinglot…
Step 1: Make the reference to the lot
Type Square Braces Array name semicolon
Car [ ] lot ;
Step 2: Make the parking spots
Array name
lot =
Keyword
new
Type
Car
Size
[100]
semicolon
;
Or the ‘one-liner’ version
Type [ ] Array name Keyword Type[Size] semi
Car [ ] lot = new Car[100] ;
Learning Processing: Slides by Don Smith 97
lot
[0]
empty
[1]
empty
[2]
empty
[3]
empty
[4]
empty
[5]
empty
NowLet’splayGeneralMotors!
Use a loop to fill up the parking lot!
void setup() {
size(200,200);
smooth();
for (int i = 0; i < lot.length; i ++ ) {
lot[i] = new Car(color(i*2),0,i*2,i/20.0);
}
}
Learning Processing: Slides by Don Smith 98
lot
[0]
Car
color
xpos
ypos
xspeed
[1]
Car
color
xpos
ypos
xspeed
[2]
Car
color
xpos
ypos
xspeed
[3]
Car
color
xpos
ypos
xspeed
[4]
Car
color
xpos
ypos
xspeed
[5]
Car
color
xpos
ypos
xspeed
Andlet’sgetthemontheroad!
Use a loop to move and display them!
void draw() {
background(255);
for (int i = 0; i < cars.length; i ++ ) {
cars[i].move();
cars[i].display();
}
}
Learning Processing: Slides by Don Smith 99
Section 5
运行控制
Invitation to Computer Science, Java Version, Third Edition 100
A B Output
0 0 0
0 1 0
1 0 0
1 1 1
A B Output
0 0 0
0 1 1
1 0 1
1 1 1
Learning Processing: Slides by Don Smith 101
WhatisaBooleanExpression?
Something that resolves to either
true or false (yes or no)
Not maybe…
Computers think in 1’s and 0’s
Remember truth tables
1 = ON = True
0 = OFF = False
Usually based on a comparison
Are you 21 years old?
Is changeCount less than 5?
Is myScore between 80 and 89?
Is lastName ‘Smith’?
AND
OR
Learning Processing: Slides by Don Smith 102
BooleanComparisonOperators
Similar to Algebra
>
<
>=
<=
==
greater than
less than
greater than or equal to
less than or equal to
eqality (equal to)
Note: ‘=‘ is the ‘assignment’ operator: x = 5;
!= inequality (not equal to)
Learning Processing: Slides by Don Smith 103
BooleanExpressionsandif
What is a Boolean Expression?
A comparison that results in either a true or a false
Where do I use it?
Usually in parenthesis, after an if:
if (age >= 21)
// True Action
if (mouseX < width/2)
// True Action
Only do ‘Action’ if condition is
True
True
Action
Condition
False
Learning Processing: Slides by Don Smith 104
Two-wayconditionals: if else
Use else for ‘false’ actions after an if test:
‘Binds’ with the closest if:
if (age >= 21)
// True Action
else // age < 21
// False Action
Take one of the two paths:
True or False
Good idea to use curly braces:
if (age >= 21){
// True Action
} else {
// False Action
}
True
Action
Condition
True
False
False
Action
105
MultipleActions
What if I have more than one thing to do if true?
Make a ‘block’ of code after the if:
if (age >= 21) {
// True Action 1
// True Action 2
} else
// False Action
Indentation is for humans
if (age >= 21)
// True Action 1
// True Action 2
Without the curly braces:
Only the first statement after a conditional is executed
True Action 2 is executed no matter what age is!
And don’t forget to ‘match’ your curly braces!
Learning Processing: Slides by Don Smith
True
Condition
False
False
Action
True
Action 1
True
Action 2
Learning Processing: Slides by Don Smith 106
Multiple-WayBranching: else if
What if you want more than two paths?
Use else if:
if (age >= 21)
// First True Action
else if (age > 18)
// Second True Action
else if (age > 5)
// Third True Action
Only one action done
Then go to the ‘bottom’
First True
Action
Second
True
Action
First
Condition
False
Second
Condition
False
True
True
Third True
Action
True
Third
Condition
False
Learning Processing: Slides by Don Smith 107
else if with else attheend
Two ‘true’ paths and one ‘neither’ path?
Use else if:
if (age >= 21)
// First True Action
else if (age > 18)
// Second True Action
else
// Both False Action
First True
Action
Second
True
Action
First
Condition
False
Second
Condition
False
True
True
Both False
Action
Learning Processing: Slides by Don Smith 108
ExampleofMulti-wayBranching
Where the mouse is determines the
background color
if (mouseX < width/3) {
background(255);
} else if (mouseX < 2*width/3) {
background(127);
} else {
background(0);
}
Multi-wayBranching: Whichtotestfirst?
Learning Processing: Slides by Don Smith 109
GradebookApplication
Determine the letter grade for a number 0-100
90 – 100: A
80 – 89.999 B
70 – 79.999 C
60 – 69.999 D
Below 60: F
How would you plan/code a solution?
What would you test for first?
What second?
How many tests do you need?
Learning Processing: Slides by Don Smith 110
NumericRangetesting
You often have to determine if a number is in
a specific range (min to max)
Example: Which range is a number in?
0-25: Print “Young”
26-50: Print “Mid-Age”
>50: Print “Mature”
How would you plan/code a solution?
What would you test for first?
What second?
Can this be done with only two tests?
Learning Processing: Slides by Don Smith 111
if else Examples
112
float r = 150; // variables
float g = 0;
float b = 0;
void setup() {
size(200,200);
}
void draw() {
background(r,g,b);
stroke(255); // Line down center
line(width/2, 0, width/2, height);
if (mouseX > width/2)
r = r + 1;
else
r = r - 1;
// If right
// more red
// Else left
// less red
// Range Check r
// Range Check r
if (r
r =
if (r
r =
> 255)
255;
< 0)
0;
}
Learning Processing: Slides by Don Smith
else ‘binds’ with closest if
You can use if with no else clause!
Rangecheckwithconstrain( )
Learning Processing: Slides by Don Smith 113
float r = 150; // variables
float g = 0;
float b = 0;
void setup() {
size(200,200);
}
void draw() {
background(r,g,b);
stroke(255); // Line down center
line(width/2, 0, width/2, height);
if (mouseX > width/2)
r = r + 1;
else
r = r - 1;
// If right
// more red
// Else left
// less red
r = constrain(r,0,255); // Range Check r
}
Three-waybranching
114
float r = 150; // variables
float g = 0;
float b = 0;
void setup() {
size(200,200);
}
void draw() {
background(r,g,b);
stroke(255);
line(width * 2/3, 0, width * 2/3, height);
line(width * 1/3, 0, width * 1/3, height);
if (mouseX > (width * 2/3)) // right 3rd
r = r + 1;
else if (mouseX < (width * 1/3)) // left 3rd
r = r -1;
else // center 3rd
ellipse(mouseX, mouseY, 30,30);
r = constrain(r,0,255); // Range Check r
}
Learning Processing: Slides by Don Smith
115
Exercise: Movearectangle…butstop!
float x = 0;
void setup() {
size(200,200);
}
void draw() {
background(255);
fill(0);
rect(x,100,20,20);
x = x + 1;
// Keep x in left half
// Conditional version:
// constrain version:
}
Learning Processing: Slides by Don Smith
A B Output
0 0 0
0 1 0
1 0 0
1 1 1
LogicalOperators: AND
Sometimes two (or more) things need to be true
before you want to do something
Example:
If age >= 16 AND permit == 1
Print “OK to drive”
How do we spell ‘AND’? &&
Learning Processing: Slides by Don Smith 116
‘Nested ifs:’
int age = 17;
int permit = 1;
if (age >= 16)
if (permit == 1)
print(“OK to Drive”);
else
print(“Ride the bus”);
else
print(“Ride the bus”);
One if, compound condition
int age = 17;
int permit= 1;
if (age >= 16 && permit == 1)
print(“OK to Drive”);
else
print(“Ride the bus”);
Remember: else ‘binds’ with closest if
(without an else)
A B Output
0 0 0
0 1 1
1 0 1
1 1 1
Learning Processing: Slides by Don Smith 117
LogicalOperators: OR
Sometimes one of (two or more) things is
enough to decide
int age = 17;
int permit = 1;
if (age >= 18 || (age >= 16 && permit == 1))
print(“OK to Drive”);
else
print(“Ride the bus”);
Example:
If age >= 18 OR (age >= 16 AND permit == 1)
Print “OK to drive”
How do we spell ‘OR’? || (two vertical bars)
Learning Processing: Slides by Don Smith 118
LogicalOperators: OR
Sometimes one of (two or more) things is
enough to decide
Example:
If age >= 18 OR (age >= 16 AND permit == 1)
Print “OK to drive”
How do we spell ‘OR’? || (two vertical bars)
int age = 17;
int permit = 1;
if (age >= 18 || (age >= 16 && permit == 1))
print(“OK to Drive”);
else
print(“Ride the bus”);
Note the use of parenthesis to ‘connect’ the AND clause
Exercise: SimpleRollover
Learning Processing: Slides by Don Smith
119
int
int
int
int
x
y
w
h
=
=
=
=
50;
50;
100;
75;
void setup() {
size(200,200);
}
void draw() {
background(255);
stroke(255);
// test if mouse is over the rectangle
if ( mouseX.. && mouseY.. && ???
// Change the color of the rectangle
rect(x,y,w,h);
}
Learning Processing: Slides by Don Smith 120
booleanvariables
You may want to ‘remember’ if something is true
or false and store it in a variable
Then you can compare it to true or false
Example:
If age >= 16 AND permit == true
Print “OK to drive”
int age = 17;
boolean permit = true;
if (age >= 16 && permit == true)
print(“OK to Drive”);
else
print(“Ride the bus”);
Learning Processing: Slides by Don Smith 121
Usinga boolean variableforButtons
A button is just a rollover area that senses
mouse clicks.
Testing if (mouse is in the area of the object) AND
mouse clicked can be quite a number of comparisons!
boolean button = false;
int ulx = 50, uly = 50, w = 100, h = 75; // rect variables
…
if (mouseX > ulx && mouseY > uly &&
mouseX < ulx + w && mouseY < uly + h &&
mousePressed)
button = true;
else
button = false;
// Later in code
if (button == true)
print(“I’ve been clicked!”);
Learning Processing: Slides by Don Smith 122
Usinga boolean variableforButtons
A button is just a rollover area that senses
mouse clicks.
Testing if (mouse is in the area of the object) AND
mouse clicked can be quite a number of comparisons!
boolean button = false;
int ulx = 50, uly = 50, w = 100, h = 75; // rect variables
…
if (mouseX > ulx && mouseY > uly &&
mouseX < ulx + w && mouseY < uly + h &&
mousePressed)
button = true;
else
button = false;
// Later in code
if(button) == true) Does the same thing as if (button == true)
print(“I’ve been clicked!”);
//
Learning Processing: Slides by Don Smith 123
//
Usinga boolean variableforButtons
A button is just a rollover area that senses
mouse clicks.
Testing if (mouse is in the area of the object) AND
mouse clicked can be quite a number of comparisons!
boolean button = false;
int ulx = 50, uly = 50, w = 100, h = 75; // rect variables
…
if (mouseX > ulx && mouseY > uly &&
mouseX < ulx + w && mouseY < uly + h &&
mousePressed)
button = true;
else
button = false;
// Later in code
if(button) == true) Does the same thing as if (button == true)
print(“I’ve been clicked!”);
Do you like the way the tests are lined up on multiple lines?
Learning Processing: Slides by Don Smith 124
Example: AButtonasaswitch
Test where the mouse is in the mousePressed()
method.
Then set a boolean variable to true or false
boolean button = false;
int ulx = 50, uly = 50, w = 100, h = 75; // rect variables
…
void draw() {
if (button)
// actions if button pressed
}
void mousePressed() {
if (mouseX > ulx && mouseY > uly &&
mouseX < ulx + w && mouseY < uly + h)
if (button) // alternate on every click
button = false;
else
button = true;
}
Learning Processing: Slides by Don Smith 125
button = false;
else
button = true;
Example: AButtonasaswitch
Test where the mouse is in the mousePressed()
method.
Then set a boolean variable to true or false
boolean button = false;
int ulx = 50, uly = 50, w = 100, h = 75; // rect variables
…
void draw() {
if (button)
// actions if button pressed
}
void mousePressed() {
if (mouseX > ulx && mouseY > uly &&
mouseX < ulx + w && mouseY < uly + h)
if (button) !button; // alternate on every shorter, eh?
= a // quite bit click
}
}
Use a boolean
variable to represent if
we are moving or not.
Change the variable
each time the mouse
pressed.
126
Exercise: Clicktostartamoving‘ball’
// Declare a boolean, set to false
int circleX = 0;
int circleY = 100;
void setup() {
size(200,200);
}
void draw() {
background(100);
stroke(255);
fill(0);
ellipse(circleX, circleY, 50, 50);
// Move the circle only after a click
}
void mousePressed() {
// react to the mouse being pressed
// Location of the mouse doesn’t matter
}
Learning Processing: Slides by Don Smith
Use a variable speed
which can be positive
or negative.
Change speed to
negative if we bounce
off the right edge.
127
Example: Abouncing‘ball’
int circleX = 0;
int speed = 1;
void setup() {
size(200,200);
smooth();
}
void draw() {
background(255);
circleX = circleX + speed;
if ( circleX > width || circleX < 0)
speed = speed * -1; // reverse course
// Display the circle at x location
stroke(0);
fill(175);
ellipse(circleX, 100, 32, 32);
}
// What will this do?
void mousePressed() {
speed = speed + 1;
}
Learning Processing: Slides by Don Smith
You can print the
variable speed to see
what it is doing.
Use println(speed)
if you want one number
per line.
128
Anoteaboutdebugging…
int circleX = 0;
int speed = 1;
void setup() {
size(200,200);
smooth();
}
void draw() {
background(255);
circleX = circleX + speed;
if ( circleX > width || circleX < 0)
speed = speed * -1; // reverse course
// Display the circle at x location
stroke(0);
fill(175);
ellipse(circleX, 100, 32, 32);
}
void mousePressed() {
speed = speed + 1;
println(speed);
}
Learning Processing: Slides by Don Smith
Section 6
循环控制
Invitation to Computer Science, Java Version, Third Edition 129
130
WhyuseIteration?
Without Iteration:
// No variables
stroke(0);
line( 50,60, 50,80);
line( 60,60, 60,80);
line( 70,60, 70,80);
line( 80,60, 80,80);
line( 90,60, 90,80);
line(100,60,100,80);
line(110,60,110,80);
line(120,60,120,80);
line(130,60,130,80);
line(140,60,140,80);
line(150,60,150,80);
Learning Processing: Slides by Don Smith
Learning Processing: Slides by Don Smith 131
WhyuseIteration?
Without Iteration:
// No variables
stroke(0);
line( 50,60, 50,80);
line( 60,60, 60,80);
line( 70,60, 70,80);
line( 80,60, 80,80);
line( 90,60, 90,80);
line(100,60,100,80);
line(110,60,110,80);
line(120,60,120,80);
line(130,60,130,80);
line(140,60,140,80);
line(150,60,150,80);
Study what changes
x’s increase each time
What is the pattern?
Add 10 each time
When does it stop?
Last line is at x = 150
// With x variable
int x = 50;
int spacing = 10;
int len = 20;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
..
132
PlanningIteration(Step1)
Without Iteration:
// No variables
stroke(0);
line( 50,60, 50,80);
line( 60,60, 60,80);
line( 70,60, 70,80);
line( 80,60, 80,80);
line( 90,60, 90,80);
line(100,60,100,80);
line(110,60,110,80);
line(120,60,120,80);
line(130,60,130,80);
line(140,60,140,80);
line(150,60,150,80);
Learning Processing: Slides by Don Smith
PlanningIteration(2)
Find the repetitive code
Learning Processing: Slides by Don Smith
// With x variable
int x = 50;
int spacing = 10;
int len = 20;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
..
133
PlanningIteration(3)
Plan the ‘exit’ condition
When to stop drawing lines
x == 150?
x > 150?
x < 150?
x <= 150?
x >= 150?
Learning Processing: Slides by Don Smith
// With x variable
int x = 50;
int spacing = 10;
int len = 20;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
..
134
135
Action(s)
Condition
TheonlyLoopYouReallyNeed: while
Use a Boolean Expression to test if we are done
Just like in if-else
True
False
There are there other types loops available:
do-while
for
Learning Processing: Slides by Don Smith
Howtoplanaloop:
Three Parts in every loop:
Setup variables
Test Condition
Change test variable
Action(s)
Change test
variable
136
True
Test
Condition
False
Make sure the loop will end!
The condition should be false at some point…
Or you have an ‘infinite’ loop! (not good)
Learning Processing: Slides by Don Smith
Setup
Learning Processing: Slides by Don Smith 137
LegsusingIteration
Use the same ‘setup’
Put the repetitive code
inside the loop
Put your exit condition
in the ‘test’
// Loop Version
int x = 50;
int spacing = 10;
int endLegs = 150;
while(x < endLegs) {
line(x,60,x,80);
x = x + spacing;
}
// With x variable
int x = 50;
int spacing = 10;
int len = 20;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
x = x + spacing;
line(x,60,x,80);
..
Learning Processing: Slides by Don Smith 138
Setup
Test
Change
ThreePartsoftheLoop
Find the three parts:
// Loop Version
int x = 50;
int spacing = 10;
int endLegs = 150;
while(x < endLegs) {
line(x,60,x,80);
x = x + spacing;
}
Let’sseeifwecanplanandwritealoop…
Look at Figure 6.5
Use 200 x 200 grid
What changes per bar?
Plan the three parts:
Setup (initial condition)
Initial y (top bar) ___
Last y: ________
Test (when to stop)
___________
Change
How far apart are bars?
___________
Learning Processing: Slides by Don Smith
Plan the width too
How wide are they? _____
Where to start? x = _____
Note: x doesn’t change!
139
GraphPapertotheRescue!
Learning Processing: Slides by Don Smith 140
50 60 70
141
Andthecodefortheloop‘fallsout’…
void setup() {
size(200,200);
background(255);
fill(125);
}
void draw() {
int y = 5;
int last = height;
while(y < last) {
rect(50,y,100,10);
y = y + 20;
}
}
Learning Processing: Slides by Don Smith
Exercise:
Learning Processing: Slides by Don Smith 142
ExitConditions: Whentostop!
How do we know when to stop?
Test is usually based on a comparison with a variable
Until age is 21
While changeCount is greater than 5
While not done
Until hitSomething is true
While dayOfMonth is less than daysInMonth
What if we don’t stop?
You probably forgot to change the test variable!
Or you changed it in the wrong direction
You have written an ‘infinite’ loop
Not good. Must ‘kill’ processing to get out!
Learning Processing: Slides by Don Smith
143
144
Yournextloop: for
Use a for loop when:
1) Your ‘test’ variable is a number
2) You know when to stop before you start
Put all three parts on one line:
for(Setup variables;Test Condition;Change test variable){
// Action(s) go here
}
Learning Processing: Slides by Don Smith
Action(s)
Change test
variable
Test
Condition
True
False
Setup
145
for loopSyntaxandExample
Use two semicolons (;) as separators:
for(Setup variables;Test Condition;Change test variable){
for( int x = 1; x < 10 ; x = x + 1) {
// Action(s) go here
}
Who came up with this?
Programmers of course
Why?
It saves typing, and it puts all three parts on one line
Learning Processing: Slides by Don Smith
Exercise: Whiletoforloop
Learning Processing: Slides by Don Smith 146
Learning Processing: Slides by Don Smith 147
Exercise
WuzzitDo?
for (int i = 0; i < 10; i++) {
rect(i*20,height/2, 5, 5);
}
int i = 0;
while (i < 10) {
ellipse(width/2,height/2, i*10, i*20);
i++;
} for (float i = 1.0; i < width; i *= 1.1) {
rect(0,i,i,i*2);
}
int x = 0;
for (int c = 255; c > 0; c –= 15) {
fill(c);
rect(x,height/2,10,10);
x = x + 10;
}
// Global " count "
int count = 0;
void setup() {
size(200,200);
}
void draw() {
count = count + 1;
background(count);
}
________
Learning Processing: Slides by Don Smith 148
// Local " count "
void setup() {
size(200,200);
}
void draw() {
int count = 0;
count = count + 1;
background(count);
}
________
Example
Global versus Local variables in loops
Which will these produce? A, B or C?
Learning Processing: Slides by Don Smith 149
for LoopVariable‘BlockScope’
for( int x = 1; x < 10; x = x + 1) {
// steps to do inside the loop
// You can use ‘x’ anywhere in this box
}
if (x > 100) // but x is gone now!
Scope is the ‘lifetime’ of a variable.
When ‘x’is declared in the for statement:
‘x’ exists only inside the ‘block’ of the for loop { }
Do you have to declare x inside the for loop? NO
int x; // Declare before loop starts (local scope)
for( x = 1; x < 10; x = x + 1) { // assign here
LoopInsidetheMainLoop
Remember that draw()is called in a ‘loop’
This is often called the ‘main’ loop
The last thing that draw()does is.. .
(remember Chapter 1?) ….. Paints the screen
How could you make a set of parallel
horizontal lines on the screen?
Learning Processing: Slides by Don Smith 150
Exercise
Render one line at a time inside a for loop:
Until the reach the bottom
Learning Processing: Slides by Don Smith 151
MarchingLinesPlan
Use a global variable to remember where on the
Y axis to start each time (between 1 and 20)
0, 1, 2, 3…. 19, 0, 1, 2, 3…
Initialize it 0
Every time through draw()
1) Clear the screen
2) Draw a set of parallel lines (20 pixels apart)
Starting at the Y axis where the global variable tells us to
Add 20 to the Y axis each time through
Loop until Y is >= the height of the screen
3) Increment the global variable by 1
If it reaches 20, set it back to 0
Learning Processing: Slides by Don Smith 152
ShuttersPlan(whatchanged?)
Use a global variable to remember where on the
Y axis to start each time (between 1 and 20)
0, 1, 2, 3…. 19, 0, 1, 2, 3…
Initialize it 0
Every time through draw()
1) Draw a set of parallel lines (20 pixels apart)
Starting at Y axis where the global variable tells us to
Add 20 to the Y axis each time through
Loop until Y is >= the height of the screen
2) Increment the global variable by 1
If it reaches 20, set it back to 0 and…
Clear the screen
Learning Processing: Slides by Don Smith 153
Learning Processing: Slides by Don Smith 154
IncrementandDecrementOperators
Loops often use a counter and increment or decrement it
as they go.
Here is a a “shortcut” way to decrement or increment a
variable:
increment operator
++x;
x++;
// increments x by one – BEFORE it is used
// increments x by one – AFTER it is used
decrement operator
--x;
x--;
// decrements x by one – BEFORE it is used
// decrements x by one – AFTER it is used
• When these operators are used as part of an expression,
then the choice of pre versus post will make a difference.
Howtomeasuredistancebetweenpoints
Take one axis (X) for example:
float distance = abs(mouseX – i);
abs() function returns a positive number
Absolute value… remember algebra!
Used in example 6.9
Exercise 6.6:
Rewrite 6.9 using a for loop
Learning Processing: Slides by Don Smith 155
Section 7
函数
Invitation to Computer Science, Java Version, Third Edition 156
Learning Processing: Slides by Don Smith 157
Modularity
What is a function?
A named block of code
Sometimes called a ‘module’, ‘method’ or a ‘procedure’
Some examples that you know are:
setup()
draw()
mousePressed()
background()
ellipse()
rect()
In pseudocode, they might be‘high-level’ headings:
Erase background
Draw Spaceship
Draw enemies
Move spaceship based on user keyboard command
Move enemies
Learning Processing: Slides by Don Smith 158
Erase background
Draw Spaceship
Draw enemies
Move spaceship
Get keyboard command
Move spaceship
Move enemies
Some functions are ‘built-in’
You can write your own!
PseudocodetoFunctions
// Modularized draw()
Each time through draw: void draw() {
background(0);
drawSpaceShip();
drawEmenies();
moveShip();
moveEnemies();
}
Learning Processing: Slides by Don Smith 159
Whyusefunctions?
Is your draw()method getting a bit long?
Two key principles of good programming:
1) Modularity
Break down code into smaller parts
More manageable and readable
Reduce the number of local variables inside a module
2) Reusability
Duplicated code (copy/paste?) is not good
Must maintain in multiple places
Better to put duplicate code in a new function and ‘call’ it from
multiple places
Learning Processing: Slides by Don Smith 160
Exercise: Modular‘Pong’Planning
What functions might be used in the game of pong?
1) Decide on the ‘rules’
One player or two player?
One player example
Two player example
2) Write Pong pseudocode (or flow chart)
3) Decide on function names
For user-defined functions
4) Think about variables you will need
Local (inside a function) or ‘global’?
Create names you can remember
TheFunction‘Definition’
Make a named ‘block’ with the following parts:
Return type
void
Function name Parameters area start block
drawShip ( ) {
// Variables and code go here
} // end drawShip
This is also called ‘declaring’ the function
You are ‘telling’ the compiler that there is a new
named block of code and how it works
Other Rules:
Define function outside all other functions
Name with the same rules as variables (letters, digits, _)
Do not use ‘reserved’ words or already used names
Learning Processing: Slides by Don Smith 161
CallingaFunction
Now that we have a function, let’s use it:
void draw() {
drawShip(); // note the semicolon!
}
You ‘Call’ functions from ‘inside’ other functions
In this case, inside draw()
You call functions by using the function name:
Return type Function name Arguments area semicolon
<empty> drawShip ( ) ;
Learning Processing: Slides by Don Smith 162
Exercise: Writeandcallafunction
Display a multi-part graphic (or a Zoog!)
Learning Processing: Slides by Don Smith 163
BouncingBallwithoutFunctions
Group code into related ‘chunks’
Learning Processing: Slides by Don Smith 164
BouncingBallwithFunctions
Name the ‘chunks’, declare functions, call them!
Learning Processing: Slides by Don Smith 165
FunctionswithArgumentsandParameters
What if you wanted to use a function to do
slightly different things?
Some examples you have seen that pass
arguments to functions include:
size(200,200);
color(100,150,0);
ellipse(x, y, width, height);
More?
What if you wanted to write your own function
that receives parameters?
Learning Processing: Slides by Don Smith 166
ArgumentsandParameters
Wikipedia Reference:
http://en.wikipedia.org/wiki/Parameter_(computer_science)
The book (and many professionals) confuse the
two words.
Per most texts and Wikipedia:
Arguments are ‘sent’
Parameters are ‘received’
167
// drawBlackCircle receives size parameter
void drawBlackCircle(int diameter) {
fill(0);
// passes arguments to ellipse()
ellipse(50, 50, diameter, diameter);
}
Learning Processing: Slides by Don Smith
Argument comes before
Parameter
168
Multiple
Arguments
void draw() {
background(0);
// Pass drawCar four
drawCar( 100,100,64,
drawCar( 50 ,75 ,32,
arguments
color(200,200,0) );
color(0,200,100) );
drawCar( 80 ,175,40, color(200,0,0) );
}
// drawCar receives four parameters
void drawCar(int x, int y, int thesize, color c) {
// Using a local variable "offset"
int offset = thesize/4;
// Draw main car body
…
}
Learning Processing: Slides by Don Smith
169
PassingVariables
void draw() {
background(0);
int size = 32;
// Pass drawCar four arguments
drawCar( 100,100,size, color(200,200,0) );
size = size + 16;
drawCar( 50 ,75 ,size, color(0,200,100) );
size = size + 16;
drawCar( 80 ,175,size, color(200,0,0) );
}
// drawCar receives four parameters
void drawCar(int x, int y, int thesize, color c) {
// Using a local variable "offset"
int offset = thesize/4;
// Draw main car body
…
}
Learning Processing: Slides by Don Smith
KeystoPassingArguments
You must pass the same number of arguments as defined
in the function parameter list.
When an argument is passed, it must be of the same type
as declared within the parameters in the function definition.
An integer must be passed into an integer
a floating point into a floating point..
The value you pass as an argument to a function can be a:
Literal value (20, 5, 4.3, etc.),
Variable (x, y, size, etc.)
The result of an expression (8 + 3, 4 * x/2, random(0,10), etc.)
Parameters act as local variables inside the receiving
function
They are only accessible within that function
Learning Processing: Slides by Don Smith 170
Learning Processing: Slides by Don Smith 171
Exercise: Writeafunctiondefinition:
void draw() {
float curHourly = 12.25;
float raisePct = 9.0;
showNewHourly(curHourly, raisePct);
}
// Make a comment line above the name
// return type function name ( parameters ) {
// Indented code goes here
// Print the new hourly rate
}
Write your own showNewHourly()function
definition to match the function call
Learning Processing: Slides by Don Smith 172
Exercise: BouncingCar
int globalX = 0;
int globalY = 100;
int speed = 1;
void draw() {
background(0);
// Call move
// Call bounce
// Call drawCar with global X and Y and other params;
}
Write your own function calls to match the
functions move, bounce and drawCar
WhatamIreallypassing?
Can the receiving function change the variable
that you pass?
That might be… dangerous…
Here are the rules in Processing and Java:
All primitive types (int, float, double, char…) are
passed by copying the contents of the variable inside
the argument into the new parameter variable.
Learning Processing: Slides by Don Smith 173
174
PassbyValue(Animated)
Let's take a closer look at how this works.
void draw() {
RAM
n
num
int n = 10;
println(n);
byValue(n);
println(n);
} // end draw()
10
void byValue(int num) {
num = 73;
println(n);
} // end byValue()
10
10
73
WuzzitDo?
Learning Processing: Slides by Don Smith 175
Returntypes
Up until now, you have used a mysterious
keyword named void before all of your functions
void
void
void
void
setup() {
draw() {
byValue(int num) {
drawCar(int x, int y, int thesize, color c) {
Remember the parts of a function definition?
Return type
void
Function name Parameters area start block
drawShip ( ) {
Here is an example that ‘return’ an int:
int sum(int a, int b, int c) {
int total = a + b + c;
return total; // Return a copy of a local variable
}
Learning Processing: Slides by Don Smith 176
177
Assigningthereturnvaluetoavariable
draw calls sum with arguments
sum receives values into parameters
sum method calculates local total
sum method returns copy of total
draw assigns returned val to answer
void draw() {
int answer;
answer = sum( 17, 42, 52);
println(answer);
noLoop();
}
int sum(int a, int b, int c) {
int total = a + b + c;
return total;
}
Learning Processing: Slides by Don Smith
178
Ausefulexample: Distancebetween2pts
float distance(float x1, float y1, float x2, float y2) {
float dx = x1 – x2; // one side of the right triangle
float dy = y1 – y2; // other side of the right triangle
// hypoteneuse length
float d = sqrt(dx*dx + dy*dy);
return d;
}
Processing has a dist()function that does the same thing…
Learning Processing: Slides by Don Smith
Section 8
面向对象编程
Invitation to Computer Science, Java Version, Third Edition 179
Learning Processing: Slides by Don Smith 180
ObjectOrientedProgramming(OOP)
OOP is a different way to view programming
Models the real world
A different view than ‘Structured’ programming
Functions break a program into ‘modules’ like an outline
What is an Object?
Usually based on a ‘noun’
It has ‘properties’
It has ‘actions’ (methods) that it can do (verbs)
An examples of an object that you know:
String
The dot operator is used to make the String do work!
WhyObjects?
OOP allows you to put data about something
and actions it can do together into one
“object”
OOP has been around since the 1960s
Most popular current languages have either
adapted or were designed with OOP
C  C++  C#
JavaScript
Java
Learning Processing: Slides by Don Smith 182
ObjectExample: Human
Attributes
Age
Height
Weight
Name
Eye color
Hair color
…
Functions
Sleep
Wake-Up
Eat
Ride something
Learning Processing: Slides by Don Smith 183
ClassesandObjects
A Class
A ‘plan’ for an object: Cookie Cutter
The general idea of a thing
Has placeholders for details, but not ‘made’ yet
It declares functions that could be done to an object
An Object
An ‘instance’ of a Class: A Cookie
A ‘real’ thing that has all of the specifics
It can be ‘told’ to execute it’s functions
You have to have a ‘plan’ before you can make an
object:
Class beforeObject
Exercise: PlanaCarClass
Let’s plan a simple Car
List data and functions
Let’s compare how we could convert the function
we wrote to show different card with objects
We’ll use our setup() and draw() methods
Learning Processing: Slides by Don Smith 185
Setupfora‘Car’beforeObjects
Use global variables for ‘properties’
Color:
Location:
Speed:
carColor
carX, carY
carSpeed
In setup()
Set the carColor
Set the starting location
Set the initial speed
In draw()
Fill background
Display car at location with color (may use a function)
Increment car’s location based on speed
186
Setupmultiple‘Cars’beforeObjects
Use global arrays of variables for ‘properties’
Allows us to use a loop to initialize a number of Cars
Declare Color array: carColor [ ]
Declare carX array:
Declare carY array:
carX [ ]
carY [ ]
Declare carSpeed array: carSpeed [ ]
In setup()
Set and initialize the arrays
In draw()
Fill background
Loop through all the cars
Display car at location with color (may use a function)
Increment car’s location based on speed
Learning Processing: Slides by Don Smith
Learning Processing: Slides by Don Smith 187
Setupa‘Car’usingObjects
One big difference with objects is that you move
all of the global variables inside the Car object
Color:
Location:
Speed:
carColor
carX, carY
carSpeed
Car object instead!
We end up with one variable to
represent the car
Instead of initializing all of those
variables, we initialize the car
object!
Learning Processing: Slides by Don Smith 188
Setupa‘Car’usingObjects
Outside of all methods (global)
Declare a ‘parking place’ for a car
In setup()
Make a new car object
based on the ‘Car’ plan)
Sets initial values for color, location and
speed
In draw()
Fill background
Tell the car to ‘move’ based on speed
Tell the car to ‘display’ itself (call a
function)
The‘Car’class
Convert the non-OOP Car Data to a Class
Non-OOP OOP
Learning Processing: Slides by Don Smith 190
Setupa‘Car’usingObjects-Data
Let’s break it down step by step
Declare the plan for the ‘Car’
Outside draw() and setup()
Put variables for color, location and speed inside
Learning Processing: Slides by Don Smith 191
Setupa‘Car’usingObjects-Constructor
We need to write instructions to build a car
It is called the ‘Constructor’ method
Move the code that was in setup()
Set variables for color, location and speed inside
Learning Processing: Slides by Don Smith 192
Setupa‘Car’usingObjects-Functions
Move the functions that did things to the car
Move the code to inside the Car class
The will be called methods of the class
Move the code that was in display()and drive()
Thewhole‘Car’(Example8.1)
class Car { // Define a class for a car
color c; // Variables.
float xpos;
float ypos;
float xspeed;
Car() { // A constructor.
c = color(175);
xpos = width/2;
ypos = height/2;
xspeed = 1;
}
void display() { // Function.
// The car is just a square
rectMode(CENTER);
stroke(0);
fill(c);
rect(xpos,ypos,20,10);
}
void drive() { // Function.
xpos = xpos + xspeed;
if (xpos > width) {
xpos = 0;
}
}
}
class Car {
Car() { // Constructor
c = color(175);
xpos = width/2;
ypos = height/2;
xspeed = 1;
}
Whatwasthatabouta‘Constructor’?
A constructor is a special method of a class
Has the same name as the class
“Builds’ the object
Sets initial values
It is ‘called’ with you use new:
void setup() {
size(200,200);
// Initialize Car object
myCar = new Car();
}
AndhereistheOOPizedversion
Is the OOP version shorter?
Is it easier to read?
Not yet maybe, but soon, and for the rest of your
life.
Learning Processing: Slides by Don Smith 195
CarClassshouldreallybeinitsownfile…
Click ‘Right Arrow’ in tabs row
Use ‘New Tab’ in menu to create a new file
Name the new tab exactly like the class = ‘Car’
Move the code for the ‘Car’ class to it
Saves to a ‘Car.pde’ file in your folder
Keep both files in the same folder
If you want to use your ‘Car’ class in another
project, simply copy the ‘Car.pde’ file there
Yourfirstmulti-fileProject!
Whatifwewanttomakemorecars?
Right now, all cars are exactly the same
Their constructor sets up the color, location…
How could we make ‘custom’ cars?
Remember parameters?
What if a Car constructor took parameters?
class Car {
Car(color colp, int xp, int yp, int speedp) {
c = colp;
xpos = xp;
ypos = yp;
xspeed = speedp;
}
Pleasereviewparameterpassing…
Make a new frog with a length of 100
Nowwecanmaketwo‘custom’cars
Use your new ‘parameterized’ constructor!
AndimagineanarrayofCars!
You can use the ‘Car’ class just like any other type
Declare an array of our new Cars object:
Car [ ] parkingLot;
setup() {
parkingLot = new Car[10];
}
But wait… what just happened?
Did you create 10 cars? No, not yet.
You created 10 parking stalls for cars
So we still have to ‘build’ the cars and set all of the
colors, locations and speeds…
parkingLot[0] = new Car(color, x, y..);
Fillingtheparkinglottheeasyway!
Once you have the parking lot created,
Car [ ] parkingLot;
setup() {
parkingLot = new Car[10];
}
Use a for loop to make a bunch of cars!
for (int i; i < 10; i++) {
parkingLot[i] = new Car(color, x, y..);
}
Arrays and loops work wonderfully together!
And they are even more fun with objects!

More Related Content

Similar to Processing语言教程 教授processing的使用技巧,具体方法和操作教程

LECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdf
LECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdfLECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdf
LECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdfSHASHIKANT346021
 
Ur Domain Haz Monoids DDDx NYC 2014
Ur Domain Haz Monoids DDDx NYC 2014Ur Domain Haz Monoids DDDx NYC 2014
Ur Domain Haz Monoids DDDx NYC 2014Cyrille Martraire
 
Interactive Mouse (Report On Processing)
Interactive Mouse (Report On Processing)Interactive Mouse (Report On Processing)
Interactive Mouse (Report On Processing)TongXu520
 
Introduction to programming - class 2
Introduction to programming - class 2Introduction to programming - class 2
Introduction to programming - class 2Paul Brebner
 
Introduction to programming - exercises 2
Introduction to programming - exercises 2Introduction to programming - exercises 2
Introduction to programming - exercises 2Paul Brebner
 
Session 04 communicating results
Session 04 communicating resultsSession 04 communicating results
Session 04 communicating resultsbodaceacat
 
Session 04 communicating results
Session 04 communicating resultsSession 04 communicating results
Session 04 communicating resultsSara-Jayne Terp
 
Four Languages From Forty Years Ago (NewCrafts 2019)
Four Languages From Forty Years Ago (NewCrafts 2019)Four Languages From Forty Years Ago (NewCrafts 2019)
Four Languages From Forty Years Ago (NewCrafts 2019)Scott Wlaschin
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2Abdul Haseeb
 
Applying your Convolutional Neural Networks
Applying your Convolutional Neural NetworksApplying your Convolutional Neural Networks
Applying your Convolutional Neural NetworksDatabricks
 
Data simulation basics
Data simulation basicsData simulation basics
Data simulation basicsDorothy Bishop
 
How to Rock a Demo
How to Rock a DemoHow to Rock a Demo
How to Rock a DemoSusan Ibach
 
Computer Graphics Concepts
Computer Graphics ConceptsComputer Graphics Concepts
Computer Graphics ConceptsSHAKOOR AB
 
Don't Call It a Comeback: Attribute Grammars for Big Data Visualization
Don't Call It a Comeback: Attribute Grammars for Big Data VisualizationDon't Call It a Comeback: Attribute Grammars for Big Data Visualization
Don't Call It a Comeback: Attribute Grammars for Big Data VisualizationLeo Meyerovich
 

Similar to Processing语言教程 教授processing的使用技巧,具体方法和操作教程 (20)

LECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdf
LECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdfLECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdf
LECTURE 6 DESIGN, DEBUGGING, INTERFACES.pdf
 
Ur Domain Haz Monoids DDDx NYC 2014
Ur Domain Haz Monoids DDDx NYC 2014Ur Domain Haz Monoids DDDx NYC 2014
Ur Domain Haz Monoids DDDx NYC 2014
 
MIPS-SPIM Taiwan
MIPS-SPIM TaiwanMIPS-SPIM Taiwan
MIPS-SPIM Taiwan
 
Interactive Mouse (Report On Processing)
Interactive Mouse (Report On Processing)Interactive Mouse (Report On Processing)
Interactive Mouse (Report On Processing)
 
Introduction to r
Introduction to rIntroduction to r
Introduction to r
 
Introduction to programming - class 2
Introduction to programming - class 2Introduction to programming - class 2
Introduction to programming - class 2
 
Compiler
CompilerCompiler
Compiler
 
Shoes
ShoesShoes
Shoes
 
Tutorial flash
Tutorial flashTutorial flash
Tutorial flash
 
Introduction to programming - exercises 2
Introduction to programming - exercises 2Introduction to programming - exercises 2
Introduction to programming - exercises 2
 
Session 04 communicating results
Session 04 communicating resultsSession 04 communicating results
Session 04 communicating results
 
Session 04 communicating results
Session 04 communicating resultsSession 04 communicating results
Session 04 communicating results
 
Four Languages From Forty Years Ago (NewCrafts 2019)
Four Languages From Forty Years Ago (NewCrafts 2019)Four Languages From Forty Years Ago (NewCrafts 2019)
Four Languages From Forty Years Ago (NewCrafts 2019)
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2
 
Applying your Convolutional Neural Networks
Applying your Convolutional Neural NetworksApplying your Convolutional Neural Networks
Applying your Convolutional Neural Networks
 
Data simulation basics
Data simulation basicsData simulation basics
Data simulation basics
 
How to Rock a Demo
How to Rock a DemoHow to Rock a Demo
How to Rock a Demo
 
Computer Graphics Concepts
Computer Graphics ConceptsComputer Graphics Concepts
Computer Graphics Concepts
 
Don't Call It a Comeback: Attribute Grammars for Big Data Visualization
Don't Call It a Comeback: Attribute Grammars for Big Data VisualizationDon't Call It a Comeback: Attribute Grammars for Big Data Visualization
Don't Call It a Comeback: Attribute Grammars for Big Data Visualization
 
Elixir
ElixirElixir
Elixir
 

Recently uploaded

ECHOES OF GENIUS - A Tribute to Nari Gandhi's Architectural Legacy. .pdf
ECHOES OF GENIUS - A Tribute to Nari Gandhi's Architectural Legacy. .pdfECHOES OF GENIUS - A Tribute to Nari Gandhi's Architectural Legacy. .pdf
ECHOES OF GENIUS - A Tribute to Nari Gandhi's Architectural Legacy. .pdfSarbjit Bahga
 
iF_Design_Trend_Report_twentytwenrythree
iF_Design_Trend_Report_twentytwenrythreeiF_Design_Trend_Report_twentytwenrythree
iF_Design_Trend_Report_twentytwenrythreeCarlgaming1
 
Latest Trends in Home and Building Design
Latest Trends in Home and Building DesignLatest Trends in Home and Building Design
Latest Trends in Home and Building DesignResDraft
 
Recycled Modular Low Cost Construction .pdf
Recycled Modular Low Cost Construction .pdfRecycled Modular Low Cost Construction .pdf
Recycled Modular Low Cost Construction .pdfjeffreycarroll14
 
BIT Khushi gandhi project.pdf graphic design
BIT Khushi gandhi project.pdf graphic designBIT Khushi gandhi project.pdf graphic design
BIT Khushi gandhi project.pdf graphic designKhushiGandhi15
 
NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...
NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...
NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...Amil baba
 
Evaluating natural frequencies and mode shapes.pptx
Evaluating natural frequencies and mode shapes.pptxEvaluating natural frequencies and mode shapes.pptx
Evaluating natural frequencies and mode shapes.pptxjoshuaclack73
 
Webhost NVME Cloud VPS Hosting1234455678
Webhost NVME Cloud VPS Hosting1234455678Webhost NVME Cloud VPS Hosting1234455678
Webhost NVME Cloud VPS Hosting1234455678Cloud99 Cloud
 
Bit Dhrumi shah Graphic Designer portfolio
Bit Dhrumi shah Graphic Designer portfolioBit Dhrumi shah Graphic Designer portfolio
Bit Dhrumi shah Graphic Designer portfoliodhrumibshah13
 
100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...
100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...
100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...pillahdonald
 
Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...
Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...
Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...mikehavy0
 
如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证ugzga
 
如何办理(UW毕业证书)华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(UW毕业证书)华盛顿大学毕业证成绩单本科硕士学位证留信学历认证如何办理(UW毕业证书)华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(UW毕业证书)华盛顿大学毕业证成绩单本科硕士学位证留信学历认证ugzga
 
Design Portofolios - Licensed Architect / BIM Specialist
Design Portofolios - Licensed Architect / BIM SpecialistDesign Portofolios - Licensed Architect / BIM Specialist
Design Portofolios - Licensed Architect / BIM SpecialistYudistira
 
The concept of motion graphics and its applications.
The concept of motion graphics and its applications.The concept of motion graphics and its applications.
The concept of motion graphics and its applications.WeatherOfficialProdu
 
如何办理(UCI毕业证书)加利福尼亚大学尔湾分校毕业证成绩单本科硕士学位证留信学历认证
如何办理(UCI毕业证书)加利福尼亚大学尔湾分校毕业证成绩单本科硕士学位证留信学历认证如何办理(UCI毕业证书)加利福尼亚大学尔湾分校毕业证成绩单本科硕士学位证留信学历认证
如何办理(UCI毕业证书)加利福尼亚大学尔湾分校毕业证成绩单本科硕士学位证留信学历认证ugzga
 
NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...
NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...
NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...Amil baba
 
一模一样英国德比大学毕业证(derby毕业证书)本科学历-国外大学文凭办理
一模一样英国德比大学毕业证(derby毕业证书)本科学历-国外大学文凭办理一模一样英国德比大学毕业证(derby毕业证书)本科学历-国外大学文凭办理
一模一样英国德比大学毕业证(derby毕业证书)本科学历-国外大学文凭办理thubko
 
如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证ugzga
 
如何办理(UMN毕业证书)明尼苏达大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(UMN毕业证书)明尼苏达大学毕业证成绩单本科硕士学位证留信学历认证如何办理(UMN毕业证书)明尼苏达大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(UMN毕业证书)明尼苏达大学毕业证成绩单本科硕士学位证留信学历认证ugzga
 

Recently uploaded (20)

ECHOES OF GENIUS - A Tribute to Nari Gandhi's Architectural Legacy. .pdf
ECHOES OF GENIUS - A Tribute to Nari Gandhi's Architectural Legacy. .pdfECHOES OF GENIUS - A Tribute to Nari Gandhi's Architectural Legacy. .pdf
ECHOES OF GENIUS - A Tribute to Nari Gandhi's Architectural Legacy. .pdf
 
iF_Design_Trend_Report_twentytwenrythree
iF_Design_Trend_Report_twentytwenrythreeiF_Design_Trend_Report_twentytwenrythree
iF_Design_Trend_Report_twentytwenrythree
 
Latest Trends in Home and Building Design
Latest Trends in Home and Building DesignLatest Trends in Home and Building Design
Latest Trends in Home and Building Design
 
Recycled Modular Low Cost Construction .pdf
Recycled Modular Low Cost Construction .pdfRecycled Modular Low Cost Construction .pdf
Recycled Modular Low Cost Construction .pdf
 
BIT Khushi gandhi project.pdf graphic design
BIT Khushi gandhi project.pdf graphic designBIT Khushi gandhi project.pdf graphic design
BIT Khushi gandhi project.pdf graphic design
 
NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...
NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...
NO1 Popular kala jadu karne wale ka contact number kala jadu karne wale baba ...
 
Evaluating natural frequencies and mode shapes.pptx
Evaluating natural frequencies and mode shapes.pptxEvaluating natural frequencies and mode shapes.pptx
Evaluating natural frequencies and mode shapes.pptx
 
Webhost NVME Cloud VPS Hosting1234455678
Webhost NVME Cloud VPS Hosting1234455678Webhost NVME Cloud VPS Hosting1234455678
Webhost NVME Cloud VPS Hosting1234455678
 
Bit Dhrumi shah Graphic Designer portfolio
Bit Dhrumi shah Graphic Designer portfolioBit Dhrumi shah Graphic Designer portfolio
Bit Dhrumi shah Graphic Designer portfolio
 
100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...
100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...
100^%)( KATLEHONG))(*((+27838792658))*))௹ )Abortion Pills for Sale in Doha, D...
 
Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...
Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...
Abortion Clinic in Springs +27791653574 Springs WhatsApp Abortion Clinic Serv...
 
如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(UCL毕业证书)伦敦大学学院毕业证成绩单本科硕士学位证留信学历认证
 
如何办理(UW毕业证书)华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(UW毕业证书)华盛顿大学毕业证成绩单本科硕士学位证留信学历认证如何办理(UW毕业证书)华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(UW毕业证书)华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
 
Design Portofolios - Licensed Architect / BIM Specialist
Design Portofolios - Licensed Architect / BIM SpecialistDesign Portofolios - Licensed Architect / BIM Specialist
Design Portofolios - Licensed Architect / BIM Specialist
 
The concept of motion graphics and its applications.
The concept of motion graphics and its applications.The concept of motion graphics and its applications.
The concept of motion graphics and its applications.
 
如何办理(UCI毕业证书)加利福尼亚大学尔湾分校毕业证成绩单本科硕士学位证留信学历认证
如何办理(UCI毕业证书)加利福尼亚大学尔湾分校毕业证成绩单本科硕士学位证留信学历认证如何办理(UCI毕业证书)加利福尼亚大学尔湾分校毕业证成绩单本科硕士学位证留信学历认证
如何办理(UCI毕业证书)加利福尼亚大学尔湾分校毕业证成绩单本科硕士学位证留信学历认证
 
NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...
NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...
NO1 Best Best Black Magic Specialist Near Me Spiritual Healer Powerful Love S...
 
一模一样英国德比大学毕业证(derby毕业证书)本科学历-国外大学文凭办理
一模一样英国德比大学毕业证(derby毕业证书)本科学历-国外大学文凭办理一模一样英国德比大学毕业证(derby毕业证书)本科学历-国外大学文凭办理
一模一样英国德比大学毕业证(derby毕业证书)本科学历-国外大学文凭办理
 
如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证
如何办理(Birmingham毕业证书)伯明翰大学学院毕业证成绩单本科硕士学位证留信学历认证
 
如何办理(UMN毕业证书)明尼苏达大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(UMN毕业证书)明尼苏达大学毕业证成绩单本科硕士学位证留信学历认证如何办理(UMN毕业证书)明尼苏达大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(UMN毕业证书)明尼苏达大学毕业证成绩单本科硕士学位证留信学历认证
 

Processing语言教程 教授processing的使用技巧,具体方法和操作教程

  • 1. LearningProcessing Beginning Daniel Shiffman Graphics from http://www.learningprocessing.com/tutorials/
  • 2. Section 1 基本概念 Invitation to Computer Science, Java Version, Third Edition 2
  • 3. What is an image? Digital Camera Source: A. Efros
  • 4. 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 20 0 255 255 255 255 255 255 255 255 255 255 75 75 75 255 255 255 255 255 255 255 255 75 95 95 75 255 255 255 255 255 255 255 255 96 127 145 175 255 255 255 255 255 255 255 255 127 145 175 175 175 255 255 255 255 255 255 255 127 145 200 200 175 175 95 255 255 255 255 255 127 145 200 200 175 175 95 47 255 255 255 255 127 145 145 175 127 127 95 47 255 255 255 255 74 127 127 127 95 95 95 47 255 255 255 255 255 74 74 74 74 74 74 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 A Grid of Intensity Values (commonto use one byte per value: 0 = black, 255 = white) =
  • 5. 255 75 75 255 255 175 175 175 255 255 200 145 175 255 255 255 200 175 175 175 255 255 145 200 200 175 175 95 200 200 175 175 95 145 175 127 127 95 Image as Grid of Values 75 95 127 145 145 145 145 75 95 145 95 95 255 175 175 127 75 75 175 95 145 200 145 200 145 175 175 175 175 127 255 255 255 75 175 175 200 175 200 127 255 175 175 127 255 255 255 255 175 175 200 175 200 127 255 95 95 95 255 255 255 255 175 95 175 95 175 95 175 200 200 175 255 255 255 175 175 175 175 175 127 255 95 95 255 175 175 127
  • 6. GraphPaper Every point on the screen is a pixel It has a location: (x, y) Learning Processing: Slides by Don Smith 6
  • 7. Upper left corner is 0,0 X is ‘across’ (to right as x increases) Y is ‘down’ (down as y increases) Learning Processing: Slides by Don Smith 7 CoordinateSystem NOT the same as your Algebra coordinate system!
  • 8. SimpleShapes What do we need to specify a shape? Point: x and y Line: Two end points? Rectangle: Two corners? Or ??? Ellipse: ???? Learning Processing: Slides by Don Smith 8
  • 9. Point Note that x (across) comes first In Processing: point(x, y); lower case ‘point’ two ‘parameters’ in parenthesis Semicolon; Learning Processing: Slides by Don Smith 9
  • 10. Line Learning Processing: Slides by Don Smith 10  Two Points: A and B  In Processing: line(x1, y1, x2, y2);    lower case ‘line’ four ‘parameters’ in parenthesis Semicolon;
  • 11. Rectangle1 From Corner: One Point for top left corner In Processing: rect(x, y, width, height); lower case ‘rect’ four ‘parameters’ in parenthesis Semicolon; NOTE: This is the default mode (CORNER) Learning Processing: Slides by Don Smith 11
  • 12. Rectangle2 From Center: One point, size In Processing: rectMode(CENTER); rect(x, y, width, height); Two lines of code Learning Processing: Slides by Don Smith 12
  • 13. Rectangle3 CORNERS: Top Left point, Bottom Right point In Processing: rectMode(CORNERS); rect(x1, y1, x2, y2); Two lines of code Learning Processing: Slides by Don Smith 13
  • 14. EllipseModes Same as rectangle modes: CENTER (x, y, width, height) CORNER (x, y, width, height) CORNERS (x1, y1, x2, y2) Draws ellipse in a ‘Bounding box’ Circle is a ‘special case’ of an ellipse (width = height) Learning Processing: Slides by Don Smith 14
  • 15. SizeMatters You can specify the size of your ‘canvas’ at the start of a ‘script’ size(width, height); Use 200 x 200 to get started It matches the ‘graphPaper200x200.doc’ file Learning Processing: Slides by Don Smith 15
  • 16. Color: Grayscale You can set the color of lines and background: 0 is black (no ‘light’) 255 is white (most ‘light’) Some examples in processing: background(255); stroke(0); fill(150); // Sets background to white // Sets outline to black // Sets interior of a shape to grey rect(50,50,75,100); // Draws shape with most recent settings Learning Processing: Slides by Don Smith 16
  • 17. GrayscaleExample To fill or not to fill If noFill() is set, shapes have only an outline What are the ‘default’ grayscales of: Background: Stroke: Fill: Learning Processing: Slides by Don Smith 17
  • 18. RGBColor Color Mixing 101: Red + Green = Yellow Red + Blue = Purple Green + Blue = Cyan (blue-green) Red + Green + Blue = White no colors = Black Learning Processing: Slides by Don Smith 18  RGB Values  Each color has a value between 0 and 255   0 means NONE of that color 255 means MAX of that color
  • 19. Learning Processing: Slides by Don Smith 19   Use fill(),background() or stroke() with three parameters:  fill(red, green, blue); Then draw a shape! // Bright red // Dark red // Pink (pale red) ManualColors background(255); noStroke(); fill(255,0,0); ellipse(20,20,16,16); fill(127,0,0); ellipse(40,20,16,16); fill(255,200,200); ellipse(60,20,16,16);
  • 20. PickingColors Learning Processing: Slides by Don Smith 20  Processing has a color selector to aid in choosing colors.  Access this via TOOLS (from the menu bar) → COLOR SELECTOR.
  • 21. There is a fourth ‘parameter’ you can use: Called ‘Alpha’ 0 means transparent 255 means opaque No fourth parameter means ‘100% opacity’ Learning Processing: Slides by Don Smith 21 Transparency // 50% opacity. fill(255,0,0,127); // 25% opacity. fill(255,0,0,63); rect(0,150,200,40);
  • 22. NowGettoWork! Plan a more interesting alien! Use grayscale! Black eyes Gray body Learning Processing: Slides by Don Smith 22
  • 23. Section 2 开发环境 Invitation to Computer Science, Java Version, Third Edition 23
  • 24. Installing Finding the files Website: www. processing.org – click Download Blackboard: Files, Tools folder Version 2.1.1 is the most current Download (110MB) processing-2.1-windows64 If you already have Java installed: Install the Windows (Without Java) expert version instead processing-xxx-expert.zip - From www.processing.org Unzip , or open and extract files Let it choose defaults (location…) Installs Java SDK automatically and examples Puts Java files in a folder under Processing Works with XP and Win7 Installs an icon on your desktop Learning Processing: Slides by Don Smith 24
  • 25. WheredoesJavafitin? Processing provides a simple ‘front end’ to Java. Processing requires Java SDK to be installed Software Development Kit Processing has it’s own library for graphics Java’s library (API) can also be used in Processing Learning Processing: Slides by Don Smith 25 Processing Source code Processing Java Compiler Portable Java Program Processing Library Java Library
  • 26. TheJavaVirtualMachine(JVM) Java was designed to run on embedded systems, it was designed around a virtual machine “Write once, run everywhere” Called the JRE (Java Runtime Environment) Portable Java Program PC Java VM Windows x86 Running Java Program Mac Java VM OS X G3/4/5 Running Java Program Cell Phone Java VM Phone OS CPU Running Java Program JRE
  • 27. SketchMenuOptions Processing has an ‘PDE’ called Sketch File: New, Open, Quit, Examples! Edit: Copy, Paste, Select, Indent, Comment… Sketch: Run, Stop, Show Sketch folder… Tools: Auto format, Color chooser… Help: Getting Started, Reference, Find in Reference… Learning Processing: Slides by Don Smith 27
  • 28. PDE 28 Menu Toolbar Sketch Tabs Text Editor Message Line Text Area Current Line# To run: Menu Sketch, Run, Ctrl-R or Toolbar Run button You either get a display window (all’s well) or an error in Message Area Learning Processing: Slides by Don Smith Display Window
  • 30. GettingStarted Learning Processing: Slides by Don Smith 30  Help, Getting Started goes to processing website and explains:       Processing Development Environment (PDE)  All menu options, hot keys Sketchbook Tabs, Multiple Files, and Classes Coordinates Programming Modes Rendering Modes
  • 31. SketchFilesandFolders… The folder where you store your sketches is called your ‘Sketchbook’ Sketch stores files under where Processing was installed May not be where you want. Use File, Save As to select a folder on your flash drive Processing remembers where you last saved Each sketch has it’s own folder File extension ‘PDE’ is a Processing Development Environment file Double click on PDE file to open Sketch for that folder Learning Processing: Slides by Don Smith 31
  • 32. Whereareyourfiles? Choose File, Preferences Select new location for default Not flash drive (not always there) Learning Processing: Slides by Don Smith 32
  • 33. YourFirstProgram Open a new sketch Default name is based on date/time In the Text window, type: // My first Program Print(“Hello World by me”); rect(10, 10, 50, 50); One comment and two lines of code Run it… If no errors, What is in the Message/Text Area? What is in the Display window? Learning Processing: Slides by Don Smith 33
  • 34. Errors The brown line tells you what is wrong Editor window: The line with the error is highlighted RECT should be lower case (rect) Learning Processing: Slides by Don Smith 34  Note: Processing only shows one error at a time
  • 35. Help,FindInReference Double click key word (highlights in yellow) Menu: Help, Find in Reference: (or Ctrl-Shift-F) Does not work if word is mis-spelled Normally goes directly to detailed page (local) Usually provides an example Learning Processing: Slides by Don Smith 35
  • 36. Lab: ZoogHeadstand Draw your alien – Upside Down! Use grayscale White head Black eyes Gray body Add a comment with your name at the top Add: print(“Zoog Headstand by <Your name>”); Save your sketch To your flash drive Submit your sketch (pde) via Blackbloard Learning Processing: Slides by Don Smith 36
  • 37. Section 3 编程基础 Invitation to Computer Science, Java Version, Third Edition 37
  • 38. Programflow Games are written with ‘loops’ Like running a race Prepare (put on shoes…) Loop putting feet forward over and over Run until the race is over Remember that programs are made of parts: Sequential Conditional Iterative Learning Processing: Slides by Don Smith 38
  • 39. Usingyourfirst‘methods’! setup()and draw()are ‘methods’ Think of them as named ‘blocks’ of code You get to write the code inside the ‘block’ New symbols and words! (just look for now) void () // { } Learning Processing: Slides by Don Smith 39
  • 40. A‘block’ofcode Parts of a program are separated into blocks In Java, C, C++, PHP and many other languages: Blocks are surrounded by curly braces: { ….. } Think of blocks like an outline set of sub-steps: 1 1a 1b 2 Programmers (and editors) line up code in blocks Usually indent the ‘statements’ inside the block Learning Processing: Slides by Don Smith 40
  • 41. setup()anddraw()methods When your program starts, Processing: Calls setup() once Continues to call draw() unti the program ends Learning Processing: Slides by Don Smith 41 Program Starts Call setup() Call draw() Done yet? Yes Program ends No
  • 42. CodeforZoogasadynamicsketch All of your code can go into two ‘blocks’:
  • 43. The‘invisible’lineofcode… When does processing ‘paint’ the screen? Learning Processing: Slides by Don Smith 43
  • 44. TrackingtheMouse Processing keeps track of where the mouse is: mouseX: The current X coordinate of the mouse mouseY: The current Y coordinate of the mouse These are both ‘key words’ that you can use! Their values change as the mouse moves An example: Learning Processing: Slides by Don Smith 44
  • 45. MoreMousetracks… Processing also keeps track of where the mouse WAS the last time you left draw(): pmouseX: The previous X coordinate of the mouse pmouseY: The previous Y coordinate of the mouse Learning Processing: Slides by Don Smith 45
  • 46. Ascribbleapplication Learning Processing: Slides by Don Smith 46  Just keep connecting the points where the mouse was and it is now:
  • 47. MouseclicksandKeypresses Learning Processing: Slides by Don Smith 47   Two ‘methods’ that you can write to handle events that might happen: Processing ‘calls’ your method when events occur:  mousePressed()  keyPressed()
  • 48. Processingsetup()method Things that you may use during setup(): size(200,200); smooth(); frameRate(30); background(255); // defaults to 60 frames/sec // clear the screen Each may be used for their own purposes Some may also be used in draw()methods What would this do to your drawing if the background(255)call was in draw()? Learning Processing: Slides by Don Smith 48
  • 49. Usingbackground(255) void setup() { size(200,200); background(255); } void draw() { line(mouseX, mouseY, 100,100); } void setup() { size(200,200); } void draw() { background(255); line(mouseX, mouseY, 100,100); } 49  Try these Learning Processing: Slides by Don Smith
  • 50. Section 4 变量 Invitation to Computer Science, Java Version, Third Edition 50
  • 51. Learning Processing: Slides by Don Smith 51 Whatisavariable? Storage Analogies: Different sizes Like a bucket Like a locker Graph Paper/Spreadsheet Many ‘storage’ places, all with unique locations (x,y) In Excel, E3 could be named ‘Billys Score’ Billy’s score can change! A B C D E F 1 2 3 4 5
  • 52. Learning Processing: Slides by Don Smith 52 Whatisavariable? In Algebra: x=y*z Named with single letters to represent some number In Programming: We use longer, more descriptive names Variables refer to ‘memory locations’ Stored in ‘RAM’ Random Access Memory Have a ‘size’ How many bytes of memory ‘wide’
  • 53. Learning Processing: Slides by Don Smith 53 Variablesmustbe‘Declared’ What is a Declaration? Programmer tells the compiler: Type Name ; What is a Type? Each type requires a specific amount of storage ‘Primitive’ types include three main categories Integers – Whole Numbers (positive and negative), no fractions Floating point – Numbers with fractional parts and exponents Characters – One letter that you can type A, B, C, a, b, c, 1, 2, 3, %, &….
  • 54. Learning Processing: Slides by Don Smith 54 AllPrimitiveTypes Integer Types byte: A very small number (-127 to +128) short: A small number (-32768 to +32767) int: long: A large number (-2,147,483,648 to +2,147,483,647) A huge number Floating Point Types float: A huge number with decimal places double: Much more precise, for heavy math Other Types boolean: true or false char: One symbol in single quotes ‘a’
  • 55. 55 PrimitiveTypeStorage Integer Types byte: short: int: long: Floating Point Types float: double: Other Types boolean: char: Learning Processing: Slides by Don Smith
  • 56. Learning Processing: Slides by Don Smith 56 PrimitiveTypeExamples Integer Types byte: short: int: long: 123 1984 1784523 234345456789 Floating Point Types float: double: 4.0 3.14159 Other Types boolean: true char: ‘a’
  • 57. Numericversus‘Character’types How do you decide if you need a numeric or a character type? If you plan on doing ‘math’ on the variable, then you MUST use a numeric type What is the letter ‘a’ times the letter ‘c’? Notice the single quotes around characters If you plan on using “Strings” (later), they are just words made up of characters. “Bob” and “Mary” are Strings (of characters) Notice the double quotes around strings What is the string “Bob” times the string “Mary”? Learning Processing: Slides by Don Smith 57
  • 58. Learning Processing: Slides by Don Smith 58 DeclaringandInitializingVariables What is Initialization? Setting an initial value into the contents of the variable Pseudocode: Set NumPlayers to 5 Can be done in two ways: During Declaration: On one line int count = 50; // declare and initialize After declaration: On two lines int count; count = 50; // declare the variable // initialize the value Can also be initialized with a calculation! int max = 100; int min = 10; int count = max – min; // calculation
  • 59. PongVariables What variables would be required to play? Scores? Paddle locations? Ball location? Net location Screen Size? Learning Processing: Slides by Don Smith 59
  • 60. Learning Processing: Slides by Don Smith 60 NamingVariables There are some ‘rules’ and some ‘best practices’ Rules Letters, Digits and underscore ( _ ) are OK to use Cannot start with a digit ( 0,1,…9 ) Cannot use reserved words mouseX, int, size.. Best Practices Use descriptive names boolean moreToDo; Use ‘camelHump’ notation Start with lower case Each new word starts with Upper Case
  • 61. DeclarationandInitializationExamples Type name (optional initialization) ; int count = 0; char letter = 'a'; double d = 132.32; boolean happy = false; float x = 4.0; float y; // Declare an int , initialized to 0 // Declare a char, initialized to 'a' // Declare a double, initialized to 132.32 // Declare a boolean, initialized to false // Declare a float, initialized to 4.0 // Declare a float (no assignment) float z = x * y + 15.0; // Declare a float, initialize it to // x times y plus 15.0. After declaration Assignments: count = 1; letter = ‘b’; happy = true; y = x + 5.2; // Assign the value of x plus 5.2 Learning Processing: Slides by Don Smith 61
  • 62. DeclarationandInitializationIssues You can only initialize a variable to a value of the same, or compatible type: Which initializations are compatible? int count = ‘a’; char letter = 0; double deposit = “Fred”; boolean happy = 1; float feet = 6; int inches = feet * 12; long giant = feet * 3.0; Learning Processing: Slides by Don Smith 62
  • 63. DeclarationandInitializationIssues You can only initialize a variable to a value of the same, or compatible type. Which initializations are compatible? int count = ‘a’; char letter = 0; double deposit = “Fred”; boolean happy = 1; float feet = 6; int inches = feet * 12; long giant = feet * 3.0; Learning Processing: Slides by Don Smith 63
  • 64. WheretoDeclareVariables Remember that your code is in ‘blocks’ Variables can go inside or outside these blocks For now, we will put them ‘outside’ (before) blocks
  • 65. VaryingVariables: Example Remember that processing calls draw()in a loop If you want the variable to change every time: Declare and initialize it outside of draw()! Change it inside draw()! Moves as circleX increases 
  • 66. Callto draw() circleX 1 0 2 1 3 2 4 3 5 4 … 200 199 66 WhathappensinPre-example? circleX Is initialized to 0 Used first time draw()is called ellipse(circleX, circleY, 50,50); Then circleX = circleX + 1; Next time draw()is called, circleX is 1 ellipse(circleX, circleY, 50,50); Then circleX = circleX + 1; Next time draw()is called, circleX is 2 ellipse(circleX, circleY, 50,50); Then circleX = circleX + 1; .. Until circleX is over 200, and the circle just moves off the right side of the screen, never to be seen again! It is often useful to make a ‘table’ of all of the variables that are being changed every time through a ‘loop’ Learning Processing: Slides by Don Smith
  • 67. Callto draw() circleX circleY circleW circleH 1 0 0 50 100 2 0.5 0.5 50.5 100.5 3 1.0 1.0 51 101 10 4.5 4.5 54.5 104.5 30 14.5 14.5 64.5 114.5 100 49.5 49.5 99.5 149.5 200 99.5 99.5 149.5 199.5 UsingManyVariables Make things more interesting using more variables! Declare and initialize them outside of draw()! Change them inside draw()!
  • 68. Learning Processing: Slides by Don Smith 68 SystemVariables Processing provides many ‘built-in’ variables: These are not for you to play with, but may change! mouseX , mouseY, pmouseX and pmouseY width: Width (in pixels) of sketch window height: Height (in pixels) of sketch window frameCount: Number of frames processed frameRate: Rate (per sec.) that frames are processed screen.height, screen.width: Entire screen key: Most recent key pressed on keyboard keyCode: Numeric code for which key pressed mousePressed: True or false (pressed or not?) mouseButton: Which button (left, right, center)
  • 69. Learning Processing: Slides by Don Smith 69 Random: Varietyisthespiceoflife Processing (and all programming languages) provide a way to get a random value when your program runs. random() is a ‘function’ that returns a float You can assign this number to a variable and use it! Some examples:
  • 70. Whatisthat(int)and(1,100)stuff? (int) Since random()returns a floating point number and w is an int, we need to change the type from float to int. This is called ‘casting’ random(1,100) ; (1,100) are ‘parameters’ which tell the random function the range of numbers to return w will be between 1 and 99 (not quite 100) Learning Processing: Slides by Don Smith 70
  • 71. MakeZoogMove! Use variables to make Zoog move and change! 1) Make Zoog rise from below the screen Need variables for the Zoog’s X and Y locations Note: Locations of ALL of Zoog’s parts need to use them If left eye is left 30 and down 50 from the center of the head: ellipse( zoogX – 30, zoogY + 50, 20, 30); 2) Change his eye color randomly as he moves Need variables for Zoog’s eye color (R,G and B) Learning Processing: Slides by Don Smith 71
  • 72. Lab: MovingZoog Use variables and random() to make a Zoog move from upper left to lower right of the screen. Starting point is provided (Example 4.8) Plan! Declare variables Use variables Use Random Learning Processing: Slides by Don Smith 72
  • 73. 1 2 3 4 5 6 7 8 9 10 73 Whydowecare(aboutarrays)? What if you have a whole bunch of cars (or aliens or balls or ???) bouncing around the screen? How do we keep track of where each one is? int car1X, car1Y, car2X, car2Y, car3X, car3Y…… How about keeping them in a ‘table’ or a ‘grid’ CarX table: Each ‘column’ has a number You can refer to CarX table, column 3 for Car3… Note that all of the values in the row must be the same data type Learning Processing: Slides by Don Smith
  • 74. Learning Processing: Slides by Don Smith 74 WhentouseanArray Any time a program requires multiple instances of similar data, it might be time to use an array. For example, an array can be used to store: The scores of four players in a game A selection of 10 colors in a design program A list of fish objects in an aquarium simulation The days per month in a scheduling program
  • 75. 75 Whatisanarray? A variable is a named location in memory. An array is a named set of locations in memory A ‘list’ of variables Each element of the list has a number called an ‘index’ Starts at 0! Learning Processing: Slides by Don Smith
  • 76. 76 Whystartat0? Whynot1? Which of the following is why arrays start at 0? A) B) C) D) Because programmers think that way Because I say so So that programmers can make ‘the big bucks’ So you can use loops easily to ‘walk’ the array Here’s a preview of adding up all the ‘votes’: int sumArray(int size) { int sum = 0; for (int c = 0; c < size; c++) { sum = sum + votes[c]; // huh? [ ]? } return sum; } Learning Processing: Slides by Don Smith
  • 77. HowtoDeclareanarray(Step1) Create the array variable (with the name and type) Make a named ‘list’ with the following parts: Type Square Braces Array name semicolon int [ ] arrayOfInts ; You are ‘declaring’ that There is an array named arrayOfInts The elements inside are of type int You have not (YET) declared how many are in inside Other Rules: Arrays can be declared anywhere you can declare a variable Do not use ‘reserved’ words or already used names Learning Processing: Slides by Don Smith 77
  • 78. HowtoCreateanarray(Step2) Reserve memory for all of the elements in the list: Array name Keyword Type Size semicolon arrayOfInts = new int [42] ; Learning Processing: Slides by Don Smith 78 You are reserving memory for: The array named arrayOfInts Needs storage for [42] elements the size of type int Now you (and the compiler) know how many are in inside You cannot change the size after you declare it! arrayOfInts [0] [1] [2] [3] [4] … [41] int int int int int int
  • 79. TwoStepsononeline: Declare and Create at the same time: Type Braces Array name Keyword Type Size semi int [] arrayOfInts = new int [42] ; You are ‘declaring’ that There is an array named arrayOfInts The elements inside are of type int You are reserving memory for the array Needs storage for [42] elements the size of type int Note that the size cannot be changed, so you should make enough room when you start! Learning Processing: Slides by Don Smith 79
  • 80. Exercise: Writethedeclarationsfor: Declare the array variable (step 1) for these: Learning Processing: Slides by Don Smith 80
  • 81. Exercise: Writethedeclarationsfor: Declare the array variable (step 1) for these: // type [] arrayName ; int [] arrayOfInts; float [] hundredFloats; Zoog [] zoogArmy; Learning Processing: Slides by Don Smith 81
  • 82. Exercise: Writethedeclarationsfor: Declare storage (step 2) for the following: Learning Processing: Slides by Don Smith 82
  • 83. Exercise: Writethedeclarationsfor: Declare storage (step 2) for the following: // arrayName = new type[size]; arrayOfInts = new int[30]; hundredFloats = new float[100]; zoogArmy = new Zoog[56]; Learning Processing: Slides by Don Smith 83
  • 84. Exercise: Writethedeclarationsfor: Both Steps 1 and 2 on the same line: Learning Processing: Slides by Don Smith 84
  • 85. Exercise: Writethedeclarationsfor: Both Steps 1 and 2 on the same line: // type [] arrayName = new type[size]; int [] arrayOfInts = new int[30]; float [] hundredFloats = new float[100]; Zoog [] zoogArmy = new Zoog[56]; Learning Processing: Slides by Don Smith 85
  • 86. Exercise: What’swrongwiththese? May be valid, maybe not! Learning Processing: Slides by Don Smith 86
  • 87. 87 InitializinganArray The ‘long’ way int [] stuff = new int[3]; stuff[0] = 8; stuff[1] = 3; stuff[2] = 1; The one-liner way: int [] stuff = { 8, 3, 1 }; The compiler counts the number of elements (3) Sets the size automatically! Fills the contents with the values inside the { }; Values are separated by commas Learning Processing: Slides by Don Smith
  • 88. InitializingwithIteration Rolling 5 dice (Yahtzee) Example The ‘hard’ way Learning Processing: Slides by Don Smith 88 int[] die = new int[5]; = = = = = (int)random(0,6); (int)random(0,6); (int)random(0,6); (int)random(0,6); (int)random(0,6); die[0] die[1] die[2] die[3] die[4] Using a while loop: int n = 0; while (n < 5) { die[n] = random(0,6); n = n + 1; }
  • 89. InitializingwithIteration Rolling 5 dice (Yahtzee) Example The ‘hard’ way Learning Processing: Slides by Don Smith 89 int[] die = new int[5]; die[0] die[1] die[2] die[3] die[4] = = = = = (int)random(0,6); (int)random(0,6); (int)random(0,6); (int)random(0,6); (int)random(0,6); Using a for loop: for (int n = 0; n < 5; n++ ) { die[n] = (int)random(0,6); }
  • 90. Learning Processing: Slides by Don Smith 90 Exercise: Loop/Arrayexample: Using a for loop to initialize an array: float[] values = new float[6]; for (int i = 0; i < values.length; i++) values[i] = 0; Note the use of values.length The array knows how long it is! Now write code to square each entry: int [] nums = { 5, 4, 2, 7, 6, 8, 5, 2, 6, 14 };
  • 91. Learning Processing: Slides by Don Smith 91 Exercise: Loop/Arraycontinued: int [] nums = { 5, 4, 2, 7, 6, 8, 5, 2, 6, 14 };
  • 92. Learning Processing: Slides by Don Smith 92 Walkingofftheendofthearray… A very common problem is trying to access an element in the array that doesn’t exist: int[] xpos = new int[10]; Remember that we start at element 0 What is the index of the last element? ______ What happens if we try to access element [10]? for (int i = 0; i <= 10; i++ ) { xpos[i] = 0; } Exception in thread "Animation Thread" java.lang.ArrayIndexOutOfBoundsException: 10
  • 93. Learning Processing: Slides by Don Smith 93 ArraysLab: PreliminarytoTheSnake Declare and initialize two ‘global’ arrays: int[] xpos = new int[10]; int[] ypos = new int[10]; Initialize them in setup() for (int i = 0; i < xpos.length; i++ ) { xpos[i] = 0; ypos[i] = 0; } Each time the mouse is clicked, store the mouseX and mouseY into the next available spot in the array (fill from left to right) Each time through draw, display a line between each location saved in the array.
  • 94. AdditionalProcessingArrayfeatures Processing provides a set of functions to help manage arrays (covered in 9.9): shorten() concat() -- Puts two arrays together subset() append() splice() expand() – Make an array larger in size! sort() – Sort all the elements in the array reverse() – Reverse the order of all elements Learning Processing: Slides by Don Smith 94
  • 95. ArraysofObjects Using arrays to store multiple objects is a very powerful programming feature We will use the Car class (from Chapter 8), and create a screen full of unique cars Learning Processing: Slides by Don Smith 95
  • 96. The‘Car’ClassRevisited class Car { // Define a class below the rest of the program. color c; // Variables. float xpos, ypos, xspeed; // Constructor with three parameters Car(color c_, float xpos_, float ypos_, float xspeed_) { c = c_; xpos = xpos_; ypos = ypos_; xspeed = xspeed_; } void display() { // Function. // The car is just a square rectMode(CENTER); stroke(0); fill(c); rect(xpos,ypos,20,10); } void move() { // Function. xpos = xpos + xspeed; if (xpos > width) { xpos = 0; } } }
  • 97. Maketheparkinglot… Step 1: Make the reference to the lot Type Square Braces Array name semicolon Car [ ] lot ; Step 2: Make the parking spots Array name lot = Keyword new Type Car Size [100] semicolon ; Or the ‘one-liner’ version Type [ ] Array name Keyword Type[Size] semi Car [ ] lot = new Car[100] ; Learning Processing: Slides by Don Smith 97 lot [0] empty [1] empty [2] empty [3] empty [4] empty [5] empty
  • 98. NowLet’splayGeneralMotors! Use a loop to fill up the parking lot! void setup() { size(200,200); smooth(); for (int i = 0; i < lot.length; i ++ ) { lot[i] = new Car(color(i*2),0,i*2,i/20.0); } } Learning Processing: Slides by Don Smith 98 lot [0] Car color xpos ypos xspeed [1] Car color xpos ypos xspeed [2] Car color xpos ypos xspeed [3] Car color xpos ypos xspeed [4] Car color xpos ypos xspeed [5] Car color xpos ypos xspeed
  • 99. Andlet’sgetthemontheroad! Use a loop to move and display them! void draw() { background(255); for (int i = 0; i < cars.length; i ++ ) { cars[i].move(); cars[i].display(); } } Learning Processing: Slides by Don Smith 99
  • 100. Section 5 运行控制 Invitation to Computer Science, Java Version, Third Edition 100
  • 101. A B Output 0 0 0 0 1 0 1 0 0 1 1 1 A B Output 0 0 0 0 1 1 1 0 1 1 1 1 Learning Processing: Slides by Don Smith 101 WhatisaBooleanExpression? Something that resolves to either true or false (yes or no) Not maybe… Computers think in 1’s and 0’s Remember truth tables 1 = ON = True 0 = OFF = False Usually based on a comparison Are you 21 years old? Is changeCount less than 5? Is myScore between 80 and 89? Is lastName ‘Smith’? AND OR
  • 102. Learning Processing: Slides by Don Smith 102 BooleanComparisonOperators Similar to Algebra > < >= <= == greater than less than greater than or equal to less than or equal to eqality (equal to) Note: ‘=‘ is the ‘assignment’ operator: x = 5; != inequality (not equal to)
  • 103. Learning Processing: Slides by Don Smith 103 BooleanExpressionsandif What is a Boolean Expression? A comparison that results in either a true or a false Where do I use it? Usually in parenthesis, after an if: if (age >= 21) // True Action if (mouseX < width/2) // True Action Only do ‘Action’ if condition is True True Action Condition False
  • 104. Learning Processing: Slides by Don Smith 104 Two-wayconditionals: if else Use else for ‘false’ actions after an if test: ‘Binds’ with the closest if: if (age >= 21) // True Action else // age < 21 // False Action Take one of the two paths: True or False Good idea to use curly braces: if (age >= 21){ // True Action } else { // False Action } True Action Condition True False False Action
  • 105. 105 MultipleActions What if I have more than one thing to do if true? Make a ‘block’ of code after the if: if (age >= 21) { // True Action 1 // True Action 2 } else // False Action Indentation is for humans if (age >= 21) // True Action 1 // True Action 2 Without the curly braces: Only the first statement after a conditional is executed True Action 2 is executed no matter what age is! And don’t forget to ‘match’ your curly braces! Learning Processing: Slides by Don Smith True Condition False False Action True Action 1 True Action 2
  • 106. Learning Processing: Slides by Don Smith 106 Multiple-WayBranching: else if What if you want more than two paths? Use else if: if (age >= 21) // First True Action else if (age > 18) // Second True Action else if (age > 5) // Third True Action Only one action done Then go to the ‘bottom’ First True Action Second True Action First Condition False Second Condition False True True Third True Action True Third Condition False
  • 107. Learning Processing: Slides by Don Smith 107 else if with else attheend Two ‘true’ paths and one ‘neither’ path? Use else if: if (age >= 21) // First True Action else if (age > 18) // Second True Action else // Both False Action First True Action Second True Action First Condition False Second Condition False True True Both False Action
  • 108. Learning Processing: Slides by Don Smith 108 ExampleofMulti-wayBranching Where the mouse is determines the background color if (mouseX < width/3) { background(255); } else if (mouseX < 2*width/3) { background(127); } else { background(0); }
  • 110. GradebookApplication Determine the letter grade for a number 0-100 90 – 100: A 80 – 89.999 B 70 – 79.999 C 60 – 69.999 D Below 60: F How would you plan/code a solution? What would you test for first? What second? How many tests do you need? Learning Processing: Slides by Don Smith 110
  • 111. NumericRangetesting You often have to determine if a number is in a specific range (min to max) Example: Which range is a number in? 0-25: Print “Young” 26-50: Print “Mid-Age” >50: Print “Mature” How would you plan/code a solution? What would you test for first? What second? Can this be done with only two tests? Learning Processing: Slides by Don Smith 111
  • 112. if else Examples 112 float r = 150; // variables float g = 0; float b = 0; void setup() { size(200,200); } void draw() { background(r,g,b); stroke(255); // Line down center line(width/2, 0, width/2, height); if (mouseX > width/2) r = r + 1; else r = r - 1; // If right // more red // Else left // less red // Range Check r // Range Check r if (r r = if (r r = > 255) 255; < 0) 0; } Learning Processing: Slides by Don Smith else ‘binds’ with closest if You can use if with no else clause!
  • 113. Rangecheckwithconstrain( ) Learning Processing: Slides by Don Smith 113 float r = 150; // variables float g = 0; float b = 0; void setup() { size(200,200); } void draw() { background(r,g,b); stroke(255); // Line down center line(width/2, 0, width/2, height); if (mouseX > width/2) r = r + 1; else r = r - 1; // If right // more red // Else left // less red r = constrain(r,0,255); // Range Check r }
  • 114. Three-waybranching 114 float r = 150; // variables float g = 0; float b = 0; void setup() { size(200,200); } void draw() { background(r,g,b); stroke(255); line(width * 2/3, 0, width * 2/3, height); line(width * 1/3, 0, width * 1/3, height); if (mouseX > (width * 2/3)) // right 3rd r = r + 1; else if (mouseX < (width * 1/3)) // left 3rd r = r -1; else // center 3rd ellipse(mouseX, mouseY, 30,30); r = constrain(r,0,255); // Range Check r } Learning Processing: Slides by Don Smith
  • 115. 115 Exercise: Movearectangle…butstop! float x = 0; void setup() { size(200,200); } void draw() { background(255); fill(0); rect(x,100,20,20); x = x + 1; // Keep x in left half // Conditional version: // constrain version: } Learning Processing: Slides by Don Smith
  • 116. A B Output 0 0 0 0 1 0 1 0 0 1 1 1 LogicalOperators: AND Sometimes two (or more) things need to be true before you want to do something Example: If age >= 16 AND permit == 1 Print “OK to drive” How do we spell ‘AND’? && Learning Processing: Slides by Don Smith 116 ‘Nested ifs:’ int age = 17; int permit = 1; if (age >= 16) if (permit == 1) print(“OK to Drive”); else print(“Ride the bus”); else print(“Ride the bus”); One if, compound condition int age = 17; int permit= 1; if (age >= 16 && permit == 1) print(“OK to Drive”); else print(“Ride the bus”); Remember: else ‘binds’ with closest if (without an else)
  • 117. A B Output 0 0 0 0 1 1 1 0 1 1 1 1 Learning Processing: Slides by Don Smith 117 LogicalOperators: OR Sometimes one of (two or more) things is enough to decide int age = 17; int permit = 1; if (age >= 18 || (age >= 16 && permit == 1)) print(“OK to Drive”); else print(“Ride the bus”); Example: If age >= 18 OR (age >= 16 AND permit == 1) Print “OK to drive” How do we spell ‘OR’? || (two vertical bars)
  • 118. Learning Processing: Slides by Don Smith 118 LogicalOperators: OR Sometimes one of (two or more) things is enough to decide Example: If age >= 18 OR (age >= 16 AND permit == 1) Print “OK to drive” How do we spell ‘OR’? || (two vertical bars) int age = 17; int permit = 1; if (age >= 18 || (age >= 16 && permit == 1)) print(“OK to Drive”); else print(“Ride the bus”); Note the use of parenthesis to ‘connect’ the AND clause
  • 119. Exercise: SimpleRollover Learning Processing: Slides by Don Smith 119 int int int int x y w h = = = = 50; 50; 100; 75; void setup() { size(200,200); } void draw() { background(255); stroke(255); // test if mouse is over the rectangle if ( mouseX.. && mouseY.. && ??? // Change the color of the rectangle rect(x,y,w,h); }
  • 120. Learning Processing: Slides by Don Smith 120 booleanvariables You may want to ‘remember’ if something is true or false and store it in a variable Then you can compare it to true or false Example: If age >= 16 AND permit == true Print “OK to drive” int age = 17; boolean permit = true; if (age >= 16 && permit == true) print(“OK to Drive”); else print(“Ride the bus”);
  • 121. Learning Processing: Slides by Don Smith 121 Usinga boolean variableforButtons A button is just a rollover area that senses mouse clicks. Testing if (mouse is in the area of the object) AND mouse clicked can be quite a number of comparisons! boolean button = false; int ulx = 50, uly = 50, w = 100, h = 75; // rect variables … if (mouseX > ulx && mouseY > uly && mouseX < ulx + w && mouseY < uly + h && mousePressed) button = true; else button = false; // Later in code if (button == true) print(“I’ve been clicked!”);
  • 122. Learning Processing: Slides by Don Smith 122 Usinga boolean variableforButtons A button is just a rollover area that senses mouse clicks. Testing if (mouse is in the area of the object) AND mouse clicked can be quite a number of comparisons! boolean button = false; int ulx = 50, uly = 50, w = 100, h = 75; // rect variables … if (mouseX > ulx && mouseY > uly && mouseX < ulx + w && mouseY < uly + h && mousePressed) button = true; else button = false; // Later in code if(button) == true) Does the same thing as if (button == true) print(“I’ve been clicked!”); //
  • 123. Learning Processing: Slides by Don Smith 123 // Usinga boolean variableforButtons A button is just a rollover area that senses mouse clicks. Testing if (mouse is in the area of the object) AND mouse clicked can be quite a number of comparisons! boolean button = false; int ulx = 50, uly = 50, w = 100, h = 75; // rect variables … if (mouseX > ulx && mouseY > uly && mouseX < ulx + w && mouseY < uly + h && mousePressed) button = true; else button = false; // Later in code if(button) == true) Does the same thing as if (button == true) print(“I’ve been clicked!”); Do you like the way the tests are lined up on multiple lines?
  • 124. Learning Processing: Slides by Don Smith 124 Example: AButtonasaswitch Test where the mouse is in the mousePressed() method. Then set a boolean variable to true or false boolean button = false; int ulx = 50, uly = 50, w = 100, h = 75; // rect variables … void draw() { if (button) // actions if button pressed } void mousePressed() { if (mouseX > ulx && mouseY > uly && mouseX < ulx + w && mouseY < uly + h) if (button) // alternate on every click button = false; else button = true; }
  • 125. Learning Processing: Slides by Don Smith 125 button = false; else button = true; Example: AButtonasaswitch Test where the mouse is in the mousePressed() method. Then set a boolean variable to true or false boolean button = false; int ulx = 50, uly = 50, w = 100, h = 75; // rect variables … void draw() { if (button) // actions if button pressed } void mousePressed() { if (mouseX > ulx && mouseY > uly && mouseX < ulx + w && mouseY < uly + h) if (button) !button; // alternate on every shorter, eh? = a // quite bit click } }
  • 126. Use a boolean variable to represent if we are moving or not. Change the variable each time the mouse pressed. 126 Exercise: Clicktostartamoving‘ball’ // Declare a boolean, set to false int circleX = 0; int circleY = 100; void setup() { size(200,200); } void draw() { background(100); stroke(255); fill(0); ellipse(circleX, circleY, 50, 50); // Move the circle only after a click } void mousePressed() { // react to the mouse being pressed // Location of the mouse doesn’t matter } Learning Processing: Slides by Don Smith
  • 127. Use a variable speed which can be positive or negative. Change speed to negative if we bounce off the right edge. 127 Example: Abouncing‘ball’ int circleX = 0; int speed = 1; void setup() { size(200,200); smooth(); } void draw() { background(255); circleX = circleX + speed; if ( circleX > width || circleX < 0) speed = speed * -1; // reverse course // Display the circle at x location stroke(0); fill(175); ellipse(circleX, 100, 32, 32); } // What will this do? void mousePressed() { speed = speed + 1; } Learning Processing: Slides by Don Smith
  • 128. You can print the variable speed to see what it is doing. Use println(speed) if you want one number per line. 128 Anoteaboutdebugging… int circleX = 0; int speed = 1; void setup() { size(200,200); smooth(); } void draw() { background(255); circleX = circleX + speed; if ( circleX > width || circleX < 0) speed = speed * -1; // reverse course // Display the circle at x location stroke(0); fill(175); ellipse(circleX, 100, 32, 32); } void mousePressed() { speed = speed + 1; println(speed); } Learning Processing: Slides by Don Smith
  • 129. Section 6 循环控制 Invitation to Computer Science, Java Version, Third Edition 129
  • 130. 130 WhyuseIteration? Without Iteration: // No variables stroke(0); line( 50,60, 50,80); line( 60,60, 60,80); line( 70,60, 70,80); line( 80,60, 80,80); line( 90,60, 90,80); line(100,60,100,80); line(110,60,110,80); line(120,60,120,80); line(130,60,130,80); line(140,60,140,80); line(150,60,150,80); Learning Processing: Slides by Don Smith
  • 131. Learning Processing: Slides by Don Smith 131 WhyuseIteration? Without Iteration: // No variables stroke(0); line( 50,60, 50,80); line( 60,60, 60,80); line( 70,60, 70,80); line( 80,60, 80,80); line( 90,60, 90,80); line(100,60,100,80); line(110,60,110,80); line(120,60,120,80); line(130,60,130,80); line(140,60,140,80); line(150,60,150,80); Study what changes x’s increase each time What is the pattern? Add 10 each time When does it stop? Last line is at x = 150
  • 132. // With x variable int x = 50; int spacing = 10; int len = 20; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); .. 132 PlanningIteration(Step1) Without Iteration: // No variables stroke(0); line( 50,60, 50,80); line( 60,60, 60,80); line( 70,60, 70,80); line( 80,60, 80,80); line( 90,60, 90,80); line(100,60,100,80); line(110,60,110,80); line(120,60,120,80); line(130,60,130,80); line(140,60,140,80); line(150,60,150,80); Learning Processing: Slides by Don Smith
  • 133. PlanningIteration(2) Find the repetitive code Learning Processing: Slides by Don Smith // With x variable int x = 50; int spacing = 10; int len = 20; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); .. 133
  • 134. PlanningIteration(3) Plan the ‘exit’ condition When to stop drawing lines x == 150? x > 150? x < 150? x <= 150? x >= 150? Learning Processing: Slides by Don Smith // With x variable int x = 50; int spacing = 10; int len = 20; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); .. 134
  • 135. 135 Action(s) Condition TheonlyLoopYouReallyNeed: while Use a Boolean Expression to test if we are done Just like in if-else True False There are there other types loops available: do-while for Learning Processing: Slides by Don Smith
  • 136. Howtoplanaloop: Three Parts in every loop: Setup variables Test Condition Change test variable Action(s) Change test variable 136 True Test Condition False Make sure the loop will end! The condition should be false at some point… Or you have an ‘infinite’ loop! (not good) Learning Processing: Slides by Don Smith Setup
  • 137. Learning Processing: Slides by Don Smith 137 LegsusingIteration Use the same ‘setup’ Put the repetitive code inside the loop Put your exit condition in the ‘test’ // Loop Version int x = 50; int spacing = 10; int endLegs = 150; while(x < endLegs) { line(x,60,x,80); x = x + spacing; } // With x variable int x = 50; int spacing = 10; int len = 20; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); x = x + spacing; line(x,60,x,80); ..
  • 138. Learning Processing: Slides by Don Smith 138 Setup Test Change ThreePartsoftheLoop Find the three parts: // Loop Version int x = 50; int spacing = 10; int endLegs = 150; while(x < endLegs) { line(x,60,x,80); x = x + spacing; }
  • 139. Let’sseeifwecanplanandwritealoop… Look at Figure 6.5 Use 200 x 200 grid What changes per bar? Plan the three parts: Setup (initial condition) Initial y (top bar) ___ Last y: ________ Test (when to stop) ___________ Change How far apart are bars? ___________ Learning Processing: Slides by Don Smith Plan the width too How wide are they? _____ Where to start? x = _____ Note: x doesn’t change! 139
  • 141. 141 Andthecodefortheloop‘fallsout’… void setup() { size(200,200); background(255); fill(125); } void draw() { int y = 5; int last = height; while(y < last) { rect(50,y,100,10); y = y + 20; } } Learning Processing: Slides by Don Smith
  • 143. ExitConditions: Whentostop! How do we know when to stop? Test is usually based on a comparison with a variable Until age is 21 While changeCount is greater than 5 While not done Until hitSomething is true While dayOfMonth is less than daysInMonth What if we don’t stop? You probably forgot to change the test variable! Or you changed it in the wrong direction You have written an ‘infinite’ loop Not good. Must ‘kill’ processing to get out! Learning Processing: Slides by Don Smith 143
  • 144. 144 Yournextloop: for Use a for loop when: 1) Your ‘test’ variable is a number 2) You know when to stop before you start Put all three parts on one line: for(Setup variables;Test Condition;Change test variable){ // Action(s) go here } Learning Processing: Slides by Don Smith Action(s) Change test variable Test Condition True False Setup
  • 145. 145 for loopSyntaxandExample Use two semicolons (;) as separators: for(Setup variables;Test Condition;Change test variable){ for( int x = 1; x < 10 ; x = x + 1) { // Action(s) go here } Who came up with this? Programmers of course Why? It saves typing, and it puts all three parts on one line Learning Processing: Slides by Don Smith
  • 147. Learning Processing: Slides by Don Smith 147 Exercise WuzzitDo? for (int i = 0; i < 10; i++) { rect(i*20,height/2, 5, 5); } int i = 0; while (i < 10) { ellipse(width/2,height/2, i*10, i*20); i++; } for (float i = 1.0; i < width; i *= 1.1) { rect(0,i,i,i*2); } int x = 0; for (int c = 255; c > 0; c –= 15) { fill(c); rect(x,height/2,10,10); x = x + 10; }
  • 148. // Global " count " int count = 0; void setup() { size(200,200); } void draw() { count = count + 1; background(count); } ________ Learning Processing: Slides by Don Smith 148 // Local " count " void setup() { size(200,200); } void draw() { int count = 0; count = count + 1; background(count); } ________ Example Global versus Local variables in loops Which will these produce? A, B or C?
  • 149. Learning Processing: Slides by Don Smith 149 for LoopVariable‘BlockScope’ for( int x = 1; x < 10; x = x + 1) { // steps to do inside the loop // You can use ‘x’ anywhere in this box } if (x > 100) // but x is gone now! Scope is the ‘lifetime’ of a variable. When ‘x’is declared in the for statement: ‘x’ exists only inside the ‘block’ of the for loop { } Do you have to declare x inside the for loop? NO int x; // Declare before loop starts (local scope) for( x = 1; x < 10; x = x + 1) { // assign here
  • 150. LoopInsidetheMainLoop Remember that draw()is called in a ‘loop’ This is often called the ‘main’ loop The last thing that draw()does is.. . (remember Chapter 1?) ….. Paints the screen How could you make a set of parallel horizontal lines on the screen? Learning Processing: Slides by Don Smith 150
  • 151. Exercise Render one line at a time inside a for loop: Until the reach the bottom Learning Processing: Slides by Don Smith 151
  • 152. MarchingLinesPlan Use a global variable to remember where on the Y axis to start each time (between 1 and 20) 0, 1, 2, 3…. 19, 0, 1, 2, 3… Initialize it 0 Every time through draw() 1) Clear the screen 2) Draw a set of parallel lines (20 pixels apart) Starting at the Y axis where the global variable tells us to Add 20 to the Y axis each time through Loop until Y is >= the height of the screen 3) Increment the global variable by 1 If it reaches 20, set it back to 0 Learning Processing: Slides by Don Smith 152
  • 153. ShuttersPlan(whatchanged?) Use a global variable to remember where on the Y axis to start each time (between 1 and 20) 0, 1, 2, 3…. 19, 0, 1, 2, 3… Initialize it 0 Every time through draw() 1) Draw a set of parallel lines (20 pixels apart) Starting at Y axis where the global variable tells us to Add 20 to the Y axis each time through Loop until Y is >= the height of the screen 2) Increment the global variable by 1 If it reaches 20, set it back to 0 and… Clear the screen Learning Processing: Slides by Don Smith 153
  • 154. Learning Processing: Slides by Don Smith 154 IncrementandDecrementOperators Loops often use a counter and increment or decrement it as they go. Here is a a “shortcut” way to decrement or increment a variable: increment operator ++x; x++; // increments x by one – BEFORE it is used // increments x by one – AFTER it is used decrement operator --x; x--; // decrements x by one – BEFORE it is used // decrements x by one – AFTER it is used • When these operators are used as part of an expression, then the choice of pre versus post will make a difference.
  • 155. Howtomeasuredistancebetweenpoints Take one axis (X) for example: float distance = abs(mouseX – i); abs() function returns a positive number Absolute value… remember algebra! Used in example 6.9 Exercise 6.6: Rewrite 6.9 using a for loop Learning Processing: Slides by Don Smith 155
  • 156. Section 7 函数 Invitation to Computer Science, Java Version, Third Edition 156
  • 157. Learning Processing: Slides by Don Smith 157 Modularity What is a function? A named block of code Sometimes called a ‘module’, ‘method’ or a ‘procedure’ Some examples that you know are: setup() draw() mousePressed() background() ellipse() rect() In pseudocode, they might be‘high-level’ headings: Erase background Draw Spaceship Draw enemies Move spaceship based on user keyboard command Move enemies
  • 158. Learning Processing: Slides by Don Smith 158 Erase background Draw Spaceship Draw enemies Move spaceship Get keyboard command Move spaceship Move enemies Some functions are ‘built-in’ You can write your own! PseudocodetoFunctions // Modularized draw() Each time through draw: void draw() { background(0); drawSpaceShip(); drawEmenies(); moveShip(); moveEnemies(); }
  • 159. Learning Processing: Slides by Don Smith 159 Whyusefunctions? Is your draw()method getting a bit long? Two key principles of good programming: 1) Modularity Break down code into smaller parts More manageable and readable Reduce the number of local variables inside a module 2) Reusability Duplicated code (copy/paste?) is not good Must maintain in multiple places Better to put duplicate code in a new function and ‘call’ it from multiple places
  • 160. Learning Processing: Slides by Don Smith 160 Exercise: Modular‘Pong’Planning What functions might be used in the game of pong? 1) Decide on the ‘rules’ One player or two player? One player example Two player example 2) Write Pong pseudocode (or flow chart) 3) Decide on function names For user-defined functions 4) Think about variables you will need Local (inside a function) or ‘global’? Create names you can remember
  • 161. TheFunction‘Definition’ Make a named ‘block’ with the following parts: Return type void Function name Parameters area start block drawShip ( ) { // Variables and code go here } // end drawShip This is also called ‘declaring’ the function You are ‘telling’ the compiler that there is a new named block of code and how it works Other Rules: Define function outside all other functions Name with the same rules as variables (letters, digits, _) Do not use ‘reserved’ words or already used names Learning Processing: Slides by Don Smith 161
  • 162. CallingaFunction Now that we have a function, let’s use it: void draw() { drawShip(); // note the semicolon! } You ‘Call’ functions from ‘inside’ other functions In this case, inside draw() You call functions by using the function name: Return type Function name Arguments area semicolon <empty> drawShip ( ) ; Learning Processing: Slides by Don Smith 162
  • 163. Exercise: Writeandcallafunction Display a multi-part graphic (or a Zoog!) Learning Processing: Slides by Don Smith 163
  • 164. BouncingBallwithoutFunctions Group code into related ‘chunks’ Learning Processing: Slides by Don Smith 164
  • 165. BouncingBallwithFunctions Name the ‘chunks’, declare functions, call them! Learning Processing: Slides by Don Smith 165
  • 166. FunctionswithArgumentsandParameters What if you wanted to use a function to do slightly different things? Some examples you have seen that pass arguments to functions include: size(200,200); color(100,150,0); ellipse(x, y, width, height); More? What if you wanted to write your own function that receives parameters? Learning Processing: Slides by Don Smith 166
  • 167. ArgumentsandParameters Wikipedia Reference: http://en.wikipedia.org/wiki/Parameter_(computer_science) The book (and many professionals) confuse the two words. Per most texts and Wikipedia: Arguments are ‘sent’ Parameters are ‘received’ 167 // drawBlackCircle receives size parameter void drawBlackCircle(int diameter) { fill(0); // passes arguments to ellipse() ellipse(50, 50, diameter, diameter); } Learning Processing: Slides by Don Smith Argument comes before Parameter
  • 168. 168 Multiple Arguments void draw() { background(0); // Pass drawCar four drawCar( 100,100,64, drawCar( 50 ,75 ,32, arguments color(200,200,0) ); color(0,200,100) ); drawCar( 80 ,175,40, color(200,0,0) ); } // drawCar receives four parameters void drawCar(int x, int y, int thesize, color c) { // Using a local variable "offset" int offset = thesize/4; // Draw main car body … } Learning Processing: Slides by Don Smith
  • 169. 169 PassingVariables void draw() { background(0); int size = 32; // Pass drawCar four arguments drawCar( 100,100,size, color(200,200,0) ); size = size + 16; drawCar( 50 ,75 ,size, color(0,200,100) ); size = size + 16; drawCar( 80 ,175,size, color(200,0,0) ); } // drawCar receives four parameters void drawCar(int x, int y, int thesize, color c) { // Using a local variable "offset" int offset = thesize/4; // Draw main car body … } Learning Processing: Slides by Don Smith
  • 170. KeystoPassingArguments You must pass the same number of arguments as defined in the function parameter list. When an argument is passed, it must be of the same type as declared within the parameters in the function definition. An integer must be passed into an integer a floating point into a floating point.. The value you pass as an argument to a function can be a: Literal value (20, 5, 4.3, etc.), Variable (x, y, size, etc.) The result of an expression (8 + 3, 4 * x/2, random(0,10), etc.) Parameters act as local variables inside the receiving function They are only accessible within that function Learning Processing: Slides by Don Smith 170
  • 171. Learning Processing: Slides by Don Smith 171 Exercise: Writeafunctiondefinition: void draw() { float curHourly = 12.25; float raisePct = 9.0; showNewHourly(curHourly, raisePct); } // Make a comment line above the name // return type function name ( parameters ) { // Indented code goes here // Print the new hourly rate } Write your own showNewHourly()function definition to match the function call
  • 172. Learning Processing: Slides by Don Smith 172 Exercise: BouncingCar int globalX = 0; int globalY = 100; int speed = 1; void draw() { background(0); // Call move // Call bounce // Call drawCar with global X and Y and other params; } Write your own function calls to match the functions move, bounce and drawCar
  • 173. WhatamIreallypassing? Can the receiving function change the variable that you pass? That might be… dangerous… Here are the rules in Processing and Java: All primitive types (int, float, double, char…) are passed by copying the contents of the variable inside the argument into the new parameter variable. Learning Processing: Slides by Don Smith 173
  • 174. 174 PassbyValue(Animated) Let's take a closer look at how this works. void draw() { RAM n num int n = 10; println(n); byValue(n); println(n); } // end draw() 10 void byValue(int num) { num = 73; println(n); } // end byValue() 10 10 73
  • 176. Returntypes Up until now, you have used a mysterious keyword named void before all of your functions void void void void setup() { draw() { byValue(int num) { drawCar(int x, int y, int thesize, color c) { Remember the parts of a function definition? Return type void Function name Parameters area start block drawShip ( ) { Here is an example that ‘return’ an int: int sum(int a, int b, int c) { int total = a + b + c; return total; // Return a copy of a local variable } Learning Processing: Slides by Don Smith 176
  • 177. 177 Assigningthereturnvaluetoavariable draw calls sum with arguments sum receives values into parameters sum method calculates local total sum method returns copy of total draw assigns returned val to answer void draw() { int answer; answer = sum( 17, 42, 52); println(answer); noLoop(); } int sum(int a, int b, int c) { int total = a + b + c; return total; } Learning Processing: Slides by Don Smith
  • 178. 178 Ausefulexample: Distancebetween2pts float distance(float x1, float y1, float x2, float y2) { float dx = x1 – x2; // one side of the right triangle float dy = y1 – y2; // other side of the right triangle // hypoteneuse length float d = sqrt(dx*dx + dy*dy); return d; } Processing has a dist()function that does the same thing… Learning Processing: Slides by Don Smith
  • 179. Section 8 面向对象编程 Invitation to Computer Science, Java Version, Third Edition 179
  • 180. Learning Processing: Slides by Don Smith 180 ObjectOrientedProgramming(OOP) OOP is a different way to view programming Models the real world A different view than ‘Structured’ programming Functions break a program into ‘modules’ like an outline What is an Object? Usually based on a ‘noun’ It has ‘properties’ It has ‘actions’ (methods) that it can do (verbs) An examples of an object that you know: String The dot operator is used to make the String do work!
  • 181. WhyObjects? OOP allows you to put data about something and actions it can do together into one “object” OOP has been around since the 1960s Most popular current languages have either adapted or were designed with OOP C  C++  C# JavaScript Java
  • 182. Learning Processing: Slides by Don Smith 182 ObjectExample: Human Attributes Age Height Weight Name Eye color Hair color … Functions Sleep Wake-Up Eat Ride something
  • 183. Learning Processing: Slides by Don Smith 183 ClassesandObjects A Class A ‘plan’ for an object: Cookie Cutter The general idea of a thing Has placeholders for details, but not ‘made’ yet It declares functions that could be done to an object An Object An ‘instance’ of a Class: A Cookie A ‘real’ thing that has all of the specifics It can be ‘told’ to execute it’s functions You have to have a ‘plan’ before you can make an object: Class beforeObject
  • 184. Exercise: PlanaCarClass Let’s plan a simple Car List data and functions Let’s compare how we could convert the function we wrote to show different card with objects We’ll use our setup() and draw() methods
  • 185. Learning Processing: Slides by Don Smith 185 Setupfora‘Car’beforeObjects Use global variables for ‘properties’ Color: Location: Speed: carColor carX, carY carSpeed In setup() Set the carColor Set the starting location Set the initial speed In draw() Fill background Display car at location with color (may use a function) Increment car’s location based on speed
  • 186. 186 Setupmultiple‘Cars’beforeObjects Use global arrays of variables for ‘properties’ Allows us to use a loop to initialize a number of Cars Declare Color array: carColor [ ] Declare carX array: Declare carY array: carX [ ] carY [ ] Declare carSpeed array: carSpeed [ ] In setup() Set and initialize the arrays In draw() Fill background Loop through all the cars Display car at location with color (may use a function) Increment car’s location based on speed Learning Processing: Slides by Don Smith
  • 187. Learning Processing: Slides by Don Smith 187 Setupa‘Car’usingObjects One big difference with objects is that you move all of the global variables inside the Car object Color: Location: Speed: carColor carX, carY carSpeed Car object instead! We end up with one variable to represent the car Instead of initializing all of those variables, we initialize the car object!
  • 188. Learning Processing: Slides by Don Smith 188 Setupa‘Car’usingObjects Outside of all methods (global) Declare a ‘parking place’ for a car In setup() Make a new car object based on the ‘Car’ plan) Sets initial values for color, location and speed In draw() Fill background Tell the car to ‘move’ based on speed Tell the car to ‘display’ itself (call a function)
  • 189. The‘Car’class Convert the non-OOP Car Data to a Class Non-OOP OOP
  • 190. Learning Processing: Slides by Don Smith 190 Setupa‘Car’usingObjects-Data Let’s break it down step by step Declare the plan for the ‘Car’ Outside draw() and setup() Put variables for color, location and speed inside
  • 191. Learning Processing: Slides by Don Smith 191 Setupa‘Car’usingObjects-Constructor We need to write instructions to build a car It is called the ‘Constructor’ method Move the code that was in setup() Set variables for color, location and speed inside
  • 192. Learning Processing: Slides by Don Smith 192 Setupa‘Car’usingObjects-Functions Move the functions that did things to the car Move the code to inside the Car class The will be called methods of the class Move the code that was in display()and drive()
  • 193. Thewhole‘Car’(Example8.1) class Car { // Define a class for a car color c; // Variables. float xpos; float ypos; float xspeed; Car() { // A constructor. c = color(175); xpos = width/2; ypos = height/2; xspeed = 1; } void display() { // Function. // The car is just a square rectMode(CENTER); stroke(0); fill(c); rect(xpos,ypos,20,10); } void drive() { // Function. xpos = xpos + xspeed; if (xpos > width) { xpos = 0; } } }
  • 194. class Car { Car() { // Constructor c = color(175); xpos = width/2; ypos = height/2; xspeed = 1; } Whatwasthatabouta‘Constructor’? A constructor is a special method of a class Has the same name as the class “Builds’ the object Sets initial values It is ‘called’ with you use new: void setup() { size(200,200); // Initialize Car object myCar = new Car(); }
  • 195. AndhereistheOOPizedversion Is the OOP version shorter? Is it easier to read? Not yet maybe, but soon, and for the rest of your life. Learning Processing: Slides by Don Smith 195
  • 196. CarClassshouldreallybeinitsownfile… Click ‘Right Arrow’ in tabs row Use ‘New Tab’ in menu to create a new file Name the new tab exactly like the class = ‘Car’ Move the code for the ‘Car’ class to it Saves to a ‘Car.pde’ file in your folder Keep both files in the same folder If you want to use your ‘Car’ class in another project, simply copy the ‘Car.pde’ file there
  • 198. Whatifwewanttomakemorecars? Right now, all cars are exactly the same Their constructor sets up the color, location… How could we make ‘custom’ cars? Remember parameters? What if a Car constructor took parameters? class Car { Car(color colp, int xp, int yp, int speedp) { c = colp; xpos = xp; ypos = yp; xspeed = speedp; }
  • 199. Pleasereviewparameterpassing… Make a new frog with a length of 100
  • 200. Nowwecanmaketwo‘custom’cars Use your new ‘parameterized’ constructor!
  • 201. AndimagineanarrayofCars! You can use the ‘Car’ class just like any other type Declare an array of our new Cars object: Car [ ] parkingLot; setup() { parkingLot = new Car[10]; } But wait… what just happened? Did you create 10 cars? No, not yet. You created 10 parking stalls for cars So we still have to ‘build’ the cars and set all of the colors, locations and speeds… parkingLot[0] = new Car(color, x, y..);
  • 202. Fillingtheparkinglottheeasyway! Once you have the parking lot created, Car [ ] parkingLot; setup() { parkingLot = new Car[10]; } Use a for loop to make a bunch of cars! for (int i; i < 10; i++) { parkingLot[i] = new Car(color, x, y..); } Arrays and loops work wonderfully together! And they are even more fun with objects!