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);
    }
}
4

1 回答 1

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";
    }
}
于 2015-12-28T15:59:41.683 回答