P.49 (Add pressKey and playSong Method to Piano Class)


private void pressKey(int i) {
  if(i >= 0 && i < 90) {
    if(i <= 20)
      pianoWhiteKey[i].whiteKeyDownUp(); // i <= 20 are for white keys
    if(i >= 50 && i != 52 && i != 56 && i != 59) 
      pianoBlackKey[i-50].blackKeyDownUp(); // i >= 50: some are for black keys
  }
}
  
public void playSong() {
  // Sound of Music
  int[] notes =  
      {1,1,2,3,99,1,3,1,3,99,2,3,4,4,3,2,4,99,3,4,5,99,3,
       5,3,5,99,4,5,6,6,5,4,6,99,5,99,1,2,3,4,5,6,99,6,
       99,2,3,54,5,6,7,99,7,99,3,54,55,6,7,8,99,8,7,56,6,
       4,7,5,8,5,3,2,0};
  
  int i = 0;  
  while(notes[i] != 0) {
    if((notes[i] >= 1 && notes[i] <= 12) || (notes[i] >= 51 && notes[i] <= 61))
      pressKey(notes[i]-1);
    else 
      Greenfoot.delay(15);
    i++;
  }
}
Last modified on
Engineering DIY Workshop 2018