所以目前,我们的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);
}
}
答案 0 :(得分:0)
我从您的问题中了解到,您希望具有不同图像的类,而不是在同一类中更改图像的选项。
有几种方法可以做到这一点;这是一个简单的问题,只是为了给你一个想法:
import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot)
abstract public class Key extends Actor
{
private boolean isDown;
private String key;
private String sound;
abstract String getImageFileName();
abstract String getDownImageFileName();
/**
* 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();
String image = getDownImageFileName();
setImage(image);
isDown = true;
}
if ( isDown && !Greenfoot.isKeyDown(key))
{
String image = getImageFileName();
setImage(image);
isDown = false;
}
}
/**
* Play the note of this key.
*/
public void play()
{
Greenfoot.playSound(sound);
}
}
然后你可以添加新的类,每个类都有自己的图像:
public class WhiteKey extends Key
{
@Override
String getImageFileName()
{
return "white-key.png";
}
@Override
String getDownImageFileName()
{
return "white-key-down.png";
}
}
public class BlackKey extends Key
{
@Override
String getImageFileName()
{
return "black-key.png";
}
@Override
String getDownImageFileName()
{
return "black-key-down.png";
}
}