如何在Pygame上使用操纵杆同时移动和射击?

时间:2019-02-25 14:55:24

标签: python pygame openai-gym

我正在使用Open AI Gym开发“太空侵略者”,并感谢Pygame进行展示。但是,即使我将它们附加在队列中,我也不知道如何同时沿操纵杆轴移动和使用操纵杆按钮进行拍摄。这是我的代码:

def find_num_action(action_list) :
    if len(action_list)>1 :
        if (1 in action_list) :
            if (2 in action_list) and (3 in action_list) :
                num_action = 1
            elif (2 in action_list) :
                num_action = 4
            elif (3 in action_list) :
                num_action = 5
            else :
                num_action = 1

        elif (2 in action_list) and (3 in action_list) :
            num_action = 0

        elif (2 in action_list) :
            num_action = 2

        elif (3 in action_list) :
            num_action = 3

    elif len(action_list) == 1 :
        num_action = action_list[0]
    else :
        num_action = 0
    return num_action

running = True
pygame.key.set_repeat(50, 20)
fps = 40
clock = pygame.time.Clock()

while running:

    for event in pygame.event.get():
        action_list = []

        # Actions : ['NOOP', 'FIRE', 'RIGHT', 'LEFT', 'RIGHTFIRE', 'LEFTFIRE']

        if event.type == QUIT :
            running = False

        if event.type == JOYBUTTONDOWN :
            if event.button == 2 :
                action_list.append(1)

    axis = mon_joystick.get_axis(0)
    if axis > 0:
        action_list.append(2)
    if axis < 0:
        action_list.append(3)

    num_action = find_num_action(action_list)

    obs, reward, done, info = env.step(num_action)

    clock.tick(fps)

1 个答案:

答案 0 :(得分:1)

更新:我找到了一个不使用Pygame事件但使用Pygame的get_button函数的解决方案,该函数返回按钮的状态(无论是否按下)。

def find_num_action(action_list, shoot) :

    # Actions : ['NOOP', 'FIRE', 'RIGHT', 'LEFT', 'RIGHTFIRE', 'LEFTFIRE']

    num_action = 0
    if (shoot) :
        if (2 in action_list and 3 in action_list) :
            num_action = 1
        elif (2 in action_list) :
            num_action = 4
        elif (3 in action_list) :
            num_action = 5
        else :
            num_action = 1
    else :
        if (2 in action_list and 3 in action_list) :
            num_action = 0
        elif (2 in action_list) :
            num_action = 2
        elif (3 in action_list) :
            num_action = 3
    return num_action

running = True
pygame.key.set_repeat(50, 20)
fps = 40
clock = pygame.time.Clock()

while running:

    action_list = []
    shoot = False

    for event in pygame.event.get():
        if event.type == QUIT :
            running = False

    shoot = mon_joystick.get_button(2)
    axis = mon_joystick.get_axis(0)
    if axis > 0:
        action_list.append(2)
    if axis < 0:
        action_list.append(3)

    num_action = find_num_action(action_list, shoot)

    obs, reward, done, info = env.step(num_action)

    clock.tick(fps)