Пример #1
0
def randomize_file_select():
    if get_global_label() == "SMRPG_NA":
        addresses = [0x34757, 0x3489a, 0x34ee7, 0x340aa, 0x3501e]
    elif get_global_label() == "SMRPG_JP":
        addresses = [0x347d7, 0x3490d, 0x34f59, 0x340fa, 0x35099]
    else:
        return
    choices = {"peach": range(7, 13),
               "bowser": range(13, 19),
               "mallow": range(19, 25),
               "geno": range(25, 31),
               }
    values = random.choice(choices.values())
    values = [values[i] for i in [0, 1, 0, 0, 1]]
    f = open(get_outfile(), "r+b")
    for addr, value in zip(addresses, values):
        f.seek(addr)
        f.write(chr(value))

    if get_global_label() != "SMRPG_NA":
        return
    f.seek(0x3EF140)
    seed = str(get_seed()).center(10)
    f.write(seed)
    f.close()
Пример #2
0
def get_text(pointer):
    label = get_global_label()
    f = open(get_outfile(), "r+b")
    f.seek(pointer)
    s = ""
    while True:
        peek = f.read(1)
        if label == "AOS_NA" and ord(peek) == 1:
            break
        elif ord(peek) == 0xF0:
            pointer = f.tell()
            peek2 = f.read(1)
            if ord(peek2) == 0:
                break
            f.seek(pointer)
        s += peek
    if label == "AOS_NA":
        trim = [chr(0), chr(6), chr(0xa)]
    else:
        s = s.lstrip(chr(0))
        trim = [chr(0), chr(0xa)]
    while s[-1] in trim:
        for c in trim:
            s = s.rstrip(c)
    pointer = f.tell()
    f.close()
    return s, pointer
Пример #3
0
 def map_crystal_job(cls, value):
     if "GBA" in get_global_label():
         try:
             return {27: 20, 26: 21, 25: 22, 24: 23, 19: 24, 18: 25}[value]
         except KeyError:
             pass
     return (7 - (value % 8)) + ((value / 8) * 8)
Пример #4
0
    def rank(self):
        if hasattr(self, "_rank"):
            return self._rank

        if 'GBA' in get_global_label():
            BANNED_INDEXES = [0x50]
        else:
            BANNED_INDEXES = [0x150]
        if self.index in BANNED_INDEXES:
            self._rank = -1
            return self.rank

        for m in MonsterObject.every:
            m.is_boss
            m._rank = -1

        candidates = [
            m for m in MonsterObject.every
            if m.index not in BANNED_INDEXES and m.hp and m.level
        ]
        sorted_hp = sorted(candidates,
                           key=lambda m: (m.hp, m.level, m.signature))
        sorted_level = sorted(candidates,
                              key=lambda m: (m.level, m.hp, m.signature))
        candidates = sorted(
            candidates,
            key=lambda m:
            (max(sorted_hp.index(m), sorted_level.index(m)), m.signature))

        for m in candidates:
            m._rank = candidates.index(m)

        return self.rank
Пример #5
0
 def cleanup(self):
     if "GBA" in get_global_label() and self.is_freelancer:
         knight = [
             jco for jco in JobCrystalObject.every if jco.crystal_index == 7
         ]
         if knight:
             knight[0].crystal_index = self.crystal_index
         self.crystal_index = 7
Пример #6
0
 def rank(self):
     if hasattr(self, "_rank"):
         return self._rank
     try:
         prices = [w.price for w in self.wares]
     except KeyError, e:
         if get_global_label() == "FFDOS_MOB":
             self._rank = -1
             return self.rank
         else:
             raise e
Пример #7
0
    def intershuffle(cls):
        candidates = sorted(
            [jco for jco in JobCrystalObject.every if jco.intershuffle_valid],
            key=lambda jco: (jco.ability_ap_rank, jco.signature))
        shuffled = []
        while candidates:
            max_index = len(candidates) - 1
            index = random.randint(0, max_index)
            degree = JobCrystalObject.random_degree**0.25
            if degree <= 0.5:
                degree = degree * 2
                a, b = 0, index
            else:
                degree = (degree - 0.5) * 2
                a, b = index, max_index
            index = int(round((a * (1 - degree)) + (b * degree)))
            index = random.randint(0, index)
            chosen = candidates[index]
            shuffled.append(chosen)
            candidates.remove(chosen)

        candidates = sorted(shuffled,
                            key=lambda jco: (jco.rank, jco.signature))
        if 'GBA' not in get_global_label():
            assert len(candidates) == len(shuffled) == 21
        else:
            assert len(candidates) == len(shuffled) == 25
        for c, s in zip(candidates, shuffled):
            c.crystal_index = s.old_data["crystal_index"]

        freelancer = [jco for jco in candidates if jco.is_freelancer][0]
        fight_crystals = [jco for jco in shuffled if jco.has_fight_command]
        if freelancer not in fight_crystals:
            assert not freelancer.has_fight_command
            chosen = fight_crystals[0]
            freelancer.crystal_index, chosen.crystal_index = (
                chosen.crystal_index, freelancer.crystal_index)
        assert freelancer.has_fight_command

        if 'r' in get_flags():
            chance = int(RemoveJobs.random_degree * 100)
            print('Removing jobs ({}% chance)...'.format(chance))
            for c in candidates:
                if random.random() < RemoveJobs.random_degree:
                    c.crystal_index = freelancer.crystal_index
