우선 셋업을 위해 Conda 가상환경을 준비하고 다음의 라이브러리를 인스톨한다
pip install gym
pip install matplotlib
pip install JSAnimation
pip uninstall pyglet -y
pip install pyglet==1.2.4
conda install -c conda-forge ffmpeg
# 구현에 사용할 패키지 임포트
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import gym
from JSAnimation.IPython_display import display_animation
from matplotlib import animation
from IPython.display import display
def display_frames_as_gif(frames):
'''
Displays a list of frames as a gif, with controls
'''
plt.figure(figsize=(frames[0].shape[1]/72.0, frames[0].shape[0]/72.0), dpi=72)
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=50)
anim.save('movie_cartpole.mp4')
display(display_animation(anim, default_mode='loop'))
import gym
import numpy as np
# 환경 생성
env = gym.make("CartPole-v1", render_mode='rgb_array')
observation, info = env.reset() # 환경 초기화 시 반환값 구조 변경
frames = [] # 각 프레임을 저장할 리스트
for step in range(0, 200):
frames.append(env.render()) # 각 시각의 이미지를 추가
action = np.random.choice(2) # 0(왼쪽), 1(오른쪽) 중 하나 선택
observation, reward, done, truncated, info = env.step(action) # step의 반환값 구조 변경
if done or truncated: # 에피소드가 끝났으면 루프 종료
break
# 애니메이션을 파일로 저장하고 재생
display_frames_as_gif(frames)
