pygame.key.get_pressed()不起作用

时间:2015-04-24 19:23:01

标签: python raspberry-pi

我正在尝试从用户那里获取持续输入并根据它做事。我正在尝试在pygame模块中使用key.get_pressed()函数。但是,我无法让它发挥作用。我已经查看了所有其他类似的问题,但这些解决方案似乎都不起作用。

import pygame, RCcarFunctions, time
pygame.init()
keypressed = pygame.key.get_pressed()
try:
  while True:
    if keypressed == "pygame.K_w":
      RCcarFunctions.forward()
    elif keypressed  == "pygame.K_a":
      RCcarFunctions.spinleft()
    elif keypressed == "pygame.K_s":
      RCcarFunctions.reverse()
    elif keypressed == "pygame.K_d":
      RCcarFunctions.spinright()
    elif keypressed == "pygame.K_ESCAPE":
      RCcarFunctions.stop()
    pygame.event.pump()
except KeyboardInterrupt:
  RCcarFunctions.cleanup()

3 个答案:

答案 0 :(得分:0)

pygame.key.get_pressed()来电转移到while True循环中,如下所示:

import pygame, RCcarFunctions, time
pygame.init()
try:
  while True:
    keypressed = pygame.key.get_pressed()
    if keypressed == "pygame.K_w":
      RCcarFunctions.forward()
    elif keypressed  == "pygame.K_a":
      RCcarFunctions.spinleft()
    elif keypressed == "pygame.K_s":
      RCcarFunctions.reverse()
    elif keypressed == "pygame.K_d":
      RCcarFunctions.spinright()
    elif keypressed == "pygame.K_ESCAPE":
      RCcarFunctions.stop()
    pygame.event.pump()
except KeyboardInterrupt:
  RCcarFunctions.cleanup()

答案 1 :(得分:0)

您需要将代码移动到循环内的var tables = Object.keys($database);

您还需要验证它返回的内容:  由常数索引的bool列表。 https://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed

get_pressed()

答案 2 :(得分:0)

我找到了解决方案!使用事件que并轮询所需键的状态。如果他们'down'将bool切换为True,如果他们'up'将bool切换为false(每个键分别为bool)。然后在事件之外的que检查每个bool的状态,基于那样做。

我遇到的主要问题是我没有初始化显示,我完全没有意识到你必须为pygame初始化显示才能工作。初始化显示后,我开始工作了。

pygame.init()
size = (640,480)
pygame.display.setmode((640,480))
while True:
  for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
      if event.key == pygame.K_w:
        forward = True
      elif event.key == pygame.K_a:
        left = True
      elif event.key == pygame.K_s:
        reverse = True
      elif event.key == pygame.K_d:
        right = True
    elif event.type == pygame.KEYUP:
      if event.key == pygame.K_w:
        forward = False
      elif event.key == pygame.K_a:
        left = False
      elif event.key == pygame.K_s:
        reverse = False
      elif event.key == pygame.K_d:
        right = False
  if forward & right:
    RCcarFunctions.right()
  elif forward & left:
    RCcarFunctions.left()
  elif forward:
    RCcarFunctions.forward()
  elif left:
    RCcarFunctions.spinleft()
  elif reverse:
    RCcarFunctions.reverse()
  elif right:
    RCcarFunctions.spinright()
  else:
    RCcarFunctions.stop()
except KeyboardInterrupt:
  print ("\ncleaning up")
  RCcarFunctions.cleanup()