Chapter 2 - The First Program: Little Crab

Chapter 2 - The First Program: Little Crab

Chapter 5 Making Music: An On-Screen Piano (Part 2 Using Arrays) Creating a Music Simulation: Placing Multiple keys by using a for-loop /** * Create the Piano Keys For loop that iterates 12 times */ public void makeKeys() { for (int i = 0; i<12; i++) {

addObject (new Key ("g", "3g.wav"), i*63 + 54, 140); } } Creating a new Key object Position on the Piano is depend on the current using fixed letter and fixed soundfile (for now) value of i (plus a fixed offset value) Different notes for each key This approach is unsatisfactory, because it creates the same Key object multiple times. What we actually want to do is create different Keys using a sequence of Parameters. For example: Key Name:

"a" "b" "c" "d" "e" "f" "g" Note File Name: "3a.wav" "3b.wav" "3c.wav" "3d.wav "3e.wav" "3f.wav "3g.wav"

The First Data Structure: Arrays An array is an ordered list of values. All the values have to be of the same data type. Example: This array holds 10 values that are indexed from 0 to 9 Each value has a numeric index The entire array has a single name 0 keyNames"a" 1

2 3 4 5 6 7 8 9 "b" "c" "d" "e" "f" "g" "h"

"i" An array of size N is indexed from zero to N-1 "j" Declaring an Arrays This indicates its an array of Strings String [ ] keyNames = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l" }; This array holds 12 values from String0[]to 11 0

11 a 1 b 2 3 4 c d e

5 f 6 g 7 h 8 i 9 j k

A particular value in an array is referenced using the array name followed by the index in square brackets. For example: keyNames[2] refers to the value "c" (the 3rd value in the array) keyNames[0] contains the string "a" keyNames[1] contains the string "b" 10 l Creating Arrays Arrays can have any type of data, like integer, double, boolean, char or String. Every array needs to have a name.

Arrays can be filled with values at the point of declaration. int [] scores = { 95, 100, 85, 80, 90, 75, 100 }; double [] payments = { 120.10, 445.95, 100.00, 12.12 }; boolean [] answerKey = { true, false, true, true, false }; char [] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' }; String [] names = { "John", "Doe", "Mary", "Lamb" }; The length of Arrays int [] scores = { 95, 100, 85, 80, 90, 75, 100 }; double [] payments = { 120.10, 445.95, 100.00, 12.12 }; boolean [] answerKey = { true, false, true, true, false }; char [] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' }; String [] names = { "John", "Doe", "Mary", "Lamb" }; Each array has a length. The length of an array is the number of values that are stored in the array. We can access this value by typing arrayname.length.

For example, the scores array above has 7 elements, so scores.length = 7. payments has 4 elements so payments.length = 4. Creating Arrays You declare an array by giving its data type followed by square brackets, followed by the name, like so: int [] scores; double [] payments; boolean [] answerKey; char [] letters; These arrays are being declared but they are not being given any values yet String [] names;

You must declare an array (and any variable) before you can use it. As we did in the last slide, you can initialize an array on the same line that it is being declared. But you dont have to do this. Creating Arrays Arrays have a fixed size. You can decide what that size is by initializing or by allocating a certain amount of space without initializing: int [] scores = new int[10]; double [] payments = new double[20]; boolean [] answerKey = new answerKey[5]; char [] letters = new char[26]; String [] names = new String[100]; Although the values are not initialized, scores now has 10

elements, so scores.length = 10. payments has 20 elements, so payments.length = 20. answerKey still has 5 so answerKey.length = 5, and so on. Using Arrays Each element in an array can be accessed separately, by using the name of the array + the index of the value in [ ]. The numeric value can even be a integer variable instead of a fixed value. An array element can used like a normal variable, i.e. it can be assigned a value, printed, or used in a calculation. Some examples: scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1]) / 2; JOptionPane.showMessageDialog(null,"Top = " + scores[5]);

Using Arrays and Loops By combining arrays and loops, we can traverse and apply operations to every value in an array. For example in the following code, all the scores are being doubled: for (int i = 0; i < scores.length; ++i) { scores[i] = 2 * scores[i]; } Another example, the following code sets every value in the array to zero: for (int i = 0; i < scores.length; ++i) { scores[i] = 0; } Consecutive Keyboard Keys On a computer keyboard it doesnt make sense to have the keys a through g represent the notes

