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

2012/3/8

chapter 5 piano

wahaj wahaj

2012/3/8

#
im on chapter five in the book and i dont seem to understand how it is programmed. there are several commands i dont understand. ill list the code for "key"(actor) below 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()
    {
        keyAnimation();
        
    }
    public void keyAnimation()
    {
        if (!isDown && Greenfoot.isKeyDown(key) )
        {
            setImage("white-key-down.png");
            isDown = true;
            play();
        }
        if ( isDown && !Greenfoot.isKeyDown(key) )
       
        {
            setImage("white-key.png");
            isDown = false;
        }
    }
    public void play()
    {
        Greenfoot.playSound(sound);
    }

}
i dont understnad why public Key(String keyName, String soundFile ) has what it has in the parentheses. why is it there and what does it do? i dont think soundFile is an actual command so why is it equal to the variable sound? also in the end in the code Greenfoot.playSound(sound); why is the sound in the parantheses?
sp33dy sp33dy

2012/3/8

#
Hi, Although I've not read the book, this is pretty straight forward java. Basically: public Key(String keyName, String soundFile) is the constructor for the Key Actor. Basically, when you create a new Key, you do so by: new Key(<keyName>,<soundFile>); For example: new Key("A","whistle.wav"); Now, that constructing method, put's the string "A" into the class variable key and the sound file name into sound class varilable (lines 6 & 7). If you then look at line 28, the if statement looks to see if key pressed is the value in the key class variable (i.e. you constructed this Actor with "A"), so it looks for "A". If it is, the method play() is called. If you look at this method at line 41, it calls the playSound method, passing in the sound class varilable you populated with the second parameter to the constructor. This is a good design because you can create several Key Actors with different assignments, i.e.: new key("A","sound1.wav"); new Key("B","sound2.wav"); and so on. Hope this helps.
You need to login to post a reply.