Beispiel #1
0
def generate_with_plandomizer(filename):
    distribution_file = load_spoiler(
        os.path.join(test_dir, 'plando', filename + '.json'))
    try:
        settings = load_settings(distribution_file['settings'],
                                 seed='TESTTESTTEST',
                                 filename=filename)
    except KeyError:  # No settings dict in distribution file, create minimal consistent configuration
        settings = Settings({
            'enable_distribution_file':
            True,
            'distribution_file':
            os.path.join(test_dir, 'plando', filename + '.json'),
            'compress_rom':
            "None",
            'count':
            1,
            'create_spoiler':
            True,
            'output_file':
            os.path.join(test_dir, 'Output', filename),
            'seed':
            'TESTTESTTEST'
        })
    main(settings)
    spoiler = load_spoiler('%s_Spoiler.json' % settings.output_file)
    return distribution_file, spoiler
Beispiel #2
0
 def multiple_run(settings, window):
     orig_seed = settings.seed
     for i in range(settings.count):
         settings.update_seed(orig_seed + '-' + str(i))
         window.update_title("Generating Seed...%d/%d" %
                             (i + 1, settings.count))
         main(settings, window)
Beispiel #3
0
    def testing_console_for_one_task_and_viewing_it(self, mock_input):
        expected_output = '''
    0. Exit
    1. Add task
    2. View task
    3. Mark a task as complete
    4. Save list to file
    

    0. Exit
    1. Add task
    2. View task
    3. Mark a task as complete
    4. Save list to file
    
Incomplete Tasks:
1. Complete the assignment

    0. Exit
    1. Add task
    2. View task
    3. Mark a task as complete
    4. Save list to file
    
'''
        with patch('sys.stdout', new=StringIO()) as fake_out:
            main()
        self.assertEqual(expected_output, fake_out.getvalue())
        os.remove("dump.pkl")
Beispiel #4
0
 def generateRom():
     guiargs = Namespace
     guiargs.seed = int(seedVar.get()) if seedVar.get() else None
     guiargs.count = int(countVar.get()) if countVar.get() != '1' else None
     guiargs.bridge = bridgeVar.get()
     guiargs.create_spoiler = bool(createSpoilerVar.get())
     guiargs.suppress_rom = bool(suppressRomVar.get())
     guiargs.compress_rom = bool(compressRomVar.get())
     guiargs.open_forest = bool(openForestVar.get())
     guiargs.open_door_of_time = bool(openDoorVar.get())
     guiargs.nodungeonitems = bool(dungeonItemsVar.get())
     guiargs.beatableonly = bool(beatableOnlyVar.get())
     guiargs.hints = bool(hintsVar.get())
     guiargs.rom = romVar.get()
     try:
         if guiargs.count is not None:
             seed = guiargs.seed
             for _ in range(guiargs.count):
                 main(seed=seed, args=guiargs)
                 seed = random.randint(0, 999999999)
         else:
             main(seed=guiargs.seed, args=guiargs)
     except Exception as e:
         messagebox.showerror(title="Error while creating seed", message=str(e))
     else:
         messagebox.showinfo(title="Success", message="Rom patched successfully")
Beispiel #5
0
 def test_fuzzer(self):
     fuzz_settings = [
         Settings({
             'randomize_settings': True,
             'compress_rom': "None",
             'create_spoiler': True,
             'output_file': os.path.join(output_dir, 'fuzz-%d' % i),
         }) for i in range(10)
     ]
     out_keys = [
         'randomize_settings', 'compress_rom', 'create_spoiler',
         'output_file', 'seed'
     ]
     for settings in fuzz_settings:
         output_file = '%s_Spoiler.json' % settings.output_file
         settings_file = '%s_%s_Settings.json' % (settings.output_file,
                                                  settings.seed)
         with self.subTest(out=output_file, settings=settings_file):
             try:
                 main(settings)
                 spoiler = load_spoiler(output_file)
                 self.verify_woth(spoiler)
                 self.verify_playthrough(spoiler)
                 self.verify_disables(spoiler)
             except Exception as e:
                 # output the settings file in case of any failure
                 with open(settings_file, 'w') as f:
                     d = {k: settings.__dict__[k] for k in out_keys}
                     json.dump(d, f, indent=0)
                 raise
Beispiel #6
0
 def generateRom():
     guiargs = Namespace
     guiargs.seed = int(seedVar.get()) if seedVar.get() else None
     guiargs.count = int(countVar.get()) if countVar.get() != '1' else None
     guiargs.mode = modeVar.get()
     guiargs.logic = logicVar.get()
     guiargs.goal = goalVar.get()
     guiargs.difficulty = difficultyVar.get()
     guiargs.algorithm = algorithmVar.get()
     guiargs.shuffle = shuffleVar.get()
     guiargs.heartbeep = heartbeepVar.get()
     guiargs.create_spoiler = bool(createSpoilerVar.get())
     guiargs.suppress_rom = bool(suppressRomVar.get())
     guiargs.nodungeonitems = bool(dungeonItemsVar.get())
     guiargs.beatableonly = bool(beatableOnlyVar.get())
     guiargs.quickswap = bool(quickSwapVar.get())
     guiargs.shuffleganon = bool(shuffleGanonVar.get())
     guiargs.rom = romVar.get()
     guiargs.jsonout = None
     guiargs.sprite = spriteVar.get() if spriteVar.get() else None
     try:
         if guiargs.count is not None:
             seed = guiargs.seed
             for i in range(guiargs.count):
                 main(seed=seed, args=guiargs)
                 seed = random.randint(0, 999999999)
         else:
             main(seed=guiargs.seed, args=guiargs)
     except Exception as e:
         messagebox.showerror(title="Error while creating seed", message=str(e))
     else:
         messagebox.showinfo(title="Success", message="Rom patched successfully")
