所以目前,我们的 Key 类只能产生白键。这是因为我已经硬编码了关键图像的文件名(“white-key.png”和“white-key-down.png”)。如何使用抽象来修改 Key 类,以便它可以显示白键或黑键?
import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot)
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()
{
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);
}
}