forked from ArchipelagoMW/Archipelago
- Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathGenerate.py
More file actions
Latest commit
666 lines (576 loc) · 32.3 KB
/
Copy pathGenerate.py
File metadata and controls
666 lines (576 loc) · 32.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
from __future__ importannotations
importargparse
importcopy
importlogging
importos
importrandom
importstring
importsys
importurllib.parse
importurllib.request
fromcollectionsimportCounter
fromitertoolsimportchain
fromtypingimportAny
importModuleUpdate
ModuleUpdate.update()
importUtils
importOptions
fromBaseClassesimportseeddigits, get_seed, PlandoOptions
fromUtilsimportparse_yamls, version_tuple, __version__, tuplize_version
defmystery_argparse(argv: list[str] |None=None) ->argparse.Namespace:
fromsettingsimportget_settings
settings=get_settings()
defaults=settings.generator
parser=argparse.ArgumentParser(description="CMD Generation Interface, defaults come from host.yaml.")
parser.add_argument('--weights_file_path', default=defaults.weights_file_path,
help='Path to the weights file to use for rolling game options, urls are also valid')
parser.add_argument('--sameoptions', help='Rolls options per weights file rather than per player',
action='store_true')
parser.add_argument('--player_files_path', default=defaults.player_files_path,
help="Input directory for player files.")
parser.add_argument('--seed', help='Define seed number to generate.', type=int)
parser.add_argument('--multi', default=defaults.players, type=lambdavalue: max(int(value), 1))
parser.add_argument('--spoiler', type=int, default=defaults.spoiler)
parser.add_argument('--outputpath', default=settings.general_options.output_path,
help="Path to output folder. Absolute or relative to cwd.") # absolute or relative to cwd
parser.add_argument('--race', action='store_true', default=defaults.race)
parser.add_argument('--meta_file_path', default=defaults.meta_file_path)
parser.add_argument('--log_level', default=defaults.loglevel, help='Sets log level')
parser.add_argument('--log_time', help="Add timestamps to STDOUT",
default=defaults.logtime, action='store_true')
parser.add_argument("--csv_output", action="store_true",
help="Output rolled player options to csv (made for async multiworld).")
parser.add_argument("--plando", default=defaults.plando_options,
help="List of options that can be set manually. Can be combined, for example \"bosses, items\"")
parser.add_argument("--skip_prog_balancing", action="store_true",
help="Skip progression balancing step during generation.")
parser.add_argument("--skip_output", action="store_true",
help="Skips generation assertion and output stages and skips multidata and spoiler output. "
"Intended for debugging and testing purposes.")
parser.add_argument("--spoiler_only", action="store_true",
help="Skips generation assertion and multidata, outputting only a spoiler log. "
"Intended for debugging and testing purposes.")
args=parser.parse_args(argv)
ifargs.skip_outputandargs.spoiler_only:
parser.error("Cannot mix --skip_output and --spoiler_only")
elifargs.spoiler==0andargs.spoiler_only:
parser.error("Cannot use --spoiler_only when --spoiler=0. Use --skip_output or set --spoiler to a different value")
ifnotos.path.isabs(args.weights_file_path):
args.weights_file_path=os.path.join(args.player_files_path, args.weights_file_path)
ifnotos.path.isabs(args.meta_file_path):
args.meta_file_path=os.path.join(args.player_files_path, args.meta_file_path)
args.plando=PlandoOptions.from_option_string(args.plando)
returnargs
defget_seed_name(random_source) ->str:
returnf"{random_source.randint(0, pow(10, seeddigits) -1)}".zfill(seeddigits)
defmain(args=None) ->tuple[argparse.Namespace, int]:
# __name__ == "__main__" check so unittests that already imported worlds don't trip this.
if__name__=="__main__"and"worlds"insys.modules:
raiseException("Worlds system should not be loaded before logging init.")
ifnotargs:
args=mystery_argparse()
seed=get_seed(args.seed)
if__name__=="__main__":
Utils.init_logging(f"Generate_{seed}", loglevel=args.log_level, add_timestamp=args.log_time)
random.seed(seed)
seed_name=get_seed_name(random)
ifargs.race:
logging.info("Race mode enabled. Using non-deterministic random source.")
random.seed() # reset to time-based random source
weights_cache: dict[str, tuple[Any, ...]] = {}
ifargs.weights_file_pathandos.path.exists(args.weights_file_path):
try:
weights_cache[args.weights_file_path] =read_weights_yamls(args.weights_file_path)
exceptExceptionase:
raiseValueError(f"File {args.weights_file_path} is invalid. Please fix your yaml.") frome
logging.info(f"Weights: {args.weights_file_path} >> "
f"{get_choice('description', weights_cache[args.weights_file_path][-1], 'No description specified')}")
ifargs.meta_file_pathandos.path.exists(args.meta_file_path):
try:
meta_weights=read_weights_yamls(args.meta_file_path)[-1]
exceptExceptionase:
raiseValueError(f"File {args.meta_file_path} is invalid. Please fix your yaml.") frome
logging.info(f"Meta: {args.meta_file_path} >> {get_choice('meta_description', meta_weights)}")
try: # meta description allows us to verify that the file named meta.yaml is intentionally a meta file
del(meta_weights["meta_description"])
exceptExceptionase:
raiseValueError("No meta description found for meta.yaml. Unable to verify.") frome
ifargs.sameoptions:
raiseException("Cannot mix --sameoptions with --meta")
else:
meta_weights=None
player_id: int=1
player_files: dict[int, str] = {}
player_errors: list[str] = []
forfileinos.scandir(args.player_files_path):
fname=file.name
iffile.is_file() andnotfname.startswith(".") andnotfname.lower().endswith(".ini") and \
os.path.join(args.player_files_path, fname) notin {args.meta_file_path, args.weights_file_path}:
path=os.path.join(args.player_files_path, fname)
try:
weights_for_file= []
fordoc_idx, yamlinenumerate(read_weights_yamls(path)):
ifyamlisNone:
logging.warning(f"Ignoring empty yaml document #{doc_idx+1} in {fname}")
else:
weights_for_file.append(yaml)
weights_cache[fname] =tuple(weights_for_file)
exceptExceptionase:
logging.exception(f"Exception reading weights in file {fname}")
player_errors.append(
f"{len(player_errors) +1}. "
f"File {fname} is invalid. Please fix your yaml.\n{Utils.get_all_causes(e)}"
)
# sort dict for consistent results across platforms:
weights_cache= {key: valueforkey, valueinsorted(weights_cache.items(), key=lambdak: k[0].casefold())}
forfilename, yaml_datainweights_cache.items():
iffilenamenotin {args.meta_file_path, args.weights_file_path}:
foryamlinyaml_data:
logging.info(f"P{player_id} Weights: {filename} >> "
f"{get_choice('description', yaml, 'No description specified')}")
player_files[player_id] =filename
player_id+=1
args.multi=max(player_id-1, args.multi)
ifargs.multi==0:
ifplayer_errors:
errors="\n\n".join(player_errors)
raiseValueError(f"Encountered {len(player_errors)} error(s) in player files. "
f"See logs for full tracebacks.\n\n{errors}")
raiseValueError(
"No individual player files found and number of players is 0. "
"Provide individual player files or specify the number of players via host.yaml or --multi."
)
logging.info(f"Generating for {args.multi} player{'s'ifargs.multi>1else''}, "
f"{seed_name} Seed {seed} with plando: {args.plando}")
ifnotweights_cache:
ifplayer_errors:
errors="\n\n".join(player_errors)
raiseValueError(f"Encountered {len(player_errors)} error(s) in player files. "
f"See logs for full tracebacks.\n\n{errors}")
raiseException(f"No weights found. "
f"Provide a general weights file ({args.weights_file_path}) or individual player files. "
f"A mix is also permitted.")
fromworlds.AutoWorldimportAutoWorldRegister
args.outputname=seed_name
args.sprite=dict.fromkeys(range(1, args.multi+1), None)
args.sprite_pool=dict.fromkeys(range(1, args.multi+1), None)
args.name= {}
ifmeta_weights:
forcategory_name, category_dictinmeta_weights.items():
forkeyincategory_dict:
option=roll_meta_option(key, category_name, category_dict)
ifoptionisnotNone:
forpathinweights_cache:
foryamlinweights_cache[path]:
ifcategory_nameisNone:
forcategoryinyaml:
ifcategoryinAutoWorldRegister.world_typesand \
keyinOptions.CommonOptions.type_hints:
yaml[category][key] =option
elifcategory_namenotinyaml:
logging.warning(f"Meta: Category {category_name} is not present in {path}.")
elifkey=="triggers":
if"triggers"notinyaml[category_name]:
yaml[category_name][key] = []
fortriggerinoption:
yaml[category_name][key].append(trigger)
else:
yaml[category_name][key] =option
settings_cache: dict[str, tuple[argparse.Namespace, ...] |None] = {fname: Noneforfnameinweights_cache}
ifargs.sameoptions:
forfname, yamlsinweights_cache.items():
try:
settings_cache[fname] =tuple(roll_settings(yaml, args.plando) foryamlinyamls)
exceptExceptionase:
logging.exception(f"Exception reading settings in file {fname}")
player_errors.append(
f"{len(player_errors) +1}. "
f"File {fname} is invalid. Please fix your yaml.\n{Utils.get_all_causes(e)}"
)
# Exit early here to avoid throwing the same errors again later
ifplayer_errors:
errors="\n\n".join(player_errors)
raiseValueError(f"Encountered {len(player_errors)} error(s) in player files. "
f"See logs for full tracebacks.\n\n{errors}")
player_path_cache: dict[int, str] = {}
forplayerinrange(1, args.multi+1):
player_path_cache[player] =player_files.get(player, args.weights_file_path)
name_counter: Counter[str] =Counter()
args.player_options= {}
player=1
whileplayer<=args.multi:
path=player_path_cache[player]
ifnotpath:
player_errors.append(f'No weights specified for player {player}')
player+=1
continue
fordoc_index, yamlinenumerate(weights_cache[path]):
name=yaml.get("name")
try:
# Use the cached settings object if it exists, otherwise roll settings within the try-catch
# Invariant: settings_cache[path] and weights_cache[path] have the same length
cached=settings_cache[path]
settings_object: argparse.Namespace= (cached[doc_index] ifcachedelseroll_settings(yaml, args.plando))
fork, vinvars(settings_object).items():
ifvisnotNone:
try:
getattr(args, k)[player] =v
exceptAttributeError:
setattr(args, k, {player: v})
exceptExceptionase:
raiseException(f"Error setting {k} to {v} for player {player}") frome
# name was not specified
ifplayernotinargs.name:
ifpath==args.weights_file_path:
# weights file, so we need to make the name unique
args.name[player] =f"Player{player}"
else:
# use the filename
args.name[player] =os.path.splitext(os.path.split(path)[-1])[0]
args.name[player] =handle_name(args.name[player], player, name_counter)
exceptExceptionase:
logging.exception(f"Exception reading settings in file {path} document #{doc_index+1} "
f"(name: {args.name.get(player, name)})")
player_errors.append(
f"{len(player_errors) +1}. "
f"File {path} document #{doc_index+1} (name: {args.name.get(player, name)}) is invalid. "
f"Please fix your yaml.\n{Utils.get_all_causes(e)}")
# increment for each yaml document in the file
player+=1
iflen(set(name.lower() fornameinargs.name.values())) !=len(args.name):
player_errors.append(
f"{len(player_errors) +1}. "
f"Names have to be unique. Names: {Counter(name.lower() fornameinargs.name.values())}"
)
ifplayer_errors:
errors="\n\n".join(player_errors)
raiseValueError(f"Encountered {len(player_errors)} error(s) in player files. "
f"See logs for full tracebacks.\n\n{errors}")
returnargs, seed
defread_weights_yamls(path) ->tuple[Any, ...]:
try:
ifurllib.parse.urlparse(path).schemein ('https', 'file'):
yaml=str(urllib.request.urlopen(path).read(), "utf-8-sig")
else:
withopen(path, 'rb') asf:
yaml=str(f.read(), "utf-8-sig")
exceptExceptionase:
raiseException(f"Failed to read weights ({path})") frome
fromyaml.errorimportMarkedYAMLError
try:
returntuple(parse_yamls(yaml))
exceptMarkedYAMLErrorasex:
ifex.problem_mark:
lines=yaml.splitlines()
ifex.context_mark:
relevant_lines="\n".join(lines[ex.context_mark.line:ex.problem_mark.line+1])
else:
relevant_lines=lines[ex.problem_mark.line]
error_line=" "*ex.problem_mark.column+"^"
raiseException(f"{ex.context}{ex.problem} on line {ex.problem_mark.line}:"
f"\n{relevant_lines}\n{error_line}")
raiseex
definterpret_on_off(value) ->bool:
return {"on": True, "off": False}.get(value, value)
defconvert_to_on_off(value) ->str:
return {True: "on", False: "off"}.get(value, value)
defget_choice_legacy(option, root, value=None) ->Any:
ifoptionnotinroot:
returnvalue
iftype(root[option]) islist:
returninterpret_on_off(random.choices(root[option])[0])
iftype(root[option]) isnotdict:
returninterpret_on_off(root[option])
ifnotroot[option]:
returnvalue
ifany(root[option].values()):
returninterpret_on_off(
random.choices(list(root[option].keys()), weights=list(map(int, root[option].values())))[0])
raiseRuntimeError(f"All options specified in \"{option}\" are weighted as zero.")
defget_choice(option, root, value=None) ->Any:
ifoptionnotinroot:
returnvalue
iftype(root[option]) islist:
returnrandom.choices(root[option])[0]
iftype(root[option]) isnotdict:
returnroot[option]
ifnotroot[option]:
returnvalue
ifany(root[option].values()):
returnrandom.choices(list(root[option].keys()), weights=list(map(int, root[option].values())))[0]
raiseRuntimeError(f"All options specified in \"{option}\" are weighted as zero.")
classSafeFormatter(string.Formatter):
defget_value(self, key, args, kwargs):
ifisinstance(key, int):
ifkey<len(args):
returnargs[key]
else:
return"{"+str(key) +"}"
else:
returnkwargs.get(key, "{"+key+"}")
defhandle_name(name: str, player: int, name_counter: Counter[str]):
name_counter[name.lower()] +=1
number=name_counter[name.lower()]
new_name="%".join([x.replace("%number%", "{number}").replace("%player%", "{player}") forxinname.split("%%")])
new_name=SafeFormatter().vformat(new_name, (), {"number": number,
"NUMBER": (numberifnumber>1else''),
"player": player,
"PLAYER": (playerifplayer>1else'')})
# Run .strip twice for edge case where after the initial .slice new_name has a leading whitespace.
# Could cause issues for some clients that cannot handle the additional whitespace.
new_name=new_name.strip()[:16].strip()
ifnew_name=="Archipelago":
raiseException(f"You cannot name yourself \"{new_name}\"")
returnnew_name
defupdate_weights(weights: dict, new_weights: dict, update_type: str, name: str) ->dict:
logging.debug(f'Applying {new_weights}')
cleaned_weights= {}
foroptioninnew_weights:
option_name=option.lstrip("+-")
ifoption.startswith("+") andoption_nameinweights:
cleaned_value=weights[option_name]
new_value=new_weights[option]
ifisinstance(new_value, set):
cleaned_value.update(new_value)
elifisinstance(new_value, list):
cleaned_value.extend(new_value)
elifisinstance(new_value, dict):
counter_value=Counter(cleaned_value)
counter_value.update(new_value)
cleaned_value=dict(counter_value)
else:
raiseException(f"Cannot apply merge to non-dict, set, or list type {option_name},"
f" received {type(new_value).__name__}.")
cleaned_weights[option_name] =cleaned_value
elifoption.startswith("-") andoption_nameinweights:
cleaned_value=weights[option_name]
new_value=new_weights[option]
ifisinstance(new_value, set):
cleaned_value.difference_update(new_value)
elifisinstance(new_value, list):
forelementinnew_value:
cleaned_value.remove(element)
elifisinstance(new_value, dict):
counter_value=Counter(cleaned_value)
counter_value.subtract(new_value)
cleaned_value=dict(counter_value)
else:
raiseException(f"Cannot apply remove to non-dict, set, or list type {option_name},"
f" received {type(new_value).__name__}.")
cleaned_weights[option_name] =cleaned_value
else:
# Options starting with + and - may modify values in-place, and new_weights may be shared by multiple slots
# using the same .yaml, so ensure that the new value is a copy.
cleaned_value=copy.deepcopy(new_weights[option])
cleaned_weights[option_name] =cleaned_value
new_options=set(cleaned_weights) -set(weights)
weights.update(cleaned_weights)
ifnew_options:
fornew_optioninnew_options:
logging.warning(f'{update_type} Suboption "{new_option}" of "{name}" did not '
f'overwrite a root option. '
f'This is probably in error.')
returnweights
defroll_meta_option(option_key, game: str, category_dict: dict) ->Any:
fromworldsimportAutoWorldRegister
ifnotgame:
returnget_choice(option_key, category_dict)
ifgameinAutoWorldRegister.world_types:
game_world=AutoWorldRegister.world_types[game]
options=game_world.options_dataclass.type_hints
ifoption_keyinoptions:
ifoptions[option_key].supports_weighting:
returnget_choice(option_key, category_dict)
returncategory_dict[option_key]
ifoption_key=="triggers":
returncategory_dict[option_key]
raiseOptions.OptionError(f"Error generating meta option {option_key} for {game}.")
defroll_linked_options(weights: dict) ->dict:
weights=copy.deepcopy(weights) # make sure we don't write back to other weights sets in same_settings
foroption_setinweights["linked_options"]:
if"name"notinoption_set:
raiseValueError("One of your linked options does not have a name.")
try:
ifOptions.roll_percentage(option_set["percentage"]):
logging.debug(f"Linked option {option_set['name']} triggered.")
new_options=option_set["options"]
forcategory_name, category_optionsinnew_options.items():
currently_targeted_weights=weights
ifcategory_name:
currently_targeted_weights=currently_targeted_weights[category_name]
update_weights(currently_targeted_weights, category_options, "Linked", option_set["name"])
else:
logging.debug(f"linked option {option_set['name']} skipped.")
exceptExceptionase:
raiseValueError(f"Linked option {option_set['name']} is invalid. "
f"Please fix your linked option.") frome
returnweights
defroll_triggers(weights: dict, triggers: list, valid_keys: set) ->dict:
weights=copy.deepcopy(weights) # make sure we don't write back to other weights sets in same_settings
weights["_Generator_Version"] =Utils.__version__
fori, option_setinenumerate(triggers):
try:
currently_targeted_weights=weights
category=option_set.get("option_category", None)
ifcategory:
currently_targeted_weights=currently_targeted_weights[category]
key=get_choice("option_name", option_set)
ifkeynotincurrently_targeted_weights:
logging.warning(f'Specified option name {option_set["option_name"]} did not '
f'match with a root option. '
f'This is probably in error.')
trigger_result=get_choice("option_result", option_set)
result=get_choice(key, currently_targeted_weights)
currently_targeted_weights[key] =result
ifresult==trigger_resultandOptions.roll_percentage(get_choice("percentage", option_set, 100)):
forcategory_name, category_optionsinoption_set["options"].items():
currently_targeted_weights=weights
ifcategory_name:
currently_targeted_weights=currently_targeted_weights[category_name]
update_weights(currently_targeted_weights, category_options, "Triggered", option_set["option_name"])
valid_keys.add(key)
exceptExceptionase:
raiseValueError(f"Your trigger number {i+1} is invalid. "
f"Please fix your triggers.") frome
returnweights
defhandle_option(ret: argparse.Namespace, game_weights: dict, option_key: str, option: type[Options.Option], plando_options: PlandoOptions):
try:
ifoption_keyingame_weights:
ifnotoption.supports_weighting:
player_option=option.from_any(game_weights[option_key])
else:
player_option=option.from_any(get_choice(option_key, game_weights))
else:
player_option=option.from_any(option.default) # call the from_any here to support default "random"
setattr(ret, option_key, player_option)
exceptExceptionase:
raiseOptions.OptionError(f"Error generating option {option_key} in {ret.game}") frome
else:
fromworldsimportAutoWorldRegister
player_option.verify(AutoWorldRegister.world_types[ret.game], ret.name, plando_options)
defroll_settings(weights: dict, plando_options: PlandoOptions=PlandoOptions.bosses):
"""
Roll options from specified weights, usually originating from a .yaml options file.
Important note:
The same weights dict is shared between all slots using the same yaml (e.g. generic weights file for filler slots).
This means it should never be modified without making a deepcopy first.
"""
fromworldsimportAutoWorldRegister
if"linked_options"inweights:
weights=roll_linked_options(weights)
valid_keys= {"triggers"}
if"triggers"inweights:
weights=roll_triggers(weights, weights["triggers"], valid_keys)
requirements=weights.get("requires", {})
ifrequirements:
version=requirements.get("version", __version__)
iftuplize_version(version) >version_tuple:
raiseException(f"Settings reports required version of generator is at least {version}, "
f"however generator is of version {__version__}")
required_plando_options=PlandoOptions.from_option_string(requirements.get("plando", ""))
ifrequired_plando_optionsnotinplando_options:
ifrequired_plando_options:
raiseException(f"Settings reports required plando module {str(required_plando_options)}, "
f"which is not enabled.")
games=requirements.get("game", {})
forgame, versioningames.items():
ifgamenotinAutoWorldRegister.world_types:
continue
ifnotversion:
raiseException(f"Invalid version for game {game}: {version}.")
ifisinstance(version, str):
version= {"min": version}
if"min"inversionandtuplize_version(version["min"]) >AutoWorldRegister.world_types[game].world_version:
raiseException(f"Settings reports required version of world \"{game}\" is at least {version['min']}, "
f"however world is of version "
f"{AutoWorldRegister.world_types[game].world_version.as_simple_string()}.")
if"max"inversionandtuplize_version(version["max"]) <AutoWorldRegister.world_types[game].world_version:
raiseException(f"Settings reports required version of world \"{game}\" is no later than {version['max']}, "
f"however world is of version "
f"{AutoWorldRegister.world_types[game].world_version.as_simple_string()}.")
ret=argparse.Namespace()
foroption_keyinOptions.PerGameCommonOptions.type_hints:
ifoption_keyinweightsandoption_keynotinOptions.CommonOptions.type_hints:
raiseException(f"Option {option_key} has to be in a game's section, not on its own.")
ret.game=get_choice("game", weights)
ifnotisinstance(ret.game, str):
ifret.gameisNone:
raiseException('"game" not specified')
raiseException(f"Invalid game: {ret.game}")
ifret.gamenotinAutoWorldRegister.world_types:
fromworldsimportfailed_world_loads
picks=Utils.get_fuzzy_results(ret.game, list(AutoWorldRegister.world_types) +failed_world_loads, limit=1)[0]
ifpicks[0] infailed_world_loads:
raiseException(f"No functional world found to handle game {ret.game}. "
f"Did you mean '{picks[0]}' ({picks[1]}% sure)? "
f"If so, it appears the world failed to initialize correctly.")
raiseException(f"No world found to handle game {ret.game}. Did you mean '{picks[0]}' ({picks[1]}% sure)? "
f"Check your spelling or installation of that world.")
ifret.gamenotinweights:
raiseException(f"No game options for selected game \"{ret.game}\" found.")
world_type=AutoWorldRegister.world_types[ret.game]
game_weights=weights[ret.game]
forweightinchain(game_weights, weights):
ifweight.startswith("+"):
raiseException(f"Merge tag cannot be used outside of trigger contexts. Found {weight}")
ifweight.startswith("-"):
raiseException(f"Remove tag cannot be used outside of trigger contexts. Found {weight}")
if"triggers"ingame_weights:
weights=roll_triggers(weights, game_weights["triggers"], valid_keys)
game_weights=weights[ret.game]
ret.name=get_choice('name', weights)
foroption_key, optioninOptions.CommonOptions.type_hints.items():
setattr(ret, option_key, option.from_any(get_choice(option_key, weights, option.default)))
foroption_key, optioninworld_type.options_dataclass.type_hints.items():
handle_option(ret, game_weights, option_key, option, plando_options)
valid_keys.add(option_key)
ifret.game=="A Link to the Past":
# TODO there are still more LTTP options not on the options system
valid_keys|= {"sprite_pool", "sprite", "random_sprite_on_event"}
roll_alttp_settings(ret, game_weights)
# log a warning for options within a game section that aren't determined as valid
foroption_keyingame_weights:
ifoption_keyinvalid_keys:
continue
logging.warning(f"{option_key} is not a valid option name for {ret.game} and is not present in triggers "
f"for player {ret.name}.")
returnret
defroll_alttp_settings(ret: argparse.Namespace, weights):
ret.sprite_pool=weights.get('sprite_pool', [])
ret.sprite=get_choice_legacy('sprite', weights, "Link")
if'random_sprite_on_event'inweights:
randomoneventweights=weights['random_sprite_on_event']
ifget_choice_legacy('enabled', randomoneventweights, False):
ret.sprite='randomon'
ret.sprite+='-hit'ifget_choice_legacy('on_hit', randomoneventweights, True) else''
ret.sprite+='-enter'ifget_choice_legacy('on_enter', randomoneventweights, False) else''
ret.sprite+='-exit'ifget_choice_legacy('on_exit', randomoneventweights, False) else''
ret.sprite+='-slash'ifget_choice_legacy('on_slash', randomoneventweights, False) else''
ret.sprite+='-item'ifget_choice_legacy('on_item', randomoneventweights, False) else''
ret.sprite+='-bonk'ifget_choice_legacy('on_bonk', randomoneventweights, False) else''
ret.sprite='randomonall'ifget_choice_legacy('on_everything', randomoneventweights, False) elseret.sprite
ret.sprite='randomonnone'ifret.sprite=='randomon'elseret.sprite
if (notret.sprite_poolorget_choice_legacy('use_weighted_sprite_pool', randomoneventweights, False)) \
and'sprite'inweights: # Use sprite as a weighted sprite pool, if a sprite pool is not already defined.
forkey, valueinweights['sprite'].items():
ifkey.startswith('random'):
ret.sprite_pool+= ['random'] *int(value)
else:
ret.sprite_pool+= [key] *int(value)
if__name__=='__main__':
importatexit
confirmation=atexit.register(input, "Press enter to close.")
erargs, seed=main()
fromMainimportmainasERmain
multiworld=ERmain(erargs, seed)
if__debug__:
importgc
importsys
importweakref
weak=weakref.ref(multiworld)
delmultiworld
gc.collect() # need to collect to deref all hard references
assertnotweak(), f"MultiWorld object was not de-allocated, it's referenced {sys.getrefcount(weak())} times." \
" This would be a memory leak."
# in case of error-free exit should not need confirmation
atexit.unregister(confirmation)