Beispiel #7
0
def start():

    settings, gui, args_loglevel, no_log_file = get_settings_from_command_line_args(
    )

    if is_bundled() and len(sys.argv) == 1:
        # for the bundled builds, if we have no arguments, the user
        # probably wants the gui. Users of the bundled build who want the command line
        # interface shouuld specify at least one option, possibly setting a value to a
        # default if they like all the defaults
        close_console()
        guiMain()
        sys.exit(0)

    # set up logger
    loglevel = {
        'error': logging.ERROR,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'debug': logging.DEBUG
    }[args_loglevel]
    logging.basicConfig(format='%(message)s', level=loglevel)

    logger = logging.getLogger('')

    if not no_log_file:
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H-%M-%S')
        log_dir = local_path('Logs')
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        log_path = os.path.join(log_dir, '%s.log' % st)
        log_file = logging.FileHandler(log_path)
        log_file.setFormatter(
            logging.Formatter('[%(asctime)s] %(message)s', datefmt='%H:%M:%S'))
        logger.addHandler(log_file)

    if not settings.check_version:
        try:
            version_error = check_version(settings.checked_version)
        except VersionError as e:
            logger.warning(str(e))

    try:
        if gui:
            guiMain(settings)
        elif settings.cosmetics_only:
            cosmetic_patch(settings)
        elif settings.patch_file != '':
            from_patch_file(settings)
        elif settings.count != None and settings.count > 1:
            orig_seed = settings.seed
            for i in range(settings.count):
                settings.update_seed(orig_seed + '-' + str(i))
                main(settings)
        else:
            main(settings)
    except Exception as ex:
        logger.exception(ex)
def run():
    printSeparater()
    print_('%s:' % nowStr(), 'Running...')
    main()
    print_('%s:' % nowStr(), 'DONE')
    printSeparater()

    sys.exit() 
Beispiel #9
0
def get_Tweets(scr_name):
    sucessful = False
    try:
        main(scr_name)
        sucessful = True
    except Exception as e:
        sucessful = False


    return jsonify({'successful': sucessful})
Beispiel #10
0
 def testing_console_for_two_task_and_marking_one_as_complete_then_saving_it_to_file(self, mock_input):
     with patch('sys.stdout', new=StringIO()) as fake_out:
         main()
     path_desktop = "."  # os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop')
     file_path = path_desktop + "/MyTasks.txt"
     with open(file_path, "r") as file:
         content = file.readlines()
     all_tasks = ''.join([str(elem) for elem in content])
     self.assertEqual("Incomplete Tasks:\n1. Meet Ema at 7\nComplete Tasks:\n1. Complete the assignment\n",
                      all_tasks)
     os.remove(file_path)
     os.remove("dump.pkl")
Beispiel #11
0
 def test_testcases(self):
     test_files = [filename
                   for filename in os.listdir(test_dir)
                   if filename.endswith('.sav')]
     for filename in test_files:
         with self.subTest(filename=filename):
             settings = load_settings(filename, seed='TESTTESTTEST')
             main(settings)
             # settings.output_file contains the first part of the filename
             spoiler = load_spoiler('%s_Spoiler.json' % settings.output_file)
             self.verify_woth(spoiler)
             self.verify_playthrough(spoiler)
             self.verify_disables(spoiler)
Beispiel #12
0
def start():

    settings, gui, args_loglevel, no_log_file = get_settings_from_command_line_args(
    )

    # set up logger
    loglevel = {
        'error': logging.ERROR,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'debug': logging.DEBUG
    }[args_loglevel]
    logging.basicConfig(format='%(message)s', level=loglevel)

    logger = logging.getLogger('')

    if not no_log_file:
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H-%M-%S')
        log_dir = local_path('Logs')
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        log_path = os.path.join(log_dir, '%s.log' % st)
        log_file = logging.FileHandler(log_path)
        log_file.setFormatter(
            logging.Formatter('[%(asctime)s] %(message)s', datefmt='%H:%M:%S'))
        logger.addHandler(log_file)

    if not settings.check_version:
        try:
            check_version(settings.checked_version)
        except VersionError as e:
            logger.warning(str(e))

    try:
        if gui:
            guiMain(settings)
        elif settings.cosmetics_only:
            cosmetic_patch(settings)
        elif settings.patch_file != '':
            from_patch_file(settings)
        elif settings.count != None and settings.count > 1:
            orig_seed = settings.seed
            for i in range(settings.count):
                settings.update_seed(orig_seed + '-' + str(i))
                main(settings)
        else:
            main(settings)
    except Exception as ex:
        logger.exception(ex)
        sys.exit(1)
def start():
    args = parse_arguments(None)

    if is_bundled() and len(sys.argv) == 1:
        # for the bundled builds, if we have no arguments, the user
        # probably wants the gui. Users of the bundled build who want the command line
        # interface shouuld specify at least one option, possibly setting a value to a
        # default if they like all the defaults
        from Gui import guiMain
        close_console()
        guiMain()
        sys.exit(0)

    # ToDo: Validate files further than mere existance
    if not args.jsonout and not os.path.isfile(args.rom):
        input(
            'Could not find valid base rom for patching at expected path %s. Please run with -h to see help for further information. \nPress Enter to exit.'
            % args.rom)
        sys.exit(1)
    if any([
            sprite is not None and not os.path.isfile(sprite)
            and not get_sprite_from_name(sprite)
            for sprite in args.sprite.values()
    ]):
        if not args.jsonout:
            input(
                'Could not find link sprite sheet at given location. \nPress Enter to exit.'
            )
            sys.exit(1)
        else:
            raise IOError('Cannot find sprite file at %s' % args.sprite)

    # set up logger
    loglevel = {
        'error': logging.ERROR,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'debug': logging.DEBUG
    }[args.loglevel]
    logging.basicConfig(format='%(message)s', level=loglevel)

    if args.gui:
        from Gui import guiMain
        guiMain(args)
    elif args.count is not None:
        seed = args.seed
        for _ in range(args.count):
            main(seed=seed, args=args)
            seed = random.randint(0, 999999999)
    else:
        main(seed=args.seed, args=args)
