Exemplo n.º 1
0
def test_randomize_ram():
    pyboy = PyBoy(default_rom, window_type="dummy", randomize=False)
    # RAM banks should all be 0 by default
    assert not any([pyboy.get_memory_value(x)
                    for x in range(0x8000, 0xA000)]), "VRAM not zeroed"
    assert not any([pyboy.get_memory_value(x) for x in range(0xC000, 0xE000)
                    ]), "Internal RAM 0 not zeroed"
    assert not any([pyboy.get_memory_value(x)
                    for x in range(0xFE00, 0xFEA0)]), "OAM not zeroed"
    assert not any([pyboy.get_memory_value(x) for x in range(0xFEA0, 0xFF00)
                    ]), "Non-IO internal RAM 0 not zeroed"
    assert not any([pyboy.get_memory_value(x) for x in range(0xFF4C, 0xFF80)
                    ]), "Non-IO internal RAM 1 not zeroed"
    assert not any([pyboy.get_memory_value(x) for x in range(0xFF80, 0xFFFF)
                    ]), "Internal RAM 1 not zeroed"
    pyboy.stop(save=False)

    pyboy = PyBoy(default_rom, window_type="dummy", randomize=True)
    # RAM banks should have at least one nonzero value now
    assert any([pyboy.get_memory_value(x)
                for x in range(0x8000, 0xA000)]), "VRAM not randomized"
    assert any([pyboy.get_memory_value(x) for x in range(0xC000, 0xE000)
                ]), "Internal RAM 0 not randomized"
    assert any([pyboy.get_memory_value(x)
                for x in range(0xFE00, 0xFEA0)]), "OAM not randomized"
    assert any([pyboy.get_memory_value(x) for x in range(0xFEA0, 0xFF00)
                ]), "Non-IO internal RAM 0 not randomized"
    assert any([pyboy.get_memory_value(x) for x in range(0xFF4C, 0xFF80)
                ]), "Non-IO internal RAM 1 not randomized"
    assert any([pyboy.get_memory_value(x) for x in range(0xFF80, 0xFFFF)
                ]), "Internal RAM 1 not randomized"
    pyboy.stop(save=False)
Exemplo n.º 2
0
def test_mooneye(clean, rom):
    global saved_state
    # Has to be in here. Otherwise all test workers will import this file, and cause an error.
    mooneye_dir = "mooneye"
    if not os.path.isdir(mooneye_dir):
        print(
            urllib.request.urlopen(
                "https://pyboy.dk/mirror/LICENSE.mooneye.txt").read())
        mooneye_data = io.BytesIO(
            urllib.request.urlopen(
                "https://pyboy.dk/mirror/mooneye.zip").read())
        with ZipFile(mooneye_data) as _zip:
            _zip.extractall(mooneye_dir)

    if saved_state is None:
        # HACK: We load any rom and load it until the last frame in the boot rom.
        # Then we save it, so we won't need to redo it.
        pyboy = PyBoy(default_rom, window_type="dummy")
        pyboy.set_emulation_speed(0)
        saved_state = io.BytesIO()
        for _ in range(59):
            pyboy.tick()
        pyboy.save_state(saved_state)
        pyboy.stop(save=False)

    pyboy = PyBoy(rom, window_type="headless")
    pyboy.set_emulation_speed(0)
    saved_state.seek(0)
    if clean:
        for _ in range(59):
            pyboy.tick()
    else:
        pyboy.load_state(saved_state)

    for _ in range(180 if "div_write" in rom else 40):
        pyboy.tick()

    png_path = Path(f"test_results/{rom}.png")
    image = pyboy.botsupport_manager().screen().screen_image()
    if OVERWRITE_PNGS:
        png_path.parents[0].mkdir(parents=True, exist_ok=True)
        image.save(png_path)
    else:
        old_image = PIL.Image.open(png_path)
        if "acceptance" in rom:
            # The registers are too volatile to depend on. We crop the top out, and only match the assertions.
            diff = PIL.ImageChops.difference(image.crop((0, 72, 160, 144)),
                                             old_image.crop((0, 72, 160, 144)))
        else:
            diff = PIL.ImageChops.difference(image, old_image)

        if diff.getbbox() and not os.environ.get("TEST_CI"):
            image.show()
            old_image.show()
            diff.show()
        assert not diff.getbbox(), f"Images are different! {rom}"

    pyboy.stop(save=False)
Exemplo n.º 3
0
    def __init__(self, filename, max_steps, visualize=False):

        self.pyboy = PyBoy(filename,
                           window_type="headless" if not visualize else "SDL2",
                           window_scale=3,
                           debug=visualize,
                           game_wrapper=True)
        assert self.pyboy.cartridge_title() == "SUPER MARIOLAN"

        self.pyboy.set_emulation_speed(0)
        self.mario = self.pyboy.game_wrapper()
        self.mario_lives = None
        self.mario_size = 0

        self.fitness_score = 0
        self.previous_fitness_score = 0
        self.previous_direction = 0
        self._level_progress_max = 0

        self.observation_space = (16, 20)
        self.action_space = [4]

        self.max_steps = max_steps

        self.pair_actions = {"5": 13, "3": 11, "4": 12, "0": 0}

        self.action_jump = [
            WindowEvent.PRESS_BUTTON_A, WindowEvent.RELEASE_BUTTON_A
        ]

        self.action_direction = [
            WindowEvent.PRESS_ARROW_LEFT, WindowEvent.PRESS_ARROW_RIGHT, 0
        ]
Exemplo n.º 4
0
    def test_start_level(self):
        pyboy = PyBoy(supermarioland_rom,
                      window_type="dummy",
                      game_wrapper=True)
        pyboy.set_emulation_speed(0)

        starting_level = (2, 1)
        env = pyboy.openai_gym(observation_type="minimal",
                               action_type="toggle",
                               world_level=starting_level)
        if env is None:
            raise Exception(
                "'env' is None. Did you remember to install 'gym'?")
        observation = env.reset()

        print(env.game_wrapper.world, starting_level)
        assert env.game_wrapper.world == starting_level

        env.game_wrapper.set_lives_left(0)
        env.step(4)  # PRESS LEFT

        for _ in range(200):
            env.step(0)
        assert env.game_wrapper.time_left == 399
        assert env.game_wrapper.world == starting_level
Exemplo n.º 5
0
def test_tiles():
    pyboy = PyBoy(tetris_rom, window_type='headless', disable_input=True)
    pyboy.set_emulation_speed(0)

    tile = pyboy.get_window_tile_map().get_tile(0, 0)
    image = tile.image()
    assert isinstance(image, PIL.Image.Image)
    ndarray = tile.image_ndarray()
    assert isinstance(ndarray, np.ndarray)
    assert ndarray.shape == (8, 8, 4)
    assert ndarray.dtype == np.uint8
    data = tile.image_data()
    assert data.shape == (8, 8)

    for identifier in range(384):
        t = pyboy.get_tile(identifier)
        assert t.identifier == identifier
        if identifier > 0xFF:
            assert t.index[1] == identifier - botsupport.constants.LOW_TILEDATA_NTILES
        else:
            assert t.index[1] == identifier
    with pytest.raises(Exception):
        pyboy.get_tile(-1)
    with pytest.raises(Exception):
        pyboy.get_tile(385)

    pyboy.stop(save=False)
Exemplo n.º 6
0
def run_rom(rom):
    pyboy = PyBoy(rom, window_type="dummy")
    pyboy.set_emulation_speed(0)
    t = time.time()
    result = ""
    while not pyboy.tick():
        b = pyboy._serial()
        if b != "":
            result += b
            t = time.time()

        if pyboy._is_cpu_stuck():
            break

    for _ in range(10):
        pyboy.tick()
    pyboy.stop(save=False)
    result += pyboy._serial(
    )  # Getting the absolute last. Some times the tests says "Failed X tests".
    if result == "":
        n = 0
        while True:
            char = pyboy.get_memory_value(0xA004 + n)
            if char != 0:
                result += chr(char)
            n += 1

            if n > 250:
                break
    return result
