Computer Programming 2 - PowerPoint PPT Presentation

1 / 235
About This Presentation
Title:

Computer Programming 2

Description:

BGCOLOR is background color. TEXT is the color of the text HTML ... BODY BGCOLOR=black TEXT='54ff9f ' CENTER h1 Check this out! /h1 ... – PowerPoint PPT presentation

Number of Views:115
Avg rating:3.0/5.0
Slides: 236
Provided by: paulc1
Category:

less

Transcript and Presenter's Notes

Title: Computer Programming 2


1
Computer Programming 2
  • Mr. Simon
  • Lowell High School
  • San Francisco, CA

2
Course Requirements
  • Successful completion of Computer Programming 1
  • 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 getI recommend
    freewebs.com or freehostspace.com)

3
Who should take this class?
  • Ayone interested in a career as computer
    programmer or game designer
  • Ayone considering a college major in
  • Computer Science
  • Engineering
  • Math
  • Physics
  • Biology
  • Economics
  • Information Science
  • Ayone curious about how software is created

4
What youll learn
  • OOP
  • Components Event Driven Programming
  • Control structures (e.g. if, while)
  • Functions
  • Computer Graphics
  • Good Programming Style
  • A good foundation for studying computer science
    in college

5
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

6
Programming Assignments
  • Use free software Processing
  • Available online or from me
  • Its critical to your success that you spend
    adequate time programming and fully understand
    the assignments
  • Programming can be very time consumingclass time
    alone may not be enough
  • All programs should be sent by email to
    room334_at_gmail.com

7
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

8
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

9
Web and email
  • Send programs to room334_at_gmail.com
  • Send questions to simart_at_null.net
  • Check mrsimon.net for assignments, grades,
    software and other information

10
Log Off!
  • Please remember to logoff each time you finish
    with the computer, otherwise other people will be
    able to access your work!

11
Assignment 0
  • Send an email to room334_at_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 or freehostspace.com
  • Log Off when youre done

12
Getting your own website
  • Providers of free websites
  • http//freehostspace.com
  • http//www.webs.com
  • http//geocities.yahoo.com/
  • http//www.netfirms.com
  • http//www.50megs.com
  • http//www.angelfire.lycos.com/
  • http//www.100megs.com
  • Know of ay others?

13
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

14
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

15
freehostspace.com
  • Once you get the confirmation email, login in,
    choose Website Manager and then Subdomain Manager

16
freehostspace.com
  • Make up a subdomain name, and choose "Add
    Subdomain"
  • I chose mrsimon.scienceontheweb.net

17
uploading to freehostspace.com
  • Choose File Manager
  • Double click on the folder with your subdomain
    name

18
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

19
Problem Create a class to represent "flat
dice". A flat die always rolls the same number.
  • First, ask "What do flat dice have? What do flat
    dice do?"
  • They have an integer we will need one int
    variable
  • They roll and get shown on the screen, so we'll
    need at least 2 functions roll() and show()

20
Problem Create a class to represent "flat
dice". A flat die always rolls the same number.
21
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 class shows what
    dice will have and do, when some are actually
    made.

22
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 FlatDie()
  • You can create a variable for a FlatDie()
  • FlatDie oneDie new FlatDie()
  • int num 5

23
The dot operator
  • Once you have made an instance of a class, you
    can access its parts with a dot
  • FlatDie oneDie new FlatDie()
  • oneDie.roll()
  • text("Roll is " oneDie.num,20,20)

24
Now I'll add code to draw() so that everytime
the screen is drawn, the die shows up
  • void draw()
  • FlatDie aDie new FlatDie()
  • aDie.roll()
  • aDie.show(50,50)
  • text("You rolled a " aDie.num,10,90)

25
Now I'll add code to draw() so that everytime
the screen is drawn, the die shows up
  • void draw()
  • FlatDie aDie new FlatDie()
  • aDie.roll()
  • aDie.show(50,50)
  • text("You rolled a " aDie.num,10,90)

