首页 > 解决方案 > Pygame击键事件没有发生

问题描述

在带有 python3.7 windows 10 的 pygame 1.9.4 上运行,我在按键时没有收到任何 KEYDOWN 和 KEYUP 事件。

我编写了许多 pygame 程序,并认为我了解事件处理,但这让我很难过。将 event.pump() 添加到循环中没有区别。在使用 ctrl-C 终止后,实际的击键显示在 shell 中。

import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
frame = 0

while True:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            break

        if event.type == pygame.KEYDOWN:
            print('Keydown')
            if event.key == pygame.K_z:
                print('z down')
            if pygame.key.get_pressed(pygame.K_z):
                print('z pressed')

        if event.type == pygame.KEYUP:
            print('Keyup')
            if event.key == pygame.K_z:
                print('z up')

    pygame.display.flip()            
    clock.tick(1)
    frame +=1
    print(frame)

`

标签: pythonpygamekeyboard-events

解决方案


尝试这种方式让你的玩家移动,我想你可以包括 print('z down') 部分

moving_right = False
moving_left = False

while True:
 moving_right == True:
    player_location[0] += 4
if moving_left == True:
    player_location[0] -= 4

for event in pygame.event.get(): # event loop
    if event.type == QUIT: # check for window quit
        pygame.quit() # stop pygame
        sys.exit() # stop script
    if event.type == KEYDOWN:
        if event.key == K_RIGHT:
            moving_right = True
        if event.key == K_LEFT:
            moving_left = True
    if event.type == KEYUP:
        if event.key == K_RIGHT:
            moving_right = False
        if event.key == K_LEFT:
            moving_left = False

推荐阅读