본문 바로가기

pygame_phyics

[pygame] 버튼, text 줄넘김 구현

버튼을 클릭하려면 마우스가 버튼 위에 있는지 , 마우스를 클릭 한지 확인해야 한다 

 

 

버튼:

class Button:
    def __init__(self, position):
        self.default = pygame.Surface((50, 50), pygame.SRCALPHA)
        self.default.fill((0, 0, 0))
        self.clicked = pygame.Surface((50, 50), pygame.SRCALPHA)
        self.clicked.fill((255, 255, 255))
        self.image = self.default
        self.rect = self.image.get_rect(center=position)
        self.position = position
        self.click_event = lambda: print("click!")
        self.last_pressed = 0
        
    def update(self):
        
        self.mouse_pressed = pygame.mouse.get_pressed()[0]# 0: 왼쪽 버튼, 1: 마우스 휠, 2: 오른쪽 버튼
        # pygame.mouse.get_pos() 마우스 위치
        # self.rect.collidepoint : pygame.Rect 범위에 주어진 점이 들어가 있는지 검사
        self.in_mouse = self.rect.collidepoint(pygame.mouse.get_pos()) 
        
        iif self.in_mouse: 마우스가 들어왔다면
            if self.mouse_pressed > self.last_pressed: 마우스가 클릭하는 순간
                self.click_event() 클릭 이벤트
                self.image = self.clicked 
        if self.mouse_pressed < self.last_pressed: 마우스가 클릭 해제하는 순간
            self.image = self.default
        
        self.rect = self.image.get_rect(center=self.position)
        
        self.last_pressed = self.mouse_pressed
        
    def render(self, surface):
        surface.blit(self.image, self.rect)

 

self.mouse_pressed = pygame.mouse.get_pressed()[0]으로 왼쪽버튼 이 클릭상태인지 확인하고

 

self.in_mouse = self.rect.collidepoint(pygame.mouse.get_pos()) 으로 마우스가 버튼에 들어왔는지 확인합니다

 

text:

 

class Text:
    def __init__(self, position, size, color, Font, interval):
        self.position = position
        self.Font = Font
        self.font = pygame.font.SysFont(Font, size)
        self.size = size
        self.interval = interval
        self.color = color
        self.text = ""
    
    def get_position(self, __index: int): # 글자에 상대위치 반환 self.position 을 0, 0 으로 했을떄
        line = self.get_line(__index)
        text = self.text[:__index].split("\n")[-1]
        x, _ = self.font.size(text)
        y = self.size + self.interval
        y *= line
        return x-5, -y

    def get_line(self, __index: int): 글자에 라인 반환
        text = self.text[:__index]
        line = text.count("\n")
        return line

    def render(self, surface : pygame.Surface):
        texts = self.text.split("\n") # 줄로 나눠서
        self.images = [self.font.render(text, True, self.color) for text in texts] 각각 따로 렌더합니다
        positions = []
        x, y = self.position
        for i in texts:
            positions.append((x, y))
            y += self.size + self.interval
        surface.blits(list(zip(self.images, positions)))

 

줄넘김은 render 할떄 "\n" 기준으로 분활해서 각각 따로 렌더한다음에 y 좌표를 크기 + 간격 을 더하면서 그립니다