From bcb7929e69fcc0434c8a1c656e587867e1ecb384 Mon Sep 17 00:00:00 2001 From: djib Date: Sat, 10 Sep 2022 14:02:25 +0200 Subject: [PATCH] Add detection of short and long press on buttons --- maths-attacks.p8 | 76 +++++++++++++++++++++++++++++++++--------------- 1 file changed, 52 insertions(+), 24 deletions(-) diff --git a/maths-attacks.p8 b/maths-attacks.p8 index 058912e..3f00d5d 100644 --- a/maths-attacks.p8 +++ b/maths-attacks.p8 @@ -3,37 +3,65 @@ version 37 __lua__ -- maths attacks -- -- by djib -- -btn_stat = false -btnp_stat = false -held_stat = false -switch = false - function _init() + init_btn_status() end function _update() - btn_stat = false - if btn(➡️) then - btn_stat = true - end - btnp_stat = false - if btnp(➡️) then - btnp_stat = true - end - if btnp(➡️) and btn(➡️) then - if switch then - held_stat = true - else - switch=true - end - else - held_stat = false - end - + update_btn_status(❎) + update_btn_status(🅾️) end function _draw() - print(tostr(btn_stat) .. "-" .. tostr(btnp_stat) .. "-" tostr(held_stat)) + cls() + print("❎ - pressed:"..tostr(btn_pressed(❎)).." - held:"..tostr(btn_held(❎)),1,1) + print("🅾️ - pressed:"..tostr(btn_pressed(🅾️)).." - held:"..tostr(btn_held(🅾️)),1,10) +end +-->8 +-- buttons -- + +function init_btn_status() + -- no repeating delay for keyboard + poke(0x5f5d,255) + -- true when pressed + btn_down_status={} + -- true when quickly released + btn_up_status={} + -- true when held + btn_held_status={} +end + +function update_btn_status(button) + -- button was already pressed -- + if btn_down_status[button] then + -- button was held + if btnp(button) then + btn_held_status[button]=true + btn_down_status[button]=false + end + -- button no longer pressed + if not btn(button) then + btn_up_status[button]=true + btn_down_status[button]=false + end + else + if btnp(button) then + btn_down_status[button]=true + end + if not btn(button) then + btn_held_status[button]=false + btn_down_status[button]=false + btn_up_status[button]=false + end + end +end + +function btn_held(button) + return btn_held_status[button] +end + +function btn_pressed(button) + return btn_up_status[button] end __gfx__ 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000