1
\$\begingroup\$

Slick2D's Input class has a isKeyPressed() method that returns a boolean value according to whether the specified key has been pressed. I want to check if a key has been released in the same fashion.

I looked into adding a KeyListener to the input object, and overriding the keyReleased() method. However, because I am currently handling input in the update() method of my BasicGame, this would fracture my code by handling input in two different places, which I'd like to avoid.

\$\endgroup\$
1
\$\begingroup\$

So you've got callbacks, but you really want state.

Here's an adapter:

Every frame (or on callbacks), update an associative map (HashMap in Java lingo) that maps from key codes to a status of whether that key was just pressed, is held down or was just released.

// In a `GameState` class

game.onTick()
    // Turn "released" keys off and "pressed" keys "held"
    for k,status of keys
        if status is "pressed"  then keys[k] = "held"
        if status is "released" then keys[k] = null
        // otherwise stay the same

game.onKeyPressed(k)
    keys[k] = "pressed"

game.onKeyReleased(k)
    keys[k] = "released"

Then interrogate that map from everywhere else that cares.

In Java, it'll likely be faster and more readable by refactoring all the state Strings to Enums, but this is is the idea. Of course, implementing getKeyReleased is then a HashMap-access one-liner.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Very cool. I like this solution. \$\endgroup\$ – user2066880 Mar 8 '14 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.