|
import pygame |
|
from constants import * |
|
|
|
class Button: |
|
def __init__(self, text, x, y, font_name='Arial', font_size=18, color=(255, 255, 255), |
|
background_color=(0, 0, 255), hover_color=(0, 102, 255), padding=10): |
|
self.font = pygame.font.SysFont(font_name, font_size) |
|
self.text_surface = self.font.render(text, True, color) |
|
self.padding = padding |
|
self.set_background_color(background_color) |
|
self.background_color = background_color |
|
self.hover_color = hover_color |
|
self.rect = self.surface.get_rect() |
|
self.rect.x = x |
|
self.rect.y = y |
|
|
|
|
|
|
|
def blit_to_center(self, s1, s2): |
|
if s1.get_width() < s2.get_width() or s1.get_height() < s2.get_height(): |
|
s1, s2 = s2, s1 |
|
s1.blit(s2, ((s1.get_width() - s2.get_width()) // 2, (s1.get_height() - s2.get_height()) // 2)) |
|
return s1 |
|
|
|
|
|
def check_is_mouse_hover(self, mouse_pos): |
|
return self.rect.collidepoint(mouse_pos) |
|
|
|
|
|
|
|
def update(self, mouse_pos): |
|
if self.check_is_mouse_hover(mouse_pos): |
|
self.set_background_color(self.hover_color) |
|
else: |
|
self.set_background_color(self.background_color) |
|
|
|
|
|
|
|
def set_background_color(self, color): |
|
self.background = pygame.Surface( |
|
(self.text_surface.get_width() + self.padding * 2, self.text_surface.get_height() + self.padding * 2)) |
|
self.background.fill(color) |
|
self.surface = self.blit_to_center(self.background, self.text_surface) |
|
|
|
|