Skip to content

[Pygame] 簡單的文字輸入框製作筆記

Last Updated on 2021-09-09 by Clay

文字輸入框(input box)是一個遊戲中常見的元件,可以讓我們輸入在畫面中輸入文字,以此來與遊戲互動。

不過 Pygame 是個非常底層的遊戲引擎框架,幾乎沒有給予任何元件的模組,所以如果我們需要製作文字的輸入框,我們可能可以透過 Rect 元件來實作。

下面會是完整程式、與逐段落介紹。程式碼不長,六十幾行罷了。


完整程式碼

# coding: utf-8
import pygame


def main():
    # Settings
    width = 600
    height = 300
    color_background = (0, 0, 0)
    color_inactive = (100, 100, 200)
    color_active = (200, 200, 255)
    color = color_inactive
    text = ""
    active = False
    running = True

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

    # Font
    font = pygame.font.Font(None, 32)

    # Input box
    input_box = pygame.Rect(100, 100, 140, 32)

    # Run
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                active = True if input_box.collidepoint(event.pos) else False

                # Change the current color of the input box
                color = color_active if active else color_inactive

            if event.type == pygame.KEYDOWN:
                if active:
                    if event.key == pygame.K_RETURN:
                        print(text)
                        text = ""
                    elif event.key == pygame.K_BACKSPACE:
                        text = text[:-1]
                    else:
                        text += event.unicode

        # Input box
        text_surface = font.render(text, True, color)
        input_box_width = max(200, text_surface.get_width()+10)
        input_box.w = input_box_width
        input_box.center = (width/2, height/2)

        # Updates
        screen.fill(color_background)
        screen.blit(text_surface, (input_box.x+5, input_box.y+5))
        pygame.draw.rect(screen, color, input_box, 3)
        pygame.display.flip()


if __name__ == "__main__":
    main()



Output:

這裡並沒有把終端機一起錄入,實際上在我們輸入文字後按下 Enter 鍵,是可以看到這些文字顯示在終端機上的。


程式碼介紹

首先,匯入必要的套件 pygame

# coding: utf-8
import pygame



這裡開始寫 main() 函式,會在最底下 if __name__ == "__main__": 來執行。

以及各種設定。

def main():
    # Settings
    width = 600
    height = 300
    color_background = (0, 0, 0)
    color_inactive = (100, 100, 200)
    color_active = (200, 200, 255)
    color = color_inactive
    text = ""
    active = False
    running = True



初始化,並設定視窗、文字,以及最重要的『輸入框』(input_box)。

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

    # Font
    font = pygame.font.Font(None, 32)

    # Input box
    input_box = pygame.Rect(100, 100, 140, 32)



接下來的程式全部都在更新畫面的無窮迴圈中執行,這是 Pygame 中很重要的一環。

    # Run
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                active = True if input_box.collidepoint(event.pos) else False

                # Change the current color of the input box
                color = color_active if active else color_inactive

            if event.type == pygame.KEYDOWN:
                if active:
                    if event.key == pygame.K_RETURN:
                        print(text)
                        text = ""
                    elif event.key == pygame.K_BACKSPACE:
                        text = text[:-1]
                    else:
                        text += event.unicode

        # Input box
        text_surface = font.render(text, True, color)
        input_box_width = max(200, text_surface.get_width()+10)
        input_box.w = input_box_width
        input_box.center = (width/2, height/2)

        # Updates
        screen.fill(color_background)
        screen.blit(text_surface, (input_box.x+5, input_box.y+5))
        pygame.draw.rect(screen, color, input_box, 3)
        pygame.display.flip()


幾個比較需要重點提醒的地方在:

  • input_box.collidepoint(event.pos) 這段是在事件型態為滑鼠點擊時觸發,確認是否點擊到輸入框;有點到輸入框時就會變色。
  • pygame.K_RETURN 是按下 Enter 鍵的事件。
  • pygame.K_BACKSPACE 是按下刪除鍵的事件。
  • input_box_width = max(200, text_surface.get_width()+10) 是在輸入的字串長度超過原先輸入框時增加其寬度

References


Read More

Leave a Reply