26
With a class writing a program with 13 flat dice
isn't much harder
27
Here's what the whole program looks like
28
What would be the output of this applet? (Hint
it's a trick question)
  • FlatDie aDie new FlatDie()
  • //aDie.roll()
  • aDie.show(50,50)
  • text("You rolled a " aDie.num,10,90)

29
What would be the output of this applet? (Hint
it's a trick question)
  • FlatDie aDie new FlatDie()
  • //aDie.roll()
  • aDie.show(50,50)
  • text("You rolled a " aDie.num,10,90)
  • Zero! Since aDie was never rolled, num was never
    initialized.

30
The Constructor
  • A Constructor is a special function that
    initializes the variables
  • class FlatDie
  • int num
  • FlatDie()
  • num3
  • //other java code not shown

31
Remember Pong?
  • What code should go in the Ball constructor?
  • class Ball
  • int x,y
  • boolean up,right
  • Ball()
  • ???
  • //lots more java

32
Each of the 4 variables needs to be initialized
  • class Ball
  • int x,y
  • boolean up,right
  • Ball()
  • x 150
  • y 50
  • uptrue
  • rightfalse
  • //lots more java

33
Practice Quiz Question Find the output
  • Thing one
  • Thing two
  • void setup()
  • one new Thing()
  • two new Thing()
  • println("1 " one.nNum)
  • two.nNum one.nNum 3
  • println("2 " two.nNum)
  • one.nNum two.nNum one.nNum
  • println("3 " one.nNum)
  • class Thing
  • int nNum
  • Thing()
  • nNum 2

34
Practice Quiz Questions
  • True/False A constructor is a function.
  • Fill in the blank so that num is initialized with
    one of the following random integers 1,2,3,4
  • int num __________________
  • Find the output of the following program
  • println("Testing " 1 2 3)
  • println("Testing " (1 2 3))

35
Problem Write a program where the dice are
different random sizes
36
Problem Write a program where the dice are
different random sizes
  • Now, what does every die have?
  • (think, what does it have that makes it
    different?)
  • class Die
  • ??

37
How many lines of code in the constructor?
  • class Die
  • int dots, sideLength
  • Die()
  • ??

38
What else do we need?
  • class Die
  • int dots, sideLength
  • Die()
  • dots int(random(1,7))
  • sideLength int(random(20,80))
  • ??

39
Now let's finish the program
  • class Die
  • int dots, sideLength
  • Die()
  • dots int(random(1,7))
  • sideLength int(random(20,80))
  • void show(int x, int y)
  • fill(255)
  • rect(x,y,sideLength,sideLength)
  • //code for dots not shown

40
  • void setup() //not shown
  • void draw()
  • ??
  • class Die
  • int dots, sideLength
  • Die()
  • dots int(random(1,7))
  • sideLength int(random(20,80))
  • void show(int x, int y) //not shown

41
  • void draw()
  • while(??)
  • Die bob new Die()
  • bob.show(??,??)
  • class Die
  • int dots, sideLength
  • Die()
  • dots int(random(1,7))
  • sideLength int(random(20,80))
  • void show(int x, int y) //not shown

42
  • void draw()
  • int xPosition 0
  • while(??)
  • Die bob new Die()
  • bob.show(??,??)

43
  • void draw()
  • int xPosition 0
  • while(??)
  • Die bob new Die()
  • bob.show(xPosition,150)

44
  • void draw()
  • int xPosition 0
  • while(xPosition lt 450)
  • Die bob new Die()
  • bob.show(xPosition,150)
  • ??

45
  • void draw()
  • int xPosition 0
  • while(xPosition lt 450)
  • Die bob new Die()
  • bob.show(xPosition,150)
  • xPosition xPosition ??

46
  • void draw()
  • int xPosition 0
  • while(xPosition lt 450)
  • Die bob new Die()
  • bob.show(xPosition,150)
  • xPosition xPosition
  • bob.sideLength

47
Practice Quiz Question
  • Circle the picture that best matches the output
  • void setup()
  • size(100,100)
  • void draw()
  • int yPos 10
  • while(yPos lt 100)
  • Widget widgie new Widget()
  • widgie.show(50,yPos)
  • yPos yPos widgie.diam
  • class Widget
  • int diam
  • Widget()

48
Writing HTML code
  • Web pages are created using HTML code
  • Processing automatically generates HTML code for
    you, but it's useful to understand how to write
    HTML yourself
  • HTML is not programming, it stands for HyperText
    MARKUP Language
  • "Markup" means formatting the appearance of the
    page

49
Writing HTML code
  • You can create HTML code with many programs, I
    usually use Word Pad
  • HTML commands are called tags, and are between lt
    gt and often come in pairs
  • ltHTMLgt is the tag that marks the beginning of the
    of the webpage
  • lt/HTMLgt marks the end of the head
  • Web pages are divided into a head and a body

50
The head contains the title
  • ltHTMLgt
  • ltHEADgtltTITLEgtMr. Simon's Java programslt/TITLEgt
  • lt/HEADgt
  • lt/HTMLgt

51
the title shows up at the very top
  • ltHTMLgt
  • ltHEADgtltTITLEgtMr. Simon's Java programslt/TITLEgt

52
the body tag can include the background and text
colors
  • ltHTMLgt
  • ltHEADgtltTITLEgtMr. Simon's Programs!lt/TITLEgt
  • lt/HEADgt
  • ltBODY BGCOLORblack TEXTwhitegt
  • ltCENTERgt
  • lth1gtCheck out these cool programs!lt/h1gt
  • lt/CENTERgt
  • lt/BODYgt
  • lt/HTMLgt

53
BGCOLOR is background colorTEXT is the color of
the text
  • ltHTMLgt
  • ltHEADgtltTITLEgtMr. Simon's Programs!lt/TITLEgt
  • lt/HEADgt
  • ltBODY BGCOLORblack TEXTwhitegt
  • ltCENTERgt
  • lth1gtCheck out these cool programs!lt/h1gt
  • lt/CENTERgt
  • lt/BODYgt
  • lt/HTMLgt

54
Colors can also be specified with hexadecimal
codes
  • ltBODY BGCOLORblack TEXT"54ff9f "gt
  • ltCENTERgt
  • lth1gtCheck this out!lt/h1gt

55
Adding links
  • ltHTMLgt
  • ltHEADgtltTITLEgtMr. Simon's Programs!lt/TITLEgt
  • lt/HEADgt
  • ltBODY BGCOLORblack TEXTwhite LINKyellow
    VLINKmagentagt
  • ltCENTERgt
  • lth1gtCheck out these cool programs!lt/h1gt
  • lta href"twodice.html"gtRoll Two Dicelt/agt
  • lt/CENTERgt
  • lt/BODYgt
  • lt/HTMLgt

56
LINK is the color of the links, and VLINK is the
color of the "viewed links"
  • ltHTMLgt
  • ltHEADgtltTITLEgtMr. Simon's Programs!lt/TITLEgt
  • lt/HEADgt
  • ltBODY BGCOLORblack TEXTwhite LINKyellow
    VLINKmagentagt
  • ltCENTERgt
  • lth1gtCheck out these cool programs!lt/h1gt
  • lta href"twodice.html"gtRoll Two Dicelt/agt
  • lt/CENTERgt
  • lt/BODYgt
  • lt/HTMLgt

57
The homepage for your website is index.html
  • When someone browses to your website, the first
    page they see is index.html
  • While webs.com will automatically make an
    index.html for you, freehostspace requires you to
    make your own and upload it
  • The website has a sample homepage you can use for
    your index.html
  • Just copy and paste it into Wordpad

58
Saving from Wordpad
  • Then, choose Save As
  • Name it "index.html" (including the quotes)
  • And choose Text Document for the type
  • You are now ready to upload your homepage

59
Writing a page that loads an Applet
  • You can create your own custom webpages, rather
    than using the ones processing creates for you
  • The code for the applet is pretty ugly. Rather
    than write it from scratch, we'll copy it from
    the html that processing makes
  • First, export your applet. Then right click on
    index.html and open it in word pad

60
Loading an Applet
  • Copy the code between ltobject and lt/objectgt
    right after lt!if !IE gt -- gt

61
The finished page
  • Here's what it looks like
  • ltHTMLgt
  • ltHEADgtltTITLEgtMr. Simon's first Java
    Program!lt/TITLEgt
  • lt/HEADgt
  • ltBODY BGCOLORblack TEXTwhitegt
  • ltCENTERgt
  • lth1gtCheck this out!lt/h1gt
  • ltobject classid"javaTwoMoreDice.class"
  • type"application/x-java-applet"
  • archive"TwoMoreDice.jar"
  • . . . . . . . . .Lots of HTML not shown
  • lt/objectgt
  • lt!--if !IEgt --gt
  • lt/objectgt
  • lt/CENTERgt
  • lt/BODYgt
  • lt/HTMLgt

62
Some useful html tags
  • bold ltbgttextlt/bgt
  • italicized ltigttextlt/igt
  • type-written ltttgttextlt/ttgt
  • Headings lth1gtLargest Headinglt/h1gt through
    lth6gtSmallest Headinglt/h6gt
  • Horizontal Rule lthrgt
  • Paragraph ltpgt ... lt/pgt
  • Font Sizes ltfont size1gt slightly larger font
    lt/fontgt (you can use other numbers, including
    negative)

63
Some useful html tags
  • Important Alignments add align"left" ,
    align"right", align"center" i.e. lth1
    align"right"gtbig heading right alignedlt/h1gt
  • Line break ltbrgt i.e. Line One.ltbrgtLine Two.
  • Preformatted Text ltpregt ... lt/pregt
  • Regular link lta href"http//url_here.com/"gttext
    for linklt/agt
  • Mail Link lta href"mailtousername_at_host.com"gtemai
    l melt/agt
  • Inline Images ltimg src"http//url_here.com/direc
    tory/graphic.gif"gt
  • Center Tag ltcentergt lt/centergt
  • ltimg src "somePicture.jpg"gtlt/imggt

64
Some useful html tags
  • (Hidden) Comments lt!-- Your user cannot see this
    unless they read your source code --gt
  • Unordered List
  • ltulgt
  • ltligt first item lt/ligt
  • ltligt second item lt/ligt
  • lt/ulgt
  • Ordered List (numbered)
  • ltolgt
  • ltligt item 1 lt/ligt
  • ltligt item 2 lt/ligt
  • lt/olgt
  • ltcodegt lt/codegt Uses courier font

65
GUI Components
  • GUI stands for Graphical User Interface
  • Things like buttons, check boxes, progress bars,
    text fields, etc.
  • In Processing, we add libraries (extra java code)
    to get GUI components
  • For this class, we'll use interfascia
    http//www.superstable.net/interfascia/

66
Install interfascia (at school)
  • Borrow an interfascia CD from Mr. Simon
  • Open the CD and copy the interfascia 003 folder
  • Paste that folder into
  • My Documents Processing libraries
  • Test out your installation with the sample
    program on the page after the next

67
Install interfascia (at home)
  • Download interfascia
  • Right click on the folder, and choose "Extract
    All"
  • Browse to My Documents Processing libraries
    and click OK
  • Click Next and Finish
  • Test out your installation with the sample
    program on the next page

68
An example Program
  • import interfascia.
  • GUIController c
  • IFButton b1, b2
  • int rectSize 100
  • void setup()
  • size(200, 100)
  • c new GUIController (this)
  • b1 new IFButton ("Bigger", 20, 40, 50, 17)
  • b2 new IFButton ("Smaller", 20, 60, 50, 17)
  • b1.addActionListener(this)
  • b2.addActionListener(this)
  • c.add (b1)
  • c.add (b2)
  • void draw()
  • background(0)
  • fill(255)

69
An example Program
  • import interfascia.
  • GUIController c
  • IFButton b1, b2
  • int rectSize 100
  • void setup()
  • size(200, 100)
  • c new GUIController (this)
  • b1 new IFButton ("Bigger", 20, 40, 50, 17)
  • b2 new IFButton ("Smaller", 20, 60, 50, 17)
  • b1.addActionListener(this)
  • b2.addActionListener(this)
  • c.add (b1)
  • c.add (b2)
  • void draw()
  • background(0)
  • fill(255)

70
import interfascia.
  • import statement allows us to use other
    programmer's code without cutting and pasting it
    into our program
  • It "manages complexity" and helps to make our
    program simpler and easier to read and understand

71
actionPerformed()
  • actionPerformed() is like mouseClicked() or
    keyTyped()
  • When a button is pressed, actionPerformed() is
    called
  • If there is more than one button in your program,
    you can find out which button was clicked with
    e.getSource()

72
"Look and Feel"
  • The "Look and Feel" of the button includes
  • baseColor - the default color for the background
  • borderColor- the color of the outline (like
    stroke())
  • highlightColor- the color of the button when you
    hold the mouse over it
  • activeColor- the color of the button when you
    click it
  • textColor- the color of the text on the button

73
"Look and Feel"
  • Once you create a new "Look and Feel" you apply
    it to a Button after you've added the button to
    the controller
  • You only need to do this once, usually in setup()
  • Here's an example where I create a new "Look and
    Feel" called newLook and apply it to Button b1
  • IFLookAndFeel newLook
  • new IFLookAndFeel(this,
    IFLookAndFeel.DEFAULT)
  • newLook.baseColor color(255, 0, 0)
  • newLook.highlightColor color(70, 135, 70)
  • newLook.activeColor color(255,255,0)
  • newLook.borderColor color(0,0,255)
  • b1.setLookAndFeel(newLook)

74
"Look and Feel"
  • If you want all the buttons to have the same look
    and feel, set the look and feel to the controller
    before you add the buttons
  • IFLookAndFeel newLook
  • new IFLookAndFeel(this,
    IFLookAndFeel.DEFAULT)
  • newLook.baseColor color(255, 0, 0)
  • newLook.highlightColor color(70, 135, 70)
  • newLook.activeColor color(255,255,0)
  • newLook.borderColor color(0,0,255)
  • c.setLookAndFeel(newLook)
  • b1 new IFButton ("Bigger", 20, 40, 50, 17)
  • b2 new IFButton ("Smaller", 20, 60, 50, 17)
  • b1.addActionListener(this)
  • b2.addActionListener(this)
  • c.add (b1)
  • c.add (b2)

75
Uploading to your website
  • You'll notice two additional executable jar files
    when you export your applet
  • You only need to upload core and interfascia once

76
- /
  • Arithmetic operators, like -- and
  • num num 2 same as num 2
  • num num 17 same as num 17
  • num num - 3 same as num - 3
  • num num / 11 same as num / 11
  • Be careful, these have side effects!

77
Side effects
  • is not the same as 1
  • The output of the following code fragments is
    different
  • int num 4
  • println(num 1)
  • println(num)
  • //not the same as
  • int num 4
  • println(num)
  • println(num)

78
Side effects
  • is not the same as 1
  • The output of the following code fragments is
    different
  • int num 4
  • println(num 1) //displays 5
  • println(num) //displays 4
  • //not the same as
  • int num 4
  • println(num) //displays 5
  • println(num) //displays 5

79
Side effects
  • num
  • Has a side effect the value of num is now 5
  • num 1
  • Has no side effect the value of num is unchanged
  • Rule Always use 1 unless you are sure you want
    to change the value using

80
What number will be displayed after buttons one,
two and three are pressed in that order?
  • import interfascia.
  • GUIController c
  • IFButton b1, b2, b3
  • int value
  • void setup()
  • size(200, 100)
  • value 4
  • c new GUIController (this)
  • b1 new IFButton ("One", 20, 40, 50, 17)
  • b2 new IFButton ("Two", 20, 60, 50, 17)
  • b3 new IFButton ("Three", 20, 80, 50, 17)
  • b1.addActionListener(this)
  • b2.addActionListener(this)
  • b3.addActionListener(this)
  • c.add (b1)
  • c.add (b2)
  • c.add (b3)

81
Digital Audio and Music
  • You may have seen sound waves represented like
    this

82
Digital Audio and Music
  • This is a picture representing the vibrations
    that are sensed by our ears
  • The vibrations, called sound waves, create
    pressure on our ear drum that we sense as sound

83
Amplitude
  • Small up and down variations like this are sensed
    as soft or quiet

84
Amplitude
  • Large up and down swings are sensed as loud

85
Frequency
  • If the peaks and valleys are close together we
    sense it as "high pitched" or treble

86
Frequency
  • If the peaks and valleys are far apart together
    we sense it as "low pitched" or bass

87
Demo
88
Digital Audio and Music
  • Sound waves are stored digitally as streams of
    positive and negative decimals
  • Might be 0.0 0.42284906 0.76155484 0.9498813
    0.9533962 0.776279 0.4595966 0.071568534
    -0.30784124 -0.385844 -0.100973964 0.16315886
    0.35497138 0.44508645 0.4310813 0.335351
    0.19698942 0.060041666 -0.03869301
    -0.079125404 -0.06222722 -0.008282244
    0.05032392 0.07969847 0.055455804 -0.02892235
    -0.15876007 -0.3009491 -0.41223812 -0.450995
    -0.38939917 -0.22280076 0.0263986 0.311675
    0.57175916 0.7444452 0.78161657 0.6618374
    0.39731562 0.03329304 -0.3603183 -0.7033825
    -0.9229034 -0.96936864 -0.82828283 -0.524150

89
Digital Audio and Music
  • Every so often, we sample the amplitude and
    record it as a number
  • The samples in this picture are shown as vertical
    lines
  • The third sample might be 0.0 0.42284906
    0.76155484 0.9498813 0.9533962 0.776279
    0.4595966 0.071568534 -0.30784124 -0.385844
    -0.100973964 0.16315886 0.35497138 0.44508645
    0.4310813 0.335351 0.19698942 0.060041666
    -0.03869301 -0.079125404 -0.06222722
    -0.008282244 0.05032392 0.07969847 0.055455804
    -0.02892235 -0.15876007 -0.3009491
    -0.41223812 -0.450995 -0.38939917 -0.22280076
    0.0263986 0.311675 0.57175916 0.7444452
    0.78161657 0.6618374 0.39731562 0.03329304
    -0.3603183 -0.7033825 -0.9229034 -0.96936864
    -0.82828283 -0.524150

0.76155484
90
Digital Audio and Music
  • The amplitude is between 1.0 and -1.0
  • Just looking at this portion of the wave 0.0
    0.42284906 0.76155484 0.8498813 0.9533962
    0.876279 0.69362718 0.5595966 0.34587211
    0.121568534 0.0 -0.25784124 -0.30627893
    -0.27903551 -0.203674590 0.0

91
Sound buffer
  • As the sound is playing on our computer, small
    chunks of numbers that record the part of the
    sound we are hearing are stored in the Sound
    Buffer
  • The size of the sound buffer is usually 512, but
    can be set to other values
  • At 512, that means there are 512 decimals, or
    floats, each between 1 and -1

92
Minim
  • Minim is a library that makes it easy to play
    mp3s and access the Sound Buffer
  • Download and install Minim to the libraries
    folder just like you did with interfascia
  • Here's a sample Minim program that plays a song

93
Using Minim to play a mp3
  • import ddf.minim.signals.
  • import ddf.minim.
  • import ddf.minim.analysis.
  • import ddf.minim.effects.
  • Minim minim
  • AudioPlayer song
  • void setup()
  • minim new Minim(this)
  • // this loads mysong.mp3 from the data folder
  • song minim.loadFile("mysong.mp3")
  • song.play()
  • void draw() //empty for now

94
Using Minim to get to the Sound Buffer
  • To allow for stereo, there are two buffers,
    song.left and song.right
  • We could make a very simple visualizer by using
    the first value in the left buffer to change the
    size of an ellipse like
  • void draw()
  • background(255,0,0)
  • int diameter int(
  • abs(song.left.get(0)) 200 )
  • ellipse(50,50,diameter,diameter)

95
Using Minim to get to the Sound Buffer
  • song.left.get(0) is the first float in the buffer
  • Since it could be negative we'll use the absolute
    value function abs()
  • Then we'll multiply it by 200 and drop the
    decimals so we'll get a diameter between 0 and
    200 for our ellipse
  • void draw()
  • background(255,0,0)
  • int diameter int(
  • abs(song.left.get(0)) 200 )
  • ellipse(50,50,diameter,diameter)

96
Using the largest float in the Sound Buffer
  • We can make a better visualizer by using the
    largest float in the Sound Buffer
  • void draw()
  • background(255,0,0)
  • float biggest 0
  • for(int i 0 i lt song.bufferSize() i)
  • if(abs(song.left.get(i)) gt biggest)
  • biggest abs(song.left.get(i))
  • int diameter int(200 biggest)
  • ellipse(50,50,diameter,diameter)

97
Using the all the floats in the Sound Buffer
  • We could write a loop to use all the floats in
    the Buffer
  • void draw()
  • background(255,0,0)
  • for(int i 0 i lt song.bufferSize() i)
  • float amplitude song.left.get(i)
  • int height int(200 amplitude)
  • rect(i,50,2, height)

98
Practice Quiz Question
  • Circle and modify the parts of the code on the
    following page, so that the dice are smaller, and
    there are gaps of 50 on each side of the dice
    (i.e. the x position of the first die is 50 and
    the last is 550)

Before
After
99
  • void setup()
  • size(600,200)
  • //other code not shown
  • void draw()
  • background(0)
  • int xPosition 0
  • while(xPosition lt 600)
  • Die one new Die()
  • one.show(xPosition,100)
  • xPosition xPosition one.sideLength
  • class Die
  • int roll, sideLength

100
Loops
  • Loops make things happen over and over again
  • If you are doing the same thing over and over
    again with small variations, use a loop
  • For example, you could write a loop to display
    six Xs
  • X X X X X X

101
Loops
  • for(int i ? i lt ? i?)
  • print("X ")
  • X X X X X X

102
Loops
  • for(int i 1 i lt 6 i)
  • print("X ")
  • X X X X X X

103
Nested Loops
  • Now, how would I repeat that pattern three times
    so that it looked like this?
  • X X X X X X
  • X X X X X X
  • X X X X X X

104
Nested Loops
  • for(??)
  • for(int i 1 i lt 6 i)
  • print("X ")
  • ??
  • X X X X X X
  • X X X X X X
  • X X X X X X

105
Nested Loops
  • for(int j 1 j lt 3 j)
  • for(int i 1 i lt 6 i)
  • print("X ")
  • println() //ends the line
  • X X X X X X
  • X X X X X X
  • X X X X X X

106
Nested Loops
  • Putting a loop inside another loop is called
    Nesting
  • for(int j 1 j lt 3 j)
  • for(int i 1 i lt 6 i)
  • print("X ")
  • println() //ends the line

107
Nested Loops
  • Notice the row and column arrangement
  • for(int j 1 j lt 3 j)
  • for(int i 1 i lt 6 i)
  • print("X ")
  • println() //ends the line
  • X X X X X X
  • X X X X X X
  • X X X X X X

3 rows
108
Nested Loops
  • Notice the row and column arrangement
  • for(int j 1 j lt 3 j)
  • for(int i 1 i lt 6 i)
  • print("X ")
  • println() //ends the line
  • X X X X X X
  • X X X X X X
  • X X X X X X

6 columns
109
Nested Loops
  • Which loop is generating the three rows?
  • Which loop is generating the six columns?
  • for(int j 1 j lt 3 j)
  • for(int i 1 i lt 6 i)
  • print("X ")
  • println() //ends the line
  • X X X X X X
  • X X X X X X
  • X X X X X X

110
A good thing to remember
  • The outer loop can be used to generate a number
    of rows
  • The inner loop can be used to generate a number
    of columns
  • for(int j 1 j lt 3 j)
  • for(int i 1 i lt 6 i)
  • print("X ")
  • println() //ends the line

111
Practice Quiz Question
  • Write a program using nested loops that will
    create the following pattern of Xs
  • X X X X X
  • X X X X X
  • X X X X X
  • X X X X X

112
Nested loops and graphics
  • Let's say I wanted to make a grid of circles that
    looked like this
  • I can tell it has 8 rows and 6 columns
  • So I'll need appropriate loops

113
One loop will make the x coordinates and the
other the y
  • for( ?? ) //8 rows
  • for( ?? ) //6 columns
  • ellipse(x,y,5,5)

114
If I move down one row, what's changing, x or y?
  • for( ?? ) //8 rows
  • for( ?? ) //6 columns
  • ellipse(x,y,5,5)

115
The outer loop changes y and the inner loop
changes x
  • for(int y ?? y lt ?? y ?? ) //8 rows
  • for(int x ?? x lt ?? x ?? //6 columns
  • ellipse(x,y,5,5)

116
The outer loop changes y and the inner loop
changes x
  • for(int y 10 y lt 80 y 10 ) //8 rows
  • for(int x 20 x lt 70 x 10 //6 columns
  • ellipse(x,y,5,5)

117
The outer loop changes y and the inner loop
changes x
  • for(int y 10 y lt 80 y 10 )
  • //8 rows at 10 20 30 40 50 60 70 80
  • for(int x 20 x lt 70 x 10
  • //6 columns at 20 30 40 50 60 70
  • ellipse(x,y,5,5)

118
Practice Quiz Question
  • Write a program using nested loops that will
    create a similar pattern of ellipses

119
Practice Quiz Question
  • If it's helpful, here are some coordinates
  • (Yours doesn't have to look exactly like mine)

120
2 dimensional arrays
  • Can be thought of as a grid with rows and
    columns

column 0 1 2
-3
-1
5
row 0
7
12
13
row 1
121
2 dimensional arrays
  • int nums -3, -1, 5,
  • 7, 12, 13
  • //Note rows first, then columns
  • println(nums12) //displays 13
  • println(nums21) //Crash!

column 0 1 2
-3
-1
5
row 0
7
12
13
row 1
122
The Battleship program
  • In Battleship, we have a two dimensional array of
    buttons
  • IFButton buttons

123
The Battleship program
  • Don't worry too much about the arithmetic in the
    nested loops that is arranging them into rows and
    columns
  • for(int r 0 r lt rows r)
  • for(int c 0 c lt cols c)
  • int x c buttonSize 40
  • int y r buttonSize 60
  • buttonsrc new IFButton ("", x, y,
    buttonSize, buttonSize)
  • buttonsrc.addActionListener(this)
  • control.add (buttonsrc)

124
The Battleship program
  • In OOP we think about our program as a collection
    of interacting objects
  • In the Battleship program, the objects include
    Buttons and a Ship
  • The Button class has already been written, but we
    will need to write a class that models a Ship
  • Before writing code for the Ship class, we should
    ask ourselves what a ship HAS, and also what it
    DOES.

125
The Battleship program
  • We use functions to represent what the object
    does and variables for what it has.
  • class Ship
  • //some variables
  • Ship() //constructor
  • //other functions

126
The Battleship program
  • Our Ship is hiding behind four Buttons, so our
    class will need four IFButton variables
  • class Ship
  • IFButton b1,b2,b3,b4
  • Ship() //constructor
  • //other functions

127
The Battleship program
  • The constructor's job is to initialize the
    variables
  • class Ship
  • IFButton b1,b2,b3,b4
  • Ship() //constructor
  • b1 ??
  • b2 ??
  • b3 ??
  • b4 ??
  • //other functions

128
The Battleship program
  • Eventually we'll hide the ship randomly, but to
    get started, we can just choose any four buttons
  • class Ship
  • IFButton b1,b2,b3,b4
  • Ship() //constructor
  • b1 buttons02
  • b2 buttons12
  • b3 buttons22
  • b4 buttons32
  • //other functions

129
Creating an instance of the ship class
  • Once we have the beginnings of a ship class, we
    can make an instance with code like
  • Ship bob new Ship()

130
Checking for a hit
  • void actionPerformed (GUIEvent e)
  • IFButton shot (IFButton)e.getSource()
  • if(shot.getX() gt 145) //replace this with
  • //code that checks for a hit
  • shot.setLookAndFeel(hit)
  • else
  • shot.setLookAndFeel(miss)

131
How can we find out if bob was hit?
  • void actionPerformed (GUIEvent e)
  • IFButton shot
  • (IFButton)e.getSource()
  • if( bob ?? )
  • shot.setLookAndFeel(hit)
  • else
  • shot.setLookAndFeel(miss)

132
The isHit function
  • We'll check to see if shot is the same button as
    b1, b2, b3, or b4
  • class Ship
  • IFButton b1,b2,b3,b4
  • Ship() //constructor
  • b1 buttons02
  • b2 buttons12
  • b3 buttons22
  • b4 buttons32
  • boolean isHit(IFButton shot)
  • return false //replace this with code that
    checks to
  • //see if the ship was hit

133
Now we can call isHit()
  • void actionPerformed (GUIEvent e)
  • IFButton shot
  • (IFButton)e.getSource()
  • if( bob.isHit(shot) true )
  • shot.setLookAndFeel(hit)
  • else
  • shot.setLookAndFeel(miss)

134
A trick question!
  • How many Buttons does the following code create?
  • IFButton b1

135
None!
  • Buttons are Objects
  • What word do we need in Java to build an instance
    of a class?
  • IFButton b1

136
new
  • Now one Button, called an instance has been
    created
  • IFButton b1
  • b1 new IFButton ("one",20,40,50,17)

137
So, if this isn't a Button, what is it?
  • IFButton b1

138
It's just a name for a Button
  • IFButton b1
  • It's kind of like saying "If I ever get a dog,
    I'll name him Bob"
  • We have a name for Button that hasn't been
    created yet
  • In programming we this kind of name a pointer

139
The Binky video
  • Pointer Fun is a 3 minute video from the computer
    science dept. at Stanford

140
  • //The code from the Binky video
  • class IntObj
  • int value
  • IntObj x // Allocate the pointers x and y
  • IntObj y // (but not the IntObj pointees)
  • x new IntObj() // Allocate an IntObj pointee
  • // and set x to point to it
  • x.value 42 // Dereference x to store 42
    in its
  • //pointee
  • y.value 13// CRASH -- y does not have a
    pointee yet
  • y x // Pointer assignment sets y to point to
    x's

141
  • IntObj x
  • IntObj y

x
y
142
  • x new IntObj()

x
y
143
  • x.value 42

42
x
y
144
  • y.value 13

42
x
y
145
  • y.value 13
  • //Null Pointer exception

42
x
y
CRASH!
146
  • y x

42
x
y
147
  • y.value 13

13
x
y
148
  • //What would
  • println(x.value)
  • //Display?

13
x
y
149
  • //Answer 13

13
x
y
150
  • Change the code from the Binky video
  • so that it produces this structure

1
x
2
y
class IntObj int value IntObj x
IntObj y x new IntObj()
x.value 42 y x
y.value 13 println(x.value) println(y.value
)
151
Practice Quiz Question Find the Output if
Buttons b1 and b2 are clicked in that order
  • import interfascia.
  • GUIController c
  • IFButton b1, b2
  • int nTimes 0
  • SomeClass bob
  • void setup() //not shown
  • void draw()//not used
  • void actionPerformed(GUIEvent e)
  • nTimes
  • println(
  • "clicked " nTimes " times")
  • IFButton clicked
  • (IFButton)e.getSource()
  • if(bob.mystery(clicked)false)
  • println("first")
  • else

class SomeClass IFButton theButton
SomeClass() theButton b2 boolean
mystery( IFButton clicked)
if(theButtonclicked) return true
else return false

152
dot equals vs. double equals
  • assigns two handles
  • to the same object
  • if(x y)asks
  • Are x and y referring
  • to the same object?
  • if(x.equals(y))asks
  • Do x and y have the same value?

153
X Y refer to the same object
2
x
y
154
X Y have the same value
2
x
2
y
155
Practice Quiz Question What is the output of
this applet?
  • SomeType one new SomeType("one")
  • SomeType two new SomeType("two")
  • void setup()
  • SomeType three two
  • three.sMessage new String("three")
  • println(one.sMessage ", " two.sMessage)
  • three one
  • three.sMessage new String("four")
  • println(one.sMessage ", " two.sMessage)
  • void draw()//not used
  • class SomeType
  • String sMessage
  • SomeType(String sText)
  • sMessage sText

156
  • SomeType one new SomeType("one")
  • SomeType two new SomeType("two")

one
one
two
two
157
  • SomeType three two
  • three.sMessage new String("three)
  • System.out.println(one.sMessage
  • ", " two.sMessage)

one
one
three
two
three
158
  • three one
  • three.sMessage new String("four)
  • System.out.println(one.sMessage
  • ", " two.sMessage)

four
one
three
two
three
159
primitives (likes ints) are different than
objects
  • int n1 3
  • int n2 n1
  • n2 7
  • println(n1)

160
There are two int "mailboxes" and each has a 3
  • int n1 3
  • int n2 n1
  • n2 7
  • println(n1)

n1
3
n2
3
161
There are two int "mailboxes" and each has a 3
  • int n1 3
  • int n2 n1
  • n2 7
  • println(n1)
  • //displays 3

n1
3
n2
7
3
162
objects are created with class
  • class IntObj
  • int value
  • IntObj n1 new IntObj()
  • n1.value 3
  • IntObj n2 n1
  • n2.value 7
  • println(n1.value)

163
We've only created one new IntObj
  • class IntObj
  • int value
  • IntObj n1 new IntObj()
  • n1.value 3
  • IntObj n2 n1
  • n2.value 7
  • println(n1.value)

n1
3
n2
164
We've only created one new IntObj
  • class IntObj
  • int value
  • IntObj n1 new IntObj()
  • n1.value 3
  • IntObj n2 n1
  • n2.value 7
  • println(n1.value)
  • //displays 7

n1
7
n2
165
find the output
  • int n1 4
  • int n2 n1
  • n2 2
  • println(n1)
  • class IntObj
  • int value
  • IntObj n3 new IntObj()
  • n3.value 4
  • IntObj n4 n3
  • n4.value 2
  • println(n3.value)

166
null pointer exception
  • Remember what happened to Binky?
  • Don't let it happen to you!
  • Make sure your pointers are all assigned to point
    to something
  • If you try to use a pointer that isn't pointing
    to something, your program crashes

167
a nasty null pointer exception
  • Ship bob
  • void setup()
  • Ship bob new Ship()
  • //lots more java
  • void actionPerformed()
  • IFButton shot(IFButton)e.getSource()
  • if(bob.isHit(shot) true)
  • //lots more java

168
How many bob pointers?
  • Ship bob
  • void setup()
  • Ship bob new Ship()
  • //lots more java
  • void actionPerformed()
  • IFButton shot(IFButton)e.getSource()
  • if(bob.isHit(shot) true)
  • //lots more java

169
Now it's fixed
  • Ship bob
  • void setup()
  • bob new Ship()
  • //lots more java
  • void actionPerformed()
  • IFButton shot(IFButton)e.getSource()
  • if(bob.isHit(shot) true)
  • //lots more java

170
Arrays of Objects
  • A very powerful technique
  • Let's say you have a planet class and want to
    model the solar system
  • First, you'd declare an Array of Planets
  • Planet planets

171
Arrays of Objects
  • Then you would initialize the array
  • Planet planets
  • void setup()
  • //other code not shown
  • planets new Planet8

172
Arrays of Objects
  • How many new Planets have been created?
  • Planet planets
  • void setup()
  • //other code not shown
  • planets new Planet8

173
Arrays of Objects
  • None! All we have are 8 pointers.
  • Planet planets
  • void setup()
  • //other code not shown
  • planets new Planet8

174
Arrays of Objects
  • We nee to loop through the array to "hook those
    pointers up" to new Planets
  • Planet planets
  • void setup()
  • //other code not shown
  • planets new Planet8
  • for(int i0 ilt8 i)
  • planetsi new Planet()

175
Arrays of Objects
  • Once the array is set up, you can loop through it
    to draw and move the planets
  • void draw()
  • for(int i0 ilt8 i)
  • planetsi.move()
  • planetsi.show()

176
An outline for the Snake game
  • Snake theSnake
  • //other variables not shown
  • void setup()
  • size(600,410)
  • theSnake new Snake( ??? )
  • //lots more java
  • void draw()//not shown
  • void keyPressed()
  • theSnake.direction keyCode
  • class Segment
  • //variables and functions not shown
  • class Snake

177
The Segment class
  • Represents one of the squares that form the body
    of the snake
  • Should have everything that Segments have and do
  • class Segment
  • ??

178
The Segment class
  • What Segments have x and y coordinates, a length
    for the side of the segment, and a color.
  • What Segments do get constructed and shown to
    the screen
  • class Segment
  • ??

179
The Segment class
  • What Segments have x and y coordinates, a length
    for the side of the segment, and a color.
  • class Segment
  • int x, y, length
  • color snakeColor

180
The Segment class
  • What Segments do get constructed and shown to
    the screen
  • class Segment
  • int x, y, length
  • color snakeColor
  • Segment()
  • x ???
  • y ???
  • length ???
  • snakeColor ???
  • void show() ???

181
The Snake class
  • Represents the entire Snake
  • Should have everything that Snakes have and do
  • class Snake
  • ??

182
The Snake class
  • Snakes have An array of segments, a direction,
    the current length of the snake, and the maximum
    length of the snake
  • class Snake
  • ??

183
The Snake class
  • Snakes have An array of segments, a direction,
    a color, the current length of the snake, and the
    maximum length of the snake
  • class Snake
  • Segment segments
  • int direction
  • int currentLength
  • int maxLength

184
The Snake class
  • What Snakes do They get constructred, moved and
    drawn to the screen
  • class Snake
  • Segment segments
  • int direction
  • int currentLength
  • int maxLength
  • Snake() ???
  • void move() ???
  • void show () ???

185
The Snake constructor
  • class Snake
  • Segment segments
  • int direction
  • int currentLength
  • int maxLength
  • Snake()
  • direction ???
  • direction ???
  • currentLength ???
  • maxLength ???

186
Initializing the array of segments is probably
the trickiest part of the constructor
  • Snake()
  • //other code not shown
  • segments new SegmentmaxLength
  • for(int i 0 i lt maxLength i)
  • segmentsi new Segment())
  • //change the color of the head
  • segments0.snakeColor
  • color(255,255,0)

187
How snakes move
  • Starting from the back of the snake copy the x
    and y coordinates of the next segment. Stop when
    you get to the segment behind the head
  • The head coordinates change depending on the
    direction of travel

head
head
(5,2)
(6,2)
(7,2)
(5,2)
(6,2)
(5,3)
(5,3)
(5,4)
188
Find the output
  • char letters1 'b','c','d','e'
  • char letters2 'b','c','d','e'
  • letters10 'a'
  • for(int i 1 i lt letters1.lengthi)
  • letters1i letters1i - 1
  • println(letters1)
  • for(int i letters2.length-1 i gt 0i--)
  • letters2i letters2i - 1
  • letters20 'a'
  • println(letters2)

189
Recursionused inFractals
190
What will be displayed?
  • void setup()
  • randomNumber()
  • void draw()//not used
  • void randomNumber()
  • println(random(1))

191
What will be displayed now?
  • void setup()
  • randomNumber()
  • void draw()//not used
  • void randomNumber()
  • println(random(1))
  • randomNumber()

192
The program shows a bunch of random numbers and
then crashesthe problem is it won't stop!
  • void setup()
  • randomNumber()
  • void draw()//not used
  • void randomNumber()
  • println(random(1))
  • randomNumber()

193
Recursion A function that calls itself
  • void randomNumber()
  • println(random(1))
  • randomNumber()
  • Recursion is another way of making a loop
  • Recursion is hard to controlit's very easy to
    create an infinite loop that never stops

194
In recursion, the "stopping point" is called the
base case
  • void randomNumber(int times)
  • if(times 0)
  • println("Stop!")
  • else
  • println(random(1))
  • randomNumber(times-1)
  • The base case stops the recursive calls

195
  • void setup()
  • randomNumber(5)
  • void randomNumber(int times)
  • if(times 0)
  • println("Stop!")
  • else
  • println(random(1))
  • randomNumber(times-1)

196
Recursion
  • There are two basic ways to make things happen
    "over and over again" in programming
  • Loops
  • Recursion
  • In theory, anything you can do with loops, you
    can do with recursion ( vice versa)

197
A loop that "counts" from 1 to 10
  • void setup()
  • for(int i 1 i lt 10 i)
  • println(i)

198
A Recursive Function that "counts" from 1 to 10
  • void setup()
  • recursiveFunction(1)
  • void recursiveFunction(int num)
  • if(num 10)
  • println(num " and stop")
  • else
  • println(num)
  • recursiveFunction(num1)

199
A Recursive Function calls itself
  • void recursiveFunction(int num)
  • if(num 10)
  • println(num " and stop")
  • else
  • println(num)
  • recursiveFunction(num1)

200
Just like a loop, it has a starting point, a
stopping point, and a way to get from one to the
other
  • void setup()
  • recursiveFunction(1)
  • void recursiveFunction(int num)
  • if(num 10)
  • println(num " and stop")
  • else
  • println(num)
  • recursiveFunction(num1)

201
base case
  • Just like a loop, if recursion doesn't stop,
    we'll crash the computer
  • void recursiveFunction(int num)
  • if(num 10)
  • println(num " and stop")
  • else
  • println(num)
  • recursiveFunction(num1)
  • The if statement is called the base case
  • In the base case there is no recursive call, and
    the recursion stops

202
What is the output?
  • void setup()
  • println(mystery(4))
  • int mystery(int num)
  • if(num lt 1)
  • return 1
Write a Comment
User Comments (0)
About PowerShow.com