Refactor key handling and add keybindings configuration for game actions

This commit is contained in:
Matteo Benedetto
2025-08-19 18:59:06 +02:00
parent 4099b6f72e
commit 1269913275
6 changed files with 79 additions and 20 deletions
+32 -4
View File
@@ -2,9 +2,38 @@
# The key_pressed method is called when a key is pressed, and it contains the logic for handling different key presses.
import random
import yaml
# read yaml config file
bindings = {}
with open("conf/keybindings.yaml", "r") as f:
bindings = yaml.safe_load(f)
class KeyBindings:
def trigger(self, action):
print(f"Triggering action: {action}")
# Check if the action is in the bindings
if action in bindings[f"keybinding_{self.game_status}"]:
value = bindings[f"keybinding_{self.game_status}"][action]
# Call the corresponding method
if value:
print(f"Calling method: {value}")
if "|" in value:
method_name, *args = value.split("|")
method = getattr(self, method_name)
method(*args)
else:
getattr(self, value)()
else:
print(f"Action {action} not found in keybindings for {self.game_status}")
return
print(f"Action {action} not found in keybindings for {self.game_status}")
return None
def key_pressed(self, key, coords=None):
if key != "mouse":
key = [key, coords]
print(f"Key pressed: {key}")
keybindings = self.configs[f"keybinding_{self.game_status}"]
if key in keybindings.get("quit", []):
self.render_engine.close()
@@ -46,12 +75,11 @@ class KeyBindings:
self.points = 0
self.start_game()
def spawn_new_bomb(self):
self.spawn_bomb(self.pointer)
def quit_game(self):
self.render_engine.close()
def key_released(self, key):
if key in ["Up", "Down", "Left", "Right", 8, 9, 10, 11]:
self.stop_scrolling()
def start_scrolling(self, direction):
self.scrolling_direction = direction
if not self.scrolling: