Pygame:有没有简单的方法可以找到所按的任何字母数字的字母/数字? [英] Pygame: Is there any easy way to find the letter/number of ANY alphanumeric pressed?

查看:184
本文介绍了Pygame:有没有简单的方法可以找到所按的任何字母数字的字母/数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的游戏目前需要让人们以自己的名字参加高分板比赛.我对如何处理按键有些陌生,但是我只在寻找特定按键.是否有一种简便的方法可以按下任何键的字母而无需执行以下操作:

Game I'm working on currently needs to let people time in their name for highscore board. I'm slightly familiar with how to deal with key presses, but I've only dealt with looking for specific ones. Is there an easy way to get the letter of any key pressed without having to do something like this:

for event in pygame.event.get(): 
    if event.type == KEYUP: 
        if event.key == K_a:
           newLetter = 'a'
        elif event.key == K_b:
           newLetter = 'b'

           ...
       elif event.key == K_z:
           newLetter = 'z'

虽然可行,但我觉得有一种更有效的解决方法.我只是想不通,也找不到任何指导.

While that would work, I have a feeling there is a more efficient way to go about it. I just can't figure it out or find any guides on it.

推荐答案

基本上有两种方法:

选项1:使用 pygame.key.name() .

就像

for event in pygame.event.get():
  if event.type == pygame.KEYDOWN:
    print(pygame.key.name(event.key))

使用chr的优势在于,仅当event.key的值介于0到255(含)之间时,chr才有效.

The advantage over using chr is that chr works only if the value of event.key is between 0 and 255 (inclusive).

如果按菜单 Alt Gr Tab LShift pygame.key.name会很高兴返回menualt grtableft shift,而chr将崩溃,崩溃,返回空白并崩溃.

If you press menu, Alt Gr, Tab or LShift, pygame.key.name will happily return menu, alt gr, tab and left shift, while chr will crash, crash, return whitespace, and crash.

选项2:使用unicode属性> pygame.KEYDOWN 事件

Option 2: use the unicode attribute of the pygame.KEYDOWN event

for event in pygame.event.get():
  if event.type == pygame.KEYDOWN:
    print(event.unicode)

使用功能键时,它会为您提供字母/数字或空字符串,并且还会考虑修饰符,例如如果您在按住Shift的同时按住Shift键,它将返回A而不是a.

It will get you the letter/number or an empty string when using a function key, and it will also take modifiers into account, e.g. if you hold Shift while pressing a it will return A instead of just a.

pygame.KEYDOWN事件具有其他属性unicode和 扫描码. unicode代表一个字符串,即 输入了完全翻译的字符.这考虑到了转变 和组成键. scancode代表特定于平台的密钥 代码.

The pygame.KEYDOWN event has additional attributes unicode and scancode. unicode represents a single character string that is the fully translated character entered. This takes into account the shift and composition keys. scancode represents the platform-specific key code.

这篇关于Pygame:有没有简单的方法可以找到所按的任何字母数字的字母/数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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