Exemplo n.º 7
0
def main():
    # Automatically bump to '-OO' optimizations
    if __debug__:
        os.execl(sys.executable, sys.executable, '-OO', *sys.argv)

    bootrom = "ROMs/DMG_ROM.bin"
    romdir = "ROMs/"
    scale = 3

    # Verify directories
    if bootrom is not None and not os.path.exists(bootrom):
        print("Boot-ROM not found. Please copy the Boot-ROM to '%s'. Using replacement in the meanwhile..." % bootrom)
        bootrom = None

    if not os.path.exists(romdir) and len(sys.argv) < 2:
        print("ROM folder not found. Please copy the Game-ROM to '%s'".format(romdir))
        exit()

    try:
        # Check if the ROM is given through argv
        if len(sys.argv) > 2: # First arg is SDL2/PyGame
            filename = sys.argv[2]
        else:
            filename = getROM(romdir)

        # Start PyBoy and run loop
        pyboy = PyBoy(sys.argv[1] if len(sys.argv) > 1 else None, scale, filename, bootrom)
        while not pyboy.tick():
            pass
        pyboy.stop()

    except KeyboardInterrupt:
        print("Interrupted by keyboard")
    except Exception:
        traceback.print_exc()
Exemplo n.º 8
0
def run_rom(rom):
    # logger.info(rom)
    pyboy = PyBoy(rom,
                  window_type="dummy",
                  window_scale=1,
                  bootrom_file="ROMs/DMG_ROM.bin",
                  disable_input=True)
    # pyboy = PyBoy("ROMs/DMG_ROM.bin", window_type="SDL2", window_scale=1, bootrom_file=rom, disable_input=True)
    pyboy.disable_title()
    pyboy.set_emulation_speed(0)
    serial_output = ""
    t = time.time()
    result = None
    while not pyboy.tick():
        b = pyboy.get_serial()
        if b != "":
            serial_output += b
            t = time.time()

        if "Passed" in serial_output:
            result = ("Passed")
            break
        elif "Failed" in serial_output:
            result = (serial_output)
            break

        if time.time() - t > timeout:
            result = ("Timeout:\n" + serial_output)
            break
    pyboy.stop(save=False)
    return result
Exemplo n.º 9
0
def run_rom(args):
    rom, frame_limit = args
    pyboy = PyBoy(rom, window_type="dummy", window_scale=1, bootrom_file=utils.boot_rom, disable_input=True)
    pyboy.set_emulation_speed(0)
    serial_output = ""
    t = time.time()
    result = None
    frame_count = 0
    while not pyboy.tick():
        b = pyboy._serial()
        if b != "":
            serial_output += b
            t = time.time()

        if "Passed" in serial_output:
            result = ("Passed")
            break
        elif "Failed" in serial_output:
            result = (serial_output)
            break

        if frame_limit == -1 and time.time() - t > timeout:
            result = ("Timeout:\n" + serial_output)
            break
        elif frame_count == frame_limit:
            result = ("Frame limit reached:\n" + serial_output)
            break
        frame_count += 1
    pyboy.stop(save=False)
    return result
Exemplo n.º 10
0
def replay(ROM, replay, verify=True):
    pyboy = PyBoy(ROM, disable_input=True)
    pyboy.set_emulation_speed(0)
    with open(replay, 'rb') as f:
        recorded_input = json.loads(zlib.decompress(f.read()).decode('ascii'))

    # Filters out the blacklisted events
    recorded_input = list(
        map(
            lambda event_tuple: (
                event_tuple[0],
                list(filter(lambda x: x not in event_filter, event_tuple[1])),
                # event_tuple[2]
            ),
            recorded_input))

    frame_count = 0
    next_event = recorded_input.pop(0)

    while recorded_input != []:
        if next_event[0] == frame_count:
            for e in next_event[1]:
                pyboy.send_input(e)
                # if verify:
                #     assert verify_screen_image_np(pyboy, base64.b64decode(next_event[2].encode('utf8')))
            next_event = recorded_input.pop(0)
        frame_count += 1
        pyboy.tick()

    pyboy.stop(save=False)
