Handling key inputs for action game

Hello there.

I am working on a side scrolling action game. I have a parent class that runs a thread for main loop(active rendering). Then I have an extended thread class for key repeats. Is it a legit idea to separate threads for main loop and key input (key repeater)?

Edited: What are some general ways to implement key repeater class? Just ideas, you don’t have to write the whole code.

What do you mean by “key repeater”?

The usual way is to use have 1 thread for the game loop and use the EDT for input events.

For absolute synchronization, you could make your own queue that events would be added to, and they would be processed in the game loop.

Sure, the game loop and IO (including getting key inputs) can different threads. But IO will be part of the EDT, as it uses Swing.

To get info from the key input to the game loop, you would use “loose coupling,” i.e., collect/place the key values in an intermediate variable or array that the game loop can inspect on an as-needed basis.

Due to concurrency issues (it is impossible to predict when a value set in one thread will be readable in another thread) the intermediate variable should either be volatile or the accesses should use synchronization to guarantee visibility.

http://download.oracle.com/javase/tutorial/essential/concurrency/sync.html


ArrayList<Integer> keysPressed;

publc void keyPressed(KeyEvent e)
{
    if (!keysPressed.contains(new Integer(e.getKeyCode()))
    {
        keysPressed.add(new Integer(e.getKeyCode()));
    }
}

public void keyReleased(KeyEvent e)
{
    keysPressed.remove(new Integer(e.getKeyCode()));
}

public void mainLoop()
{
    for (int i = 0; i < keysPressed.size(); i++)
    {
        int key = keysPressed.get(i).intValue();

        if (key == KeyEvent.VK_LEFT)
        {
            player.x -= 5;
        }
        //etc.
    }
}

ra4king
According to a game programming framework algorithm book that I read, it uses a class named as KeyRepeater to control the occurrence of inputs and delay from first key input to the next consecutive key repeats (holding the key). It would sleep for a time between an input to another. The main game loop thread sleeps for a fixed time like 20 millisec.

I implemented this key repeater class to my code, but it wouldn’t match with my main game loop. The code I have right now is doing what you said. I added some counter variables and if’s to implement key delay from first input.

philfrei
I was wondering if synchronization was what I was missing. I definitely have to read into that.

Eli Delventhal
Thanks for sharing a code. I did that with Queue.

Everyone, thanks for comments.