如何在pygame中获取键盘输入?

新手上路,请多包涵

我正在 pygame 1.9.2 中制作游戏。这是一个失败的简单游戏,其中一艘船在五列坏人之间移动,这些坏人通过缓慢向下移动进行攻击。我试图让船用左右箭头键左右移动。这是我的代码:

 keys=pygame.key.get_pressed()
if keys[K_LEFT]:
    location-=1
    if location==-1:
        location=0
if keys[K_RIGHT]:
    location+=1
    if location==5:
        location=4

它工作得很好。船开得太快了。让它只向左或向右移动一个位置几乎是不可能的。我怎样才能做到每次按下键时船只移动一次?

原文由 Dan G. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 985
2 个回答

您可以从 pygame 获取事件,然后注意 KEYDOWN 事件,而不是查看 get_pressed() 返回的键(它为您提供当前按下的键,而 KEYDOWN 事件显示在 该帧 上按下了哪些键)。

您的代码现在发生的情况是,如果您的游戏以 30fps 的速度呈现,并且您按住向左箭头键半秒钟,您将更新位置 15 次。

 events = pygame.event.get()
for event in events:
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            location -= 1
        if event.key == pygame.K_RIGHT:
            location += 1

要在按住某个键时支持连续移动,您必须建立某种限制,或者基于游戏循环的强制最大帧速率,或者通过一个计数器,该计数器只允许您移动环形。

 move_ticker = 0
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
    if move_ticker == 0:
        move_ticker = 10
        location -= 1
        if location == -1:
            location = 0
if keys[K_RIGHT]:
    if move_ticker == 0:
        move_ticker = 10
        location+=1
        if location == 5:
            location = 4

然后在游戏循环的某个地方你会做这样的事情:

 if move_ticker > 0:
    move_ticker -= 1

这只会让你每 10 帧移动一次(所以如果你移动,自动收报机设置为 10,在 10 帧后它会允许你再次移动)

原文由 Haz 发布,翻译遵循 CC BY-SA 4.0 许可协议

pygame.key.get_pressed() 返回一个包含每个键状态的列表。如果按住某个键,则该键的状态为 1 ,否则为 0 。使用 pygame.key.get_pressed() 评估按钮的当前状态并获得连续移动:

 while True:

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        x -= speed
    if keys[pygame.K_RIGHT]:
        x += speed
    if keys[pygame.K_UP]:
        y -= speed
    if keys[pygame.K_DOWN]:
        y += speed

这段代码可以通过“右”减“左”和“下”减“上”来简化:

 while True:

    keys = pygame.key.get_pressed()
    x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed
    y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * speed

键盘事件(请参阅 pygame.event 模块)仅在键状态更改时发生一次。 KEYDOWN 每次按下一个键时都会发生一次事件。 KEYUP 每次释放一个键时发生一次。将键盘事件用于单个动作或移动:

 while True:

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x -= speed
            if event.key == pygame.K_RIGHT:
                x += speed
            if event.key == pygame.K_UP:
                y -= speed
            if event.key == pygame.K_DOWN:
                y += speed

另见 键和键盘事件


连续运动的最小例子: replit.com/@Rabbid76/PyGame-ContinuousMovement

 import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

rect = pygame.Rect(0, 0, 20, 20)
rect.center = window.get_rect().center
vel = 5

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            print(pygame.key.name(event.key))

    keys = pygame.key.get_pressed()

    rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel
    rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * vel

    rect.centerx = rect.centerx % window.get_width()
    rect.centery = rect.centery % window.get_height()

    window.fill(0)
    pygame.draw.rect(window, (255, 0, 0), rect)
    pygame.display.flip()

pygame.quit()
exit()


单个动作的最小示例: replit.com/@Rabbid76/PyGame-ShootBullet

 import pygame
pygame.init()

window = pygame.display.set_mode((500, 200))
clock = pygame.time.Clock()

tank_surf = pygame.Surface((60, 40), pygame.SRCALPHA)
pygame.draw.rect(tank_surf, (0, 96, 0), (0, 00, 50, 40))
pygame.draw.rect(tank_surf, (0, 128, 0), (10, 10, 30, 20))
pygame.draw.rect(tank_surf, (32, 32, 96), (20, 16, 40, 8))
tank_rect = tank_surf.get_rect(midleft = (20, window.get_height() // 2))

bullet_surf = pygame.Surface((10, 10), pygame.SRCALPHA)
pygame.draw.circle(bullet_surf, (64, 64, 62), bullet_surf.get_rect().center, bullet_surf.get_width() // 2)
bullet_list = []

run = True
while run:
    clock.tick(60)
    current_time = pygame.time.get_ticks()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.KEYDOWN:
            bullet_list.insert(0, tank_rect.midright)

    for i, bullet_pos in enumerate(bullet_list):
        bullet_list[i] = bullet_pos[0] + 5, bullet_pos[1]
        if bullet_surf.get_rect(center = bullet_pos).left > window.get_width():
            del bullet_list[i:]
            break

    window.fill((224, 192, 160))
    window.blit(tank_surf, tank_rect)
    for bullet_pos in bullet_list:
        window.blit(bullet_surf, bullet_surf.get_rect(center = bullet_pos))
    pygame.display.flip()

pygame.quit()
exit()

原文由 Rabbid76 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题