【问题标题】:How check, if button pressed twice?如何检查,如果按钮按下两次?
【发布时间】:2019-05-28 11:08:59
【问题描述】:

我可以使用 Pygame 在 Python 中按下 Enter 按钮。 现在,每次我按下按钮时,它都会在控制台中打印“一次”。 如何检测按钮是否被多次按下并打印“多次”?

  press = False
  if event.key == pygame.K_RETURN:
      press = True

      print("once")
  if press == True:
      print("more than once")

【问题讨论】:

  • 到目前为止你做了什么...
  • 你可以有一个整数变量,并在每次按下键时递增它,这样你就知道它被按下了多少次。或者,在您的情况下,甚至只是一个布尔值初始化为 False 并在您按下键时设置为 True,以确定它是否已被按下。
  • 刚刚添加了一些代码,但不知道如何继续。
  • 你认为什么是“被多次按下”?自比赛开始以来不止一次?自 X 秒以来不止一次?自从按下另一个按钮后不止一次?
  • 整场比赛一次。因为“游戏”只是为了按下按钮。

标签: python if-statement button pygame


【解决方案1】:

你快到了。只需使用if/else 块并在打印后将press 设置为True:

import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
run = True
press = False

while run:
  for e in pygame.event.get():
    if e.type == pygame.QUIT: 
        run = False
    if e.type == pygame.KEYDOWN:
        if e.key == pygame.K_RETURN:
            if not press:
                print('once')
            else:
                print('more than once')
            press = True

  screen.fill((30, 30, 30))
  pygame.display.flip()

【讨论】:

  • while 循环完成后,如何再次使 press = False?例如,如果我在一个游戏中有多个游戏圈?
猜你喜欢
  • 1970-01-01
  • 2020-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-03
  • 1970-01-01
相关资源
最近更新 更多