Hi guys, I'm having a bit of trouble with 5.18. Here's the question:
Using fixed numbers in your code, such as the 140 or 63 in the statement above, is usually not the best solution, since it makes your code vulnerable to breaking when things change. For example, if we replace the key images with nicer images that have a different size, our code would not place them correctly. We can avoid using those numbers directly by calling the getWidth() and getHeight() methods of the key’s image. To do this, first assign the key object to a local variable of type Key when you create it, and then use key.getImage().getWidth()
in place of the 63. Do a similar thing with the height. Replacing the 54 requires you to also use the getWidth() method ofthe piano’s image. After doing this,our code will always place the keys nicely,even if their size changes.
Now, my idea in pseudo code was this:
getImage from Key object
Store that image in new local variable within the method for making keys
use getWidth and getHeight on local variable
replace magic numbers in the current method with the getWidth and getHeight method
However, I can't figure out how to extract the image file from the Key object. Does anyone with the book know what to do? Here's the code for both classes:
public class Key extends Actor { private boolean isDown; private String key; private String sound; /** * Create a new key. */ public Key(String keyName, String soundFile) { key = keyName; sound = soundFile; } /** * Do the action for this key. */ public void act() { keyPress(); } public void keyPress() { if (!isDown && Greenfoot.isKeyDown(key)) { setImage ("white-key-down.png"); isDown = true; play(); } if (isDown && !Greenfoot.isKeyDown(key)) { setImage ("white-key.png"); isDown = false; } } public void play() { Greenfoot.playSound(sound); } }
public class Piano extends World { /** * Make the piano. */ public Piano() { super(800, 340, 1); makeKeys(); } public void makeKeys() { for(int i = 0; i<12; i++) { addObject (new Key ("g", "3a.wav"), i*63 + 54, 140); } } }