【问题标题】:Confused by pygame key.get_pressed() method [duplicate]被 pygame key.get_pressed() 方法弄糊涂了[重复]
【发布时间】:2020-12-22 20:16:21
【问题描述】:

我对@9​​87654323@的方法有点困惑

所以我检查了pygame网站,它说该方法将"returns a sequence of boolean values representing the state of every key on the keyboard.....and use the key constant values to index the array"

我看到人们写这样的代码:

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
       ......

问题来了:pygame.key.get_pressed() 实际上返回一个元组,那么人们如何使用括号来索引值呢?我的意思是应该像"tuple[sequence]",对吧?

【问题讨论】:

  • 元组由整数索引。键常量是整数吗?
  • pygame.K_LEFT 是一个常数,分别代表一个明确定义的数字索引。在pygame 中,存在声明K_LEFT = 276。请参阅 pygame.keypygame.localsprint(pygame.K_LEFT) 明白我的意思。

标签: python pygame


【解决方案1】:

pygame.key.get_pressed() 返回一个包含每个键状态的序列。如果按住某个键,则该键的状态为True,否则为False。使用pygame.key.get_pressed() 评估按钮的当前状态。

在 Python 中,列表和元组的元素可以通过subscription 访问。 在您的问题代码中

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
      .....

pygame.K_LEFT 是一个常数,分别代表一个明确定义的数字索引。在 pygame 中,exists 声明 K_LEFT = 276(请执行 print(pygame.K_LEFT) 以了解我的意思)。另请参阅 pygame.keypygame.locals
因此,表达式keys[pygame.K_LEFT] 检索与pygame.K_LEFT 关联的元素(值)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 2019-01-12
    • 1970-01-01
    • 2014-08-14
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    相关资源
    最近更新 更多