2 Copyright (c) 2009 Hanno Braun <hanno@habraun.net>
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
19 package net
.habraun
.kong
.input
23 import scala
.collection
.immutable
._
33 * Used to define player-key mappings. A fully configured instance of this class is needed for KeyHandler to
36 * This class is supposed to be used like this:
37 * // Define your players.
38 * object RedPlayer extends Player
39 * object BluePlayer extends Player
41 * // Define the keys. These are logical keys like "steer left", "steer right" or "fire", not the actual keys
43 * object LeftKey extends Key
44 * object RightKey extends Key
45 * object FireKey extends Key
47 * // Now that we know our keys and our players we can define the mappings between players, keys and physical
49 * val keyMap = (new KeyMap)
50 * .addMapping(RedPlayer, LeftKey, KeyEvent.VK_A) // the 'a' key steers red player to the left
51 * .addMapping(RedPlayer, RightKey, KeyEvent.VK_D) // the 'd' key steers the red player to the right
52 * .addMapping(RedPlayer, FireKey, KeyEvent.VK_W) // red player fires with 'w' key
53 * .addMapping(BluePlayer, LeftKey, KeyEvent.VK_LEFT) // define left key for blue player
54 * .addMapping(BluePlayer, RightKey, KeyEvent.VK_RIGHT) // ...
55 * .addMapping(BluePlayer, FireKey, KeyEvent.VK_UP)
57 * // Initialize the key handler.
58 * val keyHandler = new KeyHandler(keyMap)
60 * The KeyEvent class mentioned in the example is java.awt.event.KeyEvent from the Java standard library.
63 case class KeyMap(mappings
: Map
[Player
, Map
[Key
, Int
]]) {
66 this(new HashMap
[Player
, Map
[Key
, Int
]])
72 * Returns a copy of this key map with the given mapping added.
73 * Attention: Since KeyMap is immutable this will return a new KeyMap, it won't change the one you're
74 * calling this method on.
75 * Please check the description of this class for usage examples.
78 def addMapping(player
: Player
, key
: Key
, keyCode
: Int
): KeyMap
= {
79 val keysForPlayer
= if (mappings
.contains(player
)) mappings(player
) else new HashMap
[Key
, Int
]
80 KeyMap(mappings
.update(player
, keysForPlayer
+ (key
-> keyCode
)))