This site requires JavaScript, please enable it in your browser!
Greenfoot back
4SeaBass
4SeaBass wrote ...

2015/10/28

How to make the white keys respond to different keys on the piano scenario.

4SeaBass 4SeaBass

2015/10/28

#
I am a beginner and i can't seem to rap my mind around how to make the individual white keys respond to a different key. I put the parameters in but i don't know what to do now? The book says change out the "g"'s for the parameters but i don't understand how to do it?
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)

/**
 * Piano "key" class definition.
 */
public class Key extends Actor
{
    private boolean isDown;
    private String key;
    private String sound;
    /**
     * Create a new key linked to a given keyboard key,
     * and with a given sound.
     */
    
    public Key(String keyName, String soundFile)
    {
        key = keyName;
        sound = soundFile;
    }

    /**
     * Key action method.
     */
    public void act()
    {
        pianoKeys();
    }
    
    public void play()
    {
        Greenfoot.playSound("3a.wav");
    }
    
    public void pianoKeys()
    {
        if (!isDown && Greenfoot.isKeyDown("g"))
        {
            setImage("white-key-down.png");
            isDown = true;
            play();
        }
        
        if (isDown && !Greenfoot.isKeyDown("g"))
        {
            setImage("white-key.png");
            isDown = false;
        }
    }
}
davmac davmac

2015/10/28

#
In the constructor, you can see that the 'keyName' parameter is saved to the 'key' variable (line 18):
        key = keyName;
So, you can retrieve the parameter value using the 'key' variable - where there is currently '"g"' you should replace it with the 'key' variable. So on line 37 for example:
        if (!isDown && Greenfoot.isKeyDown(key))
4SeaBass 4SeaBass

2015/10/28

#
Ok thx! I will try it and see if it helps!
You need to login to post a reply.