printing user's input in pygame

2019-03-06 16:55发布

问题:

I have nearly finished a game which I was was working on for a school project but now I am struggling on a tiny part of my game. I am able to get the user's name and use it for example to write it into a leaderboards csv file, but I want to make it so that whatever the user types the game prints the user's input on to the screen just like when you are typing into a searchbox, whatever key you enter, that key is shown in the search box.

回答1:

Just create a font object, use it to render the text (which gives you a pygame.Surface) and then blit the text surface onto the screen.

Also, to add the letters to the user_input string, you can just concatenate it with the event.unicode attribute.

Here's a minimal example:

import pygame as pg

pg.init()

screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
FONT = pg.font.Font(None, 40)  # A font object which allows you to render text.
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue1')

user_input = ''

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_BACKSPACE:
                user_input = user_input[:-1]
            else:
                user_input += event.unicode

    screen.fill(BG_COLOR)
    # Create the text surface.
    text = FONT.render(user_input, True, BLUE)
    # And blit it onto the screen.
    screen.blit(text, (20, 20))
    pg.display.flip()
    clock.tick(30)

pg.quit()