创建自定义 gym env 教程

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

先讲几个基础知识

  1. init.py 的作用
    最主要的作用是: 将所在的目录标记为 Python 包的一部分。
    在 Python 中,一个包是一个包含模块(即 .py 文件)的目录,
    init.py 文件表明这个目录可以被视为一个包,允许从这个目录导入模块或其他包。
  2. class里以 _ 开头的变量,说明是私有变量,以 _ 开头方法被视为私有方法。(默认的规定,但不强制)
  3. 实例的变量的初始化可以不在 __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(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值