-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
124 lines (102 loc) · 1.64 KB
/
index.js
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*!
*
* arrows
*
* MIT
*
*/
/**
* Module dependencies.
*/
var Keys = require('keys');
var merge = require('merge');
/**
* Control flags.
*/
var ctrl = {
left: 1,
up: 2,
right: 4,
down: 8,
shoot: 16
};
/**
* Opposite directions flags.
*/
var opp = {
1: 4,
2: 8,
4: 1,
8: 2
};
/**
* Keymap.
*/
var map = {
37: ctrl.left,
38: ctrl.up,
39: ctrl.right,
40: ctrl.down,
16: ctrl.shoot, // shift
17: ctrl.shoot, // ctrl
88: ctrl.shoot, // x
90: ctrl.shoot // z
};
/**
* Arrows.
*
* @return {Object}
* @api public
*/
module.exports = function(){
// bitmasks
var down = 0;
var keys = 0;
// construct keys handler using `map`
var arrows = Keys(map);
// listen on keystrokes
arrows.on('keydown', onkeydown);
arrows.on('keyup', onkeyup);
/**
* Returns the `keys` bitmask when evaluated,
* to use with logical operations.
*
* @return {Number} keys
* @api public
*/
arrows.valueOf = function(){
return keys;
};
// merge control flags to
// use with logical operations
// i.e: arrows & arrows.left && left()
merge(arrows, ctrl);
return arrows;
/**
* Keydown handler.
*
* @param {Event} event
* @param {Number} key
* @api private
*/
function onkeydown(event, key){
// OR `key`
keys = down |= key;
// recent opposite `key` takes precedence
// so XOR old from the `keys` bitmask
if (keys & opp[key]) {
keys ^= opp[key];
}
}
/**
* Keyup handler.
*
* @param {Event} event
* @param {Number} key
* @api private
*/
function onkeyup(event, key){
// XOR `key`
keys = down ^= key;
}
};