Exemplo n.º 11
0
async def on_message(message):
    if message.author != client.user:
        if message.content.startswith(config.prefix):
            text = message.content[config.prefix_len:]

            if text.startswith("run"):
                game.gb = PyBoy("data/PokemonRouge.gb")
                game.bot_supp = game.gb.botsupport_manager()
                game.gb.set_emulation_speed(4)
                game.channel = message.channel
                game.pause = False
                await message.channel.send("Starting: " +
                                           game.gb.cartridge_title())

            elif text.startswith("stop"):
                game.gb.stop()
                game.channel = None
                game.bot_supp = None
                game.gb = None
                game.pause = True

            elif text.startswith("pause"):
                game.gb.send_input(WindowEvent.PAUSE)
                game.pause = True
            elif text.startswith("unpause"):
                game.gb.send_input(WindowEvent.PAUSE)
                game.pause = False

            elif text.startswith("name"):
                await message.channel.send("Running: " +
                                           game.gb.cartridge_title())

            elif text in input_list.keys() and message.channel == game.channel:
                game.gb.send_input(input_list[text])
Exemplo n.º 12
0
def test_rom(rom):
    logger.info(rom)
    pyboy = PyBoy("dummy", 1, rom, "ROMs/DMG_ROM.bin")
    # pyboy = PyBoy("SDL2", 1, rom, "ROMs/DMG_ROM.bin")
    pyboy.disableTitle()
    pyboy.setEmulationSpeed(False)
    serial_output = ""
    t = time.time()
    result = None
    while not pyboy.tick():
        b = pyboy.getSerial()
        if b != "":
            serial_output += b
            # print b,
            t = time.time()

        if "Passed" in serial_output:
            result = ("Passed")
            break
        elif "Failed" in serial_output:
            result = (serial_output)
            break

        if time.time() - t > timeout:
            result = ("Timeout:\n" + serial_output)
            break
    print(serial_output)
    pyboy.stop(save=False)
    return result
Exemplo n.º 13
0
def test_dmg_acid():
    # Has to be in here. Otherwise all test workers will import the file, and cause an error.
    dmg_acid_file = "dmg_acid2.gb"
    if not os.path.isfile(dmg_acid_file):
        print(
            urllib.request.urlopen(
                "https://pyboy.dk/mirror/LICENSE.dmg-acid2.txt").read())
        dmg_acid_data = urllib.request.urlopen(
            "https://pyboy.dk/mirror/dmg-acid2.gb").read()
        with open(dmg_acid_file, "wb") as rom_file:
            rom_file.write(dmg_acid_data)

    pyboy = PyBoy(dmg_acid_file, window_type="headless")
    pyboy.set_emulation_speed(0)
    for _ in range(59):
        pyboy.tick()

    for _ in range(25):
        pyboy.tick()

    png_path = Path(f"test_results/{dmg_acid_file}.png")
    image = pyboy.botsupport_manager().screen().screen_image()
    if OVERWRITE_PNGS:
        png_path.parents[0].mkdir(parents=True, exist_ok=True)
        image.save(png_path)
    else:
        old_image = PIL.Image.open(png_path)
        diff = PIL.ImageChops.difference(image, old_image)
        if diff.getbbox() and not os.environ.get("TEST_CI"):
            image.show()
            old_image.show()
            diff.show()
        assert not diff.getbbox(), f"Images are different! {dmg_acid_file}"

    pyboy.stop(save=False)
Exemplo n.º 14
0
def test_tilemap_position_list():
    pyboy = PyBoy(supermarioland_rom, window_type="headless")
    for _ in range(100):
        pyboy.tick()

    # Start the game
    pyboy.send_input(WindowEvent.PRESS_BUTTON_START)
    pyboy.tick()
    pyboy.send_input(WindowEvent.RELEASE_BUTTON_START)

    # Move right for 100 frame
    pyboy.send_input(WindowEvent.PRESS_ARROW_RIGHT)
    for _ in range(100):
        pyboy.tick()

    # Get screen positions, and verify the values
    positions = pyboy.botsupport_manager().screen().tilemap_position_list()
    for y in range(1, 16):
        assert positions[y][0] == 0  # HUD
    for y in range(16, 144):
        assert positions[y][0] == 49  # Actual screen position

    # Progress another 10 frames to see and increase in SCX
    for _ in range(10):
        pyboy.tick()

    # Get screen positions, and verify the values
    positions = pyboy.botsupport_manager().screen().tilemap_position_list()
    for y in range(1, 16):
        assert positions[y][0] == 0  # HUD
    for y in range(16, 144):
        assert positions[y][0] == 59  # Actual screen position

    pyboy.stop(save=False)
