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

2015/10/19

Piano Scenario

Mack Mack

2015/10/19

#
hey guy, so I'm using the piano scenario. I been going at it for hours and I'm staring to get frustrated. I need help entering a couple codes please. 1. Create a new String variable, sound, for the Key class. Variable 'sound' will hold the name of the sound file. 2. Add a parameter to the Key constructor. 3. Set the value of the new variable sound to the parameter in the constructor. this is the code I have entered already.
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)

public class Key extends Actor
{
    //This variable holds whether or not the key is already down
    private boolean isDown;
    // This variable holds the image that the key will have when it is up
    private String upPicture;
    // This variable holds the image that the key will have when it is down
    private String downPicture;
    // This variable holds what key on the keyboard this key represents.
    private String key;
    // This variable holds the sound that the key will play (including the file extension)
    // PUT YOUR CODE HERE
    
    /**
     * Create a new key.
     */
    public Key(String inputKey)
    {
        // Set the up picture
        upPicture = "white-key.png";
        // Set the down picture
        downPicture = "white-key-down.png";
        // Set the key to "up" by default
        setImage(upPicture);
        isDown = false;
        // Assign a letter from the keyboard to the key. The value will be sent to it 
        // via the parameter list in the constructor, and that will be set in the Piano class
        key = inputKey;
    }

    /**
     * Do the action for this key.
     */
    public void act()
    {   /**
         * isDown == false is the same thing as !isDown
        */
       if(Greenfoot.isKeyDown(key))
       {
           play();
       }
       if(!isDown && Greenfoot.isKeyDown(key))
       {
            setImage(downPicture);
            isDown = true;
       }
       else if(isDown && !Greenfoot.isKeyDown(key))
       {
            setImage(upPicture);
            isDown = false;
       }
    }
    
    /**
     * This method plays the sound for the key
     */
    public void play()
    {
        Greenfoot.playSound("2g.wav");
    }
}
danpost danpost

2015/10/19

#
It would be similar to how the key field is declared, how its value is accepted and saved in the field by the constructor.
You need to login to post a reply.