Beispiel #14
0
 def test_ammo_max_out_of_bounds_use_last_list_element(self):
     # This issue only appeared while patching
     filename = "plando-ammo-max-out-of-bounds"
     settings = Settings({
         'enable_distribution_file': True,
         'distribution_file': os.path.join(test_dir, 'plando', filename + '.json'),
         'compress_rom': "Patch",
         'count': 1,
         'create_spoiler': True,
         'create_cosmetics_log': False,
         'output_file': os.path.join(test_dir, 'Output', filename),
         'seed': 'TESTTESTTEST'
     })
     main(settings)  # Should not crash
Beispiel #15
0
def start():

    settings, gui, args_loglevel = get_settings_from_command_line_args()

    if is_bundled() and len(sys.argv) == 1:
        # for the bundled builds, if we have no arguments, the user
        # probably wants the gui. Users of the bundled build who want the command line
        # interface shouuld specify at least one option, possibly setting a value to a
        # default if they like all the defaults
        close_console()
        guiMain()
        sys.exit(0)

    # ToDo: Validate files further than mere existance
    if not os.path.isfile(settings.rom):
        input(
            'Could not find valid base rom for patching at expected path %s. Please run with -h to see help for further information. \nPress Enter to exit.'
            % settings.rom)
        sys.exit(1)

    # set up logger
    loglevel = {
        'error': logging.ERROR,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'debug': logging.DEBUG
    }[args_loglevel]
    logging.basicConfig(format='%(message)s', level=loglevel)

    logger = logging.getLogger('')
    if not settings.check_version:
        try:
            version_error = check_version(settings.checked_version)
        except VersionError as e:
            logger.warning(str(e))

    if gui:
        guiMain(settings)
    elif settings.cosmetics_only:
        cosmetic_patch(settings)
    elif settings.patch_file != '':
        from_patch_file(settings)
    elif settings.count is not None:
        orig_seed = settings.seed
        for i in range(settings.count):
            settings.update_seed(orig_seed + '-' + str(i))
            main(settings)
    else:
        main(settings)
Beispiel #16
0
 def test_presets(self):
     presetsFiles = get_preset_files()
     for fn in presetsFiles:
         with open(fn, encoding='utf-8') as f:
             presets = json.load(f)
         for name, settings_dict in presets.items():
             ofile = 'preset_' + re.sub(r'[^a-zA-Z0-9_-]+', '_', name)
             with self.subTest(name, filename=ofile):
                 settings = make_settings_for_test(
                         settings_dict, seed='TESTTESTTEST', outfilename=ofile)
                 main(settings)
                 spoiler = load_spoiler('%s_Spoiler.json' % settings.output_file)
                 self.verify_woth(spoiler)
                 self.verify_playthrough(spoiler)
                 self.verify_disables(spoiler)
Beispiel #17
0
    def generateRom():
        settings = guivars_to_settings(guivars)

        try:
            if settings.count is not None:
                orig_seed = settings.seed
                for i in range(settings.count):
                    settings.update_seed(orig_seed + '-' + str(i))
                    main(settings)
            else:
                main(settings)
        except Exception as e:
            messagebox.showerror(title="Error while creating seed", message=str(e))
        else:
            messagebox.showinfo(title="Success", message="Rom patched successfully")
Beispiel #18
0
def Sign_Students(stuid):
    print("【欢迎使用职教云补签助手】")
    print("                  By:Lan")
    date = input("请输入需要补签的日期如(2020-5-20):")
    courses = get_course(stuid, date)
    if courses == 'no':
        print("你今天没有课,好好休息")
    else:
        print("Lan职教云助手提示您:\n您今天课表如下:")
        for i in range(len(courses['courseNmae'])):
            print(
                f'【{i + 1}】:{courses["classSection"][i]}{courses["courseNmae"][i]}'
            )
        index = int(input("请输入你要改签到分数的课程:")) - 1
        activities = get_activity(stuid, courses["courseId"][index],
                                  courses["openClassId"][index])
        buqianname = []
        buqianid = []
        for j in range(len(activities)):
            datatype = activities[j]['DataType']
            if datatype == "签到":
                buqianname.append(activities[j]['Title'])
                buqianid.append(activities[j]['Id'])
        for i in range(len(buqianid)):
            print(f'【{i}】{buqianname[i]}')
        target = int(input("请输入要改分的序号:"))
        SignId = buqianid[target]
        activityid = activities[target]['Id']
        url = 'https://zjyapp.icve.com.cn/newmobileapi/faceTeach/getCheckStuInfo'
        data = {
            'signId': SignId,
            'activityId': activityid,
        }
        html = requests.post(url=url, data=data).json()
        for i in html['signedList']:
            if i['StuId'] == stuid:
                SignStuId = i['SignStuId']
        get_grade = input("请输入要改的分数(1-5):")
        grade_url = 'https://zjyapp.icve.com.cn/newmobileapi/faceTeach/saveSignStuScore'
        data = {'signId': SignId, 'signStuIds': SignStuId, 'score': get_grade}
        result = requests.post(url=grade_url, data=data).json()['msg']
        print(result)
        print("返回首页菜单")
        from Main import main
        main()
Beispiel #19
0
    def Reconfigure():
        ScriptName = data['ScriptName']

        if os.path.isfile('Scripts/' + ScriptName + '.json'):
            data['Auto'] = False
            data['ScriptName'] = None
            with open('Scripts/Loads.json', 'w') as wJson:
                json.dump(data, wJson, indent=4)
            os.remove('Scripts/' + ScriptName + '.json')
            global Discovered
            Discovered = False
            CHARACTERS[0] = ""
            time.sleep(.2)
            ThreadSearcher.join()
            SelectCharacter.destroy()
            time.sleep(.4)
            from Main import main
            main()