Exemplo n.º 15
0
def pyboy():
    pyboy = PyBoy(tetris_rom,
                  window_type="headless",
                  disable_input=True,
                  game_wrapper=True)
    pyboy.set_emulation_speed(0)
    return pyboy
Exemplo n.º 16
0
def main():
    argv = parser.parse_args()
    log_level(argv.log_level)

    logger.info(
        """
The Game Boy controls are as follows:

| Keyboard key | GameBoy equivalant |
| ---          | ---                |
| Up           | Up                 |
| Down         | Down               |
| Left         | Left               |
| Right        | Right              |
| A            | A                  |
| S            | B                  |
| Return       | Start              |
| Backspace    | Select             |

The other controls for the emulator:

| Keyboard key | Emulator function       |
| ---          | ---                     |
| Escape       | Quit                    |
| D            | Debug                   |
| Space        | Unlimited FPS           |
| Z            | Save state              |
| X            | Load state              |
| I            | Toggle screen recording |
| O            | Save screenshot         |
| ,            | Rewind backwards        |
| .            | Rewind forward          |

See "pyboy --help" for how to enable rewind and other awesome features!
"""
    )

    # Start PyBoy and run loop
    pyboy = PyBoy(argv.ROM, **vars(argv))

    if argv.loadstate is not None:
        if argv.loadstate == INTERNAL_LOADSTATE:
            # Guess filepath from ROM path
            state_path = argv.ROM + ".state"
        else:
            # Use filepath given
            state_path = argv.loadstate

        valid_file_path(state_path)
        with open(state_path, "rb") as f:
            pyboy.load_state(f)

    while not pyboy.tick():
        pass

    pyboy.stop()

    if argv.profiling:
        print("\n".join(profiling_printer(pyboy._cpu_hitrate())))
Exemplo n.º 17
0
def test_misc():
    pyboy = PyBoy(any_rom,
                  window_type="dummy",
                  bootrom_file=boot_rom,
                  disable_input=True,
                  hide_window=True)
    pyboy.tick()
    pyboy.stop(save=False)
Exemplo n.º 18
0
def eval_network(epoch, child_index, child_model):
    pyboy = PyBoy('SuperMarioLand.gb',
                  game_wrapper=True)  #, window_type="headless")
    pyboy.set_emulation_speed(3)
    mario = pyboy.game_wrapper()
    mario.start_game()
    # start off with just one life each
    mario.set_lives_left(0)

    run = 0
    scores = []
    fitness_scores = []
    level_progress = []
    time_left = []
    #  prev_action = np.asarray([1,0])
    #  do_action(prev_action, pyboy)

    while run < run_per_child:

        # do some things
        action = get_action(pyboy, mario, child_model)
        action = action.detach().numpy()
        action = np.where(action < np.max(action), 0, action)
        action = np.where(action == np.max(action), 1, action)
        action = action.astype(int)
        action = action.reshape((2, ))
        #    do_action_multiple(prev_action,action,pyboy)
        do_action(action, pyboy)
        #    prev_action = action

        # Game over:
        if mario.game_over() or mario.score == max_score:
            scores.append(mario.score)
            #fitness_scores.append(mario.fitness)
            fitness_scores.append(
                fitness_calc(mario.score, mario.level_progress,
                             mario.time_left))
            level_progress.append(mario.level_progress)
            time_left.append(mario.time_left)
            if run == run_per_child - 1:
                pyboy.stop()
            else:
                mario.reset_game()
            run += 1

    child_fitness = np.average(fitness_scores)
    logger.info("-" * 20)
    logger.info("Iteration %s - child %s" % (epoch, child_index))
    logger.info("Score: %s, Level Progress: %s, Time Left %s" %
                (scores, level_progress, time_left))
    logger.info("Fitness: %s" % child_fitness)
    #logger.info("Output weight:")
    #weights = {}
    #for i, j in zip(feature_names, child_model.output.weight.data.tolist()[0]):
    #  weights[i] = np.round(j, 3)
    #logger.info(weights)

    return child_fitness
