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

2012/10/5

Getting the black keys spaced evenly on the piano

Llama Llama

2012/10/5

#
As the title says, I am having trouble getting the black keys space evenly without hard coding it. If anyone could help it would be greatly apreciated. Here is my code :
public class Piano extends World
{
    private String[] whiteKeys =
        { "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "\\" };
    private String[] whiteNotes =
        { "3c", "3d", "3e", "3f", "3g", "3a", "3b", "4c", "4d", "4e", "4f", "4g" };
    private String [] blackKeys =
        { "w", "e", "", "t", "y", "u", "", "o", "p", "", "]" } ;
    private String [] blackNotes = 
        { "3c#", "3d#", "", "3f#", "3g#", "3a#", "", "4c#", "4d#", "", "4f#" }; 
        
    /**
     * Make the piano. This means mostly, apart from defining the size,
     * making the keys and placing them into the world.
     */
    public Piano() 
    {
        super(800, 340, 1);
        makeKeys();
        createMessage();
    }
    
    /**
     * Create the piano keys and place them in the world.
     */
    private void makeKeys() 
    {
        
       
        for(int i = 0; i < whiteKeys.length; i++) {
            Key key = new Key(whiteKeys[i], whiteNotes[i]+".wav", "white-key.png", "white-key-down.png");
            addObject(key, i *key.getImage().getWidth() + key.getImage().getWidth(), key.getImage().getHeight() / 2);
            
        }
        for(int i = 0; i < whiteKeys.length-1; i++) {
            if( ! blackKeys[i].equals("") ) {
                Key key = new Key(blackKeys[i], blackNotes[i]+".wav", "black-key.png", "black-key-down.png");
                addObject(key, i *key.getImage().getWidth() + key.getImage().getWidth() * 2, key.getImage().getHeight() / 2);
            }
        }
    }
   public void createMessage()
   {
       GreenfootImage bg = getBackground();
       bg.drawString("Use keys 'a' to ':' and keys 'q', 'e', 't', 'y', 'u', 'o', 'p', ] to play the piano", 225, 300);
       
    }
}
danpost danpost

2012/10/5

#
The spacing between the black keys will be exact same amount as what you use for the white keys. The only difference will be that the offset will be one half the width of a white key more.
You need to login to post a reply.