Processing
Upcoming SlideShare
Loading in...5
×
 

Processing

on

  • 1,448 views

 

Statistics

Views

Total Views
1,448
Views on SlideShare
1,444
Embed Views
4

Actions

Likes
0
Downloads
21
Comments
0

2 Embeds 4

http://mrsimon.pbworks.com 3
http://www.slideshare.net 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Processing Processing Presentation Transcript

  • Computer Programming 1 Mr. Simon Lowell High School San Francisco, CA
  • Course Requirements:
    • No previous programming experience is expected
    • You should feel comfortable using the internet and email
    • A web based email account (e.g. GMail or Yahoo mail) that you can access from school
    • A website (free and easy to get—I recommend freewebs.com)
  • Who should take this class?
    • Anyone interested in a career as computer programmer or game designer
    • Anyone considering a college major in:
      • Computer Science
      • Engineering
      • Math
      • Physics
      • Biology
      • Economics
      • Information Science
    • Anyone curious about how software is created
  • What you’ll learn
    • How to make simple programs (including computer games like "Pong" and "Tron") that can be installed on a computer, a webpage and even a cell phone
    • Data types (e.g. int, float)
    • Control structures (e.g. if, while)
    • Functions
    • Computer Graphics
    • Good Programming Style
    • A good foundation for studying computer science in college
  • Grading Policy
    • Each six week grade:
        • 70% tests and quizzes
        • 20% programming assignments
        • 10% productive use of lab time
    • The Semester grade:
        • Average of the 3 six week
        • grades and the final exam
  • Programming Assignments
    • Use free software: Processing
    • Available online or from me
    • It’s critical to your success that you spend adequate time programming and fully understand the assignments
    • Programming can be very time consuming—class time alone may not be enough
    • All programs should be sent by email to room334@gmail.com
  • Style
    • Building a working program is not enough
    • Other programmers need to read, understand and modify your program
    • Every class, book and job may use a slightly different style
    • Good style will significantly improve your grade
  • 10 point Program Grading Scale
    • 1 pt: Name, class, assignment in comments at top
    • 2 pts: URL (web address)
    • 2 pts: Correct Style
    • 5 pts: Program Correctness
    • Always put your name, class and assignment on the subject line of the email message
  • Web and email
    • Send programs to room334@gmail.com
    • Send questions to [email_address]
    • Check mrsimon.net for assignments, grades, software and other information
  • Log Off!
    • Please remember to logoff each time you finish with the computer, otherwise other people will be able to access your work!
  • Assignment 0
    • Then, send an email to room334@gmail.com with the following information:
    • Your name, reg, class and computer #
    • Your parents/guardians name, home phone and email
    • Your parents work/daytime phone
    • Secret Code (4 digits/characters, examples: AOK1, 1776, KT85)
    • If time permits, sign up for a website at freewebs.com
    • Log Off when you’re done
  • Getting your own website
    • Providers of free websites
    • http://webs.com
    • http://www.freehostspace.com
    • http://geocities.yahoo.com/
    • http:// www.netfirms.com
    • http://www.50megs.com
    • http:// www.angelfire.lycos.com /
    • http://www.100megs.com
    • Know of any others?
  • webs.com
    • Make up a site address and password
  • webs.com
    • Fill in the forms, choose a template (you can change your mind later)
    • Make sure you select the free plan
  • webs.com
    • I choose the "blank canvas" option, though I don't think it really matters
  • freehostspace.com
    • No ads, but a little harder to use
    • You'll have to write some html to create your webpage (I'll show you how)
    • Choose the FREE Hosting Plan, and fill out the form
  • freehostspace.com
    • Choose the FREE Hosting Plan, and fill out the form
    • Leave "Get Domain Name" field blank
    • You'll be sent a username and password
  • freehostspace.com
    • Once you get the confirmation email, login in, choose Website Manager and then Subdomain Manager
  • freehostspace.com
    • Make up a subdomain name, and choose "Add Subdomain"
    • I chose mrsimon.scienceontheweb.net
  • What is Computer Programming?
  • Computer Hardware and Software, the book analogy
    • Computer Hardware is like the cover and pages of a book
    • Computer Software is like the story—the language of the book
    • Programming a computer is creating software by writing computer language
  • Computer Language (Code)
    • Like human (called “natural”) language, Computer languages have words, numbers, grammar, syntax and punctuation
    • Unlike natural language, computer languages are very limited and specialized
    • Human language often has 100,000’s of words, computer languages get by with a few hundred
  • Low Level Computer Language
    • Computers only “understand” sequences of numbers
    • The “language of numbers” is called machine language —a low level language. It looks like
    • 100011 00011 01000 000000000001000100
    • Writing low level programs is difficult and tedious
  • High Level Computer Language
    • Uses words, easier for humans
    • High level programs are written using a special program that is sort of like a word processor for computer language
    • When the code is finished, another program (called a compiler) converts the high level code to machine code
  • High Level Languages
    • C++: flexible, powerful, most common
    • Java: good for the internet, and small devices like cell phones
    • Basic: easy to learn and use
    • Scheme: good for artificial intelligence
    • Many Others: C#, C, LISP, Fortran, Pascal, Forth, COBOL, Logo. . . .
  • Fourth Generation Languages
    • Programmers are working to create language programs that can convert natural language to computer language
    • Query is one example
    • Still in the early stages, it will be some time in the future before they can be used to make useful programs
  • We'll create Java programs using Processing
    • Processing is a beginner friendly program for creating Java software
    • Completely free to download and use from processing.org
    • Runs on Windows, Macs and Linux, even off a thumb drive
    • Finished programs can be exported to a website and java enabled cell phones
    • Very powerful graphics features
  • How to make your own computer software
    • Start Processing
    • Type ellipse(50,50,80,20);
    • Press "Run"
    • You should see this:
  • How to make your own computer software
    • ellipse(50,50,80,20);
    • An example of a function
    • functions "do something" this one "draws an ellipse with this size and position"
    • The numbers are called arguments or parameters
  • Coordinates in Computer Graphics
    • In computer graphics, the coordinate system is only positive.
    • The origin is the top left corner of the window
    (0,0) + X + Y
  • ellipse( 50,50 ,80,20);
    • The first two arguments ( in Red ) are the x and y coordinates of the center of the ellipse
    50 50
  • ellipse(50,50, 80 , 20 );
    • The third argument ( in Yellow ) is the width of the ellipse
    • The fourth argument ( in Green ) is the height
    • If the width and height are the same, the result is a circle
    80 20
    • size(300,200);
    • Another function, should always be called first
    • This one increases (or decreases) the screen area
    • The two arguments are width and height
    • Keep your applets small, no bigger than 800x600, and usually smaller
  • How to make your own computer software
    • noFill();
    • ellipse(50,50,80,20);
    • A program can use any number of functions
    • The noFill() function changes how ellipses are drawn
    • Notice that noFill() has no arguments, it's parenthesis are empty
  • How to make your own computer software
    • noFill();
    • smooth();
    • ellipse(50,50,80,20);
    • smooth() also has no arguments
    • It smoothes out the curves of the ellipse
  • How to make your own computer software
    • noFill();
    • stroke(255,0,0);
    • ellipse(50,50,80,20);
    • The stroke() function changes the color of the outline
    • It's 3 arguments are the amount of Red, Green and Blue in the range 0 - 255
  • How to make your own computer software
    • noFill();
    • stroke(255,0,0);
    • strokeWeight(5);
    • ellipse(50,50,80,20);
    • The strokeWeight() function changes the thickness of the outline
  • Order is important
    • ellipse(50,50,80,20);
    • noFill();
    • stroke(255,0,0);
    • strokeWeight(5);
    • Here changing the stroke and fill has no effect, because it's done after the ellipse had already been drawn
  • Saving your work
    • By default, Processing expects you to store your programs is in the Processing folder in My Documents
    • If you want, you can change the sketchbook location to store work on a flash drive
    • Choose Edit | Preferences to configure where your programs will be stored
    • Once you start typing your program choose
    • File | Save as and give it a name
  • Java is very picky about names
    • You may get this error message:
  • Assignment #1: Olympic Rings
    • Write a program that produces a design similar to the Olympic Rings with 5 differently colored circles
    • Your program will use the following functions (some more than once):
      • strokeWeight();
      • stroke()
      • ellipse()
      • size()
      • noFill()
  • Uploading the program to your website
    • Choose File | Export
  • Uploading the program to your website
    • Processing will create a folder called Applet
    • First, rename index to something like "OlympicRings"
  • A bug in version 0148 BETA 19 August 2008
    • When you export your applet, it's not the right size.
    • Open the html file in Word Pad, and manually change the size in two places
  • Uploading the program to your website
    • Upload only these three files to your website
      • OlympicRings (html or "Firefox Document")
      • OlympicRings (Executable Jar File)
      • loading (GIF Image)
  • Uploading to freewebs.com
    • Log in and click on My Site
  • Uploading to freewebs.com
    • Click on the single file uploader
  • Uploading to freewebs.com
    • One by one, upload OlympicRings (html or "Firefox Document"), OlympicRings (Executable Jar File) and loading (GIF Image)
    • You can hold the mouse over each file to figure out which is which
    • Leave the directory pull down menu unchanged
  • Uploading to freewebs.com
    • You should see all three in the File Manager
  • uploading to freehostspace.com
    • Choose File Manager
    • Double click on the folder with your subdomain name
  • uploading to freehostspace.com
    • Scroll down to the bottom of the page to find the file upload option
    • You can upload 3 files at a time
  • From the File Manager, Click on OlympicRings.html and you should see your program. It is now on the internet for the world to see!
  • Common Mistakes
    • Put each statement on a separate line.
    • Once you call noFill() , from then on, all ellipses will be unfilled. Don't call it more than once.
    • Same with strokeWeight() . Don't call it more than once.
  • Submitting the finished assignment
    • Attach OlympicRings.pde to an email and send it to [email_address]
    • You can find the PDE file by holding your mouse over it. It's NOT in the applet folder.
  • Submitting the finished assignment
    • Make sure you have your name, assignment and class on the subject line
    • Put the link to the page in the body of the email
  • Building your homepage and linking to your assignments
    • Click on Site Manager and then click on the Edit icon next to home
  • Building your homepage and linking to your assignments
    • Move your cursor to the content box where you want the link to go, and click Link
  • Building your homepage and linking to your assignments
    • Choose My Files, click on your html file, type some text and click Insert
  • Building your homepage and linking to your assignments
    • You should now see the link on your homepage
  • The Processing "Dictionary"
    • http://processing.org/reference/index.html
    • The API* is the dictionary of a computer language
    * API stands for Application Programming Interface , but you don't really care and it won't be on the test
  • The "definition" of ellipse()
  • Drawing Functions
    • triangle()
    • rect() (also squares)
    • quad()
    • ellipse() (also circles)
    • point()
    • line()
    • bezier() and arc() (for curves)
    • beginShape() and endShape () (for polygons)
  • triangle( 150 , 20 , 20 , 280 ,280,280);
  • rect( 50 , 20 ,200, 100 );
  • quad( 50 , 20 , 220 , 80 , 250 , 160 ,30,280);
  • ellipse( 150 , 150 ,220, 80 );
  • point(150,150);
  • line( 10 , 250 , 290 , 15 );
  • The endpoints
    • bezier( 20,20 ,10,110,280,150, 280,280 );
  • These two invisible points "pull" the curve
    • bezier(20,20, 10,110 , 280,150 ,280,280);
  • The effect at the ends is weaker
    • bezier(20,20, 210,250 , 290,250 ,280,280);
  • The effect at the ends is weaker
    • bezier(20,20, 10,50 , 100 , 50 ,280,280);
  • Both points on the same side
    • bezier(20,20, 10,50 , 100 , 280 ,280,280);
  • The points can be off the screen!
    • bezier(20,20, -200,110 , 500,150 ,280,280);
  • arc() draws part of an ellipse()
    • arc( 150 , 150 , 200 , 200 , 0, PI/2);
  • arc() draws part of an ellipse()
    • arc( 150 , 150 , 100 , 200 , PI/4, 3*PI/2);
  • Polygons
    • beginShape();
    • vertex(20, 20);
    • vertex(40, 20);
    • vertex(40, 40);
    • vertex(60, 40);
    • vertex(60, 60);
    • vertex(20, 60);
    • endShape(CLOSE);
  • noStroke(); rect(50,50,200,100);
  • noFill(); rect(50,50,200,100);
  • noFill(); noStroke(); rect(50,50,200,100); Empty!
  • fill(255,0,0); rect(50,50,200,100);
  • fill(0,255,0); rect(50,50,200,100);
  • fill(0,0,255); rect(50,50,200,100);
  • fill(178,58,238); rect(50,50,200,100); RGB Color Codes: http://www.tayloredmktg.com/rgb/
  • fill(0,0,255); stroke(255,0,0); rect(50,50,200,100);
  • background(0,0,0); fill(255,0,0); rect(50,50,200,100);
  • opacity
    • You can make shapes transparent by using the four argument version of fill()
    • the fourth argument is opacity
    • size(200,200);
    • background(0);
    • fill(0,255,0, 127 );
    • ellipse(50,50,30,80);
    • fill(255,0,0, 127 );
    • rect(30,30,150,70);
    • fill(0,0,255, 127 );
    • rect(40,50,80,170);
  • Practice Quiz Question
    • Circle the picture that best matches the output
    • fill(255,0,0);
    • ellipse(10,10,50,50);
    • fill(0,255,0);
    • rect(10,10,80,20);
    • rect(10,50,20,30);
  • Practice Quiz Questions
    • True/False: The ellipse function takes 3 arguments
    • Fill in the blank: The ______ is like a dictionary of the words in a programming language
    • Circle the unnecessary line of code in the following program:
        • stroke(0,255,0);
        • ellipse(33,50,20,20);
        • stroke(0,255,0);
        • ellipse(66,50,20,20);
  • Comments
    • Two forms: Single and Multi-line
    • // Single Line
    • /* Multi-Line */
    • Tells the computer “ignore this”, this is for people
    • Good Style: Always put your name, assignment and class in comments at the top of your program
  • Comments
    • Good Style: Always put your name, assignment and class in comments at the top of your program
  • doc comments
    • Doc comments (documentation comments) are used for sharing a description of your sketch when the program is exported.
    • To make doc comments use
    • /**
    • description
    • */
  • doc comments
    • Doc comments show up on the webpage when you export the program
  • doc comments
    • You can start a new line with <br> or <p>
  • Arithmetic
    • Calculations use the following arithmetic operators : + - * / %
    • The operators can be combined with numbers to make expressions .
    • The expression 5 + 3 evaluates to 8
    • Parenthesis can be used to create more complicated expressions
    • (5 * (2 – 3)) evaluates to -5
  • Expressions can be arguments
    • What will be the height and width of the following ellipse?
    • ellipse(150,150,2*(22+78),40*(8-2));
  • Symmetry
    • Expressions can be used to make placing symmetrical arrangements easier
  • Symmetry
    • size(300,300);
    • ellipse( 150-75 ,150,40,40);
    • ellipse( 150+75 ,150,40,40);
  • Integer arithmetic
    • Division is done differently with integers than with decimals
      • 5.0/4.0 evaluates to 1.25
      • 5/4.0 evaluates to 1.25
      • 5.0/4 evaluates to 1.25
      • 5/4 evaluates to 1
    • If one or more numbers in an expression is a decimal , the result will be a decimal
    • If all the numbers in an expression are integers , the result will be an integer
  • Integer arithmetic
    • If you see an integer division expression like 5/4
    • ask yourself &quot;How many times does 4 go into 5?&quot;
  • Modulus and integer division
    • Remember how you did math in grade school?
  • Modulus and integer division
    • Remember how you did math in grade school?
  • Modulus and integer division
    • Remember how you did math in grade school?
  • Modulus and integer division
    • Remember how you did math in grade school?
    • The modulus operator gives the remainder of an integer division expression
    • 8/5
    • 8 % 5
    Modulus and integer division
  • Practice Quiz Question: Evaluate the following expressions
    • 9/4
    • 9%4
    • 21/2
    • 21%2
    • 5/8
    • 5%8
  • Variables and Declarations
    • Sometimes you want a place to store a number in computer memory.
    • You can think of this as a &quot;mailbox&quot;
    • There different sizes of &quot;mailboxes&quot; for different kinds of numbers.
      • Integers: int
      • Decimals: float
      • Characters (Letters, Punctuation & Digits): char
      • boolean holds only true or false
  • Variables and Declarations
    • Vari -ables allow values to change
  • Variable Declarations & Initializations
    • To create a mailbox, you declare it.
    • int num;
    • num is the &quot;name&quot; of the variable
    • names can't have spaces or unusual characters
    • Once its declared you can store a number in it
    • num = 5;
    • This is called initializing
    • You can also do both at once
    • int value = 17 ;
  • Using variables in expression
    • Once a variable has been declared and initialized, you can use it in an expression
    • What will be the x and y coordinates of the center of the ellipse?
    • int value1 = 17;
    • int value2 = 13;
    • ellipse( 50+value1 , 50-value2 ,12,44);
  • The assignment operator
    • = is called the assignment operator
    • It takes the value on the right , and puts it in the variable on the left
    • num = 5;
    • You can't do it the other way around!
    • 5 = num;
  • The assignment operator
    • You can't do an assignment as an argument
    • ellipse(int x = 45,55,10,10);
    • You have to do in two separate lines
    • int x = 45;
    • ellipse(x,55,10,10);
  • The type of variable must match
    • You can't put a decimal in an int
    • Otherwise you'll get an error message
  • The assignment operator
    • This looks weird if you are use to algebra, but it's very common in programming
    • int x = 3;
    • x = x + 1 ;
    • What value is in the x variable after those two lines of code are executed?
  • Variables can be reused as many times as you like
  • Now With just one change. . .
  • Good Style
    • Name your variables what they are
    • x is a good name for an x coordinate
    • num is a lousy name for the screen width
    • variable names that use more than one word should capitalize the beginning of all the words after the first
    • int numberOfPeople = 34;
    • Be careful! If type a name for a variable and it changes color, that name has already been taken!
  • &quot;Moving&quot; a circle
    • size(200,100);
    • int x = 50;
    • int y = 50;
    • ellipse(x,y,60,60);
  • &quot;Moving&quot; a circle
    • size(200,100);
    • int x = 50;
    • int y = 50;
    • ellipse(x,y,60,60);
    • x = x + 50;
  • &quot;Moving&quot; a circle
    • size(200,100);
    • int x = 50;
    • int y = 50;
    • ellipse(x,y,60,60);
    • x = x + 50;
    • ellipse(x,y,60,60);
  • &quot;Moving&quot; a circle
    • size(200,100);
    • int x = 50;
    • int y = 50;
    • ellipse(x,y,60,60);
    • x = x + 50;
    • ellipse(x,y,60,60);
    • x = x + 50;
  • &quot;Moving&quot; a circle
    • size(200,100);
    • int x = 50;
    • int y = 50;
    • ellipse(x,y,60,60);
    • x = x + 50;
    • ellipse(x,y,60,60);
    • x = x + 50;
    • ellipse(x,y,60,60);
  • Notice the difference?
    • size(200,100);
    • int x = 50;
    • int y = 50;
    • ellipse(x,y,60,60);
    • x = x + 50;
    • ellipse(x,y,60,60);
    • x = x + 50;
    • ellipse(x,y,60,60);
  • The top picture drew the left circle first , while the bottom drew the left circle last
    • size(200,100);
    • int x = 50;
    • int y = 50;
    • ellipse(x,y,60,60);
    • x = x + 50;
    • ellipse(x,y,60,60);
    • x = x + 50;
    • ellipse(x,y,60,60);
  • The bottom picture doesn't match the output of this program
    • size(200,100);
    • int x = 50;
    • int y = 50;
    • ellipse(x,y,60,60);
    • x = x + 50;
    • ellipse(x,y,60,60);
    • x = x + 50;
    • ellipse(x,y,60,60);
  • Circle the matching output
    • size(100,100);
    • int x = 50;
    • int y = 50;
    • ellipse(x,y,60,60);
    • x = x + 30;
    • ellipse(x,y,60,60);
    • y = y - 30;
    • ellipse(x,y,60,60);
  • Modern programs are very big—they are organized into Functions
    • Programs can be difficult to understand Windows Vista has over 50,000,000 lines of computer code!
    • One way to make programs easier to understand is to break them down into smaller &quot;chunks&quot; or modules
    • One name for these modules is functions
    213,000,000 Debian GNU/Linux 2005 30,000,000 Red Hat Linux 7.1 2005 86,000,000 Mac OS X 10.4 2005 50,000,000 Windows Vista Beta 2 2005 40,000,000 Windows XP 2001 29,000,000 Windows 2000 2000 16,000,000 Windows NT 4.0 1996 6,000,000 Windows NT 3.1 1993 Lines of Code Operating System Year
  • You wouldn't write a paper that was just one long paragraph
    • You'd have many paragraphs, each of which would focus on one topic
    • It's the same in programs—we divide our program into chunks called functions
    • Each function focuses on one job or task
  • Creating your own functions
    • Processing allows you to separate your program into different functions.
    • This is one of the key elements of good style , and makes programs easier to understand, modify and reuse.
    • A well designed function should do one thing ; that is you should be able to describe what it does without using the word and or or .
  • setup() and draw()
    • Processing programs that use functions must contain two special functions called setup() and draw()
    • Put things that happen only once at the beginning in setup()
    • Put code that draws in draw()
    • You may create as many additional functions as you want
  • Happy Face Example
    • Let's say I had a program that drew a happy face
  • Happy Face Example
    • Here's what it would look like separated into setup() and draw() functions
    • void setup()
    • {
    • size(200,100);
    • }
    • void draw()
    • {
    • fill(255,255,0);
    • ellipse(100,50,80,80);
    • arc(100,50,60,60,PI/8,7*PI/8);
    • fill(0,0,0);
    • ellipse(85,40,10,15);
    • ellipse(115,40,10,15);
    • }
  • The syntax of functions
    • void setup()
    • {
    • size(200,100);
    • }
    • For now, every function starts with void which marks the beginning of the head
    • Then a name followed by parenthesis
    • Curly braces mark the beginning and ending of the body of the function
    • The head and body together are called the function definition
  • Happy Face Example
    • Here I've added my own face() and head() functions
    • void setup()
    • {
    • size(200,100);
    • }
    • void draw()
    • {
    • head();
    • face();
    • }
    • void head()
    • {
    • fill(255,255,0);
    • ellipse(100,50,80,80);
    • }
    • void face()
    • {
    • arc(100,50,60,60,PI/8,7*PI/8);
    • fill(0,0,0);
    • ellipse(85,40,10,15);
    • ellipse(115,40,10,15);
    • }
  • Oops! What happened?
    • void setup()
    • {
    • size(200,100);
    • }
    • void draw()
    • {
    • face();
    • head();
    • }
    • void head()
    • {
    • fill(255,255,0);
    • ellipse(100,50,80,80);
    • }
    • void face()
    • {
    • arc(100,50,60,60,PI/8,7*PI/8);
    • fill(0,0,0);
    • ellipse(85,40,10,15);
    • ellipse(115,40,10,15);
    • }
  • Auto-Format before after
  • Simple Animation
    • We can take advantage of the way setup() and draw() work to create simple animations
    • (demo)
  • Practice Quiz Question
    • Which picture matches the output of this program?
    • void setup()
    • {
    • background(0,0,0);
    • }
    • void draw()
    • {
    • anotherMystery();
    • mysteryFunction();
    • fill(255,0,0);
    • ellipse(50,50,40,40);
    • }
    • void mysteryFunction()
    • {
    • fill(0,255,0);
    • ellipse(60,50,40,40);
    • }
    • void anotherMystery()
    • {
    • fill(0,0,255);
    • ellipse(70,50,40,40);
    • }
    A B C D
  • the background drawn once
    • int x = 0;
    • void setup()
    • {
    • background(0,0,0);
    • stroke(255,255,255);
    • noFill();
    • }
    • void draw()
    • {
    • ellipse(x,50,20,20);
    • x = x + 5;
    • }
  • the background drawn every time the screen is drawn (no trail)
    • int x = 0;
    • void setup()
    • {
    • stroke(255,255,255);
    • noFill();
    • }
    • void draw()
    • {
    • background(0,0,0);
    • ellipse(x,50,20,20);
    • x = x + 5;
    • }
  • Checking the value in a variable
    • One of the confusing things in programming is keeping track of the values as they change
    • You can print the values to the black box at the bottom of Processing with
      • print()
      • println()
  • Checking the value in a variable
    • Apparently (15%2) + 27 is 28
  • Printing Text
    • Text can be words, sentences, paragraphs, numbers and more
    • It's any collection of characters, punctuation, numbers and spaces
    • To print text use double quotes
    • print( &quot; Testing, 1, 2, 3 &quot; );
    • &quot;Testing, 1, 2, 3&quot; is an example of a literal
  • Expressions vs. Literals
    • These two function calls produce different output
    • println(&quot;2 + 3&quot;);
    • println( 2 + 3);
  • Expressions vs. Literals
    • These two function calls produce different output
    • println(&quot;2 + 3&quot;);
    • //displays 2 + 3
    • println(2 + 3);
    • //displays 5
  • print() vs. println()
    • println() means &quot;go to the next line AFTER you print.&quot;
    • print() doesn't
    • print(&quot;x&quot;);
    • print(2);
    • //displays: x2
    • println(&quot;x&quot;);
    • println(2);
    • //displays: x
    • // 2
    • You can make the output more readable by including blank whitespace
    • print(2);
    • print( &quot;and&quot; );
    • print(2);
    • print( &quot;makes&quot; );
    • print(4);
    • //displays 2and2makes4
    • print(2);
    • print( &quot; and &quot; );
    • print(2);
    • print( &quot; makes &quot; );
    • print(4);
    • //displays 2 and 2 makes 4
    • Processing generally ignores whitespace unless you place it in a literal surrounded by double quotes
    Whitespace
  • Practice with print()
    • Start Processing
    • Copy and paste the following code:
    • int var1 = 23;
    • int var2 = 7;
    • print(var1 / var2);
    • Try and guess what will be displayed
    • Check your answer by pressing play
  • Practice with print()
    • Now add quote marks
    • int var1 = 23;
    • int var2 = 7;
    • print( &quot; var1 / var2 &quot; );
    • Now, try and guess what will be displayed
    • Check your answer by pressing play
  • Practice with print()
    • Now, run the program with both versions
    • int var1 = 23;
    • int var2 = 7;
    • print(&quot;var1 / var2&quot;);
    • print(var1 / var2);
    • Again, try and guess what will be displayed
    • Check your answer by pressing play
  • Practice with print()
    • Try this
    • int var1 = 23;
    • int var2 = 7;
    • print ln (&quot;var1 / var2&quot;);
    • print ln (var1 / var2);
  • Practice Quiz Question
    • What is the output of the following program?
    • int val1 = 13;
    • int val2 = 5;
    • print(&quot;va11 / val2 = &quot;);
    • print(val1/val2);
    • println(&quot;r&quot;);
    • println(val1%val2);
  • Functions and variable declarations
    • If you declare a variable in a function, you can only use it in that function
    • void setup()
    • {
    • int num = 5;
    • println(num);
    • }
    • void draw()
    • {
    • println(num);
    • }
  • Functions and variable declarations
    • If you declare a variable in a function, you can only use it in that function
    • void setup()
    • {
    • int num = 5;
    • println(num); //OK!
    • }
    • void draw()
    • {
    • println(num);
    • }
  • Functions and variable declarations
    • If you declare a variable in a function, you can only use it in that function
    • void setup()
    • {
    • int num = 5;
    • println(num);
    • }
    • void draw()
    • {
    • println(num); //Error!
    • }
  • Functions and variable declarations
    • void setup()
    • {
    • int num = 5;
    • println(num);
    • }
    • void draw()
    • {
    • println(num); //Error!
    • }
  • The basic scope rule*
    • Scope is like a neighborhood, it's where the variable is known
    • The basic scope rule* is the scope of variable begins with it's declaration and ends with the closing curly brace of the block of code where it was declared
    • *there are exceptions to this rule, but we don't really care and we certainly aren't going to worry about it now
  • The scope of diameter is in yellow
    • void draw()
    • {
    • ellipse(30,30,50,80);
    • noFill();
    • strokeWeight(5);
    • int diameter = 100;
    • stroke(255,0,0);
    • ellipse(60,60,diameter,diameter);
    • println(diameter);
    • }
  • If you declare the variable at the top of the program outside of any function, it's scope is the entire program
    • int diameter = 10;
    • void setup()
    • {
    • println( diameter ); //OK
    • }
    • void draw()
    • {
    • ellipse(30,30,50,80);
    • noFill();
    • strokeWeight(5);
    • diameter = diameter + 10; //OK
    • stroke(255,0,0);
    • ellipse(60,60, diameter , diameter ); //OK
    • println( diameter ); //OK
    • }
  • Local vs. Global
    • A global variable can be used anywhere in the program
    • You create a global variable by declaring it at the top of the program
    • A local variable is declared in a function
  • The circle gets bigger
    • int diameter = 10;
    • void setup()
    • {
    • size(300,300);
    • noFill();
    • }
    • void draw()
    • {
    • ellipse(150,150,diameter,diameter);
    • diameter = diameter + 10;
    • }
  • The circle DOESN'T get bigger
    • void setup()
    • {
    • size(300,300);
    • noFill();
    • }
    • void draw()
    • {
    • int diameter = 10;
    • ellipse(150,150,diameter,diameter);
    • diameter = diameter + 10;
    • }
  • The if statement
    • if( num > 150 )
    • {
    • println(&quot;num is pretty big&quot;);
    • }
      • a &quot;test&quot; within parentheses ( )
      • a block of statements within curly braces { }.
    • The test is any expression that evaluates to true or false.
    • The if-statement evaluates the test and then runs the body code only if the test is true. If the test is false, the body is skipped.
  • if statement
    • int num = 5;
    • if(num > 2)
    • {
    • println(&quot;It worked!&quot;);
    • }
  • if statement
    • int num = 5;
    • if(num > 7 )
    • {
    • println(&quot;It worked!&quot;);
    • }
    Empty!
  • Using an if to &quot; start over if it gets too big &quot;
    • int diameter = 10;
    • void setup()
    • {
    • size(300,300);
    • background(0,0,0);
    • noFill();
    • stroke(255,255,255);
    • }
    • void draw()
    • {
    • ellipse(150,150,diameter,diameter);
    • diameter = diameter + 20;
    • if(diameter > 300)
    • {
    • background(0,0,0);
    • diameter = 10;
    • }
    • }
  • A Gradient
    • int redAmount = 0;
    • int blueAmount = 255;
    • int x = 0;
    • void setup()
    • {
    • size(256,256);
    • }
    • void draw()
    • {
    • stroke(redAmount,0,blueAmount);
    • line(x,0,x,255);
    • x=x+1;
    • redAmount = redAmount + 1;
    • blueAmount = blueAmount - 1;
    • }
  • A Circle that moves left to right
    • int x = 0;
    • void setup()
    • {
    • size(300,300);
    • }
    • void draw()
    • {
    • background(0);
    • ellipse(x,150,30,30);
    • x = x + 1;
    • }
  • A Circle that moves back & forth
    • int x = 0;
    • int change = 1;
    • void setup()
    • {
    • size(300,300);
    • }
    • void draw()
    • {
    • background(0);
    • ellipse(x,150,30,30);
    • x = x + change;
    • if(x > 300)
    • {
    • change = -1;
    • }
    • if(x < 0)
    • {
    • change = 1;
    • }
    • }
  • Practice quiz question
    • Circle the output that best matches the following code
    • int mystery = 0;
    • void setup()
    • {
    • noFill();
    • }
    • void draw()
    • {
    • ellipse(50,mystery,20,20);
    • mystery = mystery + 15;
    • }
  • Input
    • Most programs we see get input from people
    • The most common ways people provide input are:
      • Typing on the keyboard
      • Moving and/or clicking the mouse
  • Input
    • Processing makes input from the mouse and keyboard about as easy as it gets
    • There are several predefined &quot;system variables&quot;
      • mouseX
      • mouseY
      • key
  • Moving a circle with the mouse
    • void setup()
    • {
    • size(300,300);
    • }
    • void draw()
    • {
    • ellipse(mouseX,mouseY,30,30);
    • }
    • The ellipse will track the mouse
  • Functions that respond to events
    • keyTyped()
    • keyPressed()
    • keyReleased()
    • mouseMoved()
    • mousePressed()
    • mouseReleased()
    • mouseClicked()
    • mouseDragged()
  • Painting only if mouse is dragged
    • void setup()
    • {
    • size(300,300);
    • }
    • void draw()
    • {
    • }
    • void mouseDragged ()
    • {
    • ellipse(mouseX,mouseY,10,10);
    • }
  • More on if : Relational Operators
      • < <= == >= > !=
      • if statements are created by comparing two things
      • if(5 < 3)
      • if(num == 5)
      • if(num >= 5)
      • if(num != 5)
      • if the the comparison in the parenthesis is true, the code in the curly braces after the if executes. Otherwise it is skipped.
  • More on if : Relational Operators
      • if (num1 < num2 < num3)
      • Comparisons must be done two at a time
  • More on if : Relational Operators
      • < <= == >= > !=
      • The operators that are used for comparisons are called relational operators
  • = vs. ==
    • A single equals (called the assignment operator) MAKES two things equal
    • num = 3;
    • Don't put this in an if —it will always be true!
    • The double equals asks a question: Are these two things equal?
    • num==3
    • Use the double equals anywhere you would use a condition: if , etc.
    • if(num==3)
    • {
    • println(&quot;num is three&quot;);
    • }
  • Moving the ellipse with the keyboard
    • int x, y;
    • void setup()
    • {
    • size(300,300);
    • x = 150;
    • y = 150;
    • }
    • void draw()
    • {
    • ellipse(x,y,30,30);
    • }
    • void keyPressed()
    • {
    • if(key=='w')
    • {
    • y = y - 1;
    • }
    • }
  • Painting only if the right mouse button is clicked
    • void setup()
    • {
    • size(300,300);
    • }
    • void draw()
    • {
    • }
    • void mousePressed()
    • {
    • if(mouseButton==RIGHT )
    • {
    • ellipse(mouseX,mouseY,10,10);
    • }
    • }
  • boolean variables
    • boolean s are the smallest, simplest kind of &quot;mailbox&quot;
    • They can hold only one of two possible values: true or false
    • Examples:
    • boolean zoom = true ;
    • boolean cond = 3 >= 3 ;
    • boolean isBig = num > 7 ;
  • Painting only if the mouse is pressed and a key is pressed
    • void setup()
    • {
    • size(300,300);
    • }
    • void draw()
    • {
    • }
    • void keyPressed()
    • {
    • if( mousePressed==true )
    • {
    • ellipse(mouseX,mouseY,10,10);
    • }
    • }
  • Painting only if the mouse is pressed and a key is pressed a different way
    • void setup()
    • {
    • size(300,300);
    • }
    • void draw()
    • {
    • }
    • void mousePressed()
    • {
    • if( keyPressed==true )
    • {
    • ellipse(mouseX,mouseY,10,10);
    • }
    • }
  • Logical Operators
    • && //AND
    • || //OR
    • ! //NOT
    • Used to combine multiple conditions (&quot;tests&quot;)
    • Truth tables shown at right above
    • Examples
      • ( 0 < nCount ) && ( nCount <= 100 )
      • ( 0 < nCount ) || ( nCount <= 100 )
      • (‘A’ <= cGrade) && (cGrade <= ‘F’)
      • ! (19 >= nAge && nAge >= 13)
      • 19 < nAge || nAge < 13
  • Painting only if the mouse is dragged and the 'w' key is pressed
    • void setup()
    • {
    • size(300,300);
    • }
    • void draw()
    • {
    • }
    • void mouseDragged()
    • {
    • if( keyPressed == true && key == 'w' )
    • {
    • ellipse(mouseX,mouseY,10,10);
    • }
    • }
  • Practice Quiz Question: What is the output?
    • int num = 4;
    • float dNum = 7.2;
    • if((num > 5) && (dNum < 8))
    • {
    • println(&quot;first&quot;);
    • }
    • if((num > 5) || (dNum < 8))
    • {
    • println(&quot;second&quot;);
    • }
    • if(!(num > 5))
    • {
    • println(&quot;third&quot;);
    • }
    • if(!(dNum < 8))
    • {
    • println(&quot;fourth&quot;);
    • }
  • Watch out for this error
    • int num = 5;
    • if(num > 7);
    • {
    • println(&quot;num is big&quot;);
    • }
  • There shouldn't be a semi-colon here
    • int num = 5;
    • if(num > 7) ;
    • {
    • println(&quot;num is big&quot;);
    • }
  • There shouldn't be a semi-colon here
    • int num = 5;
    • if(num > 7) ;
    • {
    • println(&quot;num is big&quot;);
    • }
    • Is &quot;If num is greater than 7.&quot; a complete sentence?
  • Now it's fixed
    • int num = 5;
    • if(num > 7)
    • {
    • println(&quot;num is big&quot;);
    • }
    • No, the complete sentence is &quot;If num is greater than 7 then num is big.&quot;
  • Symmetrical reflections (mirrors) 300 200 (50,30)
  • Symmetrical reflections (mirrors) 300 200 (50,30) 50
  • Symmetrical reflections (mirrors) 300 200 (50,30) 50 50
  • Symmetrical reflections (mirrors) 300 200 (50,30) 50 50 (300-50,30)
  • if and if/else
    • int num = 5;
    • if(num > 150)
    • {
    • num = 5;
    • }
    • An if controls some code that either runs or doesn't
    • if(num > 150)
    • {
    • num = 5;
    • }
    • else
    • {
    • num = num + 10;
    • }
    • An if/else always runs the code in the if or the else , but never both
  • &quot;Chained&quot; if/else
    • if(temp > 80)
    • {
    • println(Go swimming&quot;);
    • }
    • else if(temp > 50)
    • {
    • println(&quot;Go Fishing&quot;);
    • }
    • else if(temp > 32)
    • {
    • println(&quot;Go hot tubbing&quot;);
    • }
    • else
    • {
    • println(&quot;Go sledding&quot;);
    • }
  • Practice Quiz Question: What is the output of this program?
    • int num1= 2;
    • int num2 = 7;
    • float decimal = 9;
    • if(num1 == 2)
    • {
    • println(&quot;First&quot;);
    • }
    • else if (num2 == 3)
    • {
    • println(&quot;Second&quot;);
    • }
    • else if (decimal == 9)
    • {
    • println(&quot;Third&quot;);
    • }
    • else
    • {
    • println(&quot;Fourth&quot;);
    • }
    • if(num2/num1 != 1)
    • {
    • println(&quot;Fifth&quot;);
    • }
    • if(num2/num1 != 3)
    • {
    • println(&quot;Sixth&quot;);
    • }
    • else
    • {
    • println(&quot;Seventh&quot;);
    • }
  • Two modes
    • Often, programs will have two &quot;modes&quot; or &quot;states&quot;
    • The combination of an if and a boolean can switch between the two
  • Two modes
    • mode = !mode
    • this line of code &quot;flips&quot; mode back and forth between true and false.
  • Random numbers
    • The random() function has two versions:
    • random(5) returns a decimal value between 0 and up to but not including 5.0
    • random(-5, 10.2) returns a decimal value between -5.0 and up to but not including 10.2.
    • To drop the decimal part of a random number, use the int() function.
    • int randNum = int( random(16) ) ;
    • randNum now holds an integer from 0 up to but not including 16
  • dice example
    • Let's say I wanted to make an applet that simulated rolling a single six sided die
    • What numbers would be possible?
  • dice example
    • Let's say I wanted to make an applet that simulated rolling a single six sided die
    • What numbers would be possible?
    • {1,2,3,4,5,6}
  • dice example
    • Let's say I wanted to make an applet that simulated rolling a single six sided die
    • What numbers would be possible?
    • {1,2,3,4,5,6}
    • int roll = ??
  • dice example
    • Let's say I wanted to make an applet that simulated rolling a single six sided die
    • What numbers would be possible?
    • {1,2,3,4,5,6}
    • int roll = int(random( ?,? ));
  • dice example
    • Let's say I wanted to make an applet that simulated rolling a single six sided die
    • What numbers would be possible?
    • {1,2,3,4,5,6}
    • int roll = int(random( ?,? ));
    +1
  • dice example
    • Let's say I wanted to make an applet that simulated rolling a single six sided die
    • What numbers would be possible?
    • {1,2,3,4,5,6}
    • int roll = int(random( 1 , 7 ));
    +1
  • A bug with negative arguments
    • What arguments would you use to get this range?
    • {-3,-2,-1,0,1,2,3}
    • int roll = int(random( ? , ? ));
  • A bug with negative arguments
    • For some reason the low limit is one less.
    • {-3,-2,-1,0,1,2,3}
    • int roll =int(random( -4 , 4 ));
  • Random Walk
    • The position or state of an object changes unpredictably (by a random amount) over time
    • Software uses random walks to model many &quot;real life&quot; things including:
      • Weather
      • Stock Prices
      • Load on a web server
      • Chemistry (gas particles)
      • Biology (food foraging)
  • A Random Walk isn't a Random Jump
    • I'd call this a random jump
    • x = int(random(0,400));
  • A Random Walk isn't a Random Jump
    • I'd call this a random jump
    • x = int(random(0,400));
    • I'd call this a random walk
    • x = x + int(random(-2,2));
  • Modeling stock prices
    • int price = 150;
    • int x = 0;
    • int oldX,oldY;
    • void setup()
    • {
    • size(300,300);
    • }
    • void draw()
    • {
    • oldX = x;
    • oldY = price;
    • x = x+ 10;
    • int changeValue =
    • int(random(-51,51));
    • price = price + changeValue;
    • line(oldX,oldY,x,price);
    • ellipse(x,price,10,10);
    • }
  • Modeling stock prices
    • int changeValue = int(random(-51,51));
    • price = price + changeValue;
  • Modeling stock prices
    • int changeValue = int(random(-51,51)) ;
    • price = price + changeValue;
  • Modeling stock prices
    • int changeValue = int(random(-51,51)) ;
    • {-50,-49,-48, … 48,49,50}
    • price = price + changeValue;
  • More Random Walk examples
    • http://www.mit.edu/~kardar/teaching/projects/chemotaxis(AndreaSchmidt)/random.htm
  •  
  • Practice Quiz Questions
    • Fill in the blanks to create the indicated random numbers
    • A random integer from 0 to 10: (including 10)
    • int(random(________))
    • A random integer from 1 to 100: (including 100)
    • int(random(________))
    • A random integer from -5 to 5: (including 5)
    • int(random(________))
  • Using Pictures and Images
    • Processing can display .gif , .jpg , .tga , and .png image
    • First, choose Sketch | Add File to select the the image you want
  • Images
    • Now, write code like this, where hallway.jpg is the name of the picture
    • PImage b;
    • void setup()
    • {
    • size(415,350);
    • b = loadImage(&quot;hallway.jpg&quot;);
    • }
    • void draw()
    • {
    • image(b, 0, 0,415,350);
    • }
  • Images
    • b is the name of the variable that holds the image
    • 0,0 is the x and y of the top left hand corner
    • 415, 350 is the width and height
    • PImage b ;
    • void setup()
    • {
    • size(415,350);
    • b = loadImage(&quot;hallway.jpg&quot;);
    • }
    • void draw()
    • {
    • image( b , 0, 0 , 415, 350 );
    • }
  • Using an image for the background()
    • Make sure the size() of the applet is the same as the size of the image.
    • PImage bill;
    • void setup()
    • {
    • size(450,315);
    • bill = loadImage(&quot;bill-gates-mugshot.jpg&quot;);
    • }
    • void draw()
    • {
    • background(bill);
    • }
  • Which dot is moving in a random walk?
  • Which dot is moving in a random walk?
  • Which dot is moving in a random walk?
  • Which dot is moving in a random walk?
  • Which dot is moving in a random walk?
  • Which dot is moving in a random walk?
  • Which dot is moving in a random walk?
  • Random Walks
    • In a random walk, you always take one step at a time
    • You don't take different size random jumps to an entirely new random location
    • In a random walk, if we leave a trail, there will not be any gaps
  • 4 Practice Quiz Questions
    • Fill in the blanks so that the x coordinate is changed in a random walk pattern by -1,0, or 1
    • x = _____ + int(random(__,__));
    • True / False (3!=4) && (2<=2)
    • Three &quot;system variables&quot; that are used for user input are ________, ________ and _______ .
    • Mark is writing a game where one coin is tossed. Every time the mouse is pressed, he will draw a single circle at a new random location, so the coin x and y coordinates will change, along with whether the coin shows heads or tails. How many variables will his program need?
  • 3D Graphics
    • One of Processing's strengths is 3D graphics
    • void setup()
    • {
    • size(300,300,P3D);
    • }
    • void draw()
    • {
    • translate(150,150,0);
    • rotateX(-.5);
    • rotateY(.5);
    • box(100);
    • }
  • 3D Graphics
    • Positions in 3D space use three coordinates x, y and z
    • Objects are drawn at (0,0,0) unless you translate them to a new position
    box(50); -x -z -y +x +z +y
  • 3D Graphics
    • box() 's one argument specifies the side length
    box(170);
  • 3D Graphics
    • box() 's three arguments specify the x, y and z dimensions
    box(50,100,150);
  • 3D Graphics
    • translate() moves the center of the box
    • In this case, we've moved the box -100 (up) in the y direction
    translate(0,-100,0); box(50);
  • 3D Graphics
    • translate() moves the center of the box
    • In this case, we've moved the box -100 (away from us) in the z direction
    translate(0,0,-100); box(50);
  • 3D Graphics
    • translate() moves the center of the box
    • In this case, we've moved the box -100 (to the left) in the x direction
    translate(-100,0,0); box(50);
  • 3D Graphics
    • sphere() works the same as box except the argument is the radius
    translate(-100,0,0); sphere(50);
  • 3D Graphics
    • rotateX() rotates the box around the x axis
    rotateX(-.5); box(50); -.5
  • 3D Graphics
    • For comparison, here it is unrotated
    box(50);
  • 3D Graphics
    • rotateX() rotates the box around the x axis
    rotateX(.5); box(50); .5
  • 3D Graphics
    • rotateY() rotates the box around the y axis
    rotateY(-.3); box(50); -.3
  • 3D Graphics
    • For comparison, here it is unrotated
    box(50);
  • 3D Graphics
    • rotateY() rotates the box around the y axis
    rotateY(.3); box(50); .3
  • 3D Graphics
    • rotateZ() rotates the box around the z axis
    rotateZ(-.4); box(50); -.4
  • 3D Graphics
    • For comparison, here it is unrotated
    box(50);
  • 3D Graphics
    • rotateZ() rotates the box around the z axis
    rotateZ(.4); box(50); .4
  • Lighting can add realism
    • background(0);
    • translate(150,150,-250);
    • fill(255);
    • rotateX(-.5);
    • rotateY(.5);
    • box(150);
  • lights();
    • background(0);
    • translate(150,150,-250);
    • fill(255);
    • rotateX(-.5);
    • rotateY(.5);
    • lights();
    • box(150);
  • pointLight(255,0,255,-235,-240, 275);
    • background(0);
    • translate(150,150,-250);
    • fill(255);
    • rotateX(-.5);
    • rotateY(.5);
    • pointLight(…);
    • box(150);
  • pointLight ( 255,0,255 , -235,-240, 275 );
    • The first three arguments ( in red ) are the RGB values of the light (in this case Magenta)
    • The last three arguments ( in yellow ) are the (x,y,z) position of the light
  • Perspective
    • void setup()
    • {
    • size(200,200,P3D);
    • background(0);
    • }
    • void draw()
    • {
    • box(100);
    • }
    • If we don't rotate or translate the box, we get a pretty boring view of it
  • Perspective
    • An alternative is to change our perspective
    • That is leave the cube as it is, but change the position of our &quot;eye&quot;
    • This is done with the camera function
  • Perspective
    • void setup()
    • {
    • size(200,200,P3D);
    • background(0);
    • }
    • void draw()
    • {
    • camera(100,100,200,0,0,0,0,1,0);
    • box(100);
    • }
  • camera( 100,100,200 , 0,0,0 ,0,1,0);
    • Camera takes 9 arguments
    • The first three are the ( x,y,z ) position of our &quot;eye&quot;
    • The next three are the ( x,y,z ) position of where our eye is looking
    • I always leave the last three as the default values 0,1,0 (y axis is up)
  • Loops
    • Looping means repeating over and over
    • If you wanted to print 10 x s to the screen, you could copy and paste code like this:
    • print(&quot;x&quot;);
    • print(&quot;x&quot;);
    • print(&quot;x&quot;);
    • print(&quot;x&quot;);
    • print(&quot;x&quot;);
    • print(&quot;x&quot;);
    • print(&quot;x&quot;);
    • print(&quot;x&quot;);
    • print(&quot;x&quot;);
    • print(&quot;x&quot;);
  • Loops
    • On the other hand, if you wanted to print 100 or 1000 or even more x s to the screen, using copy and paste would be tedious
  • while Loops
    • The simplest loop in java is the while loop
    • It uses a variable to keep track of how many repititions to make
    • The variable has a starting point , an ending point , and some way of progressing from start to end
  • Review: if statements
    • What is the output?
    • int num = 1;
    • if (num < 10)
    • {
    • println(num);
    • num = num + 1;
    • }
    • println(num);
  • Review: if statements
    • What is the output?
    • int num = 1;
    • if (num < 10)
    • {
    • println(num);
    • num = num + 1;
    • }
    • println(num);
  • while Loops
    • A while loop is identical to an if , just substitute while for if
    • Now what is the output?
    • int num = 1;
    • while (num < 10)
    • {
    • println(num);
    • num = num + 1;
    • }
    • println(num);
  • while Loops
    • A while loop is identical to an if , just substitute while for if
    • Now what is the output?
    • int num = 1;
    • while (num < 10)
    • {
    • println(num);
    • num = num + 1;
    • }
    • println(num);
  • while Loops
    • This while loops starting point is 0
    • It's ending point is before 100
    • It progresses by counting up by one
    • int count = 0;
    • while ( count < 100 )
    • {
    • println(&quot;count:&quot; + count);
    • count = count + 1;
    • }
    • println(&quot;all done&quot;);
  • while Loops
    • With a loop, it's just as easy to print 1000 x s as it is to print 10!
    • int numXs = 0;
    • while (numXs < 1000)
    • {
    • print(&quot;x&quot;);
    • numXs = numXs + 1;
    • }
  • while vs if
    • An if-statement looks at the test in the parenthesis one time and then maybe executes the body once .
    • The while-loop keeps executing the body again and again , as long as the test in the parenthesis (what I call the stopping point) is true
  • Practice Quiz Question
    • Find the output
    • int x = 3;
    • while(x < 10)
    • {
    • println(x);
    • x = x + 3;
    • }
    • println(&quot;loop stops, now x is&quot;);
    • println(x);
  • increment and decrement operators
    • The increment operator is ++
    • num++;
    • is the same as
    • num = num + 1;
    • The decrement operator is --
    • num--;
    • is the same as
    • num = num - 1;
  • while loop examples
    • Here's a while loop example that uses a loop to see how man times you can divide a number by 2
    • int num = 16;
    • int count = 0; // count how many
    • //divisions we've done
    • while (num >= 1)
    • {
    • num = num / 2;
    • count++;
    • }
    • println(count);
  • A program that uses a loop to make a gradient in the background
    • int redAmount = 0;
    • int blueAmount = 255;
    • int x = 0;
    • void setup()
    • {
    • size(256,256);
    • while(x < 256)
    • {
    • stroke(redAmount,0,blueAmount);
    • line(x,0,x,255);
    • x = x + 1;
    • redAmount = redAmount + 1;
    • blueAmount = blueAmount - 1;
    • }
    • }
    • void draw()
    • {
    • fill(0);
    • stroke(0);
    • ellipse(127,127,100,100);
    • }
  • Zero Loop Iterations
    • Since the while-loop checks the test before every iteration, it is possible for the body to not run even once:
    • int count = 100;
    • while ( count < 100 )
    • {
    • count = count + 1;
    • }
  • Infinite Loop
    • The most famous sort of bug you can get with loops
    • Because of some mis-arrangement, the loop fails to get any closer to its stopping point
    • For example, suppose the body fails to make the count bigger by accident:
    • int count = 0;
    • while (count < 100)
    • {
    • println(&quot;count:&quot; + count);
    • count = count * 1;
    • // OOPS, does not change count
    • }
  • Infinite Loop
    • The computer just sort of &quot;freezes up&quot;
    • The output is the same , over and over again
    • If this happens to you:
      • Press &quot;Cntrl&quot;, &quot;Alt&quot; + &quot;Delete&quot;
      • Click Shutdown
      • Choose Restart
  • Watch out for this
    • A particularly nasty mistake is to put a semi-colon after the parenthesis of the while loop
    • int num = 1;
    • while(num<100) ;
    • {
    • println(num);
    • num++;
    • }
  • Watch out for this
    • This creates an infinite loop and processing freezes up!
    • int num = 1;
    • while(num<100) ;
    • {
    • println(num);
    • num++;
    • }
    • &quot;while num is less that 100&quot; is not a complete sentence
  • A Geeky Joke
    • This is Apple computer’s actual address
    • It’s a geeky pun on computer programming
  • Practice Quiz Question: Circle the picture that best matches the output
    • void setup()
    • {
    • size(100,100);
    • }
    • void draw()
    • {
    • int num = 5;
    • while(num > 2)
    • {
    • ellipse(num * 15,50,20,20);
    • num--;
    • }
    • }
  • Problem: Make 100 random spheres
  • Problem: Make 100 random spheres
    • First we’ll need to figure out how to make 1!
  • Problem: Make 100 random spheres
    • I’ll need to translate the sphere to a better spot
  • Problem: Make 100 random spheres
    • Now that I’ve got one, I’ll want to add randomness so I don’t have a bunch of identical spheres piled on top of each other
  • I want to repeat the code in yellow
    • void draw()
    • {
    • background (0);
    • lights();
    • int size = int(random(3,30));
    • int offsetX = int(random(0,300));
    • int offsetY = int(random(0,300));
    • translate(offsetX,offsetY,0);
    • sphere(size);
    • }
  • I want to repeat the code in yellow
    • void draw()
    • {
    • background (0);
    • lights();
    • ???
    • while( ??? )
    • {
    • int size = int(random(3,30));
    • int offsetX = int(random(0,300));
    • int offsetY = int(random(0,300));
    • translate(offsetX,offsetY,0);
    • sphere(size); ???
    • }
    • }
  • To keep the spheres from translating off the screen, I’ll need to translate back
    • void draw()
    • {
    • //some code not shown
    • while(??)
    • {
      • int size =int(random(3,30));
      • int offsetX = int(random(0,300));
      • int offsetY = int(random(0,300));
      • translate(offsetX,offsetY,0);
      • sphere(size);
    • translate(-offsetX,-offsetY,0);
    • //other code not shown
    • }
    • }
  • Displaying Text on the screen
    • To add words or other text to your program
      • Choose Tools | Create Font
      • Pick the font and size you want, click &quot;ok&quot;
      • In setup() add code like this
    • // Load the font. Fonts must be placed within the data
    • // directory of your sketch. A font must first be created
    • // using the 'Create Font...' option in the Tools menu.
    • PFont fontA =
    • loadFont(&quot;Ziggurat-HTF-Black-32.vlw&quot;);
    • // Set the font and its size (in units of pixels)
    • textFont(fontA, 32);
      • In draw() you can now call text()
    • // Display the text at the indicated position
    • text(&quot;hello&quot;, 50, 50);
  • Displaying Text on the screen
    • You can align the text, LEFT, RIGHT or CENTER
    • textAlign(CENTER);
    • The newline character will start a new line of text
    • text(&quot;You can split up
    • text on two lines&quot;,150,150);
  • Displaying Text on the screen
    • The quotes character &quot; will display quotes to the screen
    • text(&quot; &quot; In Quotes &quot; &quot;,150,150);
  • textMode(SCREEN);
    • I have no what this does, except it makes the text look better, especially in 3D
  • What is the output? How would it change if limit were doubled to 8?
    • int count = 1;
    • int limit = 4;
    • while(count <= limit)
    • {
    • print(count);
    • print(&quot;:&quot;);
    • println(limit);
    • count++;
    • }
  • String
    • A String is any number of characters including letters, digits, spaces and punctuation
    • String greeting = &quot;Hello There!&quot;;
    • println(greeting);
    • //is the same as
    • println(&quot;Hello There!&quot;);
    • A String can be thought of as a “mailbox” to hold text
  • String variables
    • You would create a String variable when you need to store text that can change
    • String words = &quot;Testing, 1,2,3&quot;;
    • println(words);
    • words = &quot;Is this mic on?&quot;;
    • println(words);
  • Adding String s
    • The + operator combines String s together to make one bigger String
    • String s1 = &quot;abc&quot;;
    • String s2 = &quot;xyz&quot;;
    • String s3 = s1 + s2;
    • println(s3);
  • Adding String s
    • The + operator combines String s together to make one bigger String
    • String s1 = &quot;abc&quot;;
    • String s2 = &quot;xyz&quot;;
    • String s3 = s1 + s2;
    • println(s3);
    • //Displays abcxyz
  • Adding String s
    • The + operator combines String s together to make one bigger String
    • String s1 = &quot;abc&quot;;
    • String s2 = &quot;xyz&quot;;
    • String s3 = s1 + s2;
    • println(s3);
    • s3 = s2 + s1;
    • println(s3);
  • Adding String s
    • The + operator combines String s together to make one bigger String
    • String s1 = &quot;abc&quot;;
    • String s2 = &quot;xyz&quot;;
    • String s3 = s1 + s2;
    • println(s3);
    • s3 = s2 + s1;
    • println(s3);
    • //Displays xyzabc
  • Adding String s
    • The + operator is also useful for labeling output
    • Let’s say I’m debugging, and I want to know what is in the dogs variable
    • int dogs = 3;
  • Adding String s
    • I could use the + operator to label the output so I know what I’m looking at
    • int dogs = 3;
    • println(&quot;There are &quot;+ dogs +&quot; dogs.&quot;);
  • Adding String s
    • The + operator is also useful for labeling output
    • int dogs = 3;
    • println(&quot; There are &quot;+ dogs +&quot; dogs. &quot;);
    • //Displays There are 3 dogs
    • The + operator creates one big String of all the
    • things that are added together
  • for loops
    • Do exactly the same thing as while loops
  • A while loop
    • int count = 1;
    • while(count < 4)
    • {
    • println(&quot;count is &quot; + count);
    • count++;
    • }
  • A while loop
    • int count = 1;
    • while(count < 4)
    • {
    • println(&quot;count is &quot; + count);
    • count++;
    • }
    • /* Output is
    • count is 1
    • count is 2
    • count is 3 */
  • A while and a for loop that do the exactly the same thing
    • int count = 1;
    • while(count < 4)
    • {
    • println(&quot;count is &quot; + count);
    • count++;
    • }
    • Is the same as
    • for(int count = 1;count < 4;count++)
    • {
    • println(&quot;count is &quot; + count);
    • }
  • Notice both have the same 3 parts
    • int count = 1 ;
    • while( count < 4 )
    • {
    • println(&quot;count is &quot; + count);
    • count++ ;
    • }
    • Is the same as
    • for( int count = 1 ; count < 4 ; count++ )
    • {
    • println(&quot;count is &quot; + count);
    • }
  • Why both?
    • Some programmers prefer the for loop since it uses fewer lines of code
    • Most beginning programmers find the while loop easier to understand
    • Good Style : Use for loops only when you know in advance how many times you want the loop to run. In all other circumstances use a while loop.
  • Practice Quiz Question
    • Write a program that uses two for loops to produce the following output
    • x x x x x x
    • 10 9 8 7 6 5 4 3 2 1
  • Arrays
    • An array is a collection of data, all of the same data type, that is accessed with an index
    • If a variable is like a mailbox, an array is like the mailboxes at a post office or an apartment building: a row of otherwise identical boxes with different numbers.
    • [] (square brackets) are used to indicate an array
  • Arrays
    • int [] nums = {5,-4,17};
    nums [0] [1] [2] 5 -4 17
  • Arrays
    • May be declared and initialized in one line. [] can go either before or after the name of the array
    • int nums[] = {5,-4,17};
    • //or
    • int[] nums = {5,-4,17};
    • Are &quot;zero-based&quot;: First index is 0
    • println(nums[1]); //displays -4
    • You can make an array of any data type
    • char letters[] = {'a', 'b', 'c'};
    • String answers[] = {“yes”, “no”};
  • Arrays
    • Just like any variable, you can change the value that is stored there
    • char letters[] = { 'a' , 'b', 'c'};
    • println(letters[0]);
    • letters[0]='z';
    • println(letters[0]);
  • A Simple Program using an array
    • float nums[] = {5, 1.5, 7, 3.2};
    • int i = 3;
    • while(i >= 0)
    • {
    • println(nums[i]);
    • i--;
    • }
  • A Simple Program using an array
    • float nums[] = {5, 1.5, 7, 3.2};
    • int i = 3;
    • while(i >= 0)
    • {
    • println(nums[i]);
    • i--;
    • }
  • Don't confuse the index with the value that is stored there
    • float nums[] = {5, 1.5, 7, 3.2};
    • nums[2]
    • 2 is the index (think apartment number)
    • 7 is the value that is stored at index 2
  • Practice Quiz Question: What is the output of this program?
    • String words[] = {
    • &quot;The&quot;, &quot;Quick&quot;, &quot;Brown&quot;,&quot;Fox&quot;,
    • &quot;Jumped&quot;, &quot;Over&quot;, &quot;The&quot;, &quot;Lazy&quot;, &quot;Red&quot;, &quot;Dog&quot;};
    • words[2] = &quot;Blue&quot;;
    • for(int i = 0;i < 10;i=i+2)
    • {
    • println(words[i]);
    • }
  • Practice Quiz Question: What is the output of this program?
    • String words[] = {
    • &quot;The&quot;, &quot;Quick&quot;, &quot;Brown&quot;,&quot;Fox&quot;,
    • &quot;Jumped&quot;, &quot;Over&quot;, &quot;The&quot;, &quot;Lazy&quot;, &quot;Red&quot;, &quot;Dog&quot;};
    • words[2] = &quot;Blue&quot;;
    • for( int i = 0 ; i < 10 ; i=i+2 )
    • {
    • println(words[i]);
    • }
  • Practice Quiz Question: What is the output of this program?
    • String words[] = {
    • &quot;The&quot;, &quot;Quick&quot;, &quot;Brown&quot;,&quot;Fox&quot;,
    • &quot;Jumped&quot;, &quot;Over&quot;, &quot;The&quot;, &quot;Lazy&quot;, &quot;Red&quot;, &quot;Dog&quot;};
    • words[2] = &quot;Blue&quot;;
    • int i = 0;
    • while( i < 10 )
    • {
    • println(words[i]);
    • i=i+2;
    • }
  • The length of an array
    • The length of an array, is the number of elements that array can hold
    • Think of it as the number of &quot;apartments&quot; in that array
    • char [] letters = {'d','o','g','s'};
    • println(letters. length );
  • The length of an array
    • The length of an array, is the number of elements that array can hold
    • Think of it as the number of &quot;apartments&quot; in that array
    • char [] letters = {'d','o','g','s'};
    • println(letters. length );
  • The length of an array
    • length is often used with loops that go through each element in an array
    • char [] letters = {'d','o','g','s'};
    • int i = 0;
    • while(i < letters. length )
    • {
    • print(letters[i]);
    • i++;
    • }
  • The length of an array
    • length is often used with loops that go through each element in an array
    • char [] letters = {'d','o','g','s'};
    • int i = 0;
    • while(i < letters. length )
    • {
    • print(letters[i]);
    • i++;
    • }
  • the int() function
    • Java is very picky about types:
    • int num = 3.14;
    • generates an error
  • the int() function
    • We can fix the error with the int() function
    • int num = int (3.14);
    • It drops the decimals (called &quot;truncation&quot;);
  • Practice Quiz Question: What is the output?
    • float [] nums = {3.14,4.999,2.718,0.11235813};
    • println(&quot;There are &quot;+ nums.length + &quot; elements&quot;);
    • for(int i = 0; i < nums.length; i++)
    • {
    • int nNum = int(nums[i]);
    • println(nNum);
    • }
  • File Input
    • In “real life” many programs use very little graphics or none at all
    • Many programs process large amounts of data that is stored as text
    • For example, the school district has large files of names, addresses, course information and grades. It runs computer programs that use those files to print grade reports.
  • Creating a program that uses File Input in processing
    • Start a new program
    • For now, we don’t need any functions
    • The loadStrings() example from the API is a good starting point:
    • String lines[] = loadStrings(&quot;list.txt&quot;);
    • println(&quot;there are &quot; + lines.length + &quot; lines&quot;);
    • for (int i=0; i < lines.length; i++)
    • {
    • println(lines[i]);
    • }
    • Save the program
  • Then, create a text file in notepad
  • Save it to the same folder as your program Name it list (or something else)
  • Make sure the name is right
    • If the name in our code doesn’t match the name of the file, our program won’t run.
    • Otherwise, we can then load it into an Array of String s with code like:
    • String lines[] = loadStrings(&quot; list.txt &quot;);
  • list.length
    • The length of the array will be the number of lines there are in the text file
    • println(
    • &quot;there are &quot; + list.length + &quot; lines&quot;);
  • list.length
    • In this case there are 6
    • println(
    • &quot;there are &quot; + list.length + &quot; lines&quot;);
  • loadStrings() from the API
    • This loop will display each line of input on a line by itself
    • for (int i=0; i < list.length; i++)
    • {
    • println(list[i]);
    • }
  • Now that we know the program is working, we can begin to modify it
    • Our assignment is to write a program that converts Fahrenheit temperatures to Celsius temperatures
    • We’ll have a text file with three integers:
    • 212
    • 32
    • -40
  • Converting a String to an int
    • loadStrings() always returns an array of String s
    • This is a little awkward if you want to work with int egers or decimals
    int fahrenheit = lines[i]; //error!
  • the int() function
    • The problem is that the types don’t match
    • String lines[] = loadStrings(&quot;list.txt&quot;);
    • //lots of java not shown
    • int fahrenheit = lines[i];
  • the int() function
    • the int() function fixes the problem
    • String lines[] = loadStrings(&quot;list.txt&quot;);
    • //lots of java not shown
    • int fahrenheit = int( lines[i] ) ;
    • It converts a String to an int , for example &quot;6&quot; with 6
  • Practice quiz question: If we use the following data file, what will be the output?
    • String lines[] = loadStrings(&quot;list.txt&quot;);
    • println (&quot;there are &quot; + lines.length + &quot; lines&quot;);
    • for (int i= 1 ; i < lines.length; i=i+3 )
    • {
    • println (lines[i]);
    • }
  • tron
  • get()
    • Returns the color of one pixel
    • if(get(x,y) != color(0,0,0))
    • {
    • //lots of java
    • }
  • How we could check for a crash with get()
    • int x = 10;
    • int y = 150;
    • void setup()
    • {
    • size(300,300);
    • background(0);
    • fill(255);
    • ellipse(270,150,20,20);
    • }
    • void draw()
    • {
    • if(get(x,y) != color(0,0,0)) //we crashed!
    • {
    • fill(255,0,0);
    • ellipse(150,150,250,250);
    • }
    • else
    • {
    • stroke(255,0,255);
    • point(x,y);
    • x++;
    • }
    • }
  • How we could check for a crash with get()
    • int x = 10;
    • int y = 150;
    • void setup()
    • {
    • size(300,300);
    • background(0);
    • fill(255);
    • ellipse(270,150,20,20);
    • }
    • void draw()
    • {
    • if(get(x,y) != color(0,0,0)) //we crashed!
    • {
    • fill(255,0,0);
    • ellipse(150,150,250,250);
    • }
    • else
    • {
    • stroke(255,0,255);
    • point(x,y);
    • x++;
    • }
    • }
  • Writing tron
    • Don't try to write the program all at once
    • Get one detail working and then move on to the next thing
    • Let's start by making the light trail
  • Writing tron
    • The next thing would be to make the direction change based on what's in key
  • Writing tron
    • Now, we'd probably want to use get() to see if we ran into our own light trail
  • Oops, the game is over as soon as it started!
    • The problem is that we aren't moving
    • If we stay in the same place we'll put a dot on a dot
  • Keep moving
    • In setup() we can set key to get the dot moving
    • In my program I used: key = 'd'
    • Stopping is sort of the opposite
    • If I've run into a light trail I'll set key to some unused value like: key = 'x'
  • Adding a computer opponent
    • Before I add the computer, let's clean up the code
    • draw() is getting ugly
    • let's move the human code into its own function
  • Adding a computer opponent
    • There, that's better
    • Now we can use the human() function as a guide
    • computer() will be similar
  • Adding a computer opponent
    • The computer opponent will need it's own set of variables to keep track of its location and direction
  • Adding a computer opponent
    • We will write a function that is very similar to human() called computer()
    • In computer() , will use compX , compY , etc., instead of x & y
  • Adding a computer opponent
    • The problem now is that our computer won't turn
    • We need to add code to make it &quot;smart&quot;
    • Sometimes, this is called &quot;AI&quot; for artificial intelligence
  • Adding a computer opponent
    • In each of the four if statements of the computer, we will look ahead 1 place to see if we are going to run into something
    • If we are, we'll turn by changing the value of compDirection
  • Practice Quiz Questions
    • 1. How many variables would be needed for a tron player that can change position and direction?
    • 2. Write an if statement that checks to see if the position above a tron player (toward the top of the screen) is blocked.
    • 3. The following program was intended to display 3 (the sum of the first two values in the array) but instead it generates an error. Use the int() function twice to fix the problem.
    • String [] numbers = {&quot;1&quot;, &quot;2&quot;, &quot;77&quot;};
    • int numOne = numbers[0];
    • int numTwo = numbers[1];
    • println(numOne + numTwo);
    • 4. What would the following program display. (Hint: what happens when you add String s?)
    • String [] numbers = {&quot;1&quot;, &quot;2&quot;, &quot;77&quot;};
    • println(numbers[0] + numbers[1]);
  • Practice Quiz Question: Find the output
    • for(int i = 0; i <= 3; i++)
    • {
    • if(i != 0 && i <2)
    • {
    • print(&quot;A&quot;);
    • }
    • else if (i ==2 || i == 3)
    • {
    • print(&quot;B&quot;);
    • }
    • else
    • {
    • print(&quot;C&quot;);
    • }
    • }
  • Ending the game
    • Here's a problem
    • The Human crashes and the game displays &quot;Human Loses&quot;
    • But, the game keeps going, and eventually the computer crashes and the game displays &quot;Computer Loses!&quot;
  • Ending the game
    • I need to stop the game as soon as one player loses, otherwise things will get messed up
    • I'll create a boolean variable to do this
  • Ending the game
    • When a player crashes, I'll change the variable to show the game is over
  • Ending the game
    • In draw() , I'll make sure that the players only move is the game isn't over
  • Making the line thicker
    • We can make a bigger dot by making a rect angle instead of a point
    • Since rect s have a stroke and fill color, we should set both to the same color
  • Making the line thicker
    • Now there is some funny behavior
    • Up and left are fine, but we crash as soon as we turn down or right!
  • Making the line thicker
    • Look carefully at rect(x,y,5,5);
    • x and y are the coordinates of the top left corner
    • 5 is the length of each side
    (x,y)
  • Making the line thicker
    • If I take one step to the left ( x-- ), there's no problem
    • (x,y) lands on a black part of the screen
    • But, if I move to the right. . .
    (x,y)
  • Making the line thicker
    • After I take one step to the right ( x++ )
    • (x,y) lands on part of the previous rectangle
    • It's not black, so I crash and die : (
    (x,y)
  • Making the line thicker
    • Instead of moving by a distance of 1, I need to move by a distance of one more than the side length
    • That way I don't land on a part of the previous rectangle
    (x,y)
  • Making the line thicker
    • This is a great place for a variable
    • We can call it dotSize (for example)
    • Just make sure that the distance we move is ONE MORE THAN the side length
    • When we &quot;look ahead&quot; we also need to use ONE MORE THAN the side length
  • modulus
    • Let's say thumb drives cost $7 each
    • If you have $25, how many thumb drives can you buy?
    • How much money will be left over?
  • modulus
    • Let's say thumb drives cost $7 each
    • If you have $25, how many thumb drives can you buy?
    • 25 / 7 is 3
    • How much money will be left over?
    • 25 % 7 is 4
    • Modulus finds the remainder (&quot;left over&quot;) from integer division
  • modulus 25 7
  • modulus 25 7 3
  • modulus 25 7 3 21
  • modulus 25 7 3 21 4
  • modulus 25 7 3 21 4 25 / 7 25 % 7
  • writing functions with arguments
    • Up to now, all the functions we have written have had empty parenthesis and looked like
    • void function()
    • Since the parenthesis are empty, the functions do not take any arguments
    • We have used functions with arguments:
    • point(x,y);
    • line(30,50,30,250);
    • ellipse(50,10,100,80);
    • stroke(255,0,0);
  • Pass by Value arguments
    • To write a function with arguments, you add variable declarations inside the parenthesis of the function header
    • void setup()
    • {
    • area(50,100);
    • }
    • void draw(){}//empty!
    • void area ( int someWidth, int someLength )
    • {
    • println(&quot;The area is &quot;+(someWidth*someLength));
    • }
  • Pass by Value arguments
    • Notice that the data types only go in the header , NOT in the function call
    • void setup()
    • {
    • area(50,100);
    • }
    • void draw(){}//empty!
    • void area ( int someWidth, int someLength)
    • {
    • println(&quot;The area is &quot;+(someWidth*someLength));
    • }
  • Pass by Value arguments
    • When the function is call ed the arguments are copied into someWidth and someLength
    • void setup()
    • {
    • area(50,100);
    • }
    • void draw(){}//empty!
    • void area (int someWidth , int someLength )
    • {
    • println(&quot;The area is &quot;+(someWidth*someLength));
    • }
    50 100 50 100 someWidth someLength
  • Pass by Value arguments
    • void setup()
    • {
    • area(50,100);
    • }
    • void draw(){}//empty!
    • void area (int someWidth, int someLength)
    • {
    • println(&quot;The area is &quot;+(someWidth*someLength));
    • }
  • Practice Quiz Question: What is the output of this program?
    • void setup()
    • {
    • mystery1(4, 1);
    • int num = 5;
    • mystery1(4,num);
    • mystery2(5,2);
    • }
    • void draw(){}//empty!
    • void mystery1 (int a, int b)
    • {
    • println((a - 2) * (b + 3));
    • }
    • void mystery2 (float c, int d)
    • {
    • println(c / d);
    • }
  • void
    • Means &quot;nothing&quot;
    • Every function we’ve written up to now has used void and looked like:
    • void function (int num, float fNum);
    • You can replace that “nothing” with “something”
    • int function (int num, float fNum);
    • This means the function return s an integer
  • Functions that return values
    • void setup()
    • {
    • println(&quot;The answer is &quot; +
    • someFunction(4.5));
    • }
    • void draw(){}//empty!
    • float someFunction (float fNum)
    • {
    • return fNum/2;
    • }
  • Functions that return values
    • void setup()
    • {
    • println(&quot;The answer is &quot; +
    • someFunction(4.5));
    • }
    • void draw(){}//empty!
    • float someFunction (float fNum)
    • {
    • return fNum/2;
    • }
    fNum 4.5 4.5
  • Functions that return values
    • void setup()
    • {
    • println(&quot;The answer is &quot; +
    • someFunction(4.5));
    • }
    • void draw(){}//empty!
    • float someFunction (float fNum)
    • {
    • return fNum/2;
    • }
    fNum 4.5 2.25
  • Functions that return values
    • void setup()
    • {
    • println(&quot;The answer is &quot; +
    • someFunction(4.5));
    • }
    • void draw(){}//empty!
    • float someFunction (float fNum)
    • {
    • return fNum/2;
    • }
    fNum 4.5 2.25 2.25
  • return
    • Sends data back to the function call
    • println(&quot;The answer is &quot; +
    • someFunction(4.5));
    • becomes
    • println(&quot;The answer is &quot; + 2.25);
  • Practice Quiz Question: what is the output of this program?
    • void setup()
    • {
    • int num = mystery1(4,2);
    • float fract = mystery2(5,2);
    • println(num*fract);
    • }
    • void draw(){}//empty!
    • int mystery1 (int nA, int nB)
    • {
    • return nA + nB;
    • }
    • float mystery2(int nA, int nB)
    • {
    • return float(nA)/nB;
    • }
  • A program using a boolean and the mouse to switch &quot;modes&quot;
    • boolean mode = false;
    • void setup(){}//empty
    • void draw()
    • {
    • background(0);
    • if(mode == true)
    • {
    • ellipse(50,50,50,50);
    • }
    • else
    • {
    • rect(25,25,50,50);
    • }
    • }
    • void mouseClicked()
    • {
    • mode = !mode;
    • }
  • Now let's modify the program so that the ellipse has a random position
    • boolean mode = false;
    • void setup(){}//empty
    • void draw()
    • {
    • background(0);
    • if(mode == true)
    • {
    • ellipse(int(random(100)),int(random(100)),50,50); }
    • else
    • {
    • rect(25,25,50,50);
    • }
    • }
    • void mouseClicked()
    • {
    • mode = !mode;
    • }
  • noLoop() and redraw()
    • Normally, the screen is refreshed at 60hz (60 times a second)
    • Every time the screen all the code in draw() executes
    • If you call noLoop() in setup() , though, draw() only executes once
    • If you want to draw the screen again, call redraw()
  • The fixed version with noLoop() and redraw()
    • boolean mode = false;
    • void setup()
    • {
    • noLoop();
    • }
    • void draw()
    • {
    • background(0);
    • if(mode == true)
    • {
    • ellipse(int(random(100)),int(random(100)),50,50);
    • }
    • else
    • {
    • rect(25,25,50,50);
    • }
    • }
    • void mouseClicked()
    • {
    • mode = !mode;
    • redraw();
    • }
  • charAt()
    • Lets you get at the individual char acters of a String
    • What would the following code display?
    • String x = &quot;mystery&quot;;
    • println(x.charAt(2));
  • the length() of a String
    • A String can be thought of like an Array
    • The length of the String is the number of characters in the String
    • What would be displayed by this program?
    • String one = &quot;dog&quot;;
    • String two = &quot;elephant&quot;;
    • String three = &quot;&quot;;
    • println(one.length());
    • println(two.length());
    • println(three.length());
  • the length() of a String
    • String one = &quot;dog&quot;;
    • String two = &quot;elephant&quot;;
    • String three = &quot;&quot;;
    • println(one.length());
    • println(two.length());
    • println(three.length());
  • boolean functions
    • A boolean function returns true or false
    • Let's say you work at the admissions office for UC Santa Cruz where the average freshman admission has a GPA of 3.7 and an SAT of 1750*
    • Your asked to write a function that will return true if a freshman has scores that are both better than average or false if they don't
    http:// www.universityofcalifornia.edu/admissions/undergrad_adm/selecting/camp_profiles/camp_profiles_ucsc.html
  • boolean functions
    • void setup()
    • {
    • println( getsIn( 4.0, 1700 ) );
    • println( getsIn( 3.0, 1400 ) );
    • println( getsIn( 3.5, 2100 ) );
    • println( getsIn( 3.8, 1800 ) );
    • }
    • boolean getsIn( float gpa , int sat )
    • {
    • ???
    • }
  • boolean functions
    • void setup()
    • {
    • println( getsIn( 4.0, 1700 ) );
    • println( getsIn( 3.0, 1400 ) );
    • println( getsIn( 3.5, 2100 ) );
    • println( getsIn( 3.8, 1800 ) );
    • }
    • boolean getsIn( float gpa , int sat )
    • {
    • ???
    • }
  • boolean functions
    • void setup()
    • {
    • println( getsIn( 4.0, 1700 ) );
    • println( getsIn( 3.0, 1400 ) );
    • println( getsIn( 3.5, 2100 ) );
    • println( getsIn( 3.8, 1800 ) );
    • }
    • boolean getsIn( float gpa , int sat )
    • {
    • if(gpa > 3.7 && sat > 1750)
    • ???
    • }
  • boolean functions
    • void setup()
    • {
    • println( getsIn( 4.0, 1700 ) );
    • println( getsIn( 3.0, 1400 ) );
    • println( getsIn( 3.5, 2100 ) );
    • println( getsIn( 3.8, 1800 ) );
    • }
    • boolean getsIn( float gpa , int sat )
    • {
    • if(gpa > 3.7 && sat > 1750)
    • {
    • return true;
    • }
    • else
    • ???
    • }
  • boolean functions
    • void setup()
    • {
    • println( getsIn( 4.0, 1700 ) );
    • println( getsIn( 3.0, 1400 ) );
    • println( getsIn( 3.5, 2100 ) );
    • println( getsIn( 3.8, 1800 ) );
    • }
    • boolean getsIn( float gpa , int sat )
    • {
    • if(gpa > 3.7 && sat > 1750)
    • {
    • return true;
    • }
    • else
    • {
    • return false;
    • }
    • }
  • Find the output
    • void setup()
    • {
    • if(isMatch(&quot;elephant&quot;)==true)
    • {
    • println(&quot;Match 1&quot;);
    • }
    • if(isMatch(&quot;alligator&quot;)==true)
    • {
    • println(&quot;Match 2&quot;);
    • }
    • if(isMatch(&quot;ox&quot;)==true)
    • {
    • println(&quot;Match 3&quot;);
    • }
    • if(isMatch(&quot;pup fish&quot;)==true)
    • {
    • println(&quot;Match 4&quot;);
    • }
    • }
    • boolean isMatch(String sWord)
    • {
    • if(sWord.length()>=3)
    • {
    • return sWord.charAt(0) == sWord.charAt(2);
    • }
    • else
    • {
    • return false;
    • }
    • }
  • What is the output of this program?
    • void setup()
    • {
    • if(mystery(&quot;antelope&quot;, 'e')==true)
    • {
    • println(&quot;One&quot;);
    • }
    • else
    • {
    • println(&quot;Two&quot;);
    • }
    • if(mystery(&quot;aardvark&quot;, 'a')==true)
    • {
    • println(&quot;Three&quot;);
    • }
    • else
    • {
    • println(&quot;Four&quot;);
    • }
    • }
    • boolean mystery(String word, char letter)
    • {
    • int sum = 0;
    • for(int i = 0; i < word.length(); i++)
    • {
    • if(word.charAt(i) == letter)
    • {
    • sum++;
    • }
    • }
    • return sum > 2;
    • }
  • The Palindrome function: a starting point
    • void setup()
    • {
    • String lines[] = loadStrings(&quot;palindrome.txt&quot;);
    • println(&quot;there are &quot; + lines.length + &quot; lines&quot;);
    • for (int i=0; i < lines.length; i++)
    • {
    • if( palindrome(lines[i]) ==true)
    • {
    • println(lines[i] + &quot; IS a palidrome.&quot;);
    • }
    • else
    • {
    • println(lines[i] + &quot; is NOT a palidrome.&quot;);
    • }
    • }
    • }
    • boolean palindrome(String word)
    • {
    • return true ;
    • }
  • The Palindrome function
    • void setup()
    • {
    • String lines[] = loadStrings(&quot;palindrome.txt&quot;);
    • println(&quot;there are &quot; + lines.length + &quot; lines&quot;);
    • for (int i=0; i < lines.length; i++)
    • {
    • if(palindrome(lines[i])==true)
    • {
    • println(lines[i] + &quot; IS a palidrome.&quot;);
    • }
    • else
    • {
    • println(lines[i] + &quot; is NOT a palidrome.&quot;);
    • }
    • }
    • }
    • boolean palindrome(String word)
    • {
    • return true;
    • }
  • The Palindrome function
    • void setup()
    • {
    • String lines[] = loadStrings(&quot;palindrome.txt&quot;);
    • println(&quot;there are &quot; + lines.length + &quot; lines&quot;);
    • for (int i=0; i < lines.length; i++)
    • {
    • if(palindrome(lines[i])==true)
    • {
    • println(lines[i] + &quot; IS a palidrome.&quot;);
    • }
    • else
    • {
    • println(lines[i] + &quot; is NOT a palidrome.&quot;);
    • }
    • }
    • }
    • boolean palindrome(String text)
    • {
    • return false;
    • }
  • The Palindrome function
    • void setup()
    • {
    • String lines[] = loadStrings(&quot;palindrome.txt&quot;);
    • println(&quot;there are &quot; + lines.length + &quot; lines&quot;);
    • for (int i=0; i < lines.length; i++)
    • {
    • if(palindrome(lines[i])==true)
    • {
    • println(lines[i] + &quot; IS a palidrome.&quot;);
    • }
    • else
    • {
    • println(lines[i] + &quot; is NOT a palidrome.&quot;);
    • }
    • }
    • }
    • boolean palindrome(String text)
    • {
    • return false;
    • }
  • The Palindrome Algorithm
    • An Algorithm is the steps you take to solve a problem
    • What steps would you take to see if the following word is a palindrome?
    • rewriter
  • The Palindrome Algorithm
    • rewriter
  • The Palindrome Algorithm
    • rewriter
  • The Palindrome Algorithm
    • rewriter
  • The Palindrome Algorithm
    • Start by comparing the first and last letters
    • If they are the same, does that mean the word is a palindrome?
    • If they are different, does that mean the word is NOT a palindrome?
    • rewriter
    • 01234567
  • The Palindrome Algorithm
    • Start by comparing the first and last letters
    • If they are the same, does that mean the word is a palindrome?
    • If they are different, does that mean the word is NOT a palindrome?
    • rewriter
    • 01234567
    • int first = 0;
    • int last = word.length() – 1;
    • if(word.charAt(first)!=
    • word.charAt(last))
    • ????
  • The Palindrome Algorithm
    • Start by comparing the first and last letters
    • If they are the same, does that mean the word is a palindrome?
    • If they are different, does that mean the word is NOT a palindrome?
    • rewriter
    • 01234567
    • int first = 0;
    • int last = word.length() – 1;
    • if(word.charAt(first)!=
    • word.charAt(last))
    • {
    • return false;
    • }
  • The Palindrome Algorithm
    • rewriter
    • 01234567
    • int first = 0;
    • int last = word.length() – 1;
    • if(word.charAt(first)!=
    • word.charAt(last))
    • {
    • return false;
    • }
    • else
    • ???
  • The Palindrome Algorithm
    • rewriter
    • 01234567
    • int first = 0;
    • int last = word.length() – 1;
    • while(???)
    • {
    • if(word.charAt(first)!=
    • word.charAt(last))
    • ???;
    • else
    • ???
    • }
    • ???
  • Some loops never run!
    • What will be displayed by the following program?
    • int num = 100;
    • while(num < 10)
    • {
    • println(num);
    • num++;
    • }
  • Some loops never run!
    • What will be displayed by the following program? NOTHING! but with a small change. . .
    • int num = 100;
    • while(num < 10)
    • {
    • println(num);
    • num++;
    • }
  • Some loops never run!
    • What will be displayed by the following program?
    • int num = 100;
    • do
    • {
    • println(num);
    • num++;
    • }while(num < 10);
    • Now it displays 100!
  • do-while loops
    • Because the code for the control expression is at the bottom, a do-while loop always runs at lease once
    • int num = 100;
    • do
    • {
    • println(num);
    • num++;
    • }while( num < 10 );
  • while vs. do-while
    • A while may never run
    • A do-while will always run at least once, even if the control expression is false
    • Otherwise, they do the same thing
  • toUpperCase() & toLowerCase()
    • return s a new String that is all upper or lower case
    • does NOT change the original String
  • A function that &quot;removes&quot; 'a' s
    • removeAs(&quot;apple&quot;) -> &quot;pple&quot;
    • removeAs(&quot;banana&quot;) -> &quot;bnn&quot;
    • removeAs(&quot;aaaaaaa&quot;) -> &quot;&quot;
    • removeAs(&quot;bcdef&quot;) -> &quot;bcdef&quot;
    • String removeAs(String str)
    • {
    • ???
    • }
  • A function that &quot;removes&quot; 'a' s
    • String removeAs(String str)
    • {
    • String noAs = &quot;&quot;;
    • ???
    • return noAs;
    • }
  • A function that &quot;removes&quot; 'a' s
    • String removeAs(String str)
    • {
    • String noAs = &quot;&quot;;
    • for(int i = 0; i < str.length(); i++)
    • {
    • ???
    • }
    • return noAs;
    • }
  • A function that &quot;removes&quot; 'a' s
    • String removeAs(String str)
    • {
    • String noAs = &quot;&quot;;
    • for(int i = 0; i < str.length(); i++)
    • {
    • if(str.charAt(i)=='a')
    • {
    • ???
    • }
    • }
    • return noAs;
    • }
  • A function that &quot;removes&quot; 'a' s
    • String removeAs(String str)
    • {
    • String noAs = &quot;&quot;;
    • for(int i = 0; i < str.length(); i++)
    • {
    • if(str.charAt(i) != 'a')
    • {
    • ???
    • }
    • }
    • return noAs;
    • }
  • A function that &quot;removes&quot; 'a' s
    • String removeAs(String str)
    • {
    • String noAs = &quot;&quot;;
    • for(int i = 0; i < str.length(); i++)
    • {
    • if(str.charAt(i) != 'a')
    • {
    • noAs = ???
    • }
    • }
    • return noAs;
    • }
  • A function that &quot;removes&quot; 'a' s
    • String removeAs(String str)
    • {
    • String noAs = &quot;&quot;;
    • for(int i = 0; i < str.length(); i++)
    • {
    • if(str.charAt(i)!='a')
    • {
    • noAs = noAs + str.charAt(i);
    • }
    • }
    • return noAs;
    • }
  • What the whole program would look like
    • void setup()
    • {
    • println(removeAs(&quot;apple&quot;) );
    • println(removeAs(&quot;banana&quot;) );
    • println(removeAs(&quot;aaaaaaa&quot;) );
    • println(removeAs(&quot;bcdef&quot;) );
    • }
    • String removeAs(String str)
    • {
    • String noAs = &quot;&quot;;
    • for(int i = 0; i < str.length(); i++)
    • {
    • if(str.charAt(i)!='a')
    • {
    • noAs = noAs + str.charAt(i);
    • }
    • }
    • return noAs;
    • }
  • find the output
    • void setup()
    • {
    • println(mystery(&quot;yellow&quot;));
    • String test = &quot;willy nilly&quot;;
    • println(mystery(test));
    • println(mystery(test.toUpperCase()));
    • println(test);
    • }
    • String mystery(String str)
    • {
    • String s = &quot;&quot;;
    • for(int i = 0; i < str.length(); i=i+2)
    • {
    • if(str.charAt(i) != 'y')
    • {
    • s = s + str.charAt(i);
    • }
    • }
    • return s;
    • }
  • javabat.com
    • Online java practice problems
    • Example: Given a String name, e.g. &quot;Bob&quot;, return a greeting of the form &quot;Hello Bob!&quot;.
      • helloName(&quot;Bob&quot;) -> &quot;Hello Bob!&quot;
      • helloName(&quot;Alice&quot;) -> &quot;Hello Alice!&quot;
      • helloName(&quot;X&quot;) -> &quot;Hello X!&quot;
    • public String helloName(String name){
    • }
  • javabat.com
    • Online java practice problems
    • Example: Given a String name, e.g. &quot;Bob&quot;, return a greeting of the form &quot;Hello Bob!&quot;.
      • helloName(&quot;Bob&quot;) -> &quot;Hello Bob!&quot;
      • helloName(&quot;Alice&quot;) -> &quot;Hello Alice!&quot;
      • helloName(&quot;X&quot;) -> &quot;Hello X!&quot;
    • public String helloName(String name){
    • return ?? ;
    • }
  • javabat.com
    • Online java practice problems
    • Example: Given a String name, e.g. &quot;Bob&quot;, return a greeting of the form &quot;Hello Bob!&quot;.
      • helloName(&quot;Bob&quot;) -> &quot;Hello Bob!&quot;
      • helloName(&quot;Alice&quot;) -> &quot;Hello Alice!&quot;
      • helloName(&quot;X&quot;) -> &quot;Hello X!&quot;
    • public String helloName(String name){
    • return ?? + name ;
    • }
  • javabat.com
    • Online java practice problems
    • Example: Given a String name, e.g. &quot;Bob&quot;, return a greeting of the form &quot;Hello Bob!&quot;.
      • helloName(&quot;Bob&quot;) -> &quot;Hello Bob!&quot;
      • helloName(&quot;Alice&quot;) -> &quot;Hello Alice!&quot;
      • helloName(&quot;X&quot;) -> &quot;Hello X!&quot;
    • public String helloName(String name){
    • return &quot;Hello &quot; + name ;
    • }
  • javabat.com
    • public String helloName(String name){
    • return &quot;Hello &quot; + name ;
    • }
    • We can check our answer by clicking on this button at the bottom:
  • javabat.com
    • public String helloName(String name){
    • return &quot;Hello &quot; + name ;
    • }
    • The red Xs aren't good
    • Our answer is missing something
  • javabat.com
    • public String helloName(String name){
    • return &quot;Hello &quot; + name + &quot;!&quot; ;
    • }
    • Now it works
  • Practice Quiz Question
    • http://javabat.com/prob?id=String1.makeAbba
    • Given two Strings, A and B, return a new String of the form ABBA. So for example, with the Strings &quot;Hi&quot; and &quot;Bye&quot;, return &quot;HiByeByeHi&quot;.
      • makeAbba(&quot;Hi&quot;, &quot;Bye&quot;) -> &quot;HiByeByeHi&quot;
      • makeAbba(&quot;Yo&quot;, &quot;Alice&quot;) -> &quot;YoAliceAliceYo&quot;
      • makeAbba(&quot;x&quot;, &quot;y&quot;) -> &quot;xyyx&quot;
    • public String makeAbba(String a,String b){
    • }
  • Practice Quiz Question
    • http://javabat.com/prob?id=String1.withoutX
    • Given a string, if the first or last chars are 'x', return the string without those 'x' chars, and otherwise return the string unchanged.
      • withoutX(&quot;xHix&quot;) -> &quot;Hi&quot;
      • withoutX(&quot;xHi&quot;) -> &quot;Hi&quot;
      • withoutX(&quot;Hxix&quot;) -> &quot;Hxi&quot;
    • public String withoutX(String str) {
    • }
  • One possible approach
    • Check to see if the String is empty--If it is there is no work to do, just return the empty string
    • Make a local string variable and assign it the empty string
    • If the first character is not an 'x', add it to the local string variable
    • Write a loop to add all the middle characters to the local string variable
    • If the last character is not an 'x', add it to the local string variable
    • return the local string variable
    • public String withoutX(String str) {
    • if(str.length() == 0)
    • {
    • return &quot;&quot;;
    • }
    • }
    • public String withoutX(String str) {
    • if(str.length() == 0)
    • {
    • return &quot;&quot;;
    • }
    • String noXs = &quot;&quot;;
    • ???
    • }
    • str &quot;Hxix&quot;
    • noXs &quot;&quot;
    • str &quot;Hxix&quot;
    • noXs &quot;&quot;
    • str &quot;Hxix&quot;
    • noXs &quot;H&quot;
    • public String withoutX(String str) {
    • if(str.length() == 0)
    • {
    • return &quot;&quot;;
    • }
    • String noXs = &quot;&quot;;
    • if(str.charAt(0) != 'x')
    • {
    • noXs = noXs + ??? ;
    • }
    • ???
    • }
    • str &quot;Hxix&quot;
    • noXs &quot;H&quot;
    • str &quot;Hxix&quot;
    • noXs &quot;Hx&quot;
    • str &quot;Hxix&quot;
    • noXs &quot;Hxi&quot;
    • public String withoutX(String str) {
    • if(str.length() == 0)
    • {
    • return &quot;&quot;;
    • }
    • String noXs = &quot;&quot;;
    • if(str.charAt(0) != 'x')
    • {
    • noXs = noXs + ??? ;
    • }
    • for(int i = 1; i < str.length()-1; i++)
    • {
    • noXs = noXs + ??? ;
    • }
    • int last = str.length() - 1;
    • if(str.charAt(last) != ??? )
    • {
    • ??? ;
    • }
    • return ??? ;
    • }
    One possible starting point
  • Practice Quiz Question
    • http://javabat.com/prob?id=Warmup2.stringTimes
    • Given a string and a non-negative int n, return a larger string that is n copies of the original string.
      • stringTimes(&quot;Hi&quot;, 2) -> &quot;HiHi&quot;
      • stringTimes(&quot;Hi&quot;, 3) -> &quot;HiHiHi&quot;
      • stringTimes(&quot;Hi&quot;, 1) -> &quot;Hi&quot;
    • public String stringTimes(String str, int n) {
    • }
  • Cell Phone Programming
    • Sun has a “Wireless Tool Kit” (WTK) that allows programmers to create Java programs for cell phones and other devices.
    • A different version of Processing called Mobile uses the WTK
  • Configuring Mobile
    • Start Mobile
    • Choose File | Preferences and click on the Mobile tab
    • Your settings should look like this
  • Now write a program
    • Writing the program is almost identical to normal processing
  • Mobile's API is slightly different
      • You can’t change the size() of the display
      • Input is a little different
      • Colors can’t have opacity on phones
      • 3D graphics require a special library
      • There are no get() or smooth() functions
      • Fonts work a little differently
      • Best to use “text box” format for text()
      • (int) instead of int()
      • float only available on newer versions ( CLDC 1.1 )
    • So, you will need to port an existing program to the mobile environment by modifying the code
  • Cell Phone Programming
    • When you press the play button it will bring up a virtual cell phone
    • To run the program, press the button under “launch”
    • When you are happy with your program export it as a MIDlet
  • Cell Phone Programming
    • For input, you can use keyCode
    • UP , DOWN , LEFT , RIGHT and FIRE refer to the five navigation buttons
    • or you can use code like if(key == '*') to use the keypad
  • Getting the program on your cell phone is the hard part
    • First, you need a cell phone that supports Java, most don't
    • It's easiest to get the program on your cell phone using a USB cable and your phone's software
  • Inflating Balloon
    • Let's say I want to make an animation of a balloon that gets bigger, that is, it &quot;inflates&quot;
    • I'll start by asking what a balloon has and what it does
    • And then I'll write a class that models the object
    • class Balloon
    • {
    • }
  • Inflating Balloon
    • Balloon's have a size
    • For each thing it has , we create a variable
    • class Balloon
    • {
    • int size;
    • }
  • Inflating Balloon
    • What balloons do is inflate and show up on the screen
    • For each thing it does , we create a method
    • class Balloon
    • {
    • int size;
    • void inflate()
    • {
    • size++;
    • }
    • void show()
    • {
    • ellipse(150,150,size,size);
    • }
    • }
  • The Balloon constructor
    • Every class should have a special function called a constructor
    • class Balloon
    • {
    • int size;
    • Balloon()
    • {
    • size = 0;
    • }
    • void inflate()
    • {
    • size++;
    • }
    • void show()
    • {
    • ellipse(150,150,size,size);
    • }
    • }
  • The Balloon constructor
    • The constructor must have the same name as the class
    • It doesn't have a return type, not even void
    • It initializes the variables, that is, it sets them equal to their first values
    • Balloon()
    • {
    • size = 0;
    • }
  • Inflating Balloon
    • Once I've written my balloon class, I can use it to build a new Balloon() in my program
    • Balloon bob;
    • void setup()
    • {
    • bob = new Balloon();
    • size(300,300);
    • }
  • Inflating Balloon
    • Every time the screen is drawn, I want my Balloon to do it's thing
    • Balloon bob;
    • void setup()
    • {
    • bob = new Balloon();
    • size(300,300);
    • }
    • void draw()
    • {
    • background(0,0,0);
    • bob.inflate();
    • bob.show();
    • }
  • Inflating Balloon
    • The complete program looks like this
  • OOP and class
    • The Pong assignment uses a class to model what Ball s and Paddle s have and do
    • We use a class to make a &quot;plan&quot; or &quot;blueprint&quot; of the object
    • This is called Object Oriented Programming or just OOP
  • Here's the basic outline of the Bouncing Ball program
    • Ball bob; //or whatever you want to call it
    • void setup()
    • {
    • //your code here
    • }
    • void draw()
    • {
    • //your code here
    • }
    • class Ball
    • {
    • //your code here
    • }
                                                       
  • An Instance of a class
    • Creating a class is like making a blueprint for a house
    • It shows what the house will look like when you actually build it
    • Designing a blueprint is different from building a house.
    • It's the same with a class : The Ball class shows what balls will have and do, when some are actually made .
    Not the same!
  • Here's the basic outline of the Bouncing Ball program
    • Ball bob; //or whatever you want to call it
    • void setup()
    • {
    • //other code not shown
    • bob = new Ball();
    • }
    • void draw()
    • {
    • //your code here
    • }
    • class Ball
    • {
    • //your code here
    • }
                                                       
  • new
    • When you make a new object, it is said to be an instance of its class
    • In Java, you make instances of a class with the word new
    • new Ball();
    • You can create a variable for a Ball , by declaring it's type and initializing it, much like any variable
    • Ball bob = new Ball();
    • int num = 5;
  • The draw function with move, bounce and display our ball
    • Ball bob; //or whatever you want to call it
    • void setup()
    • {
    • //your code here
    • }
    • void draw()
    • {
    • //other code not shown
    • bob.move();
    • bob.bounce();
    • bob.show();
    • }
    • class Ball
    • {
    • //your code here
    • }
                                                       
  • The dot operator
    • Once you have made an instance of a class, you can access its parts with a dot
    • Ball bob; //the declaration
    • bob = new Ball(); //the initization
    • //other java code not shown
    • bob . move();
    • bob . bounce();
    • bob . show();
  • Practice Quiz question: Find the output
    • void setup()
    • {
    • Thingy bob = new Thingy();
    • bob.num = 2;
    • bob.mystery();
    • Thingy barbara = new Thingy();
    • barbara.mystery();
    • println(&quot;bob: &quot; + bob.num);
    • println(&quot;barbara: &quot; + barbara.num );
    • }
    • class Thingy
    • {
    • int num;
    • Thingy()
    • {
    • num = 3;
    • }
    • void mystery()
    • {
    • num = num *2;
    • }
    • }
  • Pong
  • Pong                                                   
  • Pong
    • For many people, Pong was the first time they used a computer
    • Brought the first computers into people's homes
    • Written by Allan Alcorn (a Lowell grad) for Atari
    • First Pong game was installed in a Sunnyvale bar in September 1972
    • Two weeks later the machine stopped working—because all the quarters had jammed it
    • Original Paddles had eight segments—different segments gave different angles
    Allan Alcorn
  • The original arcade Pong game was basically some logic chips hooked up to an actual TV set with an added coin mechanism.
  • Pong was not the first computer game
    • 10 years before Pong, there was another, much more sophisticated computer game…
  • Spacewar!
  • Spacewar!
    • Written by members of the MIT model railroad club beginning in 1961
    • They also coined the word &quot;hack&quot;
    • Code was kept in an unlocked drawer—anyone was free to modify it
    • Programmed on the Digital Equipment PDP-1, one of the first computers with a monitor
    • Club members built the world's first joysticks
    • Later modified by Atari ( stolen? ) to become Asteroids
  • Pong Spin-offs
    • Pong Doubles 1973
  • Pong Spin-offs
    • Dr. Pong 1974
  • Pong Spin-offs
    • Cocktail Pong 1974
  • Pong Spin-offs
    • Puppy Pong 1974
  • Pong Spin-offs
    • Pin Pong 1974
  • Pong Spin-offs
    • Quadra Pong 1974
  • Pong Spin-offs
    • Super Pong 1974
  • Pong Spin-offs
    • Rebound 1974
  • Pong Spin-offs
    • Slime Volleyball
  • Pong Spin-offs
    • Breakout 1976
  • Pong Spin-offs
    • Bomb Bee 1979
  • Pong Spin-offs
    • 3d pong
  • Pong Spin-offs
    • circular pong
  • Pong Spin-offs
    • Warlords
  • Pong Spin-offs
    • Pong Clock--As Pong randomly plays, the score shown is the time of day
  • Pong Spin-offs
    • Plasma Pong, uses fluid dynamics, so the ball seems to move through a fluid
  • And from these humble beginnings…
    • Computer gaming is now a huge industry with revenue over 7 billion dollars in 2005
    • 'Mario' has made twice the revenue of all the 'Star Wars' movies combined
    • Computer Games and entertainment software are the fastest growing area of the computer software industry (which is itself one of the fastest growing areas of the economy)
  • BallMaster www.blueteagames.com by Steven Zhao class of 2001 In BallMaster, you guide a flying ball through dangerous adventures. With the aid of your computerized assistant, you fend off a variety of beasts that attack you as you float through the air. Other Games: Cactus Bruce and the Corporate Monkeys, Meeklits and HeliumMan-X
  • Pong Spin-offs
    • and many, many others. . .
  • Practice Quiz Question: Find the output
    • void setup()
    • {
    • TwoNums bob = new TwoNums();
    • println(bob.mystery1());
    • TwoNums jane = new TwoNums();
    • jane.d1 = bob.d1 * 3;
    • jane.n1 = int(bob.d1);
    • println(jane.mystery1());
    • bob.mystery2();
    • println(&quot;Bob's float is &quot; + bob.d1);
    • }
    • class TwoNums
    • {
    • int n1;
    • float d1;
    • TwoNums()
    • {
    • println(&quot;Constructing a new one&quot;);
    • n1 = 2;
    • d1 = 1.5;
    • }
    • int mystery1 ()
    • {
    • return int(n1*d1);
    • }
    • void mystery2 ()
    • {
    • int nMys = mystery1();
    • d1 = nMys + d1;
    • }
    • }