rk_island/game/events.py

55 lines
1.8 KiB
Python

# Copyright (C) 2022 RozK
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from engine import (
buffer,
EVENT_FOCUS_IN, EVENT_FOCUS_OUT,
EVENT_KEY_PRESS, EVENT_KEY_RELEASE,
EVENT_BUTTON_PRESS, EVENT_BUTTON_RELEASE,
EVENT_MOTION,
Event, create_events, destroy_events, consume_events)
_max_type = max(
EVENT_FOCUS_IN, EVENT_FOCUS_OUT,
EVENT_KEY_PRESS, EVENT_KEY_RELEASE,
EVENT_BUTTON_PRESS, EVENT_BUTTON_RELEASE,
EVENT_MOTION)
_max_events = 64
class Events:
__slots__ = '_display', '_events', '_buffer', '_handlers'
def __init__(self, display):
self._display = display
self._events = create_events(display)
self._buffer = buffer(Event, _max_events)
self._handlers = [[] for _ in range(_max_type + 1)]
def __del__(self):
destroy_events(self._display, self._events)
def register(self, type, handler):
assert type <= _max_type
self._handlers[type].append(handler)
def update(self):
nevents = consume_events(self._events, self._buffer, _max_events)
if nevents:
for event in self._buffer[:nevents]:
data = event.data
for handler in self._handlers[event.type]:
handler(data)