From 6fb7fee090dc895ae6fc71d7c0a19e3f4e265b17 Mon Sep 17 00:00:00 2001 From: Kristofers Solo Date: Sat, 6 Jan 2024 05:17:09 +0200 Subject: [PATCH] feat(game): add button highlight --- src/game/screens/main.py | 13 ++++++++++++- src/game/screens/menu_button.py | 21 ++++++++++++++------- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/src/game/screens/main.py b/src/game/screens/main.py index 9e82109..6a45fd4 100644 --- a/src/game/screens/main.py +++ b/src/game/screens/main.py @@ -25,7 +25,6 @@ class Main(BaseScreen, SceenElement, TextScreen): """Update the display.""" self._draw_background() self._draw_text() - self._draw_border() pygame.display.update() def update(self) -> None: @@ -38,6 +37,18 @@ class Main(BaseScreen, SceenElement, TextScreen): elif event.type == pygame.KEYDOWN: if event.key == pygame.K_q: self.exit() + elif event.type == pygame.MOUSEBUTTONDOWN: + mouse_pos = pygame.mouse.get_pos() + for button in self.buttons: + if button.rect.collidepoint(mouse_pos): + button.on_click() + elif event.type == pygame.MOUSEMOTION: + mouse_pos = pygame.mouse.get_pos() + for button in self.buttons: + if button.rect.collidepoint(mouse_pos): + button.update(True) + else: + button.update(False) def run(self) -> None: while True: diff --git a/src/game/screens/menu_button.py b/src/game/screens/menu_button.py index 5d745ca..e658630 100644 --- a/src/game/screens/menu_button.py +++ b/src/game/screens/menu_button.py @@ -12,6 +12,7 @@ class MenuButton(Button, BaseScreen, SceenElement, TextScreen): super().__init__(text, action) self._initialize_surface() self._initialize_font() + self.hover = False def on_click(self) -> None: """Handle click event.""" @@ -20,21 +21,23 @@ class MenuButton(Button, BaseScreen, SceenElement, TextScreen): def on_hover(self) -> None: """Handle hover event.""" - self._draw_border() + self._draw_hover_background() def run(self) -> None: - """Display the button on the game surface.""" - self.draw() - - def update(self) -> None: - """Update the button.""" pass + def update(self, hover: bool = False) -> None: + """Update the button.""" + self.hover = hover + def draw(self, surface: pygame.Surface, pos: tuple[float, float]) -> None: """Draw the button on the button surface.""" self._initialize_rect(pos) self._update_display_surface() - self._draw_background() + if self.hover: + self.on_hover() + else: + self._draw_background() self._draw_text() self._draw_border() @@ -73,6 +76,10 @@ class MenuButton(Button, BaseScreen, SceenElement, TextScreen): """Fill the background of the button.""" self.surface.fill(CONFIG.colors.bg_sidebar) + def _draw_hover_background(self) -> None: + """Fill the background of the button.""" + self.surface.fill(CONFIG.colors.bg_visual) + def _draw_border(self) -> None: """Draw the border of the button.""" pygame.draw.rect(