执行CartPole-v1程序,并将运行过程存储为gif
参考链接
参考1
参考2
代码:
import gym
import matplotlib.pyplot as plt
from matplotlib import animation
def display_frames_as_gif(frames):
patch = plt.imshow(frames[0])
plt.axis("off")
def animate(i):
patch.set_data(frames[i])
anim = animation.FuncAnimation(plt.gcf(), animate, frames = len(frames), interval = 5)
anim.save("./CartPole_v1_result.gif", writer="pillow", fps = 30)
def run(env):
frames = []
for i_episode in range(5):
observation = env.reset()
for t in range(20):
frames.append(env.render(mode = "rgb_array"))
action = env.action_space.sample()
opservation, reward, done, info = env.step(action)
if done:
break
display_frames_as_gif(frames)
env = gym.make("CartPole-v1")
run(env)
env.close()
结果展示:
