Untitled

mail@pastecode.io avatar
unknown
python
2 years ago
1.8 kB
2
Indexable
Never
from typing import List

import pygame

class Button:
    def __init__(self, rect: pygame.Rect) -> None:
        # self.base_rect is going to be the one that never gets modified
        self.base_rect = rect
        # self.rect is going to be the one that is active
        self.rect = rect

    def collidepoint(self, pos: pygame.Vector2) -> bool:
        return self.rect.collidepoint(pos)

    def scale(self, scale_factor = 1.2) -> None:
        width = self.base_rect.width * scale_factor
        height = self.base_rect.height * scale_factor

        c_pos = self.base_rect.center

        self.rect = pygame.Rect(0, 0, width, height)
        self.rect.center = c_pos

class UI:
    def __init__(self) -> None:
        self.buttons: List[Button] = []

    def generate_buttons(self) -> None:
        base_pos = pygame.Vector2(30, 30)
        width = 30
        height = 30
        y_offset = 50
        x_offset = 50

        for i in range(9):
            offset_vector = pygame.Vector2(x_offset*(i%3), y_offset*(i//3))
            pos = base_pos + offset_vector

            rect = pygame.Rect(pos.x, pos.y, width, height)

            self.buttons.append(Button(rect))

    def draw_buttons(self, screen: pygame.Surface) -> None:
        mouse_pos = pygame.Vector2(pygame.mouse.get_pos())
        for button in self.buttons:
            if button.collidepoint(mouse_pos):
                button.scale(scale_factor=1.2)
            else:
                button.scale(scale_factor=1)

            pygame.draw.rect(screen, "blue", button.rect)

screen = pygame.display.set_mode((500, 500))

ui = UI()
ui.generate_buttons()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill("white")
    ui.draw_buttons(screen)
    pygame.display.flip()