forked from abyssonym/randomtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interface.py
341 lines (284 loc) · 10.6 KB
/
interface.py
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
from sys import argv
from os import stat, path, mkdir
import string
from time import time
from shutil import copyfile
from collections import defaultdict
from randomtools.tablereader import (
determine_global_table, sort_good_order, set_table_specs, set_table_extras,
set_global_output_filename, select_patches, write_patches, verify_patches,
get_random_degree, set_random_degree, set_seed, get_seed, close_file,
set_definitions, get_global_label)
from randomtools.utils import (
utilrandom as random, rewrite_snes_title, rewrite_snes_checksum,
md5hash)
sourcefile = None
outfile = None
flags = None
user_input_flags = None
difficulty = None
activated_codes = None
all_objects = None
def get_all_objects():
global all_objects
return all_objects
def get_sourcefile():
global sourcefile
return sourcefile
def get_outfile():
global outfile
return outfile
def get_flags():
global flags
return flags
def get_user_input_flags():
global user_input_flags
return user_input_flags
def get_activated_codes():
global activated_codes
return sorted(activated_codes)
def activate_code(code):
global activated_codes
activated_codes.add(code)
def rewrite_snes_meta(title, version, lorom=False):
close_file(outfile)
for o in get_all_objects():
if o.random_degree != get_random_degree():
random_degree = "??"
break
else:
random_degree = int(round((get_random_degree()**0.5) * 100))
if random_degree >= 100:
random_degree = "!!"
else:
random_degree = "{0:0>2}".format(random_degree)
rewrite_snes_title("%s %s %s" % (title, random_degree, get_seed()),
outfile, version, lorom=lorom)
rewrite_snes_checksum(outfile, lorom=lorom)
def snescopy(sourcefile, outfile):
size = stat(sourcefile).st_size
if size % 0x400 == 0:
copyfile(sourcefile, outfile)
elif size % 0x200 == 0:
print("SNES header detected. Removing header from output file.")
f = open(sourcefile, 'r+b')
data = f.read()
f.close()
data = data[0x200:]
open(outfile, 'w+').close()
f = open(outfile, 'r+b')
f.write(data)
f.close()
else:
raise Exception("Inappropriate file size for SNES rom file.")
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
def clean_and_write(objects):
objects = sort_good_order(objects)
for o in objects:
o.class_reseed('preclean')
o.full_preclean()
for o in objects:
if hasattr(o, "flag_description") and o.flag in get_flags():
print("Cleaning %s." % o.flag_description.lower())
o.class_reseed('cleanup')
o.full_cleanup()
print("Saving game objects...")
for o in objects:
o.write_all(outfile)
verify_patches(outfile)
def finish_interface():
print()
print("Randomization completed successfully.")
print("Output filename: %s" % outfile)
print("MD5 hash: %s" % md5hash(outfile))
print()
if len(argv) < 2:
input("Press Enter to close this program. ")