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

查看:24
本文介绍了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 相比的优势在于 chr 仅在 event.key 的值介于 0 和 255(含)之间时才有效.

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

如果您按 menuAlt GrTabLShiftpygame.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 属性="nofollow noreferrer">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)

使用功能键时,它会为您提供字母/数字或空字符串,并且还会考虑修饰符,例如如果你在按下 a 的同时按住 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天全站免登陆