import pygame from pygame import Surface, Rect from pygame.font import Font from physics.TickData import TickData from sprite.BoundingBox import BoundingBox from sprite.PositionScale import PositionScale from ui_elements.UiElement import UiElement class TextLabel(UiElement): def tick(self, tick_data: TickData): pass def __init__(self, text: str, x_position: float, y_position: float, font_size: int = 50, alignment: str = "left"): super().__init__() self.text = text self.x_position = x_position self.y_position = y_position self.current_width = 0 self.current_height = 0 self.alignment = alignment self.font_size = font_size self.font = Font('data/font/MilkyNice.ttf', self.font_size) def render_sprite_image(self) -> pygame.Surface: return self.font.render(str(self.text), True, pygame.Color('white')) def draw(self, screen: Surface, screen_transform: PositionScale): rendered_font = self.font.render(str(self.text), True, pygame.Color('white')) self.current_width = rendered_font.get_width() self.current_height = rendered_font.get_height() if self.alignment == "right": self.position_scale.position = (self.x_position - self.current_width, self.y_position) elif self.alignment == "left": self.position_scale.position = (self.x_position, self.y_position) elif self.alignment == "center": self.position_scale.position = (self.x_position - self.current_width / 2, self.y_position) super().draw(screen, screen_transform) def set_text(self, new_text: str): self.text = new_text def collides_point(self, position): x, y = self.get_bounding_box().get_position() # check for the collision on the x-axis if position[1] < y: return False if position[1] > y + self.current_height: return False # the y-axis check is dependent on the alignment if position[0] < x: return False if position[0] > x + self.current_width: return False # if the point is not outside the text, it is inside the text return True def get_bounding_box(self) -> BoundingBox: bounding_box_x = self.x_position if self.alignment == "right": bounding_box_x = self.x_position - self.current_width elif self.alignment == "center": bounding_box_x = self.x_position - self.current_width / 2 return BoundingBox(bounding_box_x, self.y_position, self.current_width, self.current_height)