Beispiel #20
0
def screenshot():
    if not take_shot:  # 정지 버튼을 눌렀을 때
        return

    try:
        imgGrab = ImageGrab.grab(bbox=(*start_point, *end_point))  # 이미지 캡쳐
        imgGrab.save("screen_shot.png")
        imgGrab.resize((200, 150)).save("thumbnail.gif")

        # if thumbnailLbl:
        #    thumbnailLbl.destroy()
        thumbnailImg = tk.PhotoImage(file="thumbnail.gif")
        thumbnailLbl = tk.Label(canvas, image=thumbnailImg)
        thumbnailLbl.image = thumbnailImg
        thumbnailLbl.place(x=0, y=0)

        # try:
        main()
        # except Exception:
        #     logging.error("unexpected error in main function")

        # if thumbnailLbl2:
        #    thumbnailLbl2.destroy()
        thumbnailImg2 = tk.PhotoImage(file="convert_thumbnail.gif")
        thumbnailLbl2 = tk.Label(canvas, image=thumbnailImg2)
        thumbnailLbl.image2 = thumbnailImg2
        thumbnailLbl2.place(x=200, y=0)
        print("o")

        fo = open("pc_info.json")
        json_info = json.load(fo)
        fo.close()

        if json_info["empty_seats"] == 0:
            logging.warning("no seats detected")
        else:
            logging.info("json file generated")

        emptySeatsLbl.config(text="빈 좌석:" + str(json_info["empty_seats"]))
    except:
        pass

    root.after(20000, screenshot)
Beispiel #21
0
        def html_creator(starting, ending, ratio0):
            templateLoader = jinja2.FileSystemLoader(searchpath="")
            templateEnv = jinja2.Environment(loader=templateLoader)
            TEMPLATE_FILE = "template_suggestions.html"
            template = templateEnv.get_template(TEMPLATE_FILE)

            outputText = template.render(range=dates_header(starting, ending),
                                         table=main(dates(starting, ending),
                                                    ratio0))
            html_file = open("suggestions" + '.html', 'w')
            html_file.write(outputText)
            html_file.close()
Beispiel #22
0
    def post(self):
        # Getting Post data
        post_json = request.get_json()

        # Convert JSON into Dictionary
        post_dict = json.loads(post_json)

        # Key values of post data
        file_name = post_dict['file_name']

        text = main(file_name)

        return {"text": text, "status": "successfull"}, 201
Beispiel #23
0
 def test_2(self):
     filename = '../inputs/input2'
     self.assertEqual(
         {
             2: {
                 'shops': 3,
                 'positions': [[3, 3], [4, 2]]
             },
             4: {
                 'shops':
                 4,
                 'positions': [[1, 3], [2, 3], [2, 4], [3, 2], [3, 3],
                               [3, 4], [3, 5], [4, 3], [4, 4]]
             }
         }, main(filename))
Beispiel #24
0
 def test_1(self):
     filename = '../inputs/input1'
     self.assertEqual(
         {
             1: {
                 'shops': 3,
                 'positions': [[3, 4]]
             },
             2: {
                 'shops': 4,
                 'positions': [[1, 3], [2, 2]]
             },
             4: {
                 'shops':
                 5,
                 'positions': [[1, 3], [1, 4], [2, 2], [2, 3], [3, 1],
                               [3, 2], [4, 2]]
             }
         }, main(filename))
Beispiel #25
0
def predict():
    if request.method == 'POST':
        # Get the image from post request
        img = base64_to_pil(request.json)

        # Save the image to ./uploads
        img.save("image.png")

        # Make prediction
        preds = main("image.png")

        # Process your result for human
        # pred_proba = "{:.3f}".format(np.amax(preds))    # Max probability

        # result = str(pred_class[0][0][1])              # Convert to string
        # result = result.replace('_', ' ').capitalize()

        # Serialize the result, you can add additional fields
        return jsonify(result=preds)

    return None
Beispiel #26
0
def question():
    response = jsonify(main("apple.docx"))
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    return response
Beispiel #27
0
    flag = False
    for i in range(1, length):
        if arg_list[i] == '-arg':
            break;
        if flag:
            path += ' '
        path += arg_list[i]
        flag = True
    return path


if __name__ == '__main__':
    check_if_first_time()
    try:
        length = len(sys.argv)
        arg_list = list(sys.argv)
        if '-arg' in arg_list:
            original_path = getpath(__file__)
            p = str(sys.argv)
            file_path = make_path(arg_list, length)
            arg = all_args(arg_list)
            # print(arg, file_path)
            main(arg, original_path)
        else:
            arg = get_args(arg_list, len(arg_list))
            main(arg, original_path=os.getcwd())
            # print(arg)

    except Exception as e:
        main(original_path=os.getcwd())
Beispiel #28
0
regSpaces = 15
avSpaces = regSpaces

def on_connect(client, userdata, flags, rc):
    client.subscribe("zone_1")

def on_message(client, userdata, message):
    available -= 1
    sensors.displayUpdate(display, avSpaces, regSpaces)

mqttc.on_connect = on_connect
mqttc.on_message = on_message

