GameCanvas offers an alternate method for responding to key presses, which are expected to be the way for the user to control the game. Instead of passively waiting for the key event callbacks defined in Canvas, GameCanvas offers a method that returns the current state of the keys:
public int getKeyStates()
This is attractive for games because it gives your application more control. Instead of waiting for the system to invoke the key callback methods in Canvas, you can immediately find out the state of the device keys.
The returned integer uses one bit to represent each of the nine game actions. A one bit indicates a key press, while a zero bit indicates no key press. Each of the bits is represented by a constant in the GameCanvas class as shown in Table 11-1.
|
GAMECANVAS BIT CONSTANTS |
CORRESPONDING CANVAS GAME ACTION CONSTANT |
|---|---|
|
UP_PRESSED |
UP |
|
DOWN_PRESSED |
DOWN |
|
LEFT_PRESSED |
LEFT |
|
RIGHT_PRESSED |
RIGHT |
|
FIRE_PRESSED |
FIRE |
|
GAME_A_PRESSED |
GAME_A |
|
GAME_B_PRESSED |
GAME_B |
|
GAME_C_PRESSED |
GAME_C |
|
GAME_D_PRESSED |
GAME_D |
By grabbing the current state of the keys (a technique called polling), you can respond to user actions within the game loop instead of relying on the event callback methods, which run in a different thread. You could expand the example GameCanvas loop presented above as follows to respond to key presses:
Graphics g = getGraphics(); while(true) { // Check for user input. int ks = getKeyStates(); if ((ks & UP_PRESSED) != 0) moveUp(); else if ((ks & DOWN_PRESSED) != 0) moveDown(); // ... // Update game state. // Draw stuff using g. flushGraphics(); }
If you're still paying attention, you're probably wondering what happens when the user presses and release a key between the times when your application calls getKeyStates(). The key states are latched, which means that a key press sets the corresponding bit and makes it stick until the next call to getKeyStates(). Every time you call getKeyStates(), the latched values are all cleared.