Arrow key input with open ai gym?


#1

Is there any way to get keyboard input such as arrow keys with gym games? For example, I just want to make a simple interactive cart pole using keyboard (LEFT, RIGHT). I tried with readchar, but cart pole hangs.

def human_play(replay_buffer):
    s = env.reset()
    while True:
        env.render()

        # Choose an action from keyboard
        # FIXME: keyin does not work gym ai
        key = readchar.readkey()
        if key not in arrow_keys.keys():
            print("Game aborted!")
            break

        a = arrow_keys[key]
        print(a)

        s1, reward, done, _ = env.step(a)

        if done:
            break

#2

Here’s an example where the action is based on user input. Some environments require a tuple as input which you will notice by looking at the ‘example action’ that’s printed to the screen. To input a tuple just input (0,1,0) including the parenthesis. For CartPole you will need to enter 1 to move left and 0 to move right

import gym
env = gym.make('CartPole-v0')
for _ in range(10):
    s = env.reset()
    print('init_state: {} example action: {}'.format(s, env.action_space.sample()))
    while True:
        env.render()
        s, reward, done, _ = env.step(eval(input('')))
        print('state: {} reward: {} done: {}'.format(s, reward, done))
        if done:
            break

#3

Thanks! Very nice. However, do you think we can just use arrow keys like real games?