This site requires JavaScript, please enable it in your browser!
Greenfoot back
gyrlonfilm
gyrlonfilm wrote ...

2013/5/29

help with piano example in Greenfoot

gyrlonfilm gyrlonfilm

2013/5/29

#
Hi All, I am working on my assignment for school and this question has thrown me for a loop, no pun intended, this chapter is about loops and arrays. I am working on exercise 5.18 (not the same as the book example) and it says: "According to the text, Greenfoot refers to objects by the midpoint of their lengths and widths. Recall that the piano is 800 pixels wide. With this information in mind, copy the new loop code you entered to correctly place the keys in the space below. Rewrite it (in this document only—not in your working Greenfoot program) to create the keys from right to left, instead of left to right, and force the rightmost key to be flush against the right side of the screen. The remaining keys should be next to each other, with no space between them." I am confused in general how the program knows that the keys are set from left to right in the first place. Where in the code would you see this? Here is the code example from the piano class: import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot) /** * A piano that can be played with the computer keyboard. * * @author: M. Kolling * @version: 0.1 */ public class Piano extends World { /** * Make the piano. */ public Piano() { super(800, 340, 1); makeKeys(); } /** * This method makes the below keys when compile is hit or the program opens. */ private void makeKeys() { int i = 0; while (i < 12) { addObject (new Key ("g", "3a.wav"), i*63 + 54, 140); i = i + 1; } } } Here is the key class: import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot) /** * A key on a piano keyboard. This key is associated with a keyboard * key and a sound file, which is played when the key is pressed. * * @author: M. Kolling * @version: 0.3 */ public class Key extends Actor { private boolean isDown; private String key; private String sound; /** * Create a new key linked to a given keyboard key, and * with a given sound. */ public Key(String keyName, String soundFile) { key = keyName; sound = soundFile; } /** * Do the action for this key. */ public void act() { if (!isDown && Greenfoot.isKeyDown(key)) { play(); setImage ("white-key-down.png"); isDown = true; } if (isDown && !Greenfoot.isKeyDown(key)) { setImage ("white-key.png"); isDown = false; } } /** * Play the note of this key. */ public void play() { Greenfoot.playSound(sound); } }
danpost danpost

2013/5/29

#
gyrlonfilm wrote...
I am confused in general how the program knows that the keys are set from left to right in the first place. Where in the code would you see this?
I am confused in general how the program knows that the keys are set from left to right in the first place. Where in the code would you see this? I bolded the key words, no pun intended.
You need to login to post a reply.