Files
Gymnasium/gym/spaces/discrete.py

38 lines
936 B
Python
Raw Normal View History

2016-04-27 08:00:58 -07:00
import numpy as np
import gym
from .space import Space
2016-04-27 08:00:58 -07:00
class Discrete(Space):
2016-04-27 08:00:58 -07:00
"""
{0,1,...,n-1}
2016-06-11 23:10:58 -07:00
Example usage:
self.observation_space = spaces.Discrete(2)
2016-04-27 08:00:58 -07:00
"""
def __init__(self, n):
2016-04-27 08:00:58 -07:00
self.n = n
super(Discrete, self).__init__((), np.int64)
self.np_random = np.random.RandomState()
def seed(self, seed):
self.np_random.seed(seed)
2016-04-27 08:00:58 -07:00
def sample(self):
return self.np_random.randint(self.n)
2016-04-27 08:00:58 -07:00
def contains(self, x):
if isinstance(x, int):
as_int = x
elif isinstance(x, (np.generic, np.ndarray)) and (x.dtype.kind in np.typecodes['AllInteger'] and x.shape == ()):
as_int = int(x)
else:
return False
return as_int >= 0 and as_int < self.n
2016-04-27 08:00:58 -07:00
def __repr__(self):
return "Discrete(%d)" % self.n
2016-04-27 08:00:58 -07:00
def __eq__(self, other):
return isinstance(other, Discrete) and self.n == other.n