a through g because they are not in consecutive order on the keyboard, so your finger position would be difficult and different from when using a piano or a synthesizer. So makes more sense to use a consecutive row of keys on the keyboard to represent the consecutive notes: Consecutive Keyboard Keys There are 7 notes in the C major scale octaves: CDEFGAB So if we want to cover octaves 2 and 3, we need 14 consecutive keys, and that can be done using the second row of keys, which includes the Tab key, the Q key, the W key, and so on up to the backslash key \: Consecutive Keyboard

Keys Using Arrays the tab key Backslash is an escape character for other keys like \b or \n, so you use \\ to treat it just as a backslash public class Piano extends World { private String[] whiteKeys = {"q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "\\, enter" }; private String[] whiteNotes =

{ "2c", "2d", "2e", "2f", "2g", "2a", "2b", "3c", "3d", "3e", "3f", "3g", "3a", "3b" }; public Piano() { super(900, 340, 1); makeKeys(); } // other methods omitted } 14 keys requires more space horizontally so this has gone from 800 to 900 pixels Creating the White Keys /**

We moved the creation of a * Create the Piano Keys new key out of the */ addObject method to make public void makeKeys() it make it easier to read { for (int i = 0; i < whiteKeys.length; i++) { Key key = new Key (whiteKeys[i], whiteNotes[i] + ".wav"); addObject (key, 40 + i*63, 140); } } Sending the name of each key and each note to the constructor Creating the White Keys

/** * Create the Piano Keys */ public void makeKeys() { for (int i = 0; i < whiteKeys.length; i++) { Key key = new Key (whiteKeys[i], whiteNotes[i] + ".wav"); addObject (key, 40 + i*63, 140); } } String concatenation: Two Strings are combined, using the + symbol. This again results in a String. Code to set up the White

Keys 14 White Keys each with a Different Note: Adding Black Keys To add black keys to the Key class, all we need to do is store information in the Key class to differentiate between which set of image files to use. The white and black keys will use different image files for the key when it is up, and different image files for the key when it is down. These two image file names will now be stored in the following two variables: private String upImageFile; private String downImageFile; Adding Black Keys

Now the constructor needs an extra parameter to get the color information in order to set the value of those two variables to the appropriate image file names: public Key (String keyName, String noteName, String colorName) { key = keyName; sound = noteName + ".wav"; upImageFile = colorName + "-key.png"; downImageFile = colorName + "-key-down.png"; Change the Key setImage(upImageFile); Class so That It Can } Makes sure that the

right Up-Image is showing Make Either White or Black Keys for Up and Down key Adding Black Keys We now use the upImageFile and downImageFile variables in place of the actual filenames we used earlier public void act() { if ( !isDown && Greenfoot.isKeyDown(key) ) { setImage(downImageFile); white/black-keyplay(); down.png isDown = true;

} if ( isDown && !Greenfoot.isKeyDown(key) ) { setImage(upImageFile); white/blackisDown = false; key.png } } Consecutive Keyboard Keys Now that the Key class can handle black keys, we need to decide what keys to use. Each octave has 5 sharp notes: C#D#F#G#A# For two octaves, well need another 10 consecutive keys. Black keys go above white keys, so lets use the numeric keys on the first row: 1, 2, 3 and so on up to 0:

14 White Keys and 10 Black Keys Each with a Different Note: First key. Skipped keys. Consecutive Keyboard Keys Using Arrays public class Piano extends World { private String[] whiteKeys = { "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "\\, enter" }; private String[] whiteNotes = { "2c", "2d", "2e", "2f", "2g", "2a", "2b", "3c", "3d", "3e", "3f", "3g", "3a", "3b" };

private String[] blackKeys = { "1", "2", " ", "3", "4", "5", " ", "6", "7", " ", "8", "9", "0" }; private String[] blackNotes = { "2c#", "2d#", " ", "2f#", "2g#", "2a#", " ", "3c#", "3d#", " ", "3f#", "3g#", "3a#" }; // constructor and methods omitted } Creating White and Black Keys /** * Create the Piano Keys */ public void makeKeys() { for (int i = 0; i < whiteKeys.length; i++) { Key key = new Key (whiteKeys[i],

sets whiteNotes[i],"white"); white keys addObject (key, 40 + i*63, 140); spots where } you for (int i = 0; i < blackKeys.length; i++) { skip a black if (i != 2 && i != 6 && i != 9) { sets key Key key = new Key black keys(blackKeys[i],blackNotes[i],"black"); addObject (key, 70 + i*63, 86); }

} } 14 White Keys and 10 Black Keys Each with a Different Note: Reacting to keyboard input public void act() { checkKeys(); } public void checkKeys() { if ( !isDown && Greenfoot.isKeyDown(key) ) { setImage(downImageFile); play(); isDown = true; }

if ( isDown && ! Greenfoot.isKeyDown(key) ) { setImage(upImageFile); isDown = false; } } Checking for Mouse Clicks You can check for mouse clicks on the Piano Keys using the Greenfoot mouseClicked() method. But, just like with the keys, we need to keep track of when the mouse click started and ended, so well use a variable called isPushed to keep track like isDown did for isKeyDown(), and well add a call to checkMouse() to our act() method: private boolean isPushed = false; call this from the act() method

public void checkMouse() { if ( !isPushed && Greenfoot.mouseClicked(this) ) { setImage(downImageFile); play(); isPushed = true; } if ( isPushed && !Greenfoot.mouseClicked(this) ) { setImage(upImageFile); isPushed = false; } Checking for Mouse Clicks The only problem with this is that mouse clicks are very quick and so the key-down image changes back to the key-up image too quickly. So we need to add a delay to how long the keydown image stays around before changing back to the key-up

image. To do this we will create the following variable: private long keyDownTime = 0; When the mouse first clicks a key, well record in milliseconds when that happened (using System.currentTimeMillis()): keyDownTime = System.currentTimeMillis(); Then we wont show the key up image until 1/5th of a second has passed, which is 200 milliseconds. So we wont show the key up image until System.currentTimeMillis() is greater than keyDownTime + 200. Checking for Mouse Clicks When we apply this logic we get: private boolean isPushed = false; private long keyDownTime = 0; public void checkMouse() { if ( !isPushed && Greenfoot.mouseClicked(this) ) {

setImage(downImageFile); play(); isPushed = true; keyDownTime = System.currentTimeMillis(); } if ( isPushed && !Greenfoot.mouseClicked(this) ) { if (System.currentTimeMillis() > keyDownTime + 200) { setImage(upImageFile); isPushed = false; } } } Concept Summary

Recently Viewed Presentations

  • Information Assurance in a Distributed Forensic Cluster Nick

    Information Assurance in a Distributed Forensic Cluster Nick

    The ability to run legacy software like sculptor, bulk_extractor or AFF would be a bonus. It would be an advantage to be able to handle multiple file system volumes within one real file system . this would enable us to...
  • THE SKELETAL SYSTEM - Highlands High School

    THE SKELETAL SYSTEM - Highlands High School

    THE SKELETAL SYSTEM ... THE SKELETON IS FIBROUS MEMBRANE AND CARTILAGE WHICH ARE FLEXIBLE. (this is important for the fetus to get through the birth canal) fetus just prior to birth HORMONAL IMBALANCES GH (growth hormone) is a hormone that...
  • Welding Safety 29 CFR 1926.350-354 Subpart J PPT-094-01

    Welding Safety 29 CFR 1926.350-354 Subpart J PPT-094-01

    Welding Safety. 29 CFR 1926.350-354. Subpart J. PPT-094-01. Bureau of Workers' Compensation . PA Training for Health & Safety (PATHS) Welding, by its very nature, has the opportunity to injure those actively engaged. Welding can use dual compressed gases or...
  • ภาพนิ่ง 1

    ภาพนิ่ง 1

    * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *...
  • Kantian Ethics

    Kantian Ethics

    A virtue ethicist may argue that Fletcher gives little weight to character, because the entire theory is based on end outcome. In concerning yourself with outcomes, you can easily ignore the wider aspects of being a moral person, acting in...
  • Early Humans Chapter 1 Section 1 Early Humans:

    Early Humans Chapter 1 Section 1 Early Humans:

    Early Humans: Key Terms History is the story of humans in the past, and historians are the people who study and write about humans of the past. Anthropologists study how humans developed and related to each other. Archaeologists hunt for...
  • Methods in Enzymology Aily Qin 1.   1955  60

    Methods in Enzymology Aily Qin 1. 1955 60

    时下备受争论的热点话题转基因食品(gmo)所应用的核心技术就是dna重组 《酶学方法》中关于dna重组的卷册讲述了dna分离,杂交,克隆,突变,基因产物的分离方法以及基因克隆的不同载体系统,比如在酵母细胞中进行基因的克隆等等。
  • Earnings per Share: IAS 33 - MEFielding - Home

    Earnings per Share: IAS 33 - MEFielding - Home

    Convertible instruments are included in the DEPS calculation when dilutive. Convertible preferred shares. Assumed to be anti-dilutive if the related dividend per ordinary share is greater than BEPS. Convertible debt. Anti-dilutive whenever the after-tax interest per ordinary share is greater...