Skip to content

[Pygame] 簡單的按鈕點擊事件

一款遊戲中,『按鈕』(button)也是必不可少的重要元件,我們可能會需要設計出讓玩家離開遊戲的按鈕,或是觸發某些遊戲事件的按鈕…… 等等。

但是 Pygame 這個遊戲引擎框架比較底層,並沒有封裝任何按鈕元件,所以可以直接寫一個 Rect 元件加上顏色與文字,並偵測滑鼠點擊事件。

偵測滑鼠點擊在 Rect 元件中倒是容易,直接使用 collidepoint() 來判斷事件位置即可。

詳細實作方法可以參考下方程式碼。


完整程式碼

# coding: utf-8
import pygame


def main():
    # Settings
    width = 800
    height = 600
    color_bg = (0, 0, 0)
    color_text = (200, 200, 200)
    button_clicked = False
    running = True

    # Init
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    pygame.display.set_caption("Rect Demo")

    # Text
    font = pygame.font.SysFont("Arial", 35)
    text = font.render("Button", True, color_text)
    text_clicked = font.render("Clicked", True, color_text)
    text_rect = text_clicked.get_rect(center=(width/2, height/2))

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

            if event.type == pygame.MOUSEBUTTONDOWN:
                button_clicked = True if text_rect.collidepoint(event.pos) else False

        # Screen
        screen.fill(color_bg)

        # Draw
        pygame.draw.rect(screen, (100, 100, 100), text_rect)

        if button_clicked:
            screen.blit(text_clicked, text_rect)
        else:
            screen.blit(text, text_rect)

        # Updates
        pygame.display.update()


if __name__ == "__main__":
    main()



Output:

在點擊之後,按鈕的文字會改變。


References


Read More

Leave a Reply