Lesson 4 of 5 · 2 min
A handheld adventure
The well known Pokémon Red experiments show the approach: read the screen and a few memory values, reward exploration of new places, and run many emulators at once.
# run locally: env.py, with your own legally obtained ROM
import gymnasium as gym, numpy as np
from pyboy import PyBoy
BUTTONS = ["up", "down", "left", "right", "a", "b"]
class Explore(gym.Env):
def __init__(self, rom):
self.boy = PyBoy(rom, window="null")
self.action_space = gym.spaces.Discrete(len(BUTTONS))
self.observation_space = gym.spaces.Box(0, 255, (72, 80, 1), np.uint8)
def screen(self):
return np.array(self.boy.screen.ndarray[::2, ::2, :1], dtype=np.uint8)
def reset(self, seed=None, options=None):
super().reset(seed=seed)
with open("start.state", "rb") as f:
self.boy.load_state(f)
self.seen, self.steps = [], 0
return self.screen(), {}
def step(self, action):
self.boy.button(BUTTONS[action], 8)
self.boy.tick(24)
frame = self.screen()
small = frame[::4, ::4].astype(np.int16)
new = all(np.abs(small - old).mean() > 12 for old in self.seen)
if new:
self.seen.append(small)
self.steps += 1
return frame, float(new), False, self.steps >= 2048, {}