0
所以目前我们的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);
}
}