Example #1
0
def state(game):
    errors = []
    states = retro.list_states(game)
    if not states:
        return [], []

    rom = retro.get_romfile_path(game)
    path = retro.get_game_path(game)
    emu = retro.RetroEmulator(rom)
    for statefile in states:
        try:
            with gzip.open(os.path.join(path, statefile + '.state'),
                           'rb') as fh:
                state = fh.read()
        except (IOError, zlib.error):
            errors.append((game, 'state failed to decode: %s' % statefile))
            continue

        emu.set_state(state)
        emu.step()

    del emu
    gc.collect()

    return [], errors
Example #2
0
def state(game, inttype):
    errors = []
    states = retro.data.list_states(game, inttype)
    if not states:
        return [], []

    rom = retro.data.get_romfile_path(game,
                                      inttype | retro.data.Integrations.STABLE)
    emu = retro.RetroEmulator(rom)
    for statefile in states:
        try:
            with gzip.open(
                    retro.data.get_file_path(game, statefile + '.state',
                                             inttype), 'rb') as fh:
                state = fh.read()
        except (IOError, zlib.error):
            errors.append((game, 'state failed to decode: %s' % statefile))
            continue

        emu.set_state(state)
        emu.step()

    del emu
    gc.collect()

    return [], errors
Example #3
0
 def __init__(self):
     self.r = retro.RetroEmulator(config["Emulation options"]["ROM"])
     self.buttons = [
         0, 0, 0, 0, 0, 0, 0, 0
     ]  #["b","a","select","start","ui_up","ui_down","ui_left","ui_right","a","b"]
     self.audiorate = self.r.get_audio_rate()
     self.stream = sounddevice.OutputStream(self.audiorate,
                                            dtype=numpy.int16)
     self.stream.start()
     self.screen = None
Example #4
0
def load(game, inttype):
    errors = []
    rom = retro.data.get_romfile_path(game, inttype)
    emu = retro.RetroEmulator(rom)

    emu.step()

    del emu
    gc.collect()

    return [], errors
Example #5
0
    def __init__(self,
                 game,
                 state=retro.State.DEFAULT,
                 scenario=None,
                 info=None,
                 use_restricted_actions=retro.Actions.FILTERED,
                 record=False,
                 players=1,
                 inttype=retro.data.Integrations.STABLE,
                 obs_type=retro.Observations.IMAGE,
                 retro_run_id=None):
        if not hasattr(self, 'spec'):
            self.spec = None
        self._obs_type = obs_type
        self.shm = None
        self.img = None
        self.ram = None
        self.viewer = None
        self.gamename = game
        self.statename = state
        self.initial_state = None
        self.players = players
        metadata = {}
        rom_path = retro.data.get_romfile_path(game, inttype)
        self.disas = retro.dispel.ingest(rom_path)
        metadata_path = retro.data.get_file_path(game, 'metadata.json',
                                                 inttype)

        if state == retro.State.NONE:
            self.statename = None
        elif state == retro.State.DEFAULT:
            self.statename = None
            try:
                with open(metadata_path) as f:
                    metadata = json.load(f)
                if 'default_player_state' in metadata and self.players <= len(
                        metadata['default_player_state']):
                    self.statename = metadata['default_player_state'][
                        self.players - 1]
                elif 'default_state' in metadata:
                    self.statename = metadata['default_state']
                else:
                    self.statename = None
            except (IOError, json.JSONDecodeError):
                pass

        if self.statename:
            self.load_state(self.statename, inttype)

        self.data = retro.data.GameData()

        if info is None:
            info = 'data'

        if info.endswith('.json'):
            # assume it's a path
            info_path = info
        else:
            info_path = retro.data.get_file_path(game, info + '.json', inttype)

        if scenario is None:
            scenario = 'scenario'

        if scenario.endswith('.json'):
            # assume it's a path
            scenario_path = scenario
        else:
            scenario_path = retro.data.get_file_path(game, scenario + '.json',
                                                     inttype)

        self.system = retro.get_romfile_system(rom_path)

        # Set up the shm if we're using the SNES emulator
        self._init_shm(retro_run_id)

        # We can't have more than one emulator per process. Before creating an
        # emulator, ensure that unused ones are garbage-collected
        gc.collect()
        self.em = retro.RetroEmulator(rom_path)
        self.em.configure_data(self.data)
        self.em.step()

        core = retro.get_system_info(self.system)
        self.buttons = core['buttons']
        self.num_buttons = len(self.buttons)

        try:
            assert self.data.load(
                info_path,
                scenario_path), 'Failed to load info (%s) or scenario (%s)' % (
                    info_path, scenario_path)
        except Exception:
            del self.em
            raise

        self.button_combos = self.data.valid_actions()
        if use_restricted_actions == retro.Actions.DISCRETE:
            combos = 1
            for combo in self.button_combos:
                combos *= len(combo)
            self.action_space = gym.spaces.Discrete(combos**players)
        elif use_restricted_actions == retro.Actions.MULTI_DISCRETE:
            self.action_space = gym.spaces.MultiDiscrete([
                len(combos) if gym_version >= (0, 9, 6) else
                (0, len(combos) - 1) for combos in self.button_combos
            ] * players)
        else:
            self.action_space = gym.spaces.MultiBinary(self.num_buttons *
                                                       players)

        kwargs = {}
        if gym_version >= (0, 9, 6):
            kwargs['dtype'] = np.uint8

        if self._obs_type == retro.Observations.RAM:
            shape = self.get_ram().shape
        else:
            img = [self.get_screen(p) for p in range(players)]
            shape = img[0].shape
        self.observation_space = gym.spaces.Box(low=0,
                                                high=255,
                                                shape=shape,
                                                **kwargs)

        self.use_restricted_actions = use_restricted_actions
        self.movie = None
        self.movie_id = 0
        self.movie_path = None
        if record is True:
            self.auto_record()
        elif record is not False:
            self.auto_record(record)
        self.seed()
        if gym_version < (0, 9, 6):
            self._seed = self.seed
            self._step = self.step
            self._reset = self.reset
            self._render = self.render
            self._close = self.close
