pocket-friends/pocket_friends/game_files/io/input_handler.py

82 lines
3.4 KiB
Python

import pygame
import pocket_friends.game_files.io.gpio_handler as gpio_handler
class InputHandler:
"""
Class that is implemented into surfaces in order to control the
pressing of buttons on both the real hardware and on a keyboard.
Attributes:
clock (pygame.time.Clock): Pygame clock used for input time calculations.
last_input_tick (int): The tick that the last input was registered on.
"""
def __init__(self, pygame_clock):
"""
Create a InputHandler object using a given Pygame clock.
Args:
pygame_clock (pygame.time.Clock): A pygame clock to use as the clock for input time calculations.
"""
self.clock = pygame_clock
self.last_input_tick = 0
def create_event(self, pressed_button):
"""
Create a pygame event given a GPIO code and post it to the pygame event handler.
Args:
pressed_button (int): The GPIO code to be registered and pressed.
"""
# Register a button click so long as the last button click happened no less than two frames ago
if pygame.time.get_ticks() - self.last_input_tick > self.clock.get_time() * 2 or not gpio_handler.ON_HARDWARE:
pygame.event.post(pygame.event.Event(pygame.KEYDOWN, {'key': pressed_button}))
pygame.event.post(pygame.event.Event(pygame.KEYUP, {'key': pressed_button}))
self.last_input_tick = pygame.time.get_ticks()
def handle_gpio(self):
"""
Handle GPIO events and create events for them.
"""
for pressed_button in gpio_handler.BUTTONS:
code = gpio_handler.BUTTONS.get(pressed_button)
# Check if a button has been pressed. If it has, create a pygame event for it.
if gpio_handler.get_press(code):
self.create_event(code)
def handle_keyboard(self):
"""Handle keyboard presses and generate corresponding GPIO codes to create events."""
# Checks if a corresponding keyboard key has been pressed. If it has, emulate a button press.
for keyboard_event in pygame.event.get():
if keyboard_event.type == pygame.QUIT:
running = False
if keyboard_event.type == pygame.KEYDOWN:
if keyboard_event.key == pygame.K_a:
self.create_event(gpio_handler.BUTTONS.get('a'))
if keyboard_event.key == pygame.K_b:
self.create_event(gpio_handler.BUTTONS.get('b'))
if keyboard_event.key == pygame.K_PERIOD:
self.create_event(gpio_handler.BUTTONS.get('j_i'))
if keyboard_event.key == pygame.K_RIGHT:
self.create_event(gpio_handler.BUTTONS.get('j_r'))
if keyboard_event.key == pygame.K_LEFT:
self.create_event(gpio_handler.BUTTONS.get('j_l'))
if keyboard_event.key == pygame.K_DOWN:
self.create_event(gpio_handler.BUTTONS.get('j_d'))
if keyboard_event.key == pygame.K_UP:
self.create_event(gpio_handler.BUTTONS.get('j_u'))
if keyboard_event.key == pygame.K_ESCAPE:
running = False
def update(self):
"""Run either the GPIO handler or the keyboard handler to check for input and create events."""
if gpio_handler.ON_HARDWARE:
self.handle_gpio()
else:
self.handle_keyboard()