在 pygame 中打印用户的输入 [英] printing user's input in pygame

查看:72
本文介绍了在 pygame 中打印用户的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎完成了我为学校项目工作的游戏,但现在我在游戏的一小部分上挣扎.我能够获取用户的姓名并使用它例如将其写入排行榜 csv 文件,但我想让它无论用户键入什么游戏都会将用户的输入打印到屏幕上,就像您打字时一样进入搜索框,无论您输入什么键,该键都会显示在搜索框中.

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.

推荐答案

只需创建一个字体对象,用它来渲染文本(它会给你一个 pygame.Surface),然后 blit 文本表面到屏幕上.

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.

此外,要将字母添加到 user_input 字符串,您只需将其与 event.unicode 属性连接即可.

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

这是一个最小的例子:

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()

这篇关于在 pygame 中打印用户的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