-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKeypressHandler.java
103 lines (92 loc) · 2.59 KB
/
KeypressHandler.java
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import greenfoot.Actor;
import greenfoot.Greenfoot;
import greenfoot.GreenfootImage;
/**
* KeypressHandler handles key presses and register them to different
* components when needed.
*
* @author Team APCSA 2019
* @author Yijie Gui
* @version 2019-05-21
*/
@SuppressWarnings("WeakerAccess")
public class KeypressHandler extends Actor
{
/** This should contain the key visualizers, in a row */
private final Key[] keys;
/** Key flashes, in a row */
private final KeyFlash[] keyFlashes;
/**
* Constructor for objects of class KeypressHandler
*/
public KeypressHandler()
{
// Create key array
keys = new Key[Constants.NUM_COLS];
// Create key flashes array
keyFlashes = new KeyFlash[Constants.NUM_COLS];
// This actor does not need to have image
setImage((GreenfootImage) null);
}
/**
* Initialize keypress handler.
*/
public void init()
{
// Create keys and initialize
for (int i = 0; i < keys.length; i++)
{
getWorld().addObject(keys[i] = new Key(i, Constants.KEYS[i]), 0, 0);
keys[i].init();
getWorld().addObject(keyFlashes[i] = new KeyFlash(i), 0, 0);
keyFlashes[i].init();
}
}
/**
* Act: Detect key down for all the key buttons and call
* registerKeyPress() if the key is pressed. It basically converts
* Greenfoot.isKeyDown(), which returns a boolean value representing
* if the key is down, to method calls when keys are pressed or
* released.
*/
public void act()
{
// Update key status
for (Key key : keys)
{
boolean keyDown = Greenfoot.isKeyDown(key.getKeyboardButton());
boolean lastDown = key.isPressed();
// Key turned from up to down
if (keyDown && !lastDown)
{
key.setPressed(true);
registerKeyPress(key);
}
// Key turned from down to up
if (!keyDown && lastDown)
{
key.setPressed(false);
registerKeyRelease(key);
}
}
}
/**
* Register a key press.
*
* @param key The key.
*/
private void registerKeyPress(Key key)
{
((BeatmapWorld) getWorld()).getBeatmapController().hit(key.getColumn());
keyFlashes[key.getColumn()].press();
}
/**
* Register a key release.
*
* @param key The key.
*/
private void registerKeyRelease(Key key)
{
keyFlashes[key.getColumn()].release();
}
}