-
Notifications
You must be signed in to change notification settings - Fork 0
/
Keyboard.lua
87 lines (72 loc) · 2.35 KB
/
Keyboard.lua
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
-- Import
local math = math
local pairs = pairs
local string = string
local Class = require "Class"
local RingBuffer = require "RingBuffer"
local Keyboard = Class{
bufferSize = 0,
inputBuffer = nil
}
setfenv(1, Keyboard)
local keys = {
up = "up",
down = "down",
left = "left",
right = "right",
z = "z",
x = "x"
}
-- Key state data structure
local KeyState = Class{pressed = false}
-- Keyboard state data structure -- keeps track of every key in the keyboard
local KeyboardState = Class{}
function KeyboardState:init()
for key, value in pairs(keys) do
self[value] = KeyState()
end
end
function Keyboard:init(bufferSize)
self.inputBuffer = RingBuffer(bufferSize)
self.inputBuffer:insertElement(KeyboardState())
self.inputBuffer:insertElement(KeyboardState())
end
function Keyboard:update()
self.inputBuffer:insertElement(self.inputBuffer:headElement():clone())
end
function Keyboard:updateKey(key, keyState)
if keys[key] then
self.inputBuffer:headElement()[key].pressed = keyState
end
end
function Keyboard:keyPressed(key, frameTolerance)
if not frameTolerance then frameTolerance = 0
elseif frameTolerance > self.inputBuffer:size() - 1 then frameTolerance = self.inputBuffer:size() - 1 end
for i, state in RingBuffer.reverseIterator(self.inputBuffer, frameTolerance) do
if state[key].pressed then
return true
end
end
return false
end
function Keyboard:keyJustPressed(key, frameTolerance)
if not frameTolerance then frameTolerance = 0
elseif frameTolerance > self.inputBuffer:size() - 2 then frameTolerance = self.inputBuffer:size() - 2 end
for i, state in RingBuffer.reverseIterator(self.inputBuffer, frameTolerance) do
if state[key].pressed and not self.inputBuffer:getElement(i - 1)[key].pressed then
return true
end
end
return false
end
function Keyboard:keyJustReleased(key, frameTolerance)
if not frameTolerance then frameTolerance = 0
elseif frameTolerance > self.inputBuffer:size() - 2 then frameTolerance = self.inputBuffer:size() - 2 end
for i, state in RingBuffer.reverseIterator(self.inputBuffer, frameTolerance) do
if not state[key].pressed and self.inputBuffer:getElement(i - 1)[key].pressed then
return true
end
end
return false
end
return Keyboard