Example #6
0
    def __init__(self,
                 game,
                 state=retro.STATE_DEFAULT,
                 scenario=None,
                 info=None,
                 use_restricted_actions=retro.ACTIONS_FILTERED,
                 record=False):
        if not hasattr(self, 'spec'):
            self.spec = None
        self.img = None
        self.viewer = None
        self.gamename = game
        self.statename = state

        game_path = retro.get_game_path(game)
        rom_path = retro.get_romfile_path(game)
        metadata_path = os.path.join(game_path, 'metadata.json')

        if state == retro.STATE_NONE:
            self.initial_state = None
        elif state == retro.STATE_DEFAULT:
            self.initial_state = None
            try:
                with open(metadata_path) as f:
                    metadata = json.load(f)
                if 'default_state' in metadata:
                    with gzip.open(
                            os.path.join(game_path, metadata['default_state'])
                            + '.state', 'rb') as fh:
                        self.initial_state = fh.read()
            except (IOError, json.JSONDecodeError):
                pass
        else:
            if not state.endswith('.state'):
                state += '.state'

            with gzip.open(os.path.join(game_path, state), 'rb') as fh:
                self.initial_state = fh.read()

        self.data = GameData()

        if info is None:
            info = 'data'

        if info.endswith('.json'):
            # assume it's a path
            info_path = info
        else:
            info_path = os.path.join(game_path, info + '.json')

        if scenario is None:
            scenario = 'scenario'

        if scenario.endswith('.json'):
            # assume it's a path
            scenario_path = scenario
        else:
            scenario_path = os.path.join(game_path, scenario + '.json')

        system = retro.get_romfile_system(rom_path)

        # We can't have more than one emulator per process. Before creating an
        # emulator, ensure that unused ones are garbage-collected
        gc.collect()
        self.em = retro.RetroEmulator(rom_path)
        self.em.configure_data(self.data)
        self.em.step()
        img = self.em.get_screen()

        core = retro.get_system_info(system)
        self.BUTTONS = core['buttons']
        self.NUM_BUTTONS = len(self.BUTTONS)
        self.BUTTON_COMBOS = self.data.valid_actions()

        try:
            assert self.data.load(
                info_path,
                scenario_path), 'Failed to load info (%s) or scenario (%s)' % (
                    info_path, scenario_path)
        except Exception:
            del self.em
            raise

        if use_restricted_actions == retro.ACTIONS_DISCRETE:
            combos = 1
            for combo in self.BUTTON_COMBOS:
                combos *= len(combo)
            self.action_space = gym.spaces.Discrete(combos)
        elif use_restricted_actions == retro.ACTIONS_MULTI_DISCRETE:
            self.action_space = gym.spaces.MultiDiscrete([
                len(combos) if gym_version >= (0, 9, 6) else
                (0, len(combos) - 1) for combos in self.BUTTON_COMBOS
            ])
        else:
            self.action_space = gym.spaces.MultiBinary(self.NUM_BUTTONS)

        kwargs = {}
        if gym_version >= (0, 9, 6):
            kwargs['dtype'] = np.uint8
        self.observation_space = gym.spaces.Box(low=0,
                                                high=255,
                                                shape=img.shape,
                                                **kwargs)

        self.use_restricted_actions = use_restricted_actions
        self.movie = None
        self.movie_id = 0
        self.movie_path = None
        if record is True:
            self.auto_record()
        elif record is not False:
            self.auto_record(record)
        self.seed()
        if gym_version < (0, 9, 6):
            self._seed = self.seed
            self._step = self.step
            self._reset = self.reset
            self._render = self.render
            self._close = self.close