while(True):
    if sensors.doubleTouchPulse(touch):
        avSpaces +=1
        mqttc.publish("zone_1", "zone_2")
        sensors.displayUpdate(display, avSpaces, regSpaces)
        
    if __name__ == "__main__":
        if sensors.buttonPulse(buttonInput):
            main()
            time.sleep(3)
            sensors.spinServo(s
            avSpaces -= 1
            sensors.displayUpdate(display, avSpaces, regSpaces)
    if sensors.buttonPulse(buttonOutput):
        mqttc.publish("exit_1", "zone_1")
        avSpaces += 1
        sensors.displayUpdate(display, avSpaces, regSpaces)
Beispiel #29
0
def profileWindow():
	from Main import main
	main()
def start():
    parser = argparse.ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument('--create_spoiler', help='Output a Spoiler File', action='store_true')
    parser.add_argument('--bridge', default='medallions', const='medallions', nargs='?', choices=['medallions', 'vanilla', 'dungeons', 'open'],
                        help='''\
                             Select requirement to spawn the Rainbow Bridge to reach Ganon's Castle. (default: %(default)s)
                             Medallions:    Collect all six medallions to create the bridge.
                             Vanilla:       Collect only the Shadow and Spirit Medallions and then view the Light Arrow cutscene.
                             All Dungeons:  Collect all spiritual stones and all medallions to create the bridge.
                             Open:          The bridge will spawn without an item requirement.
                             ''')
    parser.add_argument('--rom', default='ZOOTDEC.z64', help='Path to an OoT 1.0 rom to use as a base.')
    parser.add_argument('--loglevel', default='info', const='info', nargs='?', choices=['error', 'info', 'warning', 'debug'], help='Select level of logging for output.')
    parser.add_argument('--seed', help='Define seed number to generate.', type=int)
    parser.add_argument('--count', help='''\
                             Use to batch generate multiple seeds with same settings.
                             If --seed is provided, it will be used for the first seed, then
                             used to derive the next seed (i.e. generating 10 seeds with
                             --seed given will produce the same 10 (different) roms each
                             time).
                             ''', type=int)
    parser.add_argument('--open_forest', help='''\
                             Mido no longer blocks the path to the Deku Tree and
                             the Kokiri boy no longer blocks the path out of the forest.
                             ''', action='store_true')
    parser.add_argument('--open_door_of_time', help='''\
                             The Door of Time is open from the beginning of the game.
                             ''', action='store_true')
    parser.add_argument('--fast_ganon', help='''\
                             The barrier within Ganon's Castle leading to Ganon's Tower is dispelled from the
                             beginning of the game, the Boss Key is not required in Ganon's Tower, Ganondorf
                             gives a hint for the location of Light Arrows, and the tower collapse sequence
                             is removed.
                             ''', action='store_true')
    parser.add_argument('--nodungeonitems', help='''\
                             Remove Maps and Compasses from Itempool, replacing them by
                             empty slots.
                             ''', action='store_true')
    parser.add_argument('--beatableonly', help='''\
                             Only check if the game is beatable with placement. Do not
                             ensure all locations are reachable. This only has an effect
                             on the restrictive algorithm currently.
                             ''', action='store_true')
    parser.add_argument('--hints', help='''\
                             Gossip Stones provide helpful hints about which items are
                             in inconvenient locations if the Stone of Agony is in
                             the player's inventory.
                             ''', action='store_true')
    parser.add_argument('--kokiricolor', default='Kokiri Green', const='medallions', nargs='?', choices=['Kokiri Green', 'Goron Red', 'Zora Blue', 'Black', 'White', 'Purple', 'Yellow', 'Orange', 'Pink', 'Gray', 'Brown', 'Gold', 'Silver', 'Beige', 'Teal', 'Royal Blue', 'Sonic Blue', 'Blood Red', 'Blood Orange', 'NES Green', 'Dark Green', 'Random', 'True Random'],
                        help='''\
                             Choose the color for Link's Kokiri Tunic. (default: %(default)s)
                             Color:        Make the Kokiri Tunic this color.
                             Random:       Choose a random color from this list of colors.
                             True Random:  Choose a random color from any color the N64 can draw.
                             ''')
    parser.add_argument('--goroncolor', default='Goron Red', const='medallions', nargs='?', choices=['Kokiri Green', 'Goron Red', 'Zora Blue', 'Black', 'White', 'Purple', 'Yellow', 'Orange', 'Pink', 'Gray', 'Brown', 'Gold', 'Silver', 'Beige', 'Teal', 'Royal Blue', 'Sonic Blue', 'Blood Red', 'Blood Orange', 'NES Green', 'Dark Green', 'Random', 'True Random'],
                        help='''\
                             Choose the color for Link's Goron Tunic. (default: %(default)s)
                             Color:        Make the Goron Tunic this color.
                             Random:       Choose a random color from this list of colors.
                             True Random:  Choose a random color from any color the N64 can draw.
                             ''')
    parser.add_argument('--zoracolor', default='Zora Blue', const='medallions', nargs='?', choices=['Kokiri Green', 'Goron Red', 'Zora Blue', 'Black', 'White', 'Purple', 'Yellow', 'Orange', 'Pink', 'Gray', 'Brown', 'Gold', 'Silver', 'Beige', 'Teal', 'Royal Blue', 'Sonic Blue', 'Blood Red', 'Blood Orange', 'NES Green', 'Dark Green', 'Random', 'True Random'],
                        help='''\
                             Choose the color for Link's Zora Tunic. (default: %(default)s)
                             Color:        Make the Zora Tunic this color.
                             Random:       Choose a random color from this list of colors.
                             True Random:  Choose a random color from any color the N64 can draw.
                             ''')
    parser.add_argument('--healthSFX', default='Default', const='Default', nargs='?', choices=['Default', 'Softer Beep', 'Rupee', 'Timer', 'Tamborine', 'Recovery Heart', 'Carrot Refill', 'Navi - Hey!', 'Zelda - Gasp', 'Cluck', 'Mweep!', 'Random', 'None'],
                        help='''\
                             Select the sound effect that loops at low health. (default: %(default)s)
                             Sound:        Replace the sound effect with the chosen sound.
                             Random:       Replace the sound effect with a random sound from this list.
                             None:         Eliminate heart beeps.
                             ''')
    parser.add_argument('--suppress_rom', help='Do not create an output rom file.', action='store_true')
    parser.add_argument('--compress_rom', help='Create a compressed version of the output rom file.', action='store_true')
    parser.add_argument('--gui', help='Launch the GUI', action='store_true')
    args = parser.parse_args()

    if is_bundled() and len(sys.argv) == 1:
        # for the bundled builds, if we have no arguments, the user
        # probably wants the gui. Users of the bundled build who want the command line
        # interface shouuld specify at least one option, possibly setting a value to a
        # default if they like all the defaults
        close_console()
        guiMain()
        sys.exit(0)

    # ToDo: Validate files further than mere existance
    if not os.path.isfile(args.rom):
        input('Could not find valid base rom for patching at expected path %s. Please run with -h to see help for further information. \nPress Enter to exit.' % args.rom)
        sys.exit(1)

    # set up logger
    loglevel = {'error': logging.ERROR, 'info': logging.INFO, 'warning': logging.WARNING, 'debug': logging.DEBUG}[args.loglevel]
    logging.basicConfig(format='%(message)s', level=loglevel)

    if args.gui:
        guiMain(args)
    elif args.count is not None:
        seed = args.seed
        for _ in range(args.count):
            main(seed=seed, args=args)
            seed = random.randint(0, 999999999)
    else:
        main(seed=args.seed, args=args)
		sys.stdout.flush()
		sys.stderr.flush()
		si = file(self.stdin, 'r')
		so = file(self.stdout, 'a+')
		se = file(self.stderr, 'a+', 0)
		os.dup2(si.fileno(), sys.stdin.fileno())
		os.dup2(so.fileno(), sys.stdout.fileno())
		os.dup2(se.fileno(), sys.stderr.fileno())
	
		# write pidfile
		atexit.register(self.delpid)
		pid = str(os.getpid())
		file(self.pidfile,'w+').write("%s\n" % pid)	
		from Configuration import Configuration
		from Main import main
		main = main()
		config = Configuration()
		
		while True:
			main
			time.sleep(float(config.sleeptimer))	
			
	def delpid(self):
		os.remove(self.pidfile)

	def start(self):
		"""
		Start the daemon
		"""
		# Check for a pidfile to see if the daemon already runs
		try:
N=150 #Agent's number
#m=8 #Average degree
p=0.5 #Conection probability
E=2 #Energy curve type (1) fast increment, (2) stable and (3) Slow increment
interes=0.007974 #interest rates

sn=1 #Number of simulations (between 1000 and 10000 - typical convergence parameter applied to social science)

analyser_m=np.zeros([301,6,2])
cc=0
for l in range(2,12,2):
    m=l
    analyser=np.zeros([3,301,sn])
    
    for i in range(sn):
        analyser[:,:,i]=main(N,m,p,E,interes)
    
    #Calculated average and standar deviation
    analyser_stat=np.zeros([301,3,2])
    for i in range(3):
        for j in range (301):
            analyser_stat[j,i,0]=np.mean(analyser[i,j,:])
            analyser_stat[j,i,1]=np.std(analyser[i,j,:])
    
    analyser_m[:,cc,0]=analyser_stat[:,2,0]
    analyser_m[:,cc,1]=analyser_stat[:,2,1]
    cc=cc+1

analyser_m[0,5,0]=2005
for i in range(1,301):
    analyser_m[i,5,0]=analyser_stat[i-1,5,0]+1/12
                             ''')
    parser.add_argument('--suppress_rom', help='Do not create an output rom file.', action='store_true')
    parser.add_argument('--gui', help='Launch the GUI', action='store_true')
    parser.add_argument('--jsonout', help='''\
                            Output .json patch file instead of a patched rom. Used 
                            for VT site integration, do not use otherwise.
                            ''')
    args = parser.parse_args()

    # ToDo: Validate files further than mere existance
    if not args.jsonout and not os.path.isfile(args.rom):
        input('Could not find valid base rom for patching at expected path %s. Please run with -h to see help for further information. \nPress Enter to exit.' % args.rom)
        exit(1)
    if args.sprite is not None and not os.path.isfile(args.rom):
        input('Could not find link sprite sheet at given location. \nPress Enter to exit.' % args.sprite)
        exit(1)

    # set up logger
    loglevel = {'error': logging.ERROR, 'info': logging.INFO, 'warning': logging.WARNING, 'debug': logging.DEBUG}[args.loglevel]
    logging.basicConfig(format='%(message)s', level=loglevel)

    if args.gui:
        guiMain(args)
    elif args.count is not None:
        seed = args.seed
        for i in range(args.count):
            main(seed=seed, args=args)
            seed = random.randint(0, 999999999)
    else:
        main(seed=args.seed, args=args)
def start():
    parser = argparse.ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument('--create_spoiler', help='Output a Spoiler File', action='store_true')
    parser.add_argument('--logic', default='noglitches', const='noglitches', nargs='?', choices=['noglitches', 'minorglitches', 'nologic'],
                        help='''\
                             Select Enforcement of Item Requirements. (default: %(default)s)
                             No Glitches:
                             Minor Glitches: May require Fake Flippers, Bunny Revival
                                             and Dark Room Navigation.
                             No Logic: Distribute items without regard for
                                             item requirements.
                             ''')
    parser.add_argument('--mode', default='open', const='open', nargs='?', choices=['standard', 'open', 'swordless'],
                        help='''\
                             Select game mode. (default: %(default)s)
                             Open:      World starts with Zelda rescued.
                             Standard:  Fixes Hyrule Castle Secret Entrance and Front Door
                                        but may lead to weird rain state issues if you exit
                                        through the Hyrule Castle side exits before rescuing
                                        Zelda in a full shuffle.
                             Swordless: Like Open, but with no swords. Curtains in
                                        Skull Woods and Agahnims Tower are removed,
                                        Agahnim\'s Tower barrier can be destroyed with
                                        hammer. Misery Mire and Turtle Rock can be opened
                                        without a sword. Hammer damages Ganon. Ether and
                                        Bombos Tablet can be activated with Hammer (and Book).
                             ''')
    parser.add_argument('--goal', default='ganon', const='ganon', nargs='?', choices=['ganon', 'pedestal', 'dungeons', 'triforcehunt', 'crystals'],
                        help='''\
                             Select completion goal. (default: %(default)s)
                             Ganon:         Collect all crystals, beat Agahnim 2 then
                                            defeat Ganon.
                             Crystals:      Collect all crystals then defeat Ganon.
                             Pedestal:      Places the Triforce at the Master Sword Pedestal.
                             All Dungeons:  Collect all crystals, pendants, beat both
                                            Agahnim fights and then defeat Ganon.
                             Triforce Hunt: Places 30 Triforce Pieces in the world, collect
                                            20 of them to beat the game.
                             ''')
    parser.add_argument('--difficulty', default='normal', const='normal', nargs='?', choices=['easy', 'normal', 'hard', 'expert', 'insane'],
                        help='''\
                             Select game difficulty. Affects available itempool. (default: %(default)s)
                             Easy:            An easy setting with extra equipment.
                             Normal:          Normal difficulty.
                             Hard:            A harder setting with less equipment and reduced health.
                             Expert:          A harder yet setting with minimum equipment and health.
                             Insane:          A setting with the absolute minimum in equipment and no extra health.
                             ''')
    parser.add_argument('--timer', default='none', const='normal', nargs='?', choices=['none', 'display', 'timed', 'timed-ohko', 'ohko', 'timed-countdown'],
                        help='''\
                             Select game timer setting. Affects available itempool. (default: %(default)s)
                             None:            No timer.
                             Display:         Displays a timer but does not affect
                                              the itempool.
                             Timed:           Starts with clock at zero. Green Clocks
                                              subtract 4 minutes (Total: 20), Blue Clocks
                                              subtract 2 minutes (Total: 10), Red Clocks add
                                              2 minutes (Total: 10). Winner is player with
                                              lowest time at the end.
                             Timed OHKO:      Starts clock at 10 minutes. Green Clocks add
                                              5 minutes (Total: 25). As long as clock is at 0,
                                              Link will die in one hit.
                             OHKO:            Like Timed OHKO, but no clock items are present
                                              and the clock is permenantly at zero.
                             Timed Countdown: Starts with clock at 40 minutes. Same clocks as
                                              Timed mode. If time runs out, you lose (but can
                                              still keep playing).
                             ''')
    parser.add_argument('--progressive', default='on', const='normal', nargs='?', choices=['on', 'off', 'random'],
                        help='''\
                             Select progressive equipment setting. Affects available itempool. (default: %(default)s)
                             On:              Swords, Shields, Armor, and Gloves will
                                              all be progressive equipment. Each subsequent
                                              item of the same type the player finds will
                                              upgrade that piece of equipment by one stage.
                             Off:             Swords, Shields, Armor, and Gloves will not
                                              be progressive equipment. Higher level items may
                                              be found at any time. Downgrades are not possible.
                             Random:          Swords, Shields, Armor, and Gloves will, per
                                              category, be randomly progressive or not.
                                              Link will die in one hit.
                             ''')
    parser.add_argument('--algorithm', default='balanced', const='balanced', nargs='?', choices=['freshness', 'flood', 'vt21', 'vt22', 'vt25', 'vt26', 'balanced'],
                        help='''\
                             Select item filling algorithm. (default: %(default)s
                             balanced:    vt26 derivitive that aims to strike a balance between
                                          the overworld heavy vt25 and the dungeon heavy vt26
                                          algorithm.
                             vt26:        Shuffle items and place them in a random location
                                          that it is not impossible to be in. This includes
                                          dungeon keys and items.
                             vt25:        Shuffle items and place them in a random location
                                          that it is not impossible to be in.
                             vt21:        Unbiased in its selection, but has tendency to put
                                          Ice Rod in Turtle Rock.
                             vt22:        Drops off stale locations after 1/3 of progress
                                          items were placed to try to circumvent vt21\'s
                                          shortcomings.
                             Freshness:   Keep track of stale locations (ones that cannot be
                                          reached yet) and decrease likeliness of selecting
                                          them the more often they were found unreachable.
                             Flood:       Push out items starting from Link\'s House and
                                          slightly biased to placing progression items with
                                          less restrictions.
                             ''')
    parser.add_argument('--shuffle', default='full', const='full', nargs='?', choices=['vanilla', 'simple', 'restricted', 'full', 'crossed', 'insanity', 'restricted_legacy', 'full_legacy', 'madness_legacy', 'insanity_legacy', 'dungeonsfull', 'dungeonssimple'],
                        help='''\
                             Select Entrance Shuffling Algorithm. (default: %(default)s)
                             Full:       Mix cave and dungeon entrances freely while limiting
                                         multi-entrance caves to one world.
                             Simple:     Shuffle Dungeon Entrances/Exits between each other
                                         and keep all 4-entrance dungeons confined to one
                                         location. All caves outside of death mountain are
                                         shuffled in pairs and matched by original type.
                             Restricted: Use Dungeons shuffling from Simple but freely
                                         connect remaining entrances.
                             Crossed:    Mix cave and dungeon entrances freely while allowing
                                         caves to cross between worlds.
                             Insanity:   Decouple entrances and exits from each other and
                                         shuffle them freely. Caves that used to be single
                                         entrance will still exit to the same location from
                                         which they are entered.
                             Vanilla:    All entrances are in the same locations they were
                                         in the base game.
                             Legacy shuffles preserve behavior from older versions of the
                             entrance randomizer including significant technical limitations.
                             The dungeon variants only mix up dungeons and keep the rest of
                             the overworld vanilla.
                             ''')
    parser.add_argument('--rom', default='Zelda no Densetsu - Kamigami no Triforce (Japan).sfc', help='Path to an ALttP JAP(1.0) rom to use as a base.')
    parser.add_argument('--loglevel', default='info', const='info', nargs='?', choices=['error', 'info', 'warning', 'debug'], help='Select level of logging for output.')
    parser.add_argument('--seed', help='Define seed number to generate.', type=int)
    parser.add_argument('--count', help='''\
                             Use to batch generate multiple seeds with same settings.
                             If --seed is provided, it will be used for the first seed, then
                             used to derive the next seed (i.e. generating 10 seeds with
                             --seed given will produce the same 10 (different) roms each
                             time).
                             ''', type=int)
    parser.add_argument('--fastmenu', default='normal', const='normal', nargs='?', choices=['normal', 'instant', 'double', 'triple', 'quadruple', 'half'],
                        help='''\
                             Select the rate at which the menu opens and closes.
                             (default: %(default)s)
                             ''')
    parser.add_argument('--quickswap', help='Enable quick item swapping with L and R.', action='store_true')
    parser.add_argument('--disablemusic', help='Disables game music.', action='store_true')
    parser.add_argument('--keysanity', help='''\
                             Keys (and other dungeon items) are no longer restricted to
                             their dungeons, but can be anywhere
                             ''', action='store_true')
    parser.add_argument('--retro', help='''\
                             Keys are universal, shooting arrows costs rupees,
                             and a few other little things make this more like Zelda-1.
                             ''', action='store_true')
    parser.add_argument('--custom', default=False, help='Not supported.')
    parser.add_argument('--customitemarray', default=False, help='Not supported.')
    parser.add_argument('--nodungeonitems', help='''\
                             Remove Maps and Compasses from Itempool, replacing them by
                             empty slots.
                             ''', action='store_true')
    parser.add_argument('--beatableonly', help='''\
                             Only check if the game is beatable with placement. Do not
                             ensure all locations are reachable. This only has an effect
                             on the restrictive algorithm currently.
                             ''', action='store_true')
    # included for backwards compatibility
    parser.add_argument('--shuffleganon', help=argparse.SUPPRESS, action='store_true', default=True)
    parser.add_argument('--no-shuffleganon', help='''\
                             If set, the Pyramid Hole and Ganon's Tower are not
                             included entrance shuffle pool.
                             ''', action='store_false', dest='shuffleganon')
    parser.add_argument('--heartbeep', default='normal', const='normal', nargs='?', choices=['normal', 'half', 'quarter', 'off'],
                        help='''\
                             Select the rate at which the heart beep sound is played at
                             low health. (default: %(default)s)
                             ''')
    parser.add_argument('--heartcolor', default='red', const='red', nargs='?', choices=['red', 'blue', 'green', 'yellow'],
                        help='Select the color of Link\'s heart meter. (default: %(default)s)')
    parser.add_argument('--sprite', help='''\
                             Path to a sprite sheet to use for Link. Needs to be in
                             binary format and have a length of 0x7000 (28672) bytes,
                             or 0x7078 (28792) bytes including palette data.
                             Alternatively, can be a ALttP Rom patched with a Link
                             sprite that will be extracted.
                             ''')
    parser.add_argument('--suppress_rom', help='Do not create an output rom file.', action='store_true')
    parser.add_argument('--gui', help='Launch the GUI', action='store_true')
    parser.add_argument('--jsonout', action='store_true', help='''\
                            Output .json patch to stdout instead of a patched rom. Used
                            for VT site integration, do not use otherwise.
                            ''')
    args = parser.parse_args()

    if is_bundled() and len(sys.argv) == 1:
        # for the bundled builds, if we have no arguments, the user
        # probably wants the gui. Users of the bundled build who want the command line
        # interface shouuld specify at least one option, possibly setting a value to a
        # default if they like all the defaults
        close_console()
        guiMain()
        sys.exit(0)

    # ToDo: Validate files further than mere existance
    if not args.jsonout and not os.path.isfile(args.rom):
        input('Could not find valid base rom for patching at expected path %s. Please run with -h to see help for further information. \nPress Enter to exit.' % args.rom)
        sys.exit(1)
    if args.sprite is not None and not os.path.isfile(args.sprite):
        if not args.jsonout:
            input('Could not find link sprite sheet at given location. \nPress Enter to exit.' % args.sprite)
            sys.exit(1)
        else:
            raise IOError('Cannot find sprite file at %s' % args.sprite)

    # set up logger
    loglevel = {'error': logging.ERROR, 'info': logging.INFO, 'warning': logging.WARNING, 'debug': logging.DEBUG}[args.loglevel]
    logging.basicConfig(format='%(message)s', level=loglevel)

    if args.gui:
        guiMain(args)
    elif args.count is not None:
        seed = args.seed
        for _ in range(args.count):
            main(seed=seed, args=args)
            seed = random.randint(0, 999999999)
    else:
        main(seed=args.seed, args=args)
Beispiel #35
0
from Main import main
import matplotlib.pyplot as plt

data = []

timings = range(1000, 101000, 1000)

complexity = []
realtime = []
simtime = []

for time in timings:
    print time
    data = main(time)
    complexity += [data[0]]
    simtime += [data[1]]
    realtime += [data[2]]

print realtime
# Three subplots sharing both x/y axes
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True)
ax1.plot(timings, complexity, "b")
ax2.plot(timings, realtime, "b")
ax2.set_yscale("log")
ax3.plot(timings, simtime, "b")
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
#f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
plt.show()