aboutsummaryrefslogtreecommitdiff
path: root/src/ch/epfl/xblast/client/KeyboardEventHandler.java
blob: 2060959da86edbebad5a25051d785000e0c42c66 (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
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.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 {

    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;
    }

    /**
     * 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);
    }

}