lines-lua/input.lua
2025-06-25 17:46:31 +03:00

95 lines
2.4 KiB
Lua

-- Input system
-- TODO: replace this with universal system
local Input = {
keyboardButtons = { 'escape', 'space' },
keyboardPressed = {},
lastKeyboardPressed = {},
actions = {}
}
local function mapAction( input, action, keys )
input.actions[action] = {}
for _, key in pairs( keys ) do
table.insert( input.actions[action], key )
end
end
local function loadMap( input )
mapAction( input, 'exit', { 'escape' } )
mapAction( input, 'nextlevel', { 'space' } )
end
local function predHolded( pressed, _ )
return pressed
end
local function predPressed( pressed, lastPressed )
return pressed and not lastPressed
end
local function predReleased( pressed, lastPressed )
return not pressed and lastPressed
end
local function testAction( input, action, predicate )
for _, key in ipairs( input.actions[action] ) do
local pressed, lastPressed
pressed = input.keyboardPressed
lastPressed = input.lastKeyboardPressed
if predicate( pressed[key], lastPressed[key] ) then
return true
end
end
return false
end
function Input.init()
for btn in ipairs( Input.keyboardButtons ) do
Input.keyboardPressed[Input.keyboardButtons[btn]] = false
Input.lastKeyboardPressed[Input.keyboardButtons[btn]] = false
end
loadMap( Input )
return Input
end
function Input:update()
for k, _ in pairs( self.keyboardPressed ) do
self.lastKeyboardPressed[k] = self.keyboardPressed[k]
end
for button in ipairs( self.keyboardButtons ) do
self.keyboardPressed[self.keyboardButtons[button]] = love.keyboard.isDown( self.keyboardButtons[button] )
end
end
function Input:actionHolded( action )
return testAction( self, action, predHolded )
end
function Input:actionReleased( action )
return testAction( self, action, predReleased )
end
function Input:actionPressed( action )
return testAction( self, action, predPressed )
end
function Input:actionDiff( negative, positive )
local negResult = testAction( self, negative, predHolded )
local posResult = testAction( self, positive, predHolded )
if negResult and not posResult then
return -1
elseif posResult and not negResult then
return 1
else
return 0
end
end
return Input.init()