Пример #8
0
        for o in everything_else + battlefields:
            if hasattr(o, "mutated") and o.mutated:
                continue
            o.mutate()
            o.mutated = True


if __name__ == "__main__":
    try:
        print ('You are using the Final Fantasy Mystic Quest "A Terrible Secret" '
               'randomizer version %s.' % VERSION)
        ALL_OBJECTS = [g for g in globals().values()
                       if isinstance(g, type) and issubclass(g, TableObject)
                       and g not in [TableObject]]
        run_interface(ALL_OBJECTS, snes=True)
        if get_global_label() == "FFMQ_NA_1.1":
            DemoPlay = CharacterObject.get(0)
            DemoPlay.name_text = [texttable[c] for c in "Abyssnym"]
            while len(DemoPlay.name_text) < 16:
                DemoPlay.name_text += [0x03]
        hexify = lambda x: "{0:0>2}".format("%x" % x)
        numify = lambda x: "{0: >3}".format(x)
        minmax = lambda x: (min(x), max(x))
        clean_and_write(ALL_OBJECTS)
        if get_global_label() == "FFMQ_NA_1.1":
            write_title_screen(get_outfile(), get_seed(), get_flags())
            enemy_jump = 0xef8e
        elif get_global_label() == "FFMQ_JP":
            enemy_jump = 0xef92
        x = raw_input("Do you want to give Benjamin the power "
                      "to jump over enemies? (y/n) ")
Пример #9
0
                continue
            o.mutate()
            o.mutated = True


if __name__ == "__main__":
    try:
        print(
            'You are using the Final Fantasy Mystic Quest "A Terrible Secret" '
            'randomizer version %s.' % VERSION)
        ALL_OBJECTS = [
            g for g in globals().values() if isinstance(g, type)
            and issubclass(g, TableObject) and g not in [TableObject]
        ]
        run_interface(ALL_OBJECTS, snes=True)
        if get_global_label() == "FFMQ_NA_1.1":
            DemoPlay = CharacterObject.get(0)
            DemoPlay.name_text = [texttable[c] for c in "Abyssnym"]
            while len(DemoPlay.name_text) < 16:
                DemoPlay.name_text += [0x03]
        hexify = lambda x: "{0:0>2}".format("%x" % x)
        numify = lambda x: "{0: >3}".format(x)
        minmax = lambda x: (min(x), max(x))
        clean_and_write(ALL_OBJECTS)
        if get_global_label() == "FFMQ_NA_1.1":
            write_title_screen(get_outfile(), get_seed(), get_flags())
            enemy_jump = 0xef8e
        elif get_global_label() == "FFMQ_JP":
            enemy_jump = 0xef92
        x = raw_input("Do you want to give Benjamin the power "
                      "to jump over enemies? (y/n) ")
