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

Slides:



Advertisements
Similar presentations
Chapter 10 Introduction to Arrays
Advertisements

Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
Week 2: Primitive Data Types 1.  Programming in Java  Everything goes inside a class  The main() method is the starting point for executing instructions.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
JavaScript, Third Edition
Games and Simulations O-O Programming in Java The Walker School
Chapter 5 - Making Music: An On-Screen Piano
Java Unit 9: Arrays Declaring and Processing Arrays.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Section 2 - More Basics. The char Data Type Data type of a single character Example char letter; letter = 'C';
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Repetition in Control flow; Array data structure Chapter 5.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
File Input and Output (I/O) Engineering 1D04, Teaching Session 7.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Week 6 - Friday.  What did we talk about last time?  Loop examples.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
Arrays. Arrays are objects that help us organize large amounts of information.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
String and Lists Dr. José M. Reyes Álamo.
By Melissa Dalis Professor Susan Rodger Duke University June 2011
Lecture 5 array declaration and instantiation array reference
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
CSC 211 Java I for loops and arrays.
Arrays.
Chapter 5 – Making Music: An On-Screen Piano (Part 1 – Using Loops)
EGR 2261 Unit 10 Two-dimensional Arrays
© 2016 Pearson Education, Ltd. All rights reserved.
Foundations of Programming: Arrays
Other Kinds of Arrays Chapter 11
New Structure Recall “average.cpp” program
Arrays, For loop While loop Do while loop
Introduction to C++ Programming
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Arrays versus ArrayList
int [] scores = new int [10];
Java Programming Arrays
Can store many of the same kind of data together
ICT Gaming Lesson 3.
7 Arrays.
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Arrays in Java.
Suggested self-checks: Section 7.11 #1-11
Arrays Arrays A few types Structures of related data items
Arrays.
Week 7 - Monday CS 121.
Introduction to Computer Science
Presentation transcript:

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 */ public void makeKeys() { for (int i = 0; i<12; i++) { addObject (new Key ("g", "3g.wav"), i*63 + 54, 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)

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"

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 0 1 2 3 4 5 6 7 8 9 "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" An array of size N is indexed from zero to N-1

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 [] 0 1 2 3 4 5 6 7 8 9 10 11 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"

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.

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

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

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:

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 ‘\’:

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

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); } 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

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

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

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’:

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], whiteNotes[i],"white"); addObject (key, 40 + 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, 70 + i*63, 86); } } sets white keys spots where you skip a black key sets black keys

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

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 + 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