-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSlotsAndDaggersAccessibilityMod.cs
More file actions
1381 lines (1206 loc) · 54.5 KB
/
SlotsAndDaggersAccessibilityMod.cs
File metadata and controls
1381 lines (1206 loc) · 54.5 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;
using System.Collections;
using System.Runtime.InteropServices;
using System.Text;
using System.Reflection;
using MelonLoader;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using HarmonyLib;
using System.Collections.Generic;
using System.Linq;
[assembly: MelonInfo(typeof(SlotsAndDaggersAccessibility.AccessibilityMod), "Slots And Daggers Accessibility", "1.0.0", "Accessibility Team")]
[assembly: MelonGame("Friedemann", "SlotsAndDaggers")]
namespace SlotsAndDaggersAccessibility
{
public class AccessibilityMod : MelonMod
{
// NVDA Controller Client P/Invoke - has proper speech queuing
[DllImport("nvdaControllerClient64.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern int nvdaController_testIfRunning();
[DllImport("nvdaControllerClient64.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern int nvdaController_speakText([MarshalAs(UnmanagedType.LPWStr)] string text);
[DllImport("nvdaControllerClient64.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern int nvdaController_cancelSpeech();
// TOLK P/Invoke declarations
[DllImport("Tolk.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void Tolk_Load();
[DllImport("Tolk.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void Tolk_Unload();
[DllImport("Tolk.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern bool Tolk_Output([MarshalAs(UnmanagedType.LPWStr)] string text, bool interrupt);
[DllImport("Tolk.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern bool Tolk_Speak([MarshalAs(UnmanagedType.LPWStr)] string text, bool interrupt);
[DllImport("Tolk.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool Tolk_Silence();
[DllImport("Tolk.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern IntPtr Tolk_DetectScreenReader();
[DllImport("Tolk.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool Tolk_HasSpeech();
[DllImport("Tolk.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool Tolk_IsSpeaking();
private static bool tolkInitialized = false;
private static bool useNVDADirect = false;
private static GameObject lastSelectedObject = null;
private static string lastAnnouncedText = "";
private static float lastAnnouncementTime = 0f;
private const float ANNOUNCEMENT_COOLDOWN = 0.05f;
public static GameState previousGameState = GameState.NoState;
public static bool suppressNextButtonAnnouncement = false;
public static float suppressUIFeedbackUntil = 0f;
public override void OnInitializeMelon()
{
LoggerInstance.Msg("Initializing Slots And Daggers Accessibility Mod...");
// Try NVDA Controller Client first for proper queuing
try
{
int result = nvdaController_testIfRunning();
if (result == 0)
{
useNVDADirect = true;
LoggerInstance.Msg("NVDA Controller Client initialized successfully");
nvdaController_speakText("Slots And Daggers Accessibility Mod loaded successfully");
}
else
{
throw new Exception("NVDA not running");
}
}
catch
{
// Fallback to TOLK
try
{
Tolk_Load();
tolkInitialized = true;
IntPtr srPtr = Tolk_DetectScreenReader();
string screenReaderName = srPtr != IntPtr.Zero ? Marshal.PtrToStringUni(srPtr) : "None";
LoggerInstance.Msg($"TOLK initialized successfully. Screen reader detected: {screenReaderName}");
Speak("Slots And Daggers Accessibility Mod loaded successfully", true);
}
catch (Exception ex)
{
LoggerInstance.Error($"Failed to initialize screen reader support: {ex.Message}");
}
}
// Apply Harmony patches
try
{
LoggerInstance.Msg("Applying Harmony patches...");
HarmonyInstance.PatchAll();
LoggerInstance.Msg("Harmony patches applied successfully");
}
catch (Exception ex)
{
LoggerInstance.Error($"Failed to apply Harmony patches: {ex.Message}");
}
}
public override void OnDeinitializeMelon()
{
if (tolkInitialized)
{
LoggerInstance.Msg("Unloading TOLK...");
Tolk_Unload();
tolkInitialized = false;
}
}
public override void OnUpdate()
{
// Check for UI focus changes
CheckUIFocusChanges();
// Hotkey: P = Player Status (only during gameplay or in modifier shop)
if (UnityEngine.InputSystem.Keyboard.current != null &&
UnityEngine.InputSystem.Keyboard.current.pKey.wasPressedThisFrame)
{
MelonLogger.Msg($"P key pressed. State: {previousGameState}");
MelonLogger.Msg($"ModifierManager null: {Main.ModifierManager == null}");
if (Main.ModifierManager != null)
{
MelonLogger.Msg($"ModifierManager active: {Main.ModifierManager.gameObject.activeInHierarchy}");
}
MelonLogger.Msg($"IsInGameplay: {IsInGameplay()}");
// In modifier shop, announce chips only
// Check if ModifierManager exists and we're not in active gameplay
if (Main.ModifierManager != null &&
Main.ModifierManager.gameObject.activeInHierarchy &&
!IsInGameplay())
{
AnnounceChips();
}
// During gameplay, announce full player status
else if (IsInGameplay())
{
AnnouncePlayerStatus();
}
}
// Hotkey: E = Enemy Status (only during gameplay when enemy exists)
if (UnityEngine.InputSystem.Keyboard.current != null &&
UnityEngine.InputSystem.Keyboard.current.eKey.wasPressedThisFrame)
{
if (IsInGameplay())
{
AnnounceEnemyStatus();
}
}
}
private bool IsInGameplay()
{
// Check if we're in active gameplay states
return previousGameState == GameState.Spinning ||
previousGameState == GameState.ExecutingSlots ||
previousGameState == GameState.UsePowerUps ||
previousGameState == GameState.PlayerAttack ||
previousGameState == GameState.EncounterAttack ||
previousGameState == GameState.UpgradeShop ||
previousGameState == GameState.NewEncounter;
}
private void AnnounceChips()
{
MelonLogger.Msg("AnnounceChips called");
if (Main.PlayerInventory == null)
{
MelonLogger.Msg("PlayerInventory is null");
SpeakImmediate("Chips unavailable");
return;
}
string status = string.Format("Chips: {0}", Main.PlayerInventory.Chips);
MelonLogger.Msg($"Announcing: {status}");
SpeakImmediate(status);
}
private void AnnouncePlayerStatus()
{
if (Main.HealthManager == null || Main.PlayerInventory == null)
{
SpeakImmediate("Player status unavailable");
return;
}
string status = string.Format("Player: Health {0:F0} out of {1:F0}. Shield {2:F0}. Coins {3}.",
Main.HealthManager.CurrentHealth,
Main.HealthManager.MaxHealth,
Main.HealthManager.CurrentShield,
Main.PlayerInventory.TotalCoins);
SpeakImmediate(status);
}
private void AnnounceEnemyStatus()
{
if (Main.EncounterManager == null || Main.EncounterManager.CurrentEncounter == null)
{
SpeakImmediate("No enemy");
return;
}
var encounter = Main.EncounterManager.CurrentEncounter;
string status = string.Format("Enemy: {0}. Health {1:F0} out of {2:F0}",
encounter.name.Replace("(Clone)", "").Trim(),
encounter.CurrentHealth,
encounter.FullHealth);
// Add shield information
if (encounter.CurrentShield > 0)
{
status += string.Format(". Shield {0:F0}", encounter.CurrentShield);
}
// Add attack intention information
float physAttack = encounter.CurrentAttackStrengthPhysical;
float magAttack = encounter.CurrentAttackStrengthMagical;
if (physAttack > 0 || magAttack > 0)
{
status += ". Next attack: ";
if (physAttack > 0)
{
status += string.Format("Physical {0:F0}", physAttack);
}
if (magAttack > 0)
{
if (physAttack > 0) status += ", ";
status += string.Format("Magical {0:F0}", magAttack);
}
}
SpeakImmediate(status);
}
private void CheckUIFocusChanges()
{
if (EventSystem.current == null) return;
GameObject currentSelected = EventSystem.current.currentSelectedGameObject;
if (currentSelected != lastSelectedObject && currentSelected != null)
{
lastSelectedObject = currentSelected;
// Don't announce UI during splash screen/loading or when no proper game state
if (previousGameState == GameState.SplashScreen ||
previousGameState == GameState.NoState ||
Main.GameManager == null ||
Main.GameManager.CurrentGameState == GameState.SplashScreen ||
Main.GameManager.CurrentGameState == GameState.NoState)
{
return;
}
// Check if we should suppress this announcement
if (suppressNextButtonAnnouncement)
{
suppressNextButtonAnnouncement = false;
return;
}
MelonLogger.Msg($"[UI] Selected object: {currentSelected.name}, Components: {string.Join(", ", currentSelected.GetComponents<Component>().Select(c => c.GetType().Name))}");
AnnounceUIElement(currentSelected);
}
}
private void AnnounceUIElement(GameObject obj)
{
if (obj == null) return;
// Check for mod dongle (modifier shop)
var modDongle = obj.GetComponent<ModDongle>();
if (modDongle != null)
{
var modifier = modDongle.Modifier;
if (modifier != null)
{
string announcement = modifier.Description() + ". Cost: " + modifier.CurrentCost + " coins";
SpeakImmediate(announcement);
return;
}
}
// Check for upgrade shop option - don't announce here, UIFeedbackManager handles it
var upgradeShopOption = obj.GetComponent<UpgradeShopOption>();
if (upgradeShopOption != null)
{
// Upgrade shop announcements are handled by UIFeedbackManager, don't announce the button itself
return;
}
// Check for progress icon
var progressIcon = obj.GetComponent<ProgressIcon>();
if (progressIcon != null)
{
// Access private fields using reflection
var displayNameField = typeof(ProgressIcon).GetField("displayName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var descriptionField = typeof(ProgressIcon).GetField("description", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var unlockedField = typeof(ProgressIcon).GetField("unlocked", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (displayNameField != null)
{
string displayName = displayNameField.GetValue(progressIcon) as string;
string description = descriptionField?.GetValue(progressIcon) as string;
bool unlocked = unlockedField != null && (bool)unlockedField.GetValue(progressIcon);
string announcement = displayName;
if (!unlocked)
{
announcement += " - Locked";
}
else if (!string.IsNullOrEmpty(description))
{
announcement += ". " + description;
}
SpeakImmediate(announcement);
return;
}
}
// Check for level selection button - don't announce here, patches handle it
var levelSelectButton = obj.GetComponent<LevelSelectButton>();
if (levelSelectButton != null)
{
// Level announcements are handled by patches, don't announce the button itself
return;
}
// Check for equipment selection button - don't announce here, patches handle it
var equipmentButton = obj.GetComponent<EquipmentSelectionButton>();
if (equipmentButton != null)
{
// Equipment announcements are handled by patches, don't announce the button itself
return;
}
// Check for power-up button - don't announce here, patch handles it
var powerUpButton = obj.GetComponent<PowerUpButton>();
if (powerUpButton != null)
{
// Power-up announcements are handled by PowerUpButton_SelectButton_Patch
return;
}
// Check for slot symbol inventory icon - don't announce these
var slotSymbolIcon = obj.GetComponent<SlotSymbolInventoryIcon>();
if (slotSymbolIcon != null)
{
// Don't announce inventory icons
return;
}
// Check for slider
var slider = obj.GetComponent<Slider>();
if (slider != null)
{
string sliderName = GetUIElementLabel(obj);
if (string.IsNullOrEmpty(sliderName))
{
sliderName = obj.name.Replace("Slider", "").Replace("slider", "");
}
float percentage = (slider.value / (slider.maxValue - slider.minValue)) * 100f;
string announcement = string.Format("{0}: {1:F0}%", sliderName, percentage);
SpeakImmediate(announcement);
return;
}
// Check for toggle
var toggle = obj.GetComponent<Toggle>();
if (toggle != null)
{
string toggleName = GetUIElementLabel(obj);
if (string.IsNullOrEmpty(toggleName))
{
toggleName = obj.name.Replace("Toggle", "").Replace("toggle", "");
}
string state = toggle.isOn ? "On" : "Off";
string announcement = string.Format("{0}: {1}", toggleName, state);
SpeakImmediate(announcement);
return;
}
// Check for dropdown
var dropdown = obj.GetComponent<TMPro.TMP_Dropdown>();
if (dropdown != null)
{
string dropdownName = GetUIElementLabel(obj);
if (string.IsNullOrEmpty(dropdownName))
{
dropdownName = obj.name.Replace("Dropdown", "").Replace("dropdown", "");
}
string selectedOption = dropdown.options[dropdown.value].text;
string announcement = string.Format("{0}: {1}", dropdownName, selectedOption);
SpeakImmediate(announcement);
return;
}
Button button = obj.GetComponent<Button>();
if (button != null)
{
string buttonText = GetButtonText(obj);
// Don't announce the STOP button (start/stop spinning button)
if (!string.IsNullOrEmpty(buttonText) && buttonText.ToUpper().Contains("STOP"))
{
return;
}
if (!string.IsNullOrEmpty(buttonText))
{
// Check if this is a health/shield display and add values
string announcement = buttonText;
if (Main.HealthManager != null)
{
// Check if button text contains health or shield keywords
string lowerText = buttonText.ToLower();
if (lowerText.Contains("health") || lowerText.Contains("hp") || obj.name.ToLower().Contains("health"))
{
announcement = string.Format("{0}: {1:F0} out of {2:F0}",
buttonText,
Main.HealthManager.CurrentHealth,
Main.HealthManager.MaxHealth);
}
else if (lowerText.Contains("shield") || obj.name.ToLower().Contains("shield"))
{
announcement = string.Format("{0}: {1:F0}",
buttonText,
Main.HealthManager.CurrentShield);
}
}
// UI elements should interrupt and speak immediately (no ", button" suffix)
SpeakImmediate(announcement);
}
}
}
private string GetUIElementLabel(GameObject obj)
{
// Try to find a label in parent or sibling objects
Transform parent = obj.transform.parent;
if (parent != null)
{
// Check all children of parent for a label
foreach (Transform child in parent)
{
var tmp = child.GetComponent<TMPro.TextMeshProUGUI>();
if (tmp != null && !string.IsNullOrEmpty(tmp.text) && child.gameObject != obj)
{
return tmp.text;
}
}
}
// Try to get from the object itself
var tmpSelf = obj.GetComponentInChildren<TMPro.TextMeshProUGUI>();
if (tmpSelf != null && !string.IsNullOrEmpty(tmpSelf.text))
{
return tmpSelf.text;
}
return null;
}
private string GetButtonText(GameObject obj)
{
// Try to get text from TextMeshProUGUI
var tmp = obj.GetComponentInChildren<TMPro.TextMeshProUGUI>();
if (tmp != null && !string.IsNullOrEmpty(tmp.text))
{
return CleanButtonText(tmp.text);
}
// Try to get text from Unity UI Text
var text = obj.GetComponentInChildren<UnityEngine.UI.Text>();
if (text != null && !string.IsNullOrEmpty(text.text))
{
return CleanButtonText(text.text);
}
// Use object name as fallback
return CleanButtonText(obj.name);
}
private string CleanButtonText(string text)
{
if (string.IsNullOrEmpty(text)) return text;
// Remove common prefixes
text = text.Replace("Button Icon ", "");
text = text.Replace("Button ", "");
text = text.Replace("button icon ", "");
text = text.Replace("button ", "");
// Remove (Clone) suffix
text = text.Replace("(Clone)", "");
return text.Trim();
}
// Speak immediately, interrupting current speech (for UI elements)
public static void SpeakImmediate(string text)
{
if (string.IsNullOrEmpty(text)) return;
try
{
string cleanText = CleanText(text);
if (!string.IsNullOrEmpty(cleanText))
{
if (useNVDADirect)
{
nvdaController_cancelSpeech();
nvdaController_speakText(cleanText);
}
else if (tolkInitialized)
{
Tolk_Speak(cleanText, true);
}
}
}
catch (Exception ex)
{
MelonLogger.Error("Failed to speak immediate: " + ex.Message);
}
}
// Speak - let NVDA handle speech priorities based on user settings
public static void Speak(string text, bool interrupt = false)
{
if (string.IsNullOrEmpty(text)) return;
// Prevent duplicate announcements within cooldown period
if (text == lastAnnouncedText && Time.time - lastAnnouncementTime < ANNOUNCEMENT_COOLDOWN)
{
return;
}
try
{
string cleanText = CleanText(text);
if (!string.IsNullOrEmpty(cleanText))
{
// Log what's being spoken, current game state, and call stack
var stackTrace = new System.Diagnostics.StackTrace(1, true);
var callerFrame = stackTrace.GetFrame(0);
string caller = callerFrame != null ? $"{callerFrame.GetMethod().DeclaringType?.Name}.{callerFrame.GetMethod().Name}" : "Unknown";
MelonLogger.Msg($"[SPEAK] State: {previousGameState} | Interrupt: {interrupt} | Caller: {caller} | Text: {cleanText}");
if (useNVDADirect)
{
if (interrupt)
{
nvdaController_cancelSpeech();
}
nvdaController_speakText(cleanText);
}
else if (tolkInitialized)
{
Tolk_Speak(cleanText, interrupt);
}
lastAnnouncedText = text;
lastAnnouncementTime = Time.time;
}
}
catch (Exception ex)
{
MelonLogger.Error("Failed to speak: " + ex.Message);
}
}
private static string CleanText(string text)
{
// Simple HTML tag removal without regex
string cleanText = text;
while (cleanText.IndexOf('<') >= 0 && cleanText.IndexOf('>') > cleanText.IndexOf('<'))
{
int start = cleanText.IndexOf('<');
int end = cleanText.IndexOf('>', start);
cleanText = cleanText.Remove(start, end - start + 1);
}
return cleanText.Trim();
}
public static void SpeakDelayed(string text, float delay, bool interrupt = false)
{
MelonCoroutines.Start(SpeakDelayedCoroutine(text, delay, interrupt));
}
private static IEnumerator SpeakDelayedCoroutine(string text, float delay, bool interrupt)
{
yield return new WaitForSeconds(delay);
Speak(text, interrupt);
}
}
// ============================
// Harmony Patches
// ============================
// Patch GameManager.SwitchState to announce game state changes
[HarmonyPatch(typeof(GameManager), "SwitchState")]
public class GameManager_SwitchState_Patch
{
static void Postfix(GameState newState, GameManager __instance)
{
// If we're ending the ExecutingSlots phase, announce all accumulated results
if (AccessibilityMod.previousGameState == GameState.ExecutingSlots && newState != GameState.ExecutingSlots)
{
// Announce all accumulated symbol results in order
SlotSymbolAttack_Execute_Patch.AnnounceTotalDamage();
SlotSymbolCoin_Execute_Patch.AnnounceTotalCoins();
SlotSymbolHeal_Execute_Patch.AnnounceTotalHealing();
SlotSymbolShield_Execute_Patch.AnnounceTotalShields();
SlotSymbolRespin_Execute_Patch.AnnounceRespins();
// Suppress UIFeedbackManager announcements for 1 second to avoid duplicate symbol lists
AccessibilityMod.suppressUIFeedbackUntil = Time.time + 1f;
}
// Update previous state
AccessibilityMod.previousGameState = newState;
string announcement = GetGameStateAnnouncement(newState);
if (!string.IsNullOrEmpty(announcement))
{
// Don't interrupt during combat flow - let messages finish
bool shouldInterrupt = newState == GameState.LevelSelect ||
newState == GameState.EquipmentSelect ||
newState == GameState.NewLevel ||
newState == GameState.NewEncounter ||
newState == GameState.GameOver ||
newState == GameState.GameWon ||
newState == GameState.NoGameSession;
AccessibilityMod.Speak(announcement, shouldInterrupt);
}
}
private static string GetGameStateAnnouncement(GameState state)
{
// Most state announcements are handled by UIFeedbackManager which uses localized text
// Only announce states that don't have UI feedback
switch (state)
{
case GameState.SplashScreen:
// Read the game title from the UI if available, otherwise minimal announcement
return "Loading...";
// Don't announce these - UIFeedbackManager handles them with localized text
case GameState.LevelSelect:
case GameState.EquipmentSelect:
case GameState.NewLevel:
case GameState.NewEncounter:
case GameState.Spinning:
case GameState.ExecutingSlots:
case GameState.PlayerAttack:
case GameState.EncounterAttack:
case GameState.UsePowerUps:
case GameState.EncounterDefeat:
case GameState.UpgradeShop:
case GameState.GameOver:
case GameState.GameWon:
case GameState.NoGameSession:
return null;
default:
return null;
}
}
}
// Patch StartStopButton - disabled, no need to announce activation
// Users already hear the button text from CheckUIFocusChanges
/*
[HarmonyPatch(typeof(StartStopButton), "SelectButton")]
public class StartStopButton_SelectButton_Patch
{
static void Postfix(StartStopButton __instance)
{
AccessibilityMod.Speak("Spin button activated", false);
}
}
*/
// Patch SlotSymbolAttack execution to announce attack results
[HarmonyPatch(typeof(SlotSymbolAttack), "ExecuteCoroutine", new Type[] { typeof(int), typeof(Vector3), typeof(SpinnerWheel), typeof(int) })]
public class SlotSymbolAttack_Execute_Patch
{
private static float totalPhysDamage = 0;
private static float totalMagDamage = 0;
private static int attackCount = 0;
private static bool hasCritical = false;
static void Postfix(SlotSymbolAttack __instance, int symbolCount)
{
// Calculate actual damage including all modifiers
float physDamage = __instance.CurrentStrengthPhysical;
float magDamage = __instance.CurrentStrengthMagical;
// Add shield and coin bonuses
physDamage += __instance.CurrentPhysicalDamagePerShield * Main.HealthManager.CurrentShield;
magDamage += __instance.CurrentMagicalDamagePerShield * Main.HealthManager.CurrentShield;
physDamage += __instance.CurrentPhysicalDamagePerCoin * (float)Main.PlayerInventory.TotalCoins;
magDamage += __instance.CurrentMagicalDamagePerCoin * (float)Main.PlayerInventory.TotalCoins;
// Apply critical multipliers
if (symbolCount == 3)
{
physDamage *= 3f;
magDamage *= 3f;
hasCritical = true;
}
else if (symbolCount == 5)
{
physDamage *= 15f;
magDamage *= 15f;
hasCritical = true;
}
// Accumulate damage
totalPhysDamage += physDamage;
totalMagDamage += magDamage;
attackCount++;
}
// This will be called at end of spin
public static void AnnounceTotalDamage()
{
if (attackCount > 0)
{
string announcement = string.Format("{0} Attack{1}. ", attackCount, attackCount > 1 ? "s" : "");
if (totalPhysDamage > 0)
{
announcement += string.Format("Physical: {0:F0}. ", totalPhysDamage);
}
if (totalMagDamage > 0)
{
announcement += string.Format("Magical: {0:F0}. ", totalMagDamage);
}
if (hasCritical)
{
announcement += "Critical! ";
}
// Announce enemy health after attacks
if (Main.EncounterManager != null && Main.EncounterManager.CurrentEncounter != null)
{
announcement += string.Format("Enemy health: {0:F0}", Main.EncounterManager.CurrentEncounter.CurrentHealth);
}
AccessibilityMod.Speak(announcement, false);
// Reset counters
totalPhysDamage = 0;
totalMagDamage = 0;
attackCount = 0;
hasCritical = false;
}
}
}
// Patch SlotSymbolCoin execution to announce coin gains
[HarmonyPatch(typeof(SlotSymbolCoin), "ExecuteCoroutine", new Type[] { typeof(int), typeof(Vector3), typeof(SpinnerWheel), typeof(int) })]
public class SlotSymbolCoin_Execute_Patch
{
private static int totalCoins = 0;
private static int coinCount = 0;
private static bool hasCritical = false;
static void Postfix(SlotSymbolCoin __instance, int symbolCount)
{
int coinValue = Mathf.CeilToInt(__instance.AnalysisOnlyBaseCoinValue);
if (symbolCount == 3)
{
coinValue *= __instance.AnalysisOnlyMultiplierCritical;
hasCritical = true;
}
else if (symbolCount == 5)
{
coinValue *= __instance.AnalysisOnlyMultiplierCritical * 5;
hasCritical = true;
}
totalCoins += coinValue;
coinCount++;
}
public static void AnnounceTotalCoins()
{
if (coinCount > 0)
{
string announcement = string.Format("{0} Coin symbol{1}. Gained: {2}. ",
coinCount, coinCount > 1 ? "s" : "", totalCoins);
if (hasCritical)
{
announcement += "Critical! ";
}
announcement += string.Format("Total: {0}", Main.PlayerInventory.TotalCoins);
AccessibilityMod.Speak(announcement, false);
totalCoins = 0;
coinCount = 0;
hasCritical = false;
}
}
}
// Patch SlotSymbolHeal execution to announce healing
[HarmonyPatch(typeof(SlotSymbolHeal), "ExecuteCoroutine", new Type[] { typeof(int), typeof(Vector3), typeof(SpinnerWheel), typeof(int) })]
public class SlotSymbolHeal_Execute_Patch
{
private static float totalHeal = 0;
private static int healCount = 0;
private static bool hasCritical = false;
static void Postfix(SlotSymbolHeal __instance, int symbolCount)
{
float healValue = __instance.AnalysisOnlyBaseHeal;
if (symbolCount == 3)
{
healValue *= __instance.AnalysisOnlyMultiplierCritical;
hasCritical = true;
}
else if (symbolCount == 5)
{
healValue *= __instance.AnalysisOnlyMultiplierCritical * 5;
hasCritical = true;
}
healValue *= Main.MultiplierManager.CurrentMultiplierHeal;
totalHeal += healValue;
healCount++;
}
public static void AnnounceTotalHealing()
{
if (healCount > 0)
{
string announcement = string.Format("{0} Heal symbol{1}. Healed: {2:F0}. ",
healCount, healCount > 1 ? "s" : "", totalHeal);
if (hasCritical)
{
announcement += "Critical! ";
}
if (Main.HealthManager != null)
{
announcement += string.Format("Health: {0:F0} out of {1:F0}",
Main.HealthManager.CurrentHealth,
Main.HealthManager.MaxHealth);
}
AccessibilityMod.Speak(announcement, false);
totalHeal = 0;
healCount = 0;
hasCritical = false;
}
}
}
// Patch SlotSymbolShield execution to announce shield gains
[HarmonyPatch(typeof(SlotSymbolShield), "ExecuteCoroutine", new Type[] { typeof(int), typeof(Vector3), typeof(SpinnerWheel), typeof(int) })]
public class SlotSymbolShield_Execute_Patch
{
private static int shieldCount = 0;
private static bool hasCritical = false;
static void Postfix(SlotSymbolShield __instance, int symbolCount)
{
if (symbolCount == 3 || symbolCount == 5)
{
hasCritical = true;
}
shieldCount++;
}
public static void AnnounceTotalShields()
{
if (shieldCount > 0)
{
string announcement = string.Format("{0} Shield symbol{1}. ",
shieldCount, shieldCount > 1 ? "s" : "");
if (hasCritical)
{
announcement += "Critical! ";
}
if (Main.HealthManager != null)
{
announcement += string.Format("Total shields: {0:F0}", Main.HealthManager.CurrentShield);
}
AccessibilityMod.Speak(announcement, false);
shieldCount = 0;
hasCritical = false;
}
}
}
// Patch SlotSymbolRespin execution to announce respins
[HarmonyPatch(typeof(SlotSymbolRespin), "ExecuteCoroutine", new Type[] { typeof(int), typeof(Vector3), typeof(SpinnerWheel), typeof(int) })]
public class SlotSymbolRespin_Execute_Patch
{
private static int respinCount = 0;
static void Postfix(SlotSymbolRespin __instance)
{
respinCount++;
}
public static void AnnounceRespins()
{
if (respinCount > 0)
{
string announcement = string.Format("{0} Respin symbol{1}. Spinning again.",
respinCount, respinCount > 1 ? "s" : "");
AccessibilityMod.Speak(announcement, false);
respinCount = 0;
}
}
}
// Patch UpgradeShopOption.Select to announce cost
[HarmonyPatch(typeof(UpgradeShopOption), "Select")]
public class UpgradeShopOption_Select_Patch
{
static void Postfix(UpgradeShopOption __instance)
{
// Get the cost using reflection
var costField = typeof(UpgradeShopOption).GetField("upgradeCost", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (costField != null)
{
int cost = (int)costField.GetValue(__instance);
// Announce cost after a short delay to let the name/description be read first
string announcement = string.Format("Cost: {0} coins", cost);
AccessibilityMod.Speak(announcement, false);
}
}
}
// Patch HealthManager.AddHealth to announce health changes
[HarmonyPatch(typeof(HealthManager), "AddHealth")]
public class HealthManager_AddHealth_Patch
{
static void Postfix(HealthManager __instance, float amount)
{
if (amount > 0)
{
// Don't announce during slot execution to avoid interruptions
if (AccessibilityMod.previousGameState != GameState.ExecutingSlots)
{
AccessibilityMod.Speak("Gained " + amount.ToString("F0") + " health. Current health: " + __instance.CurrentHealth.ToString("F0") + " out of " + __instance.MaxHealth.ToString("F0"), false);
}
}
}
}
// AddCoins and TakeDamage patches removed - method signatures don't match
// Patch HealthManager.AddShields to announce shield gains
[HarmonyPatch(typeof(HealthManager), "AddShields")]
public class HealthManager_AddShields_Patch
{