-
Notifications
You must be signed in to change notification settings - Fork 450
Expand file tree
/
Copy pathBasicBot.cs
More file actions
1303 lines (1104 loc) · 37.4 KB
/
BasicBot.cs
File metadata and controls
1303 lines (1104 loc) · 37.4 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
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
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BizHawk.Client.EmuHawk.ToolExtensions;
using BizHawk.Emulation.Common;
using BizHawk.Client.Common;
using BizHawk.Client.EmuHawk.Properties;
using BizHawk.Common;
namespace BizHawk.Client.EmuHawk
{
public sealed partial class BasicBot : ToolFormBase, IToolFormAutoConfig
{
private static readonly FilesystemFilterSet BotFilesFSFilterSet = new(new FilesystemFilter("Bot files", new[] { "bot" }));
public static Icon ToolIcon
=> Resources.BasicBot;
private string _currentFileName = "";
private string CurrentFileName
{
get => _currentFileName;
set
{
_currentFileName = value;
_windowTitle = !string.IsNullOrWhiteSpace(_currentFileName)
? $"{WindowTitleStatic} - {Path.GetFileNameWithoutExtension(_currentFileName)}"
: WindowTitleStatic;
UpdateWindowTitle();
}
}
private bool _isBotting;
private long _attempts = 1;
private long _frames;
private int _targetFrame;
private bool _oldCountingSetting;
private BotAttempt _currentBotAttempt;
private BotAttempt _bestBotAttempt;
private readonly BotAttempt _comparisonBotAttempt;
private bool _replayMode;
private int _startFrame;
private string _lastRom = "";
private int _lastFrameAdvanced;
private bool _doNotUpdateValues;
private MemoryDomain _currentDomain;
private bool _bigEndian;
private int _dataSize;
private Dictionary<string, double> _cachedControlProbabilities;
private bool _previousDisplayMessage;
[RequiredService]
private IEmulator Emulator { get; set; }
[RequiredService]
private IStatable StatableCore { get; set; }
[RequiredService]
private IMemoryDomains MemoryDomains { get; set; }
[ConfigPersist]
public BasicBotSettings Settings { get; set; }
public class BasicBotSettings
{
public RecentFiles RecentBotFiles { get; set; } = new RecentFiles();
public bool TurboWhenBotting { get; set; } = true;
}
private string _windowTitle = "Basic Bot";
protected override string WindowTitle => _windowTitle;
protected override string WindowTitleStatic => "Basic Bot";
private IMovie CurrentMovie => MovieSession.Movie;
public BasicBot()
{
InitializeComponent();
Icon = ToolIcon;
NewMenuItem.Image = Resources.NewFile;
OpenMenuItem.Image = Resources.OpenFile;
SaveMenuItem.Image = Resources.SaveAs;
RecentSubMenu.Image = Resources.Recent;
RunBtn.Image = Resources.Play;
BotStatusButton.Image = Resources.Placeholder;
btnCopyBestInput.Image = Resources.Duplicate;
PlayBestButton.Image = Resources.Play;
ClearBestButton.Image = Resources.Close;
StopBtn.Image = Resources.Stop;
if (OSTailoredCode.IsUnixHost)
{
AutoSize = false;
Margin = new(0, 0, 0, 8);
}
Settings = new BasicBotSettings();
_comparisonBotAttempt = new BotAttempt();
_currentBotAttempt = new BotAttempt();
_bestBotAttempt = new BotAttempt();
_comparisonBotAttempt.is_Reset = true;
_currentBotAttempt.is_Reset = true;
_bestBotAttempt.is_Reset = true;
MainOperator.SelectedItem = ">=";
}
private void BasicBot_Load(object sender, EventArgs e)
{
// Movie recording must be active (check TAStudio because opening a project re-loads the ROM,
// which resets tools before the movie session becomes active)
if (CurrentMovie.NotActive() && !Tools.IsLoaded<TAStudio>())
{
DialogController.ShowMessageBox("In order to use this tool you must be recording a movie.");
Close();
DialogResult = DialogResult.Cancel;
return;
}
if (Config!.OpposingDirPolicy is not OpposingDirPolicy.Allow)
{
DialogController.ShowMessageBox("In order to use this tool, U+D/L+R policy in the controller binds dialog must be set to 'Allow'.");
Close();
DialogResult = DialogResult.Cancel;
return;
}
if (OSTailoredCode.IsUnixHost) ClientSize = new(707, 587);
_previousDisplayMessage = Config.DisplayMessages;
Closing += (_, _) => StopBot();
}
private Dictionary<string, double> ControlProbabilities =>
ControlProbabilityPanel.Controls
.OfType<BotControlsRow>()
.ToDictionary(tkey => tkey.ButtonName, tvalue => tvalue.Probability);
private int SelectedSlot
=> 1 + StartFromSlotBox.SelectedIndex;
private long Attempts
{
get => _attempts;
set
{
_attempts = value;
AttemptsLabel.Text = _attempts.ToString();
}
}
private long Frames
{
get => _frames;
set
{
_frames = value;
FramesLabel.Text = _frames.ToString();
}
}
private int FrameLength
{
get => (int)FrameLengthNumeric.Value;
set => FrameLengthNumeric.Value = value;
}
private ulong? MaximizeAddress
{
get => MaximizeAddressBox.ToU64();
set => MaximizeAddressBox.SetFromU64(value);
}
private int MaximizeValue
=> GetRamValue(MaximizeAddress);
private ulong? TieBreaker1Address
{
get => TieBreaker1Box.ToU64();
set => TieBreaker1Box.SetFromU64(value);
}
private int TieBreaker1Value
=> GetRamValue(TieBreaker1Address);
private ulong? TieBreaker2Address
{
get => TieBreaker2Box.ToU64();
set => TieBreaker2Box.SetFromU64(value);
}
private int TieBreaker2Value
=> GetRamValue(TieBreaker2Address);
private ulong? TieBreaker3Address
{
get => TieBreaker3Box.ToU64();
set => TieBreaker3Box.SetFromU64(value);
}
private int TieBreaker3Value
=> GetRamValue(TieBreaker3Address);
public byte MainComparisonType
{
get => (byte)MainOperator.SelectedIndex;
set => MainOperator.SelectedIndex = value < 6 ? value : 0;
}
public byte Tie1ComparisonType
{
get => (byte)Tiebreak1Operator.SelectedIndex;
set => Tiebreak1Operator.SelectedIndex = value < 6 ? value : 0;
}
public byte Tie2ComparisonType
{
get => (byte)Tiebreak2Operator.SelectedIndex;
set => Tiebreak2Operator.SelectedIndex = value < 6 ? value : 0;
}
public byte Tie3ComparisonType
{
get => (byte)Tiebreak3Operator.SelectedIndex;
set => Tiebreak3Operator.SelectedIndex = value < 6 ? value : 0;
}
public string FromSlot
{
get => StartFromSlotBox.SelectedItem != null
? StartFromSlotBox.SelectedItem.ToString()
: "";
set
{
var item = StartFromSlotBox.Items
.OfType<object>()
.FirstOrDefault(o => o.ToString() == value);
StartFromSlotBox.SelectedItem = item;
}
}
// Controls need to be set and synced after emulation, so that everything works out properly at the start of the next frame
// Consequently, when loading a state, input needs to be set before the load, to ensure everything works out in the correct order
protected override void UpdateAfter() => Update(fast: false);
protected override void FastUpdateAfter() => Update(fast: true);
public override void Stop()
{
if (_isBotting)
{
StopBot();
}
else if (_replayMode)
{
FinishReplay();
}
}
public override void Restart()
{
_ = StatableCore!; // otherwise unused due to loadstating via MainForm; however this service is very much required so the property needs to be present
if (_currentDomain == null
|| MemoryDomains.Contains(_currentDomain))
{
_currentDomain = MemoryDomains.MainMemory;
_bigEndian = _currentDomain.EndianType == MemoryDomain.Endian.Big;
_dataSize = 1;
}
if (_lastRom != MainForm.CurrentlyOpenRom)
{
_lastRom = MainForm.CurrentlyOpenRom;
SetupControlsAndProperties();
}
}
private void FileSubMenu_DropDownOpened(object sender, EventArgs e)
{
SaveMenuItem.Enabled = !string.IsNullOrWhiteSpace(CurrentFileName);
}
private void RecentSubMenu_DropDownOpened(object sender, EventArgs e)
=> RecentSubMenu.ReplaceDropDownItems(Settings.RecentBotFiles.RecentMenu(this, LoadFileFromRecent, "Bot Parameters"));
private void NewMenuItem_Click(object sender, EventArgs e)
{
CurrentFileName = "";
_bestBotAttempt.is_Reset = true;
foreach (var cp in ControlProbabilityPanel.Controls.OfType<BotControlsRow>())
{
cp.Probability = 0;
}
FrameLength = 0;
MaximizeAddress = 0;
TieBreaker1Address = 0;
TieBreaker2Address = 0;
TieBreaker3Address = 0;
StartFromSlotBox.SelectedIndex = 0;
MainOperator.SelectedIndex = 0;
Tiebreak1Operator.SelectedIndex = 0;
Tiebreak2Operator.SelectedIndex = 0;
Tiebreak3Operator.SelectedIndex = 0;
MainBestRadio.Checked = true;
MainValueNumeric.Value = 0;
TieBreak1Numeric.Value = 0;
TieBreak2Numeric.Value = 0;
TieBreak3Numeric.Value = 0;
TieBreak1BestRadio.Checked = true;
TieBreak2BestRadio.Checked = true;
TieBreak3BestRadio.Checked = true;
UpdateBestAttempt();
UpdateComparisonBotAttempt();
}
private void OpenMenuItem_Click(object sender, EventArgs e)
{
var file = OpenFileDialog(
currentFile: CurrentFileName,
path: Config!.PathEntries.ToolsAbsolutePath(),
BotFilesFSFilterSet);
if (file != null)
{
_ = LoadBotFile(file.FullName);
}
}
private void SaveMenuItem_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(CurrentFileName))
{
SaveBotFile(CurrentFileName);
}
}
private void SaveAsMenuItem_Click(object sender, EventArgs e)
{
var fileName = CurrentFileName;
if (string.IsNullOrWhiteSpace(fileName))
{
fileName = Game.FilesystemSafeName();
}
var file = SaveFileDialog(
currentFile: fileName,
path: Config!.PathEntries.ToolsAbsolutePath(),
BotFilesFSFilterSet,
this);
if (file != null)
{
SaveBotFile(file.FullName);
_currentFileName = file.FullName;
}
}
private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e)
{
TurboWhileBottingMenuItem.Checked = Settings.TurboWhenBotting;
BigEndianMenuItem.Checked = _bigEndian;
}
private void MemoryDomainsMenuItem_DropDownOpened(object sender, EventArgs e)
=> MemoryDomainsMenuItem.ReplaceDropDownItems(MemoryDomains.MenuItems(SetMemoryDomain, _currentDomain.Name).ToArray());
private void BigEndianMenuItem_Click(object sender, EventArgs e)
=> _bigEndian = !_bigEndian;
private void DataSizeMenuItem_DropDownOpened(object sender, EventArgs e)
{
_1ByteMenuItem.Checked = _dataSize == 1;
_2ByteMenuItem.Checked = _dataSize == 2;
_4ByteMenuItem.Checked = _dataSize == 4;
}
private void OneByteMenuItem_Click(object sender, EventArgs e)
{
_dataSize = 1;
}
private void TwoByteMenuItem_Click(object sender, EventArgs e)
{
_dataSize = 2;
}
private void FourByteMenuItem_Click(object sender, EventArgs e)
{
_dataSize = 4;
}
private void TurboWhileBottingMenuItem_Click(object sender, EventArgs e)
=> Settings.TurboWhenBotting = !Settings.TurboWhenBotting;
private void RunBtn_Click(object sender, EventArgs e)
{
StartBot();
}
private void StopBtn_Click(object sender, EventArgs e)
{
StopBot();
}
private void ClearBestButton_Click(object sender, EventArgs e)
{
_bestBotAttempt.is_Reset = true;
Attempts = 0;
Frames = 0;
UpdateBestAttempt();
UpdateComparisonBotAttempt();
}
private void PlayBestButton_Click(object sender, EventArgs e)
{
StopBot();
_replayMode = true;
_doNotUpdateValues = true;
// here we need to apply the initial frame's input from the best attempt
var logEntry = _bestBotAttempt.Log[0];
var controller = MovieSession.GenerateMovieController();
controller.SetFromMnemonic(logEntry);
foreach (var button in controller.Definition.BoolButtons)
{
// TODO: make an input adapter specifically for the bot?
InputManager.ButtonOverrideAdapter.SetButton(button, controller.IsPressed(button));
}
InputManager.SyncControls(Emulator, MovieSession, Config);
_ = MainForm.LoadQuickSave(SelectedSlot, true); // Triggers an UpdateValues call
_lastFrameAdvanced = Emulator.Frame;
_doNotUpdateValues = false;
_startFrame = Emulator.Frame;
SetNormalSpeed();
UpdateBotStatusIcon();
MessageLabel.Text = "Replaying";
MainForm.UnpauseEmulator();
}
private void FrameLengthNumeric_ValueChanged(object sender, EventArgs e)
{
AssessRunButtonStatus();
}
private void ClearStatsContextMenuItem_Click(object sender, EventArgs e)
{
Attempts = 0;
Frames = 0;
}
private class BotAttempt
{
public long Attempt { get; set; }
public int Maximize { get; set; }
public int TieBreak1 { get; set; }
public int TieBreak2 { get; set; }
public int TieBreak3 { get; set; }
public byte ComparisonTypeMain { get; set; }
public byte ComparisonTypeTie1 { get; set; }
public byte ComparisonTypeTie2 { get; set; }
public byte ComparisonTypeTie3 { get; set; }
public List<string> Log { get; } = new List<string>();
public bool is_Reset { get; set; }
}
private void reset_curent(long attempt_num)
{
_currentBotAttempt.Attempt = attempt_num;
_currentBotAttempt.Maximize = 0;
_currentBotAttempt.TieBreak1 = 0;
_currentBotAttempt.TieBreak2 = 0;
_currentBotAttempt.TieBreak3 = 0;
// no references to ComparisonType parameters
_currentBotAttempt.Log.Clear();
_currentBotAttempt.is_Reset = true;
}
private void copy_curent_to_best()
{
_bestBotAttempt.Attempt = _currentBotAttempt.Attempt;
_bestBotAttempt.Maximize = _currentBotAttempt.Maximize;
_bestBotAttempt.TieBreak1 = _currentBotAttempt.TieBreak1;
_bestBotAttempt.TieBreak2 = _currentBotAttempt.TieBreak2;
_bestBotAttempt.TieBreak3 = _currentBotAttempt.TieBreak3;
// no references to ComparisonType parameters
_bestBotAttempt.Log.Clear();
for (int i = 0; i < _currentBotAttempt.Log.Count; i++)
{
_bestBotAttempt.Log.Add(_currentBotAttempt.Log[i]);
}
_bestBotAttempt.is_Reset = false;
}
private class BotData
{
public BotAttempt Best { get; set; }
public Dictionary<string, double> ControlProbabilities { get; set; }
public ulong? Maximize { get; set; }
public ulong? TieBreaker1 { get; set; }
public ulong? TieBreaker2 { get; set; }
public ulong? TieBreaker3 { get; set; }
public byte ComparisonTypeMain { get; set; }
public byte ComparisonTypeTie1 { get; set; }
public byte ComparisonTypeTie2 { get; set; }
public byte ComparisonTypeTie3 { get; set; }
public bool MainCompareToBest { get; set; } = true;
public bool TieBreaker1CompareToBest { get; set; } = true;
public bool TieBreaker2CompareToBest { get; set; } = true;
public bool TieBreaker3CompareToBest { get; set; } = true;
public int MainCompareToValue { get; set; }
public int TieBreaker1CompareToValue { get; set; }
public int TieBreaker2CompareToValue { get; set; }
public int TieBreaker3CompareToValue { get; set; }
public int FrameLength { get; set; }
public string FromSlot { get; set; }
public long Attempts { get; set; }
public long Frames { get; set; }
public string MemoryDomain { get; set; }
public bool BigEndian { get; set; }
public int DataSize { get; set; }
public string HawkVersion { get; set; }
public string SysID { get; set; }
public string CoreName { get; set; }
public string GameName { get; set; }
}
private void LoadFileFromRecent(string path)
{
var result = LoadBotFile(path);
if (!result && !File.Exists(path))
{
Settings.RecentBotFiles.HandleLoadError(this, path: path);
}
}
private bool LoadBotFile(string path)
{
BotData botData;
try
{
botData = (BotData) ConfigService.LoadWithType(File.ReadAllText(path));
}
catch (Exception e)
{
using ExceptionBox dialog = new(e);
this.ShowDialogAsChild(dialog);
return false;
}
if (botData.SysID != Emulator.SystemId)
{
this.ModalMessageBox(text: $"This file was made for a different system ({botData.SysID}).");
if (!string.IsNullOrEmpty(botData.SysID)) return false; // there's little chance the file would load without throwing, and if it did, it wouldn't be useful
// else grandfathered (made with old version, sysID unknowable), user has been warned
}
// if something else is off, though, let the user decide
var hawkVersionMatches = VersionInfo.DeveloperBuild || botData.HawkVersion == VersionInfo.GetEmuVersion();
var coreNameMatches = botData.CoreName == Emulator.Attributes().CoreName;
var gameNameMatches = botData.GameName == Game.Name;
if (!(hawkVersionMatches && coreNameMatches && gameNameMatches))
{
var s = hawkVersionMatches
? coreNameMatches
? string.Empty
: $" with a different core ({botData.CoreName ?? "unknown"})"
: coreNameMatches
? " with a different version of EmuHawk"
: $" with a different core ({botData.CoreName ?? "unknown"}) on a different version of EmuHawk";
if (!gameNameMatches) s = $"for a different game ({botData.GameName ?? "unknown"}){s}";
if (!this.ModalMessageBox2(
text: $"This file was made {s}. Load it anyway?",
caption: "Confirm file load",
icon: EMsgBoxIcon.Question))
{
return false;
}
}
try
{
LoadBotFileInner(botData, path);
return true;
}
catch (Exception e)
{
using ExceptionBox dialog = new(e);
this.ShowDialogAsChild(dialog);
return false;
}
}
private void LoadBotFileInner(BotData botData, string path)
{
_bestBotAttempt.Attempt = botData.Best.Attempt;
_bestBotAttempt.Maximize = botData.Best.Maximize;
_bestBotAttempt.TieBreak1 = botData.Best.TieBreak1;
_bestBotAttempt.TieBreak2 = botData.Best.TieBreak2;
_bestBotAttempt.TieBreak3 = botData.Best.TieBreak3;
// no references to ComparisonType parameters
_bestBotAttempt.Log.Clear();
for (int i = 0; i < botData.Best.Log.Count; i++)
{
_bestBotAttempt.Log.Add(botData.Best.Log[i]);
}
_bestBotAttempt.is_Reset = false;
var probabilityControls = ControlProbabilityPanel.Controls
.OfType<BotControlsRow>()
.ToList();
foreach (var (button, p) in botData.ControlProbabilities)
{
var control = probabilityControls.Single(c => c.ButtonName == button);
control.Probability = p;
}
MaximizeAddress = botData.Maximize;
TieBreaker1Address = botData.TieBreaker1;
TieBreaker2Address = botData.TieBreaker2;
TieBreaker3Address = botData.TieBreaker3;
try
{
MainComparisonType = botData.ComparisonTypeMain;
Tie1ComparisonType = botData.ComparisonTypeTie1;
Tie2ComparisonType = botData.ComparisonTypeTie2;
Tie3ComparisonType = botData.ComparisonTypeTie3;
MainBestRadio.Checked = botData.MainCompareToBest;
TieBreak1BestRadio.Checked = botData.TieBreaker1CompareToBest;
TieBreak2BestRadio.Checked = botData.TieBreaker2CompareToBest;
TieBreak3BestRadio.Checked = botData.TieBreaker3CompareToBest;
MainValueRadio.Checked = !botData.MainCompareToBest;
TieBreak1ValueRadio.Checked = !botData.TieBreaker1CompareToBest;
TieBreak2ValueRadio.Checked = !botData.TieBreaker2CompareToBest;
TieBreak3ValueRadio.Checked = !botData.TieBreaker3CompareToBest;
MainValueNumeric.Value = botData.MainCompareToValue;
TieBreak1Numeric.Value = botData.TieBreaker1CompareToValue;
TieBreak2Numeric.Value = botData.TieBreaker2CompareToValue;
TieBreak3Numeric.Value = botData.TieBreaker3CompareToValue;
}
catch
{
MainComparisonType = 0;
Tie1ComparisonType = 0;
Tie2ComparisonType = 0;
Tie3ComparisonType = 0;
MainBestRadio.Checked = true;
TieBreak1BestRadio.Checked = true;
TieBreak2BestRadio.Checked = true;
TieBreak3BestRadio.Checked = true;
MainBestRadio.Checked = false;
TieBreak1BestRadio.Checked = false;
TieBreak2BestRadio.Checked = false;
TieBreak3BestRadio.Checked = false;
MainValueNumeric.Value = 0;
TieBreak1Numeric.Value = 0;
TieBreak2Numeric.Value = 0;
TieBreak3Numeric.Value = 0;
}
FrameLength = botData.FrameLength;
FromSlot = botData.FromSlot;
Attempts = botData.Attempts;
Frames = botData.Frames;
_currentDomain = !string.IsNullOrWhiteSpace(botData.MemoryDomain)
? MemoryDomains[botData.MemoryDomain]
: MemoryDomains.MainMemory;
_bigEndian = botData.BigEndian;
_dataSize = botData.DataSize > 0 ? botData.DataSize : 1;
UpdateBestAttempt();
UpdateComparisonBotAttempt();
if (!_bestBotAttempt.is_Reset)
{
PlayBestButton.Enabled = true;
}
CurrentFileName = path;
Settings.RecentBotFiles.Add(CurrentFileName);
MessageLabel.Text = $"{Path.GetFileNameWithoutExtension(path)} loaded";
AssessRunButtonStatus();
}
private void SaveBotFile(string path)
{
var data = new BotData
{
Best = _bestBotAttempt,
ControlProbabilities = ControlProbabilities,
Maximize = MaximizeAddress,
TieBreaker1 = TieBreaker1Address,
TieBreaker2 = TieBreaker2Address,
TieBreaker3 = TieBreaker3Address,
ComparisonTypeMain = MainComparisonType,
ComparisonTypeTie1 = Tie1ComparisonType,
ComparisonTypeTie2 = Tie2ComparisonType,
ComparisonTypeTie3 = Tie3ComparisonType,
MainCompareToBest = MainBestRadio.Checked,
TieBreaker1CompareToBest = TieBreak1BestRadio.Checked,
TieBreaker2CompareToBest = TieBreak2BestRadio.Checked,
TieBreaker3CompareToBest = TieBreak3BestRadio.Checked,
MainCompareToValue = (int)MainValueNumeric.Value,
TieBreaker1CompareToValue = (int)TieBreak1Numeric.Value,
TieBreaker2CompareToValue = (int)TieBreak2Numeric.Value,
TieBreaker3CompareToValue = (int)TieBreak3Numeric.Value,
FromSlot = FromSlot,
FrameLength = FrameLength,
Attempts = Attempts,
Frames = Frames,
MemoryDomain = _currentDomain.Name,
BigEndian = _bigEndian,
DataSize = _dataSize,
HawkVersion = VersionInfo.GetEmuVersion(),
SysID = Emulator.SystemId,
CoreName = Emulator.Attributes().CoreName,
GameName = Game.Name,
};
var json = ConfigService.SaveWithType(data);
File.WriteAllText(path, json);
CurrentFileName = path;
Settings.RecentBotFiles.Add(CurrentFileName);
MessageLabel.Text = $"{Path.GetFileName(CurrentFileName)} saved";
}
public bool HasFrameAdvanced()
{
// If the emulator frame is different from the last time it tried calling
// the function then we can continue, otherwise we need to stop.
return _lastFrameAdvanced != Emulator.Frame;
}
private void SetupControlsAndProperties()
{
MaximizeAddressBox.SetHexProperties(_currentDomain.Size);
TieBreaker1Box.SetHexProperties(_currentDomain.Size);
TieBreaker2Box.SetHexProperties(_currentDomain.Size);
TieBreaker3Box.SetHexProperties(_currentDomain.Size);
StartFromSlotBox.SelectedIndex = 0;
const int startY = 0;
const int lineHeight = 30;
const int marginLeft = 15;
int accumulatedY = 0;
int count = 0;
ControlProbabilityPanel.SuspendLayout();
ControlProbabilityPanel.Controls.Clear();
foreach (var button in Emulator.ControllerDefinition.BoolButtons)
{
var control = new BotControlsRow
{
ButtonName = button,
Probability = 0.0,
Location = new Point(marginLeft, startY + accumulatedY),
TabIndex = count + 1,
ProbabilityChangedCallback = AssessRunButtonStatus,
};
control.Scale(UIHelper.AutoScaleFactor);
ControlProbabilityPanel.Controls.Add(control);
accumulatedY += lineHeight;
count++;
}
ControlProbabilityPanel.ResumeLayout();
if (Settings.RecentBotFiles.AutoLoad)
{
LoadFileFromRecent(Settings.RecentBotFiles.MostRecent);
}
UpdateBotStatusIcon();
}
private void SetMemoryDomain(string name)
{
_currentDomain = MemoryDomains[name];
_bigEndian = _currentDomain!.EndianType == MemoryDomain.Endian.Big;
MaximizeAddressBox.SetHexProperties(_currentDomain.Size);
TieBreaker1Box.SetHexProperties(_currentDomain.Size);
TieBreaker2Box.SetHexProperties(_currentDomain.Size);
TieBreaker3Box.SetHexProperties(_currentDomain.Size);
}
private int GetRamValue(ulong? address)
{
if (address is null) return 0;
var addr = checked((long) address); //TODO MemoryDomain needs converting one day
var val = _dataSize switch
{
1 => _currentDomain.PeekByte(addr),
2 => _currentDomain.PeekUshort(addr, _bigEndian),
4 => (int) _currentDomain.PeekUint(addr, _bigEndian),
_ => _currentDomain.PeekByte(addr),
};
return val;
}
private void Update(bool fast)
{
if (_doNotUpdateValues)
{
return;
}
if (!HasFrameAdvanced())
{
return;
}
if (_replayMode)
{
int index = Emulator.Frame - _startFrame;
if (index < _bestBotAttempt.Log.Count)
{
var logEntry = _bestBotAttempt.Log[index];
var controller = MovieSession.GenerateMovieController();
controller.SetFromMnemonic(logEntry);
foreach (var button in controller.Definition.BoolButtons)
{
// TODO: make an input adapter specifically for the bot?
InputManager.ButtonOverrideAdapter.SetButton(button, controller.IsPressed(button));
}
InputManager.SyncControls(Emulator, MovieSession, Config);
_lastFrameAdvanced = Emulator.Frame;
}
else
{
FinishReplay();
}
}
else if (_isBotting)
{
if (Emulator.Frame >= _targetFrame)
{
Attempts++;
Frames += FrameLength;
_currentBotAttempt.Maximize = MaximizeValue;
_currentBotAttempt.TieBreak1 = TieBreaker1Value;
_currentBotAttempt.TieBreak2 = TieBreaker2Value;
_currentBotAttempt.TieBreak3 = TieBreaker3Value;
PlayBestButton.Enabled = true;
if (_bestBotAttempt.is_Reset || IsBetter(_bestBotAttempt, _currentBotAttempt))
{
copy_curent_to_best();
UpdateBestAttempt();
}
reset_curent(Attempts);
_doNotUpdateValues = true;
PressButtons(true);
_ = MainForm.LoadQuickSave(SelectedSlot, true);
_lastFrameAdvanced = Emulator.Frame;
_doNotUpdateValues = false;
return;
}
// Before this would have 2 additional hits before the frame even advanced, making the amount of inputs greater than the number of frames to test.
if (_currentBotAttempt.Log.Count < FrameLength) //aka do not Add more inputs than there are Frames to test
{
PressButtons(false);
_lastFrameAdvanced = Emulator.Frame;
}
}
}
private void FinishReplay()
{
MainForm.PauseEmulator();
_startFrame = 0;
_replayMode = false;
UpdateBotStatusIcon();
MessageLabel.Text = "Replay stopped";
}
private bool IsBetter(BotAttempt comparison, BotAttempt current)
{
static bool TestValue(byte operation, int currentValue, int bestValue)
=> operation switch
{
0 => (currentValue > bestValue),
1 => (currentValue >= bestValue),
2 => (currentValue == bestValue),
3 => (currentValue <= bestValue),
4 => (currentValue < bestValue),
5 => (currentValue != bestValue),
_ => false,
};
if (!TestValue(MainComparisonType, current.Maximize, comparison.Maximize)) return false;
if (current.Maximize != comparison.Maximize) return true;
if (!TestValue(Tie1ComparisonType, current.TieBreak1, comparison.TieBreak1)) return false;
if (current.TieBreak1 != comparison.TieBreak1) return true;
if (!TestValue(Tie2ComparisonType, current.TieBreak2, comparison.TieBreak2)) return false;
if (current.TieBreak2 != comparison.TieBreak2) return true;
if (!TestValue(Tie3ComparisonType, current.TieBreak3, comparison.TieBreak3)) return false;
/*if (current.TieBreak3 != comparison.TieBreak3)*/ return true;
}
private void UpdateBestAttempt()
{
if (!_bestBotAttempt.is_Reset)
{
ClearBestButton.Enabled = true;
BestAttemptNumberLabel.Text = _bestBotAttempt.Attempt.ToString();
BestMaximizeBox.Text = _bestBotAttempt.Maximize.ToString();
BestTieBreak1Box.Text = _bestBotAttempt.TieBreak1.ToString();
BestTieBreak2Box.Text = _bestBotAttempt.TieBreak2.ToString();
BestTieBreak3Box.Text = _bestBotAttempt.TieBreak3.ToString();
var sb = new StringBuilder();
foreach (var logEntry in _bestBotAttempt.Log)
{
sb.AppendLine(logEntry);
}
BestAttemptLogLabel.Text = sb.ToString();
PlayBestButton.Enabled = true;
btnCopyBestInput.Enabled = true;
}
else
{
ClearBestButton.Enabled = false;
BestAttemptNumberLabel.Text = "";
BestMaximizeBox.Text = "";
BestTieBreak1Box.Text = "";
BestTieBreak2Box.Text = "";
BestTieBreak3Box.Text = "";
BestAttemptLogLabel.Text = "";
PlayBestButton.Enabled = false;
btnCopyBestInput.Enabled = false;
}
}
private void PressButtons(bool clear_log)
{
var rand = new Random((int)DateTime.Now.Ticks);
foreach (var button in Emulator.ControllerDefinition.BoolButtons)
{
double probability = _cachedControlProbabilities[button];
bool pressed = rand.Next(100) < probability;
InputManager.ClickyVirtualPadController.SetBool(button, pressed);
}
InputManager.SyncControls(Emulator, MovieSession, Config);
if (clear_log) { _currentBotAttempt.Log.Clear(); }