aboutsummaryrefslogtreecommitdiff
path: root/src/ch/epfl/xblast/client/KeyboardEventHandler.java
blob: ab64c80771f5f5e08113b919cd27bc98f3742070 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package ch.epfl.xblast.client;

import ch.epfl.xblast.Lists;
import ch.epfl.xblast.PlayerAction;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * The game action keyboard event handler.
 *
 * @author Timothée FLOURE (257420)
 * @author Pacien TRAN-GIRARD (261948)
 */
public class KeyboardEventHandler extends KeyAdapter {

    /**
     * The default key->action mapping.
     */
    private static final Map<Integer, PlayerAction> DEFAULT_KEY_MAP = buildDefaultKeyMap();

    private static Map<Integer, PlayerAction> buildDefaultKeyMap() {
        Map<Integer, PlayerAction> playerActionMap = new HashMap<>();

        playerActionMap.put(KeyEvent.VK_UP, PlayerAction.MOVE_N);
        playerActionMap.put(KeyEvent.VK_RIGHT, PlayerAction.MOVE_E);
        playerActionMap.put(KeyEvent.VK_DOWN, PlayerAction.MOVE_S);
        playerActionMap.put(KeyEvent.VK_LEFT, PlayerAction.MOVE_W);
        playerActionMap.put(KeyEvent.VK_SPACE, PlayerAction.DROP_BOMB);
        playerActionMap.put(KeyEvent.VK_SHIFT, PlayerAction.STOP);

        return Collections.unmodifiableMap(playerActionMap);
    }

    private final Map<Integer, PlayerAction> playerActionMap;
    private final Consumer<PlayerAction> consumer;

    /**
     * Instantiates a new KeyboardEventHandler.
     *
     * @param playerActionMap the map of key codes to PlayerAction.
     * @param consumer        consumer related to the EventHandler
     */
    public KeyboardEventHandler(Map<Integer, PlayerAction> playerActionMap, Consumer<PlayerAction> consumer) {
        this.playerActionMap = Lists.immutableMap(playerActionMap);
        this.consumer = consumer;
    }

    /**
     * Instantiates a new KeyboardEventHandler with the default key mapping.
     *
     * @param consumer consumer related to the EventHandler
     */
    public KeyboardEventHandler(Consumer<PlayerAction> consumer) {
        this(DEFAULT_KEY_MAP, consumer);
    }

    /**
     * Executes the command related to the given key code.
     *
     * @param e event (pressed key)
     */
    @Override
    public void keyPressed(KeyEvent e) {
        PlayerAction act = this.playerActionMap.get(e.getKeyCode());

        if (Objects.nonNull(act))
            this.consumer.accept(act);
    }

}