import pygame class Button: def __init__(self, text, width, height, pos_x, pos_y, color, hover): """ :param text: Text inside the button. :param width: Width of the button. :param height: Height of the button. :param pos_x: X position of the button on the screen. :param pos_y: Y position of the button on the screen. :param color: Color of the button on the screen. :param hover: Color of the button on the screen when mouse is hover. """ self.text = text self.width = width self.height = height self.pos_x = pos_x self.pos_y = pos_y self.color = color self.hover = hover # create rectangle for button self.rect = pygame.Rect(self.pos_x, self.pos_y, self.width, self.height) # set font for button text self.font = pygame.font.SysFont("Arial", 30) # temp var to stor click event - so it will be executed just once self.clicked = False def draw(self, screen): """ Draw the button on the screen. :param screen: Screen object where button will be drawn. :return: Return True when button was clicked. """ action = False # get current mous position mouse_pos = pygame.mouse.get_pos() # check if mouse is over button if self.rect.collidepoint(mouse_pos): current_color = self.hover # check if left mouse button is pressed if pygame.mouse.get_pressed()[0] == 0 and self.clicked: self.clicked = False action = True else: current_color = self.color self.clicked = False # draw buttton pygame.draw.rect(screen, current_color, self.rect, border_radius = 12) # render button text text_surface = self.font.render(self.text, True, (255, 255, 255)) # place text in the middle of the button text_rect = text_surface.get_rect(center=self.rect.center) screen.blit(text_surface, text_rect) return action