按住python pygame键

时间:2018-05-05 13:02:34

标签: python pygame

我正试图让一架飞机在向左按住键时向左移动,我正在使用pygame.key.get_pressed(),但只响应一次就像普通的pygame.KEYDOWN一样 只打印'向右移动'一次

有人可以帮忙吗?

def key_control(hero_temp):
    for event in pygame.event.get():

        if event.type == pygame.QUIT:
        print('Game Exit')
        exit()

        key_state = pygame.key.get_pressed()
        if key_state[pygame.K_RIGHT]:
            print('move to right')
            hero_temp.x += 10
        if key_state[pygame.K_LEFT]:
            print('move to left')
            hero_temp.x -= 10
        if key_state[pygame.K_UP]:
            print('move to top')
            hero_temp.y -= 10
        if key_state[pygame.K_DOWN]:
            print('move to right')
            hero_temp.y += 10
        if key_state[pygame.K_SPACE]:
            print('space/shoot')
            hero_temp.fire()

2 个答案:

答案 0 :(得分:1)

你只是在你循环中调用key_state = pygame.key.get_pressed()循环,你迭代每个事件。只需将它从那里取出即可。

问题是,如果有新事件,它只会检查按下的按钮。如果没有新事件,它将不会检查按下的按钮,代码将不会被执行

def key_control(hero_temp):
    key_state = pygame.key.get_pressed()
    if key_state[pygame.K_RIGHT]:
        print('move to right')
        hero_temp.x += 10
    if key_state[pygame.K_LEFT]:
        print('move to left')
        hero_temp.x -= 10
    if key_state[pygame.K_UP]:
        print('move to top')
        hero_temp.y -= 10
    if key_state[pygame.K_DOWN]:
        print('move to right')
        hero_temp.y += 10
    if key_state[pygame.K_SPACE]:
        print('space/shoot')
        hero_temp.fire()

    for event in pygame.event.get():
        # Only gets run if there are new events
        if event.type == pygame.QUIT:
            print('Game Exit')
            exit()

答案 1 :(得分:0)

def key_control(hero_temp):
    key_state = pygame.key.get_pressed()
    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            print('Game Exit')
            exit()

        if key_state[pygame.K_RIGHT]:
            print('move to right')
            hero_temp.x += 10
        if key_state[pygame.K_LEFT]:
            print('move to left')
            hero_temp.x -= 10
        if key_state[pygame.K_UP]:
            print('move to top')
            hero_temp.y -= 10
        if key_state[pygame.K_DOWN]:
            print('move to right')
            hero_temp.y += 10
        if key_state[pygame.K_SPACE]:
            print('space/shoot')
            hero_temp.fire()