Exemplo n.º 19
0
def test_disable_title():
    # Simply tests, that no exception is generated
    pyboy = PyBoy(any_rom,
                  window_type="dummy",
                  disable_input=True,
                  hide_window=True)
    pyboy.disable_title()
    pyboy.tick()
    pyboy.stop(save=False)
Exemplo n.º 20
0
def test_all_argv():
    pyboy = PyBoy(any_rom,
                  window_type="dummy",
                  bootrom_file=utils.boot_rom,
                  disable_input=True,
                  hide_window=True)
    pyboy.tick()
    pyboy.send_input(windowevent.QUIT)
    pyboy.stop(save=False)
Exemplo n.º 21
0
def loadCartridge(filePath, quiet=True, emSpd=1):
    pyboy = PyBoy(filePath,
                  window_type="headless" if quiet else "SDL2",
                  window_scale=3,
                  debug=not quiet,
                  game_wrapper=True)
    pyboy.set_emulation_speed(emSpd)
    pyboy.cartridge_title() == "SUPER MARIOLAN"
    return pyboy
Exemplo n.º 22
0
def test_screen_buffer_and_image():
    for window, dims, cformat, boot_logo_hash_predigested in [
            # These are different because the underlying format is different. We'll test the actual image afterwards.
        ("SDL2", (160, 144), 'RGBA',
         b'=\xff\xf9z 6\xf0\xe9\xcb\x05J`PM5\xd4rX+\x1b~z\xef1\xe0\x82\xc4t\x06\x82\x12C'
         ),
        ("headless", (160, 144), 'RGBA',
         b'=\xff\xf9z 6\xf0\xe9\xcb\x05J`PM5\xd4rX+\x1b~z\xef1\xe0\x82\xc4t\x06\x82\x12C'
         ),
        ("OpenGL", (144, 160), 'RGB',
         b's\xd1R\x88\xe0a\x14\xd0\xd2\xecOk\xe8b\xae.\x0e\x1e\xb6R\xc2\xe9:\xa2\x0f\xae\xa2\x89M\xbf\xd8|'
         )
    ]:

        pyboy = PyBoy(any_rom,
                      window_type=window,
                      window_scale=1,
                      bootrom_file=boot_rom,
                      disable_input=True,
                      hide_window=True)
        pyboy.set_emulation_speed(0)
        for n in range(275):  # Iterate to boot logo
            pyboy.tick()

        assert pyboy.get_raw_screen_buffer_dims() == dims
        assert pyboy.get_raw_screen_buffer_format() == cformat

        boot_logo_hash = hashlib.sha256()
        boot_logo_hash.update(pyboy.get_raw_screen_buffer())
        assert boot_logo_hash.digest() == boot_logo_hash_predigested
        assert isinstance(pyboy.get_raw_screen_buffer(), bytes)

        # The output of `get_screen_image` is supposed to be homogeneous, which means a shared hash between versions.
        boot_logo_png_hash_predigested = (
            b'\xf4b,(\xbe\xaa\xf8\xec\x06\x9fJ-\x84\xd3I\x16\xb8'
            b'\xe3\xd0\xd5\xae\x80\x01\x1e\x96\xba!1\xeb\xd1\xce_')
        boot_logo_png_hash = hashlib.sha256()
        image = pyboy.get_screen_image()
        assert isinstance(image, PIL.Image.Image)
        image_data = io.BytesIO()
        image.save(image_data, format='BMP')
        boot_logo_png_hash.update(image_data.getvalue())
        assert boot_logo_png_hash.digest() == boot_logo_png_hash_predigested

        # get_screen_ndarray
        numpy_hash = hashlib.sha256()
        numpy_array = np.ascontiguousarray(pyboy.get_screen_ndarray())
        assert isinstance(pyboy.get_screen_ndarray(), np.ndarray)
        assert numpy_array.shape == (144, 160, 3)
        numpy_hash.update(numpy_array.tobytes())
        assert numpy_hash.digest() == (
            b'\r\t\x87\x131\xe8\x06\x82\xcaO=\n\x1e\xa2K$'
            b'\xd6\x8e\x91R( H7\xd8a*B+\xc7\x1f\x19')

        pyboy.stop(save=False)
