-
Notifications
You must be signed in to change notification settings - Fork 8
/
randomizer_window.rb
1112 lines (918 loc) · 37 KB
/
randomizer_window.rb
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require_relative 'ui_randomizer'
require_relative 'constants/options'
require_relative 'randomizer'
require_relative 'update_checker'
class RandomizerWindow < Qt::Dialog
VALID_SEED_CHARACTERS = "a-zA-Z0-9\\-_'%"
slots "update_settings()"
slots "browse_for_clean_rom()"
slots "browse_for_output_folder()"
slots "difficulty_level_changed(int)"
slots "difficulty_slider_value_changed(int)"
slots "difficulty_line_edit_value_changed()"
slots "generate_seed()"
slots "randomize_n_seeds()"
slots "open_about()"
slots "reset_settings_to_default()"
slots "save_options_preset_to_file()"
slots "load_options_preset_from_file()"
slots "load_seed_info_from_file()"
slots "paste_seed_info_from_clipboard()"
slots "experimental_enabled_changed(bool)"
def initialize
super(nil, Qt::WindowMinimizeButtonHint)
@ui = Ui_Randomizer.new
@ui.setup_ui(self)
# Add three empty items to the clean ROM recent files dropdown, one for each game.
@ui.clean_rom.addItem("")
@ui.clean_rom.addItem("")
@ui.clean_rom.addItem("")
@currently_selected_game = nil
initialize_difficulty_sliders()
preserve_default_settings()
load_settings()
connect(@ui.clean_rom, SIGNAL("activated(int)"), self, SLOT("update_settings()"))
connect(@ui.clean_rom, SIGNAL("editTextChanged(QString)"), self, SLOT("update_settings()"))
connect(@ui.clean_rom_browse_button, SIGNAL("clicked()"), self, SLOT("browse_for_clean_rom()"))
connect(@ui.output_folder, SIGNAL("editingFinished()"), self, SLOT("update_settings()"))
connect(@ui.output_folder_browse_button, SIGNAL("clicked()"), self, SLOT("browse_for_output_folder()"))
connect(@ui.generate_seed_button, SIGNAL("clicked()"), self, SLOT("generate_seed()"))
connect(@ui.seed, SIGNAL("editingFinished()"), self, SLOT("update_settings()"))
OPTIONS.each_key do |option_name|
connect(@ui.send(option_name), SIGNAL("clicked(bool)"), self, SLOT("update_settings()"))
@ui.send(option_name).installEventFilter(self)
end
connect(@ui.experimental_options_enabled, SIGNAL("clicked(bool)"), self, SLOT("experimental_enabled_changed(bool)"))
connect(@ui.randomize_button, SIGNAL("clicked()"), self, SLOT("randomize_n_seeds()"))
connect(@ui.about_button, SIGNAL("clicked()"), self, SLOT("open_about()"))
connect(@ui.reset_settings_to_default, SIGNAL("clicked()"), self, SLOT("reset_settings_to_default()"))
self.setWindowTitle("DSVania Randomizer #{DSVRANDOM_VERSION}")
connect(@ui.difficulty_level, SIGNAL("activated(int)"), self, SLOT("difficulty_level_changed(int)"))
connect(@ui.num_seeds_to_create, SIGNAL("activated(int)"), self, SLOT("update_settings()"))
update_settings()
connect(@ui.save_options_preset_button, SIGNAL("clicked()"), self, SLOT("save_options_preset_to_file()"))
connect(@ui.load_options_preset_button, SIGNAL("clicked()"), self, SLOT("load_options_preset_from_file()"))
connect(@ui.load_seed_info_button, SIGNAL("clicked()"), self, SLOT("load_seed_info_from_file()"))
connect(@ui.paste_seed_info_button, SIGNAL("clicked()"), self, SLOT("paste_seed_info_from_clipboard()"))
self.resize(self.width, 1)
self.show()
end
def bulk_test
failed_times = 0
total_tests = 100
total_tests.times do |i|
game = Game.new
game.initialize_from_rom(@ui.clean_rom.currentText, extract_to_hard_drive = false)
seed = i.to_s
options_hash = get_current_options_hash()
difficulty_settings_averages = get_current_difficulty_settings_averages()
randomizer = Randomizer.new(seed, game, options_hash, @settings[:difficulty_level], difficulty_settings_averages)
begin
randomizer.randomize() {}
rescue StandardError => e
puts "Error on seed #{seed}:"
puts e.message
failed_times += 1
end
puts "%d/%d seeds failed" % [failed_times, i+1]
end
end
def eventFilter(target, event)
if event.type() == Qt::Event::Enter
option_description = OPTIONS[target.objectName.to_sym]
@ui.option_description.text = option_description
return true
elsif event.type() == Qt::Event::Leave
@ui.option_description.text = ""
return true
end
super(target, event)
end
def load_settings
@settings_path = "randomizer_settings.yml"
if File.file?(@settings_path)
@settings = YAML::load_file(@settings_path)
else
@settings = {}
end
update_last_used_clean_rom_combobox_items()
set_clean_rom_combobox_text(@settings[:clean_rom_path]) if @settings[:clean_rom_path]
@ui.output_folder.setText(@settings[:output_folder]) if @settings[:output_folder]
@ui.seed.setText(@settings[:seed]) if @settings[:seed]
# Detects what the selected game is so we know what options to disable.
detect_current_game_by_clean_rom_combobox_text()
OPTIONS.each_key do |option_name|
@ui.send(option_name).setChecked(@settings[option_name]) unless @settings[option_name].nil?
end
num_seeds_index = @ui.num_seeds_to_create.findText(@settings[:num_seeds_to_create].to_s)
if num_seeds_index != -1
@ui.num_seeds_to_create.setCurrentIndex(num_seeds_index)
end
if @settings[:difficulty_level].nil?
@settings[:difficulty_level] = "Normal"
end
difficulty_level_options = DIFFICULTY_LEVELS[@settings[:difficulty_level]]
if difficulty_level_options
# Preset difficulty level.
difficulty_level_changed_by_name(@settings[:difficulty_level])
else
# Custom difficulty.
form_layout = @ui.scrollAreaWidgetContents.layout
DIFFICULTY_RANGES.keys.each do |option_name|
slider = @slider_widgets_by_name[option_name]
average = @settings[:difficulty_options][option_name]
if average.nil?
# If some options are missing default to what it is on easy.
average = DIFFICULTY_LEVELS.values.first[option_name]
end
slider.blockSignals(true)
slider.value = average
slider.blockSignals(false)
line_edit = @difficulty_line_edit_widgets_by_name[option_name]
line_edit.text = slider.true_value.to_s
end
difficulty_level_changed_by_name("Custom")
end
end
def save_settings
File.open(@settings_path, "w") do |f|
f.write(@settings.to_yaml)
end
end
def closeEvent(event)
save_settings()
end
def browse_for_clean_rom
if @settings[:clean_rom_path] && File.file?(@settings[:clean_rom_path])
default_dir = File.dirname(@settings[:clean_rom_path])
end
clean_rom_path = Qt::FileDialog.getOpenFileName(self, "Select ROM", default_dir, "NDS ROM Files (*.nds)")
return if clean_rom_path.nil?
set_clean_rom_combobox_text(clean_rom_path)
update_settings()
end
def browse_for_output_folder
if @settings[:output_folder] && File.directory?(@settings[:output_folder])
default_dir = @settings[:output_folder]
end
output_folder_path = Qt::FileDialog.getExistingDirectory(self, "Select output folder", default_dir)
return if output_folder_path.nil?
@ui.output_folder.text = output_folder_path
update_settings()
end
def update_settings
if @ui.clean_rom.currentText != @settings[:clean_rom_path]
# Clean ROM text changed, so update the record of what the last used ROM path is, if it's a valid DSVania ROM file.
detect_current_game_by_clean_rom_combobox_text()
end
@settings[:clean_rom_path] = @ui.clean_rom.currentText
@settings[:output_folder] = @ui.output_folder.text
@settings[:seed] = @ui.seed.text
ensure_valid_combination_of_options()
OPTIONS.each_key do |option_name|
@settings[option_name] = @ui.send(option_name).checked
end
@settings[:difficulty_level] = @ui.difficulty_level.itemText(@ui.difficulty_level.currentIndex)
@settings[:difficulty_options] = {}
DIFFICULTY_RANGES.keys.each do |option_name|
slider = @slider_widgets_by_name[option_name]
average = slider.true_value
@settings[:difficulty_options][option_name] = average
end
@settings[:num_seeds_to_create] = @ui.num_seeds_to_create.itemText(@ui.num_seeds_to_create.currentIndex)
save_settings()
end
def ensure_valid_combination_of_options
should_enable_options = {}
OPTIONS.each_key do |option_name|
should_enable_options[option_name] = true
end
if [email protected]_options_enabled.checked
@ui.experimental_options_enabled.children.each do |child|
if child.is_a?(Qt::CheckBox)
should_enable_options[child.object_name.to_sym] &&= false
end
end
end
pickup_randomizer_dependant_options = [
:randomize_boss_souls,
:randomize_villagers,
:randomize_portraits,
:randomize_red_walls,
:randomize_starting_room,
:randomize_maps,
:randomize_world_map_exits,
:por_short_mode,
]
if [email protected]_pickups.checked
pickup_randomizer_dependant_options.each do |option_name|
should_enable_options[option_name] &&= false
end
end
room_rando = @ui.randomize_maps.checked || @ui.randomize_starting_room.checked || @ui.randomize_world_map_exits.checked
#room_rando ||= @ui.randomize_room_connections.checked || @ui.randomize_area_connections.checked
if !room_rando
should_enable_options[:rebalance_enemies_in_room_rando] &&= false
end
if @ui.open_world_map.checked
should_enable_options[:randomize_world_map_exits] &&= false
end
OPTIONS.each_key do |option_name|
if should_enable_options[option_name]
@ui.send(option_name).enabled = true
else
@ui.send(option_name).enabled = false
end
end
if room_rando
@ui.unlock_boss_doors.checked = true
@ui.unlock_boss_doors.enabled = false
end
if @ui.randomize_maps.checked
@ui.randomize_boss_souls.checked = true
@ui.randomize_boss_souls.enabled = false
end
if @ui.randomize_world_map_exits.checked && @ui.randomize_world_map_exits.enabled
@ui.randomize_starting_room.checked = false
@ui.randomize_starting_room.enabled = false
end
disable_options_not_for_current_game()
if @ui.num_seeds_to_create.currentIndex == 0 # 1 seed
@ui.seed.enabled = true
else
# The seed text input is not used when generating multiple seeds.
@ui.seed.enabled = false
end
end
def disable_options_not_for_current_game
all_game_specific_options = []
GAME_SPECIFIC_OPTIONS.each do |game, options_for_game|
all_game_specific_options += options_for_game
end
all_game_specific_options.uniq!
all_game_specific_options.each do |option_name|
if [email protected](option_name).enabled
# This option was already disabled by ensure_valid_combination_of_options, so don't enable it regardless of the game it's for.
next
end
if @currently_selected_game.nil?
# If no game is selected, enable all options.
@ui.send(option_name).enabled = true
elsif GAME_SPECIFIC_OPTIONS[@currently_selected_game].include?(option_name)
# Enable all options for the selected game.
@ui.send(option_name).enabled = true
else
# Disable all options specific to the other games that the selected game does not also support.
@ui.send(option_name).enabled = false
end
end
end
def experimental_enabled_changed(enabled)
if enabled
msg = "Are you sure you want to enable the experimental section?\n\nThese options are mostly untested and are known to have bugs that can cause crashes or make seeds unwinnable."
response = Qt::MessageBox.question(self, "Enable experimental options?", msg, Qt::MessageBox::No | Qt::MessageBox::Yes, Qt::MessageBox::No)
if response == Qt::MessageBox::No
@ui.experimental_options_enabled.checked = false
end
end
end
def update_last_used_clean_rom_combobox_items
[
:last_used_dos_clean_rom_path,
:last_used_por_clean_rom_path,
:last_used_ooe_clean_rom_path,
].each_with_index do |last_used_path_key, i|
if @settings[last_used_path_key] && File.file?(@settings[last_used_path_key])
@ui.clean_rom.setItemText(i, @settings[last_used_path_key])
else
@settings[last_used_path_key] = nil
@ui.clean_rom.setItemText(i, "")
end
end
end
def detect_current_game_by_clean_rom_combobox_text
@currently_selected_game = nil
clean_rom_path = @ui.clean_rom.currentText
if File.file?(clean_rom_path)
title = File.read(clean_rom_path, 16)
case title
when "CASTLEVANIA1ACVE"
@currently_selected_game = "dos"
@settings[:last_used_dos_clean_rom_path] = clean_rom_path
update_last_used_clean_rom_combobox_items()
when "CASTLEVANIA2ACBE"
@currently_selected_game = "por"
@settings[:last_used_por_clean_rom_path] = clean_rom_path
update_last_used_clean_rom_combobox_items()
when "CASTLEVANIA3YR9E"
@currently_selected_game = "ooe"
@settings[:last_used_ooe_clean_rom_path] = clean_rom_path
update_last_used_clean_rom_combobox_items()
end
end
end
def set_clean_rom_combobox_text(text)
# If this text is one of the items in the dropdown, set that item as the selected one.
# Otherwise just set the text itself.
index = @ui.clean_rom.findText(text)
if index == -1
@ui.clean_rom.setEditText(text)
else
@ui.clean_rom.setCurrentIndex(index)
end
end
def initialize_difficulty_sliders
# Remove the grey background color of the scroll area.
@ui.scrollArea.setStyleSheet("QScrollArea {background-color:transparent;}");
@ui.scrollAreaWidgetContents.setStyleSheet("background-color:transparent;");
form_layout = @ui.scrollAreaWidgetContents.layout
@slider_widgets_by_name = {}
@difficulty_line_edit_widgets_by_name = {}
DIFFICULTY_OPTION_PRETTY_NAMES.each_with_index do |(option_name, pretty_name), i|
label = Qt::Label.new(@ui.scrollAreaWidgetContents)
label.text = pretty_name
form_layout.setWidget(i, Qt::FormLayout::LabelRole, label)
option_value_range = DIFFICULTY_RANGES[option_name]
if option_value_range.nil?
# Not a real option, just descriptive text.
next
end
horizontal_layout = Qt::HBoxLayout.new
form_layout.setLayout(i, Qt::FormLayout::FieldRole, horizontal_layout)
slider = FloatSlider.new(@ui.scrollAreaWidgetContents)
slider.minimum = option_value_range.begin
slider.maximum = option_value_range.end
slider.pageStep = ((option_value_range.end - option_value_range.begin) / 100.0).ceil * 100
slider.orientation = Qt::Horizontal
connect(slider, SIGNAL("valueChanged(int)"), self, SLOT("difficulty_slider_value_changed(int)"))
horizontal_layout.addWidget(slider)
@slider_widgets_by_name[option_name] = slider
slider.objectName = "#{option_name}_slider"
line_edit = Qt::LineEdit.new
line_edit.setMaximumSize(60, 16777215)
connect(line_edit, SIGNAL("editingFinished()"), self, SLOT("difficulty_line_edit_value_changed()"))
horizontal_layout.addWidget(line_edit)
@difficulty_line_edit_widgets_by_name[option_name] = line_edit
line_edit.objectName = "#{option_name}_line_edit"
end
@ui.difficulty_level.addItem("Custom")
DIFFICULTY_LEVELS.keys.each do |name|
@ui.difficulty_level.addItem(name)
end
end
def difficulty_slider_value_changed(value)
# Update text in the corresponding line edit.
slider = sender()
match = slider.objectName.match(/^(.+)_slider$/)
if match
option_name = match[1].to_sym
line_edit = @difficulty_line_edit_widgets_by_name[option_name]
line_edit.text = slider.true_value.to_s
@ui.difficulty_level.setCurrentIndex(0)
update_settings()
end
end
def difficulty_line_edit_value_changed
# Update text in the corresponding line edit.
line_edit = sender()
match = line_edit.objectName.match(/^(.+)_line_edit$/)
if match
new_value = line_edit.text.to_f
option_name = match[1].to_sym
slider = @slider_widgets_by_name[option_name]
slider.blockSignals(true)
slider.value = new_value
slider.blockSignals(false)
# Also update the text in the line edit after the slider has clamped the value in case it was too big or too small.
line_edit.text = slider.true_value.to_s
@ui.difficulty_level.setCurrentIndex(0)
update_settings()
end
end
def difficulty_level_changed_by_name(diff_name)
@ui.difficulty_level.count.times do |i|
if @ui.difficulty_level.itemText(i) == diff_name
difficulty_level_changed(i)
break
end
end
end
def difficulty_level_changed(diff_index)
@ui.difficulty_level.setCurrentIndex(diff_index)
difficulty_name = @ui.difficulty_level.itemText(diff_index)
difficulty_level_options = DIFFICULTY_LEVELS[difficulty_name]
if difficulty_level_options
form_layout = @ui.scrollAreaWidgetContents.layout
difficulty_level_options.each do |option_name, average|
slider = @slider_widgets_by_name[option_name]
slider.blockSignals(true)
slider.value = average
slider.blockSignals(false)
line_edit = @difficulty_line_edit_widgets_by_name[option_name]
line_edit.text = slider.true_value.to_s
end
end
update_settings()
end
def get_current_options_hash
options_hash = {}
OPTIONS.each_key do |option_name|
# Options that are disabled don't count as being checked, even though they visually remain checked when disabled.
options_hash[option_name] = @ui.send(option_name).checked && @ui.send(option_name).enabled
end
return options_hash
end
def get_current_difficulty_settings_averages
difficulty_settings_averages = {}
DIFFICULTY_RANGES.keys.each do |option_name|
slider = @slider_widgets_by_name[option_name]
average = slider.true_value
difficulty_settings_averages[option_name] = average
end
return difficulty_settings_averages
end
def generate_seed
# Generate a new random seed composed of 2 adjectives and a noun.
adjectives = File.read("./dsvrandom/seedgen_adjectives.txt").split("\n").sample(2)
noun = File.read("./dsvrandom/seedgen_nouns.txt").split("\n").sample
words = adjectives + [noun]
words.map!{|word| word.capitalize}
seed = words.join("")
@settings[:seed] = seed
@ui.seed.text = @settings[:seed]
save_settings()
end
def randomize_n_seeds
num_seeds_to_create = @settings[:num_seeds_to_create]
num_seeds_to_create = num_seeds_to_create.to_i
num_seeds_to_create = 1 if num_seeds_to_create < 1
@remaining_seeds_to_create = num_seeds_to_create
@output_filenames_written_so_far = []
generate_seed() if num_seeds_to_create > 1
randomize()
end
def load_game_and_verify_supported
unless File.file?(@ui.clean_rom.currentText)
Qt::MessageBox.warning(self, "No ROM specified", "Must specify clean ROM path.")
return nil
end
unless File.directory?(@ui.output_folder.text)
Qt::MessageBox.warning(self, "No output folder specified", "Must specify a valid output folder for the randomized ROM.")
return nil
end
game = Game.new
game.initialize_from_rom(@ui.clean_rom.currentText, extract_to_hard_drive = false)
if !["dos", "por", "ooe"].include?(GAME)
Qt::MessageBox.warning(self, "Unsupported game", "ROM is not a supported game.")
return nil
end
if REGION != :usa
Qt::MessageBox.warning(self, "Unsupported region", "Only the US versions are supported.")
return nil
end
return game
end
def randomize
game = load_game_and_verify_supported()
return if game.nil?
seed = @settings[:seed].to_s.strip.gsub(/\s/, "")
if seed.empty?
generate_seed()
seed = @settings[:seed]
end
if seed =~ /[^#{VALID_SEED_CHARACTERS}]/
Qt::MessageBox.critical(self, "Invalid seed", "Invalid seed. Seed can only have letters, numbers, dashes, underscores, and apostrophes in it.")
return
end
@settings[:seed] = seed
@ui.seed.text = @settings[:seed]
save_settings()
@sanitized_seed = seed
options_hash = get_current_options_hash()
difficulty_settings_averages = get_current_difficulty_settings_averages()
begin
randomizer = Randomizer.new(seed, game, options_hash, @settings[:difficulty_level], difficulty_settings_averages)
rescue StandardError => e
Qt::MessageBox.critical(self, "Randomization Failed", "Randomization failed with error:\n#{e.message}\n\n#{e.backtrace.join("\n")}")
return
end
max_val = options_hash.select{|k,v| k.to_s.start_with?("randomize_") && v}.length
max_val += 20 if options_hash[:randomize_pickups]
max_val += 7 if options_hash[:randomize_enemies]
max_val += 75 if options_hash[:randomize_maps]
max_val += 2 # Initialization
max_val += 1 # Applying tweaks and finishing up
@progress_dialog = ProgressDialog.new("Randomizing", "Initializing...", max_val)
@progress_dialog.execute do
begin
randomizer.randomize() do |options_completed, next_option_description|
break if @progress_dialog.nil?
Qt.execute_in_main_thread do
if @progress_dialog && !@progress_dialog.wasCanceled
@progress_dialog.setValue(options_completed)
@progress_dialog.labelText = next_option_description
end
end
end
rescue StandardError => e
Qt.execute_in_main_thread do
if @progress_dialog
@progress_dialog.setValue(max_val) unless @progress_dialog.wasCanceled
@progress_dialog.reset()
@progress_dialog = nil
end
write_logs(randomizer, is_error: true)
Qt::MessageBox.critical(self, "Randomization Failed", "Randomization failed with error:\n#{e.message}\n\n#{e.backtrace.join("\n")}")
end
return
end
Qt.execute_in_main_thread do
if @progress_dialog
@progress_dialog.setValue(max_val) unless @progress_dialog.wasCanceled
@progress_dialog.reset()
@progress_dialog = nil
end
write_to_rom(game, randomizer)
end
end
rescue NDSFileSystem::InvalidFileError, Game::InvalidFileError => e
Qt::MessageBox.warning(self, "Unrecognized game", "Specified ROM is not recognized.\nOnly the US versions are supported.")
return
end
def write_to_rom(game, randomizer)
FileUtils.mkdir_p(@ui.output_folder.text)
game_with_caps = GAME.dup
game_with_caps[0] = game_with_caps[0].upcase
game_with_caps[2] = game_with_caps[2].upcase
output_rom_filename = "#{game_with_caps} #{@sanitized_seed}.nds"
output_rom_path = File.join(@ui.output_folder.text, output_rom_filename)
max_val = game.fs.files_without_dirs.length
@progress_dialog = ProgressDialog.new("Building", "Writing files to ROM", max_val)
@progress_dialog.execute do
begin
game.fs.write_to_rom(output_rom_path) do |files_written|
next unless files_written % 100 == 0 # Only update the UI every 100 files because updating too often is slow.
break if @progress_dialog.nil?
Qt.execute_in_main_thread do
if @progress_dialog && !@progress_dialog.wasCanceled
@progress_dialog.setValue(files_written)
end
end
end
rescue StandardError => e
Qt.execute_in_main_thread do
if @progress_dialog
@progress_dialog.setValue(max_val) unless @progress_dialog.wasCanceled
@progress_dialog.close()
@progress_dialog = nil
end
write_logs(randomizer, is_error: true)
Qt::MessageBox.critical(self, "Building ROM failed", "Failed to build ROM with error:\n#{e.message}\n\n#{e.backtrace.join("\n")}")
end
return
end
Qt.execute_in_main_thread do
if @progress_dialog
@progress_dialog.setValue(max_val) unless @progress_dialog.wasCanceled
@progress_dialog.reset()
@progress_dialog = nil
end
write_logs(randomizer)
@remaining_seeds_to_create -= 1
@output_filenames_written_so_far << output_rom_filename
if @remaining_seeds_to_create > 0
generate_seed()
randomize()
else
msg = "Randomization complete.\n\n"
if @output_filenames_written_so_far.length == 1
msg << "Output ROM:\n#{output_rom_filename}\n\n"
else
msg << "Output ROMs:\n#{@output_filenames_written_so_far.join(", ")}\n\n"
end
msg << "If you get stuck, check the FAQ in the readme,\nand the progression spoiler log in the output folder."
msg << "\n\nNote that you have an infinitely usable magical ticket in your inventory, so if you get trapped in a pit use that to return to your starting room." if randomizer.needs_infinite_magical_tickets?
Qt::MessageBox.information(self, "Done", msg)
end
end
end
end
def write_logs(randomizer, is_error: false)
if is_error
logs = [randomizer.spoiler_log]
else
logs = [randomizer.spoiler_log, randomizer.non_spoiler_log]
end
logs.compact!
logs.each do |log|
log.seek(0)
spoiler_str = log.read()
game_with_caps = GAME.dup
game_with_caps[0] = game_with_caps[0].upcase
game_with_caps[2] = game_with_caps[2].upcase
if is_error
output_log_filename = "#{game_with_caps} #{@sanitized_seed} - Error Log.txt"
elsif log == randomizer.non_spoiler_log
output_log_filename = "#{game_with_caps} #{@sanitized_seed} - Non-Spoiler Log.txt"
else
output_log_filename = "#{game_with_caps} #{@sanitized_seed} - Spoiler Log.txt"
end
output_log_path = File.join(@ui.output_folder.text, output_log_filename)
File.open(output_log_path, "w") do |f|
f.write(spoiler_str)
end
end
end
def open_about
@about_dialog = Qt::MessageBox.new
@about_dialog.setTextFormat(Qt::RichText)
@about_dialog.setWindowTitle("DSVania Randomizer")
base_text = "DSVania Randomizer Version #{DSVRANDOM_VERSION}<br><br>" +
"Created by LagoLunatic<br><br>" +
"Report issues here:<br><a href=\"https://github.com/LagoLunatic/dsvrandom/issues\">https://github.com/LagoLunatic/dsvrandom/issues</a><br><br>" +
"Source code:<br><a href=\"https://github.com/LagoLunatic/dsvrandom\">https://github.com/LagoLunatic/dsvrandom</a><br><br>"
text = base_text + "Checking for updates..."
@about_dialog.setText(text)
@about_dialog.windowIcon = self.windowIcon
@about_dialog.show()
new_version = check_for_updates()
if new_version.nil?
update_text = "No new updates to the randomizer are available."
elsif new_version == :error
update_text = "There was an error checking for updates."
else
update_text = "<b>Version %s of the randomizer is available!</b><br>" % new_version
update_text += "<a href=\"%s\">Click here</a> to go to the download page." % LATEST_RELEASE_DOWNLOAD_PAGE_URL
end
text = base_text + update_text
@about_dialog.setText(text)
end
def preserve_default_settings
@default_settings = {}
OPTIONS.each_key do |option_name|
@default_settings[option_name] = @ui.send(option_name).checked
end
@default_difficulty_level = "Normal"
end
def reset_settings_to_default
any_setting_changed = false
OPTIONS.each_key do |option_name|
if @default_settings.key?(option_name)
default_value = @default_settings[option_name]
current_value = @ui.send(option_name).checked
if default_value != current_value
any_setting_changed = true
end
@ui.send(option_name).checked = default_value
end
end
if @ui.difficulty_level.currentText != @default_difficulty_level
difficulty_level_changed_by_name(@default_difficulty_level)
any_setting_changed = true
end
if any_setting_changed
update_settings()
else
Qt::MessageBox.information(self,
"Settings already default",
"You already have all the default randomization settings."
)
end
end
def keyPressEvent(event)
if event.key() == Qt::Key_Return
self.randomize_n_seeds()
else
super(event)
end
end
def save_options_preset_to_file
if @settings[:options_presets_folder] && File.directory?(@settings[:options_presets_folder])
default_dir = @settings[:options_presets_folder]
else
FileUtils.mkdir_p("./DSVRandom Presets")
default_dir = "./DSVRandom Presets"
end
preset_path, selected_filter = Qt::FileDialog.getSaveFileName(self, "Save options preset", default_dir, "DSVRandom Preset Files (*.dsvrpreset)")
return if preset_path.nil?
text = create_options_preset_from_current_settings()
return if text.nil?
File.open(preset_path, "wb") do |f|
f.write(text)
end
basename = File.basename(preset_path)
dirname = File.dirname(preset_path)
@settings[:options_presets_folder] = dirname
Qt::MessageBox.information(self, "Saved options preset", "Successfully saved options preset \"%s\"." % basename)
end
def load_options_preset_from_file
if @settings[:options_presets_folder] && File.directory?(@settings[:options_presets_folder])
default_dir = @settings[:options_presets_folder]
end
preset_path = Qt::FileDialog.getOpenFileName(self, "Select options preset", default_dir, "DSVRandom Preset Files (*.dsvrpreset)")
return if preset_path.nil?
text = File.read(preset_path)
read_seed_info(text, is_preset=true)
dirname = File.dirname(preset_path)
@settings[:options_presets_folder] = dirname
end
def load_seed_info_from_file
if @settings[:output_folder] && File.directory?(@settings[:output_folder])
default_dir = @settings[:output_folder]
end
log_path = Qt::FileDialog.getOpenFileName(self, "Select spoiler/non-spoiler log", default_dir, "Text files (*.txt)")
return if log_path.nil?
text = File.read(log_path)
read_seed_info(text)
end
def paste_seed_info_from_clipboard
text = $qApp.clipboard.text()
read_seed_info(text)
end
def create_options_preset_from_current_settings
text = StringIO.new
game = load_game_and_verify_supported
return nil if game.nil?
options = get_current_options_hash()
difficulty_level = @settings[:difficulty_level]
user_given_difficulty_settings = get_current_difficulty_settings_averages()
options_string = options.select{|k,v| v == true}.keys.join(", ")
if DIFFICULTY_LEVELS.keys.include?(difficulty_level)
difficulty_settings_string = difficulty_level
else
difficulty_settings_string = "Custom, settings:\n " + user_given_difficulty_settings.map{|k,v| "#{k}: #{v}"}.join("\n ")
end
text.puts "DSVRandom Options Preset, Game: #{LONG_GAME_NAME}, Randomizer version: #{DSVRANDOM_VERSION}"
text.puts "Selected options: #{options_string}"
text.puts "Difficulty level: #{difficulty_settings_string}"
return text.string
end
def read_seed_info(text, is_preset=false)
if is_preset
format_type = "options preset"
else
format_type = "seed info"
end
if text.nil? || text.strip == ""
if is_preset
raise "#{format_type.capitalize} is blank."
else
raise "No #{format_type} input."
end
end
if is_preset
match = text.match(/DSVRandom Options Preset, Game: ([^,]+), Randomizer version: (.+)\s+Selected options: (.+)\s+Difficulty level: (.+)/)
if match.nil?
raise "#{format_type.capitalize} is not in the proper format."
end
seed = ""
game = $1
version = $2
options = $3.split(", ").map(&:to_sym)
difficulty = $4
else
match = text.match(/Seed: ([#{VALID_SEED_CHARACTERS}]+), Game: ([^,]+), Randomizer version: (.+)\s+Selected options: (.+)\s+Difficulty level: (.+)/)
if match.nil?
raise "#{format_type.capitalize} is not in the proper format."
end
seed = $1
game = $2
version = $3
options = $4.split(", ").map(&:to_sym)
difficulty = $5
end
if version != DSVRANDOM_VERSION
raise "Wrong version! This is for #{version}, but you are on #{DSVRANDOM_VERSION}"
end
short_game_name = case game
when "Dawn of Sorrow"
"dos"
when "Portrait of Ruin"
"por"
when "Order of Ecclesia"
"ooe"
else
raise "Invalid game name: #{game}"
end
last_used_rom_path_for_this_game = @settings["last_used_#{short_game_name}_clean_rom_path".to_sym]
if last_used_rom_path_for_this_game && File.file?(last_used_rom_path_for_this_game)
set_clean_rom_combobox_text(last_used_rom_path_for_this_game)
successfully_changed_clean_rom_path = true
else
set_clean_rom_combobox_text("")
successfully_changed_clean_rom_path = false
end
@ui.seed.text = seed
options.each do |option_name|
if [email protected]_to?(option_name)
raise "Invalid options name found in #{format_type}: \"#{option_name}\""
end
@ui.send(option_name).checked = true
end
(OPTIONS.keys-options).each do |option_name|
@ui.send(option_name).checked = false
end
difficulty_level_options = DIFFICULTY_LEVELS[difficulty]
if difficulty_level_options
# Preset difficulty level.
difficulty_level_changed_by_name(difficulty)
elsif difficulty =~ /Custom/
# Custom difficulty.