printing user's input in pygame

前端 未结 1 618
别跟我提以往
别跟我提以往 2021-01-29 09:29

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

相关标签:
1条回答
  • 2021-01-29 10:17

    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()
    
    0 讨论(0)
提交回复
热议问题