Pygame程序,可以获得带帽的键盘输入

时间:2010-04-19 23:27:28

标签: python ascii character pygame shift

我有一个需要文本输入的Pygame程序。它的方式是获取键盘输入,当按下一个键时,它会呈现该键,以便将其添加到屏幕上。从本质上讲,它就像一个文本字段。问题是,当你举行轮班时,它什么都不做。我意识到这是因为程序忽略移位输入而是写入文本,如果它的数字小于128.我已经考虑过设置一个变量,当按下shift然后大写如果它是真的,但是字符串大小写只是字母,而不是东西像数字或分号。可能有一个我可以添加到ASCII数字的数字,如果按下shift键或其他东西,可以修改它吗? 修改
从本质上讲,我只是想知道是否有一个数字可以添加到ascii字符,使它看起来像是在键入时按住了shift。阅读完我原来的问题后,它似乎有点模糊。

5 个答案:

答案 0 :(得分:3)

我可以使用'event.unicode'属性来获取键入的键的值。

答案 1 :(得分:1)

将此类添加到代码中应该可以解决问题。要获取用户按下的字符,请从类中调用getCharacter函数。您可以更改if keyPress> = 32和keyPress< = 126:语句,以允许非字母字符与shift一起使用。

# The pygame module itself...
import pygame

class controls:

    def getKeyPress(self):
      for event in pygame.event.get():
         if event.type == KEYDOWN:    
             return event.key
         else:
             return False


    def getCharacter(self):

      # Check to see if the player has inputed a command
      keyinput = pygame.key.get_pressed()  

      character = "NULL"

      # Get all "Events" that have occurred.
      pygame.event.pump()
      keyPress = self.getKeyPress()

      #If the user presses a key on the keyboard then get the character
      if keyPress >= 32 and keyPress <= 126:
      #If the user presses the shift key while pressing another character then capitalise it
          if keyinput[K_LSHIFT]: 
              keyPress -= 32

          character = chr(keyPress)

      return character 

答案 2 :(得分:1)

我深入研究这个问题。 pygame中的每个键盘事件不仅包含scancode,还包含unicode表示。这不仅允许输入大写字母,还可以使用语言切换来支持多语言键盘。

这里是pygame的简单'输入/打印'示例:

#!/usr/bin/python

import pygame

pygame.init()
screen_size=(800,60)
disp=pygame.display.set_mode(screen_size, pygame.DOUBLEBUF)
msg=u""
clock=pygame.time.Clock()
default_font=pygame.font.get_default_font()
font=pygame.font.SysFont(default_font,16)

disp.fill((240,240,240,255))
pygame.display.flip()
while(not pygame.event.pump()):
    for event in pygame.event.get():
        print event
        if event.type == pygame.QUIT:
            pygame.quit()
            break
        if event.type == pygame.KEYDOWN:
            msg+=event.unicode
            disp.fill((240,240,240,255))
            disp.blit(font.render(msg,True,(30,30,30,255)),(0,0))
            pygame.display.flip()
    clock.tick(24)

答案 3 :(得分:0)

看起来减去32可以得到你想要的东西,看ASCII table。确保你真的首先处理小写字母,否则你会得到一些奇怪的字符。我不确定你的意思是大写仅适用于字母:

>>> '1234;!@#abcd'.upper()
'1234;!@#ABCD'

答案 4 :(得分:0)

我写了一个函数,在得到足够的帮助后转换字符串。它手动转换所有内容。

相关问题