Пример #10
0
def run_interface(objects, custom_degree=False, snes=False, codes=None):
    global sourcefile, outfile, flags, user_input_flags
    global activated_codes, all_objects

    all_objects = objects

    if codes is None:
        codes = {}
    activated_codes = set([])

    args = list(argv)[:5]
    num_args = len(args)
    while len(args) < 5:
        args.append(None)
    _, sourcefile, flags, seed, random_degree = tuple(args)
    if random_degree is None and num_args >= 2:
        random_degree = 0.5

    if sourcefile is None:
        print('TIP: Try dragging-and-dropping the rom file '
              'instead of typing the filename manually!')
        sourcefile = input("Rom filename? ")
        if sourcefile.startswith('"') and sourcefile.endswith('"'):
            print('NOTICE: Automatically removing '
                  'extraneous quotation marks.')
            sourcefile = sourcefile.strip('"')

    if seed is None and num_args < 2:
        seed = input("Seed? (blank for random) ").strip()

    if seed is None or seed == "":
        seed = time()
    seed = int(seed)
    seed = seed % (10**10)
    set_seed(seed)
    random.seed(seed)

    # TODO: Temporary ugly hack until all flag in rotds can be randomized
    uglyhack = input("RotDS ROM? (y/n) ").strip().lower()
    if uglyhack == "y":
        flagobjects = [o for o in objects if hasattr(o, "flag")
                   and hasattr(o, "flag_description")
                   and (o.flag == 'm' or o.flag == 'v')]
        codes = {
            "easymodo": ["easymodo"]
        }
    else:
        flagobjects = [o for o in objects if hasattr(o, "flag")
                    and hasattr(o, "flag_description")]

    flagobjects = sorted(flagobjects, key=lambda o: o.flag)
    for o in objects:
        if hasattr(o, "flag") and not hasattr(o, "flag_description"):
            for fo in flagobjects:
                if fo.flag == o.flag:
                    break
            else:
                raise Exception("%s has no flag description." % o.flag)

    allflags = "".join(sorted([f.flag for f in flagobjects]))
    user_input_flags = flags
    if allflags:
        if flags is None and num_args < 2:
            print("\nPlease input the flags for "
                  "the things you want to randomize.")
            for o in flagobjects:
                print("    %s  Randomize %s." % (o.flag,
                                                 o.flag_description.lower()))
            print()
            flags = input("Flags? (blank for all) ").strip()
            user_input_flags = flags
        elif flags is None:
            flags = allflags

    if flags:
        flags = flags.lower()
        for code, code_options in sorted(codes.items()):
            if isinstance(code_options, str):
                code_options = [code_options]
            for co in code_options:
                co = co.lower()
                if co in flags:
                    flags = flags.replace(co, "")
                    activated_codes.add(code)
                    break

    if flags and allflags:
        flags = "".join(sorted([f for f in flags if f in allflags]))
    if not (allflags and flags):
        flags = allflags

    if "." not in sourcefile:
        outfile = [sourcefile, "smc"]
    else:
        outfile = sourcefile.split(".")
    if flags == allflags:
        flagstr = ""
    else:
        flagstr = flags
    outfile = outfile[:-1] + [flagstr, str(seed), outfile[-1]]
    outfile = ".".join(outfile)
    while ".." in outfile:
        outfile = outfile.replace("..", ".")

    try:
        if snes:
            snescopy(sourcefile, outfile)
        else:
            copyfile(sourcefile, outfile)
    except (OSError, IOError) as e:
        if e.strerror == "No such file or directory":
            e.strerror = ('%s; Did you include the filename extension? For '
                          'example, ".smc", ".sfc", or ".img". ' % e.strerror)
        raise e
    set_global_output_filename(outfile)
    determine_global_table(outfile)
    set_table_specs()

    custom_degree = custom_degree or random_degree is not None
    if custom_degree:
        custom_split = False
        for o in sorted(objects, key=lambda ob: str(ob)):
            if hasattr(o, "custom_random_enable") and o.custom_random_enable:
                custom_split = True
                break

        if random_degree is None:
            if custom_split:
                print("\nIf you would like even more control over the "
                      "randomness, type \"custom\" here.")
            random_degree = input("Randomness? (default: 0.5) ").strip()
            if not random_degree:
                random_degree = 0.5

        if custom_split and (isinstance(random_degree, str) and
                             "custom" in random_degree.strip().lower()):
            custom_dict = defaultdict(set)
            for o in sorted(objects, key=lambda o: str(o)):
                if (hasattr(o, "custom_random_enable")
                        and o.custom_random_enable):
                    if o.custom_random_enable is True:
                        custom_dict[o.flag].add(o)
                    else:
                        custom_dict[o.custom_random_enable].add(o)

            for k in sorted(custom_dict):
                os = sorted(custom_dict[k], key=lambda o: o.__name__)
                onames = ", ".join([o.__name__ for o in os])
                s = input("Randomness for %s? " % onames).strip()
                if not s:
                    continue
                for o in os:
                    crd = float(s)
                    assert isinstance(crd, float)
                    crd = min(1.0, max(0.0, crd))
                    o.custom_random_degree = crd ** 2

            random_degree = input("Randomness for everything"
                                  " unspecified? ").strip()
            if not random_degree:
                random_degree = 0.5

        random_degree = float(random_degree)
        assert isinstance(random_degree, float)
        random_degree = min(1.0, max(0.0, random_degree))
        set_random_degree(random_degree ** 2)

    if num_args < 3:
        select_patches()

    print()
    if flags == allflags:
        flags = string.ascii_lowercase
        print("Randomizing %s with all flags using seed %s"
              % (sourcefile, seed), end=' ')
    else:
        flags = flags.lower()
        print("Randomizing %s with flags '%s' using seed %s"
              % (sourcefile, flags, seed), end=' ')
    if custom_degree:
        print("and randomness %s" % random_degree, end=' ')
    print("now.\n")

    if user_input_flags is None:
        user_input_flags = flags

    write_patches(outfile)
    print("Loading and ranking game objects...")
    objects = sort_good_order(objects)
    for o in objects:
        o.every
    for o in objects:
        o.ranked

    for o in objects:
        if hasattr(o, "flag_description") and o.flag in flags:
            print("Randomizing %s." % o.flag_description.lower())
        if not hasattr(o, "flag") or o.flag in flags:
            o.class_reseed('full_randomize')
            o.full_randomize()
        o.randomize_step_finished = True

    # TODO: temporary until implemantation for all supported roms
    if "ROTDS" in get_global_label():
        # create documentation folder
        folder = "docs_{0}".format(get_seed())
        if not path.isdir(folder):
            mkdir(folder)

        # print all printable objects
        for o in objects:
            if hasattr(o, "printable"):
                o.print_all(path.join(folder, o.printable + ".txt"))

    if set(flags) >= set(allflags):
        flags = allflags
