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

2015/7/23

How does this value work?

aromero2 aromero2

2015/7/23

#
I'm working on a piano exercise in which when you press a key in the keyboard the sound only play's once and not continuously...below is the code. However I'm having trouble understanding how the private boolean is down works in all of this within the loops. I know it prevents from having the sound play continuously
    public void act()
    {
        if ( !isDown && Greenfoot.isKeyDown("g"))
        {
            isDown = true; // just played a note
            setImage("white-key-down.png");
            Greenfoot.playSound("3a.wav");
        }
        
        if ( isDown && !Greenfoot.isKeyDown("g"))
        {
            isDown = false;
            setImage("white-key.png");
            
        }
        
        /****
        if (Greenfoot.isKeyDown("g"))
        {
            setImage("white-key-down.png");
            Greenfoot.playSound("3a.wav");
        }
        else
        {
            setImage("white-key.png"); ****/
        }
if the g key is kept pressed but I need someone to help me understand the "Why or How" it works, please?
gulzaibthegreat1 gulzaibthegreat1

2015/7/23

#
Your checking to see if the g key is pressed and if it is you set the 'isDown' boolean to true IF it is false and plays the note. BASICALLY this is saying that only play the note if the key was not down before. The isDown stays true now until the key is released. Since the boolean is true the sound will not play. When you release the key the isDown boolean is set to false saying you can click the key to create a sound again.
danpost danpost

2015/7/23

#
To put it another way, the 'isDown' boolean field tracks the last state of the key. The two compound 'if' conditional expressions are checking to see if the current state is not the last state and the value of 'isDown' is changed when there is a change in the state of the key (by way of the code in each 'if' code block, maintaining its proper value). The code could be written this way:
if (isDown != Greenfoot.isKeyDown("g")) // if change in state of key
{
    isDown = ! isDown; // maintain tracking field
    if (isDown) // key was pressed
    {
        setImage("white-key-down.png");
        Greenfoot.playSound("3a.wav");
    }
    else // key was released
    {
        setImage("white-key.png");
    }
}
The last 8 lines of code is close to the code you have commented out (starting at line 19).
aromero2 aromero2

2015/7/24

#
Awesome! Thanks, guys.
You need to login to post a reply.