gym-0.26.1
pygame-2.1.2
自定义环境 GridWolrdEnv
教程参考 官网自定义环境 ,我把一些可能有疑惑的地方讲解下。
首先整体文件结构, 这里省略了wrappers
gym-examples/
main.py # 这个是测试自定义的环境
setup.py
gym_examples/
__init__.py
envs/
__init__.py
grid_world.py
先讲几个基础知识
- init.py 的作用
最主要的作用是: 将所在的目录标记为 Python 包的一部分。
在 Python 中,一个包是一个包含模块(即 .py 文件)的目录,
而 init.py 文件表明这个目录可以被视为一个包,允许从这个目录导入模块或其他包。- class里以 _ 开头的变量,说明是私有变量,以 _ 开头方法被视为私有方法。(默认的规定,但不强制)
- 实例的变量的初始化可以不在 __init__函数里,比如在这里有些变量就是 在 reset 函数里初始化。
grid_world.py
原版的英文注释已经很清楚了,所以我们这里就是沿用就好了
import gym
from gym import spaces
import pygame
import numpy as np
class GridWorldEnv(gym.Env):
metadata = {
"render_modes": ["human", "rgb_array"], "render_fps":4}
def __init__(self, render_mode=None, size=5):
super().__init__()
self.size = size # The size of the square grid
self.window_size = 512 # The size of the PyGame window
# Observations are dictionaries with the agent's and the target's location.
# Each location is encoded as an element of {0, ..., `size`}^2, i.e. MultiDiscrete([size, size]).
self.observation_space = spaces.Dict(
{
"agent": spaces.Box(0, size - 1, shape=(2,), dtype=int),
"target": spaces.Box(0, size - 1, shape=(2,), dtype=int)
}
)
# We have 4 actions, corresponding to "right", "up", "left", "down"
self.action_space = spaces.Discrete(4)
"""
The following dictionary maps abstract actions from `self.action_space` to
the direction we will walk in if that action is taken.
I.e. 0 corresponds to "right", 1 to "up" etc.
"""
self._action_to_direction = {
0: np.array([1, 0]),
1: np.array(