Пример #11
0
                m = random.choice(monsters)

            if m:
                if not route_item_flag:
                    m.restore_soul()
                soul_type, soul = m.old_soul
            if soul_type < 5:
                soul_type += 5
            assert 5 <= soul_type <= 7

            LABEL_PRESET[drackey] = (soul_type << 8) | soul
            if m:
                bestiary = m.bestiary
                bestiary = bestiary.strip()
                bestiary = bestiary.rstrip(chr(6))
            elif get_global_label() == "AOS_NA":
                bestiary = ITEM_NAMES[LABEL_PRESET[drackey]]
            else:
                bestiary = None

            f = open(get_outfile(), "r+b")
            if bestiary is not None:
                ancient_addr = getattr(addresses, "ancient_%s" % key)
                ancient, _ = get_text(ancient_addr)
                if get_global_label() == "AOS_NA":
                    if len(bestiary) > len(ancient):
                        bestiary = bestiary[:len(ancient) - 3]
                        bestiary += "..."
                    while len(bestiary) < len(ancient):
                        bestiary += " "
                else:
Пример #12
0
    f.close()


if __name__ == '__main__':
    try:
        print ('You are using the Final Fantasy Legend II '
               '"Mighty Power" randomizer version %s.' % VERSION)
        print

        ALL_OBJECTS = [g for g in globals().values()
                       if isinstance(g, type) and issubclass(g, TableObject)
                       and g not in [TableObject]]

        codes = {
                 }

        run_interface(ALL_OBJECTS, snes=False, codes=codes,
                      custom_degree=True)

        clean_and_write(ALL_OBJECTS)

        if get_global_label() == 'FFL2_NA':
            rewrite_title_screen()

        finish_interface()

    except Exception:
        print_exc()
        print('ERROR:', exc_info()[1])
        input('Press Enter to close this program. ')
Пример #13
0
 def cleanup(self):
     if "GBA" not in get_global_label():
         self.innates |= 0x8
     if "zerker" in get_activated_codes():
         self.innates |= 0x800
Пример #14
0
 def name(self):
     if 'GBA' not in get_global_label() and self.job_index >= 20:
         return JOB_NAMES[self.job_index + 4]
     return JOB_NAMES[self.job_index]
Пример #15
0
        codes = {
            "zerker": ["zerker"],
            "miab": ["miab"],
            "fight": ["fight"],
            "fiesta": ["fiesta"],
        }

        run_interface(ALL_OBJECTS, snes=True, codes=codes, custom_degree=True)

        for code in codes:
            if code in get_activated_codes():
                print "%s CODE ACTIVATED." % code.upper()

        if "fiesta" in get_activated_codes():
            do_fiesta()

        hexify = lambda x: "{0:0>2}".format("%x" % x)
        numify = lambda x: "{0: >3}".format(x)
        minmax = lambda x: (min(x), max(x))
        randomize_rng()
        clean_and_write(ALL_OBJECTS)

        if "GBA" not in get_global_label():
            rewrite_snes_meta("FF5-GC", VERSION, lorom=False)
        finish_interface()
    except Exception, e:
        print "ERROR: %s" % e
        raw_input("Press Enter to close this program.")
        exit(1)