Where Should I Poll For Input?

Hi, this is my first time posting and I am relatively inexperienced with programming computer games. I have been learning in part from cokeandcode’s Space Invaders tutorials. I have lesson 104 downloaded and I am attempting to build something from scratch using it as a guideline. This tutorial and my program use LWJGL.

My question is: What is the best way to implement polling? Where should I put it?
The parts of my code which relate to my question are as follows:

Interfaces:

  • GameWindow – describes the game window; tells Game when to act using a Callback interface; the game loop runs here.

Classes:

  • Game (implements Callback) – the main hook; tells stuff what to do.
  • PlayerEntity (extends Entity) – an entity I want to move when keys are pressed.

In the original source, cokeandcode implements the key polling in a very simple way:

Inside Game:


GameWindow window = getGameWindow();

boolean leftPressed = window.isKeyPressed(KeyEvent.VK_LEFT);
boolean rightPressed = window.isKeyPressed(KeyEvent.VK_RIGHT);
boolean firePressed = window.isKeyPressed(KeyEvent.VK_SPACE);

Inside LWJGLGameWindow (implements GameWindow):


public boolean isKeyPressed(int keyCode) {
		switch(keyCode) {
		case KeyEvent.VK_SPACE:
			keyCode = Keyboard.KEY_SPACE;
			break;
		case KeyEvent.VK_LEFT:
			keyCode = Keyboard.KEY_LEFT;
			break;
		case KeyEvent.VK_RIGHT:
			keyCode = Keyboard.KEY_RIGHT;
			break;
		}
		return org.lwjgl.input.Keyboard.isKeyDown(keyCode);
	}

I know about Keyboard.next(), and I would like to use that. Should I put it in GameWindow or in Game? Or should I forgo LWJGL input and create a key listener?

I’d recommend you have a read of the LWJGL Basics Input Tutorial, it should give you a good idea on how to use input (Just read all 5 parts of the LWJGL Basics Tutorials for an overview of the LWJGL API).

I read those, was just wondering where the best place in the code to implement the code. I am guessing that it’s not too important, so I came up with something I like. Please tell me if there are any major problems with this:

  • Each time through game loop, poll for keys.
  • For every key event, add or remove the key’s keycode from an ArrayList (if the keycode is in the list, it implies that it is pressed)
  • If I want to check for a key, use function isKeyPressed(keyCode), which use ArrayList.contains() to see if the key is held down