84 lines
2.4 KiB
Python
84 lines
2.4 KiB
Python
from . import input
|
|
from pyglet.window import key
|
|
import pyglet.clock
|
|
from enum import Enum
|
|
from collections import defaultdict
|
|
|
|
bindings = defaultdict(lambda: None)
|
|
firing = defaultdict(lambda: None)
|
|
actions = []
|
|
fixed_rate = 0.003
|
|
|
|
class RepeatType(Enum):
|
|
No = 0
|
|
Interval = 1
|
|
Fixed = 2
|
|
|
|
class FiringTime(Enum):
|
|
Immediate = 0
|
|
Lazy = 1
|
|
|
|
class KeyBinding(object):
|
|
def __init__(self, key, action, repeat=RepeatType.Fixed, interval=fixed_rate, delay=FiringTime.Immediate):
|
|
self.key = key
|
|
self.action = action
|
|
self.repeat = repeat
|
|
self.interval = interval
|
|
self.repeat_offset = None
|
|
self.delay = delay
|
|
self.firedonce = False
|
|
|
|
def fire(self, clock):
|
|
global firing
|
|
self.repeatfire(clock)
|
|
firing[self.key] = True
|
|
|
|
def unfire(self, clock):
|
|
if self.delay == FiringTime.Lazy and not self.firedonce:
|
|
self.trigger()
|
|
firing[self.key] = False
|
|
|
|
def repeatfire(self, clock):
|
|
if self.repeat_offset == None:
|
|
self.repeat_offset = 0.0
|
|
if self.delay == FiringTime.Immediate:
|
|
self.trigger()
|
|
|
|
if self.repeat != RepeatType.No:
|
|
self.repeat_offset += clock
|
|
|
|
while self.repeat_offset > self.interval:
|
|
# print(f"accumulated offset by {clock} to {self.repeat_offset}")
|
|
self.repeat_offset -= self.interval
|
|
self.trigger()
|
|
|
|
def trigger(self):
|
|
global actions
|
|
# print(f"Repeat firing for {self.repeat_offset} x {self.repeat_offset / self.interval}")
|
|
actions.append(self.action)
|
|
self.firedonce = True
|
|
|
|
def process_keys(clock):
|
|
global actions
|
|
|
|
actions = []
|
|
|
|
#clock = pyglet.clock.get_default()
|
|
for keybind in bindings.keys():
|
|
binding = bindings[keybind]
|
|
is_firing = firing[keybind]
|
|
is_pressed = input.state[keybind]
|
|
if is_pressed and not is_firing:
|
|
# print(f"Starting firing for key")
|
|
binding.fire(clock)
|
|
elif not is_pressed and is_firing:
|
|
# print(f"Stopping firing for key")
|
|
binding.unfire(clock)
|
|
elif is_firing:
|
|
binding.repeatfire(clock)
|
|
|
|
def bind(key, action, repeat=RepeatType.Fixed, interval=fixed_rate, delay=FiringTime.Immediate):
|
|
global bindings
|
|
|
|
kb = KeyBinding(key, action, repeat, interval, delay)
|
|
bindings[key] = kb
|