import gym
from gym import spaces
import numpy as np
import pygame
class RandomWalk2DEnv(gym.Env):
def __init__(self):
super(RandomWalk2DEnv, self).__init__()
# 定义状态空间为2D坐标(x, y)
self.x_min, self.x_max = -10, 10 # 更新尺寸为 (-10, 10)
self.y_min, self.y_max = -10, 10 # 更新尺寸为 (-10, 10)
self.observation_space = spaces.Box(np.array([self.x_min, self.y_min]),
np.array([self.x_max, self.y_max]),
dtype=np.float32)
# 动作空间定义为2D向量,x和y分量的范围为(-1, 1)
self.action_space = spaces.Box(np.array([-1.0, -1.0]), np.array([1.0, 1.0]), dtype=np.float32)
# 初始化状态
self.state = np.array([0.0, 0.0])
# 初始化步长(每次移动的距离)
self.step_size = 1.0
# 初始化pygame
pygame.init()
# 设置窗口
self.screen_size = (800, 800)
self.screen = pygame.display.set_mode(self.screen_size)
pygame.display.set_caption("Random Walk 2D")
# 坐标转换,将-10到10的坐标映射到屏幕的像素坐标
self.scale = 40 # 缩放因子,决定每个单位坐标对应多少像素
self.origin = np.array([self.x_max, self.y_max]) # 原点在右上角
# 路径记录
self.path_x = []
self.path_y = []
def reset(self):
# 将智能体重置到原点 (0, 0)
self.state = np.array([0.0, 0.0])
self.path_x = [self.state[0]] # 重置路径记录
self.path_y = [self.state[1]] # 重置路径记录
ret
【URL】一个简单基于Gym的2D随机游走环境,用于无监督强化学习(URL)
于 2025-02-02 00:52:08 首次发布