I may be doing this in a completely horrible way, but my idea for my game engine is to create a list that a user can add a KeyMap object to. So, I have a KeyMap class and a KeyMaps class, as shown:
KeyMap
public class KeyMap implements KeyListener
{
public void keyPressed(KeyEvent arg0) {}
public void keyReleased(KeyEvent arg0) {}
public void keyTyped(KeyEvent arg0) {}
}
KeyMaps
public class KeyMaps extends JComponent
{
// Contains this object
private static KeyMaps listOfKeyMaps;
// Contains a list of KeyMap objects linked by a
// KeyMap title
private HashMap<String, KeyMap> keyMaps;
// Contains the current KeyMap to use
private KeyMap activeKeyMap;
private KeyMaps()
{
keyMaps = new HashMap<String, KeyMap>();
activeKeyMap = new SystemKeyMap();
addKeyMap ("System", activeKeyMap);
setActiveKeyMap ("System");
}
public static KeyMaps getInstance()
{
if (listOfKeyMaps == null) {
synchronized (KeyMap.class) {
if (listOfKeyMaps == null)
listOfKeyMaps = new KeyMaps();
}
}
return listOfKeyMaps;
}
public void setActiveKeyMap(String newKeyMap)
{
if (keyMaps.containsKey(newKeyMap)) {
removeKeyListener (activeKeyMap);
activeKeyMap = keyMaps.get (newKeyMap);
addKeyListener (activeKeyMap);
}
}
public boolean addKeyMap(String keymapName, KeyMap km)
{
if (keyMaps.containsKey (keymapName))
return false;
else {
keyMaps.put (keymapName, km);
return true;
}
}
public boolean removeKeymap(String keymapName)
{
if (keyMaps.containsKey (keymapName))
return false;
else {
keyMaps.remove (keymapName);
return true;
}
}
}
As you can see, my idea is for the user to be able to create a set of KeyListeners to handle KeyEvents. The KeyMaps class would hold this list while maintaining a single active KeyMap, and the ability to easily switch between them (So, you can have a different KeyMap for gameplay, the main menu, mini-games, etc.) My issue is that, I don’t think this works for a reason I’m not aware of. I created a simple KeyMap that exits the program if the use presses esc:
public class SystemKeyMap extends KeyMap
{
public void keyReleased(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ESCAPE)
System.exit (0);
}
}
You can see in the KeyMaps class that this is automatically created and activated upon starting the program. This is how I’ve implemented it into the actual game:
public abstract class Game
{
// The game window
private Screen screen;
// The container for all graphics
private Canvas canvas;
// Contains a list of KeyMaps
private KeyMaps keymaps;
/**
* Initializes the game window
*/
public Game()
{
super();
screen = new Screen();
canvas = new Canvas();
screen.add (canvas);
keymaps = KeyMaps.getInstance();
}
Nothing happens when I press the ESC button. Could I get some insight on why that is?