Exemplo n.º 23
0
def eval_genome(genome, config):
    global max_fitness

    pyboy = PyBoy('SuperMarioLand.gb',
                  game_wrapper=True)  #, window_type="headless")
    pyboy.set_emulation_speed(0)
    mario = pyboy.game_wrapper()
    mario.start_game()
    # start off with just one life each
    mario.set_lives_left(0)

    run = 0
    scores = []
    fitness_scores = []
    level_progress = []
    time_left = []

    # create NN from neat
    model = neat.nn.FeedForwardNetwork.create(genome, config)
    child_fitness = 0

    while run < run_per_child:

        # do some things
        action = get_action_neat(pyboy, mario, model)
        action = np.asarray([np.mean(val) for val in action])
        action = np.where(action < np.max(action), 0, action)
        action = np.where(action == np.max(action), 1, action)
        action = action.astype(int)
        action = action.reshape((2, ))
        do_action(action, pyboy)

        # Game over:
        if mario.game_over() or mario.score == max_score:
            scores.append(mario.score)
            fitness_scores.append(
                fitness_calc(mario.score, mario.level_progress,
                             mario.time_left))
            level_progress.append(mario.level_progress)
            time_left.append(mario.time_left)
            if run == run_per_child - 1:
                pyboy.stop()
            else:
                mario.reset_game()
            run += 1

    child_fitness = np.average(fitness_scores)
    #logger.info("-" * 20)
    #logger.info("Iteration %s - child %s" % (epoch, child_index))
    #logger.info("Score: %s, Level Progress: %s, Time Left %s" % (scores, level_progress, time_left))
    #logger.info("Fitness: %s" % child_fitness)

    return child_fitness
Exemplo n.º 24
0
    def __init__(self, args):

        self.locations = []
        self.events = [
            'D5F3', 'D60D', 'D700', 'D70B', 'D70C', 'D70D', 'D70E', 'D710',
            'D714', 'D72E', 'D751', 'D755', 'D75E', 'D773', 'D77C', 'D782',
            'D790', 'D792', 'D79A', 'D7B3', 'D7D4', 'D7D8', 'D7E0', 'D7EE',
            'D803', 'D85F'
        ]
        self.towns_visited = 0
        self.event_tot = 0
        self.badges = 0
        self.owned_pokemon = 0
        self.position = {}
        self.actions_since_moved = 0
        self.pyboy = PyBoy(
            args.rom,
            window_type=
            "headless",  # For unattended use, for example machine learning
        )
        self.pyboy.disable_title()
        self.transform = transforms.Compose(
            [transforms.Resize(64),
             transforms.ToTensor()])
        self.args = args
        self.action_space = 6
        self.pyboy.set_emulation_speed(0)
        self.buffered_state = io.BytesIO()
        if args.save_state != "":
            self.pyboy.load_state(open(args.save_state, 'rb'))
            self.pyboy.save_state(self.buffered_state)
        else:
            for n in tqdm(
                    range(4000)):  # Move ahead the desired number of frames.
                self.pyboy.tick()
                if 1298 == n:
                    self.pyboy.send_input(windowevent.PRESS_BUTTON_START)
                elif n == 1320:
                    self.pyboy.send_input(windowevent.RELEASE_BUTTON_START)
                elif n > 1320 and n % 2 == 0:
                    self.pyboy.send_input(windowevent.PRESS_BUTTON_A)
                elif n > 1320 and n % 2 != 0:
                    self.pyboy.send_input(windowevent.RELEASE_BUTTON_A)
            self.pyboy.save_state(open('start_game.state', 'wb'))
            self.pyboy.save_state(self.buffered_state)

        self.position['x'] = self.pyboy.get_memory_value(0xd361)
        self.position['y'] = self.pyboy.get_memory_value(0xd362)
        self.pyboy.send_input(SCREEN_RECORDING_TOGGLE)
        self.pyboy.tick()
        frame = self.transform(self.pyboy.get_screen_image())
        self.state_size = frame.size(-1) * frame.size(-2) * frame.size(-3)
Exemplo n.º 25
0
def pokemon():
    pyboy = PyBoy(
        'roms/Pokemon-VersionBleue(France).gb',
        window_type="headless",  # "SDL2" if hidden
        window_scale=3,
        debug=False,
        game_wrapper=True)
    pyboy.set_emulation_speed(0)

    # while not pyboy.tick():
    #     pass

    return pyboy
Exemplo n.º 26
0
def get_set_override():
    pyboy = PyBoy(default_rom, window_type="dummy")
    pyboy.tick()

    assert pyboy.get_memory_value(0xFF40) == 0x91
    assert pyboy.set_memory_value(0xFF40) == 0x12
    assert pyboy.get_memory_value(0xFF40) == 0x12

    assert pyboy.get_memory_value(0x0002) == 0xFE
    assert pyboy.override_memory_value(0x0002) == 0x12
    assert pyboy.get_memory_value(0x0002) == 0x12

    pyboy.stop(save=False)
Exemplo n.º 27
0
    def setup_pyboy(self):
        # load rom through PyBoy
        dir_path = os.path.dirname(os.path.realpath(__file__))
        rom_dir = os.path.join(dir_path, 'roms')
        self.pyboy = PyBoy(os.path.join(rom_dir, 'Pokemon.gb'))

        # set up PyBoy screen support
        self.bot_sup = self.pyboy.botsupport_manager()
        self.scrn = self.bot_sup.screen()

        # minimize PyBoy window
        pyboy_handle = ctypes.windll.user32.FindWindowW(None, "PyBoy")
        ctypes.windll.user32.ShowWindow(pyboy_handle, 6)
Exemplo n.º 28
0
    def __init__(self, rom_path, name, host, port, savestate, password):
        self.pyboy = PyBoy(rom_path)

        if savestate:
            file_like_object = open(savestate, "rb")
            self.pyboy.load_state(file_like_object)

        self.host = host
        self.port = port

        self.currMap = -1
        self.x = 0
        self.y = 0

        self.rivalMap = -1
        self.rivalX = 0
        self.rivalY = 0
        self.rivalFacing = 0
        self.rivalSpriteNum = 15

        self.prevmoFlags = [
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0
        ]
        self.rivalSprite = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        self.sprite = []

        #initial dex
        self.pokedex = pokedexOwned([
            self.pyboy.get_memory_value(t)
            for t in range(POKEDEX_RANGE_START, POKEDEX_RANGE_END + 1)
        ])

        #list of wild pokemon locked out by opp
        self.lockedOutWilds = []

        #initial badges
        self.badges = badgesOwned(self.pyboy.get_memory_value(BADGES_ACQUIRED))

        #game options
        self.gameOptions = None

        #connect to server and send nickname
        self.Connect((self.host, self.port))
        connection.Send({"action": "nickname", "nickname": name})

        #reaaal basic passwording here
        connection.Send({
            "action": "verifyPasswordCheckCapacity",
            "password": password
        })
Exemplo n.º 29
0
    def _abstractStart(self, gameROM, bootROM) -> None:
        """Start the PyBoy emulator.

    Parameters
    ----------
    gameROM: str
        File path to the game ROM to use.
    bootROM: str
        File path to the boot ROM to use.
    """
        self._pyboy = PyBoy(gameROM,
                            default_ram_file=bootROM,
                            window_type="headless")
        self._pyboy.set_emulation_speed(False)
Exemplo n.º 30
0
def test_mario_basics():
    pyboy = PyBoy(supermarioland_rom, window_type="dummy", game_wrapper=True)
    pyboy.set_emulation_speed(0)
    assert pyboy.cartridge_title() == "SUPER MARIOLAN"

    mario = pyboy.game_wrapper()
    mario.start_game(world_level=(1, 1))

    assert mario.score == 0
    assert mario.lives_left == 2
    assert mario.time_left == 400
    assert mario.world == (1, 1)
    assert mario.fitness == 0  # A built-in fitness score for AI development
    pyboy.stop()