def train_agent(cfg, env, agent):
    """
    Train an agent in environment.

    Parameters
    ----------
    cfg : dict
    env : OpenAI environment
    agent : object

    Return
    ------
    agent : object
    """
    rewards = []
    window_size = cfg['training']['print_window_size']
    max_episode_length = cfg['training']['max_episode_length']
    for episode in range(cfg['training']['nb_episodes']):
        agent.reset()
        observation_previous = env.reset()
        is_done = False
        time = 0
        while not (time >= max_episode_length) and not is_done:
            action = agent.act(observation_previous)
            observation, reward, is_done, _ = env.step(action)
            rewards.append(reward)
            agent.remember(observation_previous, action, reward, observation,
                           is_done)
            observation_previous = observation
            time += 1
        if episode % cfg['training']['print_score'] == 0 and episode > 0:
            agent.save(cfg['serialize_path'])
            print("Average score: {:>5.2f}"
                  .format(sum(rewards[-window_size:]) / window_size))
    agent.save(cfg['serialize_path'])
    return agent