pygame 中的油门按键

Throttle keypresses in pygame

我最近在编写一个平台游戏,当我遇到一个问题:用户可以垃圾邮件 space 无限跳跃。

这是我的代码:

def __init__(self, pos):
    super().__init__()
    self.image = pygame.Surface((32, 64))
    self.image.fill("green")
    self.rect = self.image.get_rect(topleft = pos)
    self.direction = pygame.math.Vector2(0, 0)
    self.speed = speed
    self.gravity = gravity
    self.jump_height = jump_height

def get_input(self):
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and keys[pygame.K_RIGHT]: pass
    elif keys[pygame.K_LEFT]: self.direction.x = -1
    elif keys[pygame.K_RIGHT]: self.direction.x = 1
    else: self.direction.x = 0
    if keys[pygame.K_SPACE]:
        self.jump()

我尝试了几件事,比如实现一个 self.antispam 布尔值,设置为 True,在 __init__ 方法中,当 [=25] 时变成 False =]键被按下,跳转方法后又转True,或者转jump方法为协程做asyncio循环,但有none有效

要跳跃,您必须使用 KEYDOWN 而不是 pygame.key.get_pressed()。使用pygame.key.get_pressed()移动但不跳跃。
pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() 评估按钮的当前状态并获得连续移动。
键盘事件(参见 pygame.event 模块)仅在键状态改变时发生一次。 KEYDOWN 事件在每次按下一个键时发生一次。 KEYUP 每松开一个键就会出现一次。将键盘事件用于单个动作,例如跳跃或发射子弹。

确保只调用 pygame.get.event() 一次(参见 ):

    def get_input(self, event_list):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and keys[pygame.K_RIGHT]: pass
        elif keys[pygame.K_LEFT]: self.direction.x = -1
        elif keys[pygame.K_RIGHT]: self.direction.x = 1
        else: self.direction.x = 0

        for event in event_list:
            if event.type == pygame.KEYDONW and event.key == pygame.K_SPACE:
                self.jump()
# application loop
while run:
    # event loop
    event_list = pygame.get.event()
    for event in event_list:
        if event.type == pygame.QUIT:
            # [...]

    player.get_input(event_list)

另一个选项是说明 SPACE 是否在之前的帧中被按下。所以你可以检测到 SPACE 被按住:

def __init__(self, pos):
    super().__init__()
    # [...]
   
    self.space_was_pressed = False

def get_input(self):
    keys = pygame.key.get_pressed()
    # [...]         

    space_is_pressed = keys[pygame.K_SPACE]  
    if space_is_pressed and not self.space_was_pressed:
        self.jump()
    self.space_was_pressed = space_is_pressed 

另见