Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 – Making Music: An On-Screen Piano (Part 2 – Using Arrays)

Similar presentations


Presentation on theme: "Chapter 5 – Making Music: An On-Screen Piano (Part 2 – Using Arrays)"— Presentation transcript:

1 Chapter 5 – Making Music: An On-Screen Piano (Part 2 – Using Arrays)

2 Creating a Music Simulation:

3 Placing Multiple keys by using a for-loop
/** * Create the Piano Keys */ public void makeKeys() { for (int i = 0; i<12; i++) { addObject (new Key ("g", "3g.wav"), i* , 140); } For loop that iterates 12 times Position on the Piano is depend on the current value of i (plus a fixed offset value) Creating a new Key object using fixed letter and fixed soundfile (for now)

4 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: Note File Name: "a" "3a.wav" "b" "3b.wav" "c" "3c.wav" "d" "3d.wav “ "e" "3e.wav" "f" "3f.wav “ "g" "3g.wav"

5 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 keyNames The entire array has a single name Each value has a numeric index "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" An array of size N is indexed from zero to N-1

6 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 0 to 11 “a” “b” “c” “d” “e” “l” “k” “j” “i” “h” “g” “f” String [] 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" keyNames[3] contains the string "d"

7 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 = { , , , }; boolean [] answerKey = { true, false, true, true, false }; char [] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' }; String [] names = { "John", "Doe", "Mary", "Lamb" };

8 The length of Arrays int [] scores = { 95, 100, 85, 80, 90, 75, 100 }; double [] payments = { , , , }; 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.

9 These arrays are being declared
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; 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 don’t have to do this. These arrays are being declared but they are not being given any values yet

10 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.

11 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]);

12 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: scores[i] = 0;

13 Consecutive Keyboard Keys
On a computer keyboard it doesn’t 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:

14 Consecutive Keyboard Keys
There are 7 notes in the C major scale octaves: C–D–E–F–G–A–B 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 ‘\’:

15 Consecutive Keyboard Keys Using Arrays
Backslash is an escape character for other keys like “\b” or “\n”, so you use “\\” to treat it just as a backslash Consecutive Keyboard Keys Using Arrays the tab key 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

16 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, i*63, 140); } We moved the creation of a new key out of the addObject method to make it make it easier to read Sending the name of each key and each note to the constructor

17 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, i*63, 140); } String concatenation: Two Strings are combined, using the “+” symbol. This again results in a String.

18 Code to set up the White Keys

19 14 White Keys each with a Different Note:

20 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;

21 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"; setImage(upImageFile); } Change the Key Class so That It Can Make Either White or Black Keys for Up and Down key images Makes sure that the right Up-Image is showing

22 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); play(); isDown = true; } if ( isDown && !Greenfoot.isKeyDown(key) ) { setImage(upImageFile); isDown = false; white/black-key-down.png white/black-key.png

23 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, we’ll need another 10 consecutive keys. Black keys go above white keys, so let’s use the numeric keys on the first row: ‘1’, ‘2’, ‘3’ and so on up to ‘0’:

24 14 White Keys and 10 Black Keys Each with a Different Note:
First key. Skipped keys.

25 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 }

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

27 14 White Keys and 10 Black Keys Each with a Different Note:

28 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;

29 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 we’ll use a variable called isPushed to keep track like isDown did for isKeyDown(), and we’ll add a call to checkMouse() to our act() method: private boolean isPushed = false; public void checkMouse() { if ( !isPushed && Greenfoot.mouseClicked(this) ) { setImage(downImageFile); play(); isPushed = true; } if ( isPushed && !Greenfoot.mouseClicked(this) ) { setImage(upImageFile); isPushed = false; call this from the act() method

30 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 key-down 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, we’ll record in milliseconds when that happened (using System.currentTimeMillis()): keyDownTime = System.currentTimeMillis(); Then we won’t show the key up image until 1/5th of a second has passed, which is 200 milliseconds. So we won’t show the key up image until System.currentTimeMillis() is greater than keyDownTime

31 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;

32 Concept Summary


Download ppt "Chapter 5 – Making Music: An On-Screen Piano (Part 2 – Using Arrays)"

Similar presentations


Ads by Google