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

2016/12/4

Check if a series of keys was pressed

LimeLava LimeLava

2016/12/4

#
For my game I want to make a simple Easter egg and so I want to check if someone has put in the konami code (Up, Up, Down, Down, Left, Right, Left, Right, B, A, Enter) and if that series of keys is pressed in that order it will spawn an Easter Egg. But KeyIsDown would not work for that.
danpost danpost

2016/12/4

#
In order to check for a sequence of keys like that, you will need to use 'getKey' -- not 'isKeyDown' (if you are only checking for the next key in the sequence, you are not checking for an incorrect key). I would start with a constant String array for the sequence:
1
2
3
4
5
6
private static final String[] konamiKeys =
{
    "up", "up", "down", "down",
    "left", "right", "left", "right",
    "b", "a", "enter"
};
and add an instance field to track the progress (an int field to point at the next key in the sequence to be detected):
1
private int keyIndex = 0;
then the act method can track the progress of the entered key sequence and act upon correct and incorrect keys, as well as completing the sequence.
LimeLava LimeLava

2016/12/6

#
So I didn't really know how to do what you said so I improvised but I had a problem. What I did was create a int variable for the keys and then added 1 to it every time someone hit the key so that when they finished hitting it it would reach a certain score and add the Easter egg. But the problem is that someone could just press one of the keys over and over again till they reached the number needed is there a way I could limit the one key press to only count one time or only count if it comes after another key?
danpost danpost

2016/12/6

#
LimeLava wrote...
What I did was create a int variable for the keys and then added 1 to it every time someone hit the key
This is the idea behind the 'keyIndex' field I had given above. However, it should only be incremented when the next key in the sequence is detected:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
String key = Greenfoot.getKey();
if (key != null) // is key detected
{
    if (konamiKeys[keyIndex].equals(key)) // is next key in sequence
    {
        if (++keyIndex == konamiKeys.length) // is last key in sequence
        {
            addObject(new EasterEgg(), << wherever >>);
        }
    }
    else // not in sequence -- start over
    {
        keyIndex = 0;
    }
}
You need to login to post a reply.