Reputation: 303
I'm currently trying to make a small chatgame in the Slick2d framework. The framework's got a method called
isKeyPressed()
and a whole long list of variables i can use to check. For instance:
input.KEY_A
Currently the only way i can register a letter, is by having a whole list of those checkers:
if (input.isKeyPressed(input.KEY_A)) {
this.text += "a";
}
if (input.isKeyPressed(input.KEY_B)) {
this.text += "b";
}
if (input.isKeyPressed(input.KEY_C)) {
this.text += "c";
}
Is there any smarter way i can do this?
I could imagine i would be able to store the input.KEYS in an array in some way, but i'm not sure if that is a proper way, and even how to implement it.
Upvotes: 1
Views: 105
Reputation: 328598
You could use a HashMap to store the mapping (!) - Assuming the KEY_XX
are integers, for example, it could look like this:
private static final Map<Integer, String> mapping = new HashMap<Integer, String> () {{
put(input.KEY_A, "a");
put(input.KEY_B, "b");
//etc
}};
for (Map.Entry<Integer, String> entry : mapping.entrySet()) {
if (input.isKeyPressed(entry.getKey()) this.text += entry.getValue();
}
The map can be made static if it is always the same so you only need to populate it once.
Note: this could be more efficient if you had an input.getKeyPressed()
method or something similar.
Upvotes: 2
Reputation: 22171
Map<Integer,Character> keyWithLetterMap = new HashMap<Integer,Character>();
//populates initially the map, for instance: keyWithLetterMap.put(input.KEY_A, 'a');
for (Map.Entry<Integer, Character> keyWithLetter : keyWithLetterMap.entrySet()) {
if(input.isKeyPressed(keyWithLetter.getKey()))
this.text += keyWithLetter.getValue();
}
Otherwise, and even better way, use enum
instead of Map
;)
Upvotes: 1