-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreasureHuntManager.cs
More file actions
1488 lines (1232 loc) · 55.2 KB
/
TreasureHuntManager.cs
File metadata and controls
1488 lines (1232 loc) · 55.2 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.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.XR.ARFoundation;
using Niantic.Lightship.AR.WorldPositioning;
[System.Serializable]
public class TreasureLocation
{
public string clueText;
public double latitude;
public double longitude;
[Header("Physical Game")]
public bool hasPhysicalGame = false;
public string physicalGameInstruction = "";
[Tooltip("Secret code that volunteers use to verify physical game completion")]
public string physicalGameSecretCode = "";
public TreasureLocation(string clue, double lat, double lng)
{
clueText = clue;
latitude = lat;
longitude = lng;
}
}
public class TreasureHuntManager : MonoBehaviour
{
[Header("UI Panels")]
public GameObject registrationPanel;
public GameObject timerPanel;
public GameObject cluePanel;
[Header("Registration UI")]
public TMP_InputField uidInput;
public Button fetchTeamDataButton;
[Header("Team Verification UI")]
public GameObject teamVerificationPanel;
public TMP_Text teamDetailsText;
public TMP_Text teamMembersText;
public TMP_Text teamNumberDisplayText;
public Button verifyTeamButton;
[Header("Timer UI")]
public TMP_Text timerDisplay;
public TMP_Text teamInfoText;
public TMP_Text waitingMessage;
[Header("Clue UI")]
public TMP_Text clueDisplayText;
public Button startHuntButton;
public TMP_Text distanceDebugText;
[Header("GPS & AR Components")]
public ARCameraManager arCameraManager;
public GameObject arScanPanel;
public RuntimeClueARImageManager runtimeClueARImageManager;
[Header("Web Server Image Manager (Alternative)")]
[Tooltip("Use this instead of RuntimeClueARImageManager when testing web server approach")]
public WebServerImageManager webServerImageManager;
public WebServerClueARImageManager webServerClueARImageManager;
public ARWorldPositioningManager wpsManager;
[Header("GPS Settings")]
public float proximityThreshold = 10f; // meters to trigger AR mode
[Header("Audio")]
public AudioSource timerCompleteSound;
[Header("Treasure Hunt Data")]
public TreasureLocation[] treasureLocations;
[Header("Mobile Debug")]
public TMP_Text mobileDebugText;
[Header("Treasure Collection UI")]
public Button collectTreasureButton;
public GameObject congratsPanel;
public TMP_Text congratsMessage;
public TMP_Text physicalGameText;
public Button nextTreasureButton;
[Header("Physical Game Verification")]
[Tooltip("Input field where volunteers enter the secret verification code")]
public TMP_InputField physicalGameCodeInput;
[Tooltip("Button to verify the physical game code")]
public Button verifyPhysicalGameButton;
[Tooltip("Text to display verification status (success/error messages)")]
public TMP_Text physicalGameStatusText;
[Header("Inventory System")]
public Button inventoryButton;
public InventoryManager inventoryManager;
[Header("Firebase Integration")]
public FirebaseRTDBFetcher firebaseRTDBFetcher;
public ProgressManager progressManager;
[Header("Scoring")]
[Tooltip("Points awarded per collected AR treasure")]
public int scorePerTreasure = 100;
[Tooltip("Optional RTDB fetcher to update main score when treasures are collected")]
public FirebaseRTDBFetcher rtdbFetcher;
// Team assignment variables
private int teamNumber;
private int wave;
private int clueIndex;
private int delayMinutes;
private DateTime startTime;
private bool isTimerActive = false;
private int totalClues;
// Firebase team data
private TeamData currentTeamData;
private bool isTeamVerified = false;
// GPS tracking variables
private ARWorldPositioningCameraHelper cameraHelper;
private bool isGPSTrackingActive = false;
private bool isNearTreasure = false;
// Physical game tracking
private bool isPhysicalGameCompleted = false;
private int cluesFound = 0;
// Enhanced tracking for duplicate protection
private HashSet<int> completedClueIndices = new HashSet<int>(); // Track fully completed clues (including physical games)
public int GetRemainingClues()
{
return totalClues - cluesFound;
}
// Check if a specific clue has been fully completed (including physical game if required)
public bool IsClueCompleted(int clueIndexToCheck)
{
return completedClueIndices.Contains(clueIndexToCheck);
}
// Mark a clue as fully completed (called after physical game completion or immediate completion)
private void MarkClueCompleted(int clueIndexToMark)
{
if (!completedClueIndices.Contains(clueIndexToMark))
{
completedClueIndices.Add(clueIndexToMark);
// Update session data with completed clues array
if (rtdbFetcher != null)
{
int[] completedArray = new int[completedClueIndices.Count];
completedClueIndices.CopyTo(completedArray);
rtdbFetcher.UpdateSessionPhase("clue", false, completedArray);
}
Debug.Log($"Clue {clueIndexToMark} marked as fully completed");
}
}
void Start()
{
// Initialize total clues count
totalClues = treasureLocations.Length;
// Validate we have clues
if (totalClues == 0)
{
Debug.LogError("No treasure locations defined! Please add clues to the array.");
if (mobileDebugText != null) mobileDebugText.text = "ERROR: No treasure locations defined!";
return;
}
// Initialize Lightship GPS helper
if (arCameraManager != null)
{
cameraHelper = arCameraManager.GetComponent<ARWorldPositioningCameraHelper>();
if (cameraHelper == null)
{
Debug.LogError("ARWorldPositioningCameraHelper not found on ARCameraManager!");
if (mobileDebugText != null) mobileDebugText.text = "ERROR: ARWorldPositioningCameraHelper not found!";
}
}
else
{
Debug.LogError("ARCameraManager not assigned!");
if (mobileDebugText != null) mobileDebugText.text = "ERROR: ARCameraManager not assigned!";
}
// Initialize UI state
ShowRegistrationPanel();
// Initialize physical game UI (hide at startup)
InitializePhysicalGameUI();
// Setup button listeners
// Note: fetchTeamDataButton is handled by FirebaseRTDBFetcher
verifyTeamButton.onClick.AddListener(OnVerifyTeam);
startHuntButton.onClick.AddListener(OnStartHunt);
nextTreasureButton.onClick.AddListener(OnNextTreasure);
if (inventoryButton != null)
inventoryButton.onClick.AddListener(OnInventoryButtonClicked);
// Only add listener if the physical game verification button exists
if (verifyPhysicalGameButton != null)
verifyPhysicalGameButton.onClick.AddListener(OnVerifyPhysicalGameCode);
// Try auto-find Firebase RTDB fetcher if not assigned
if (firebaseRTDBFetcher == null)
firebaseRTDBFetcher = FindObjectOfType<FirebaseRTDBFetcher>();
// Try auto-find RTDB fetcher if not assigned
if (rtdbFetcher == null)
rtdbFetcher = FindObjectOfType<FirebaseRTDBFetcher>();
// Try auto-find ProgressManager if not assigned
if (progressManager == null)
progressManager = FindObjectOfType<ProgressManager>();
Debug.Log($"Treasure hunt initialized with {totalClues} clues");
if (mobileDebugText != null) mobileDebugText.text = $"Treasure hunt initialized with {totalClues} clues";
}
void Update()
{
// Update timer if active
if (isTimerActive)
{
UpdateTimer();
}
// Check GPS proximity if tracking is active
if (isGPSTrackingActive && cameraHelper != null)
{
CheckProximityToTreasure();
}
}
// OnFetchTeamData method removed - now handled by FirebaseRTDBFetcher
// OnTeamDataReceived method removed - now handled by FirebaseRTDBFetcher
// Allow external data providers (e.g., RTDB) to inject team data
public void ReceiveExternalTeamData(TeamData teamData)
{
try
{
if (teamData == null)
{
Debug.LogError("Received null team data (external)");
if (mobileDebugText != null) mobileDebugText.text = "ERROR: Received invalid team data";
return;
}
currentTeamData = teamData;
// Reset fetch button state if present
if (fetchTeamDataButton != null)
{
fetchTeamDataButton.interactable = true;
var buttonText = fetchTeamDataButton.GetComponentInChildren<TMP_Text>();
if (buttonText != null) buttonText.text = "Fetch Team Data";
}
// Show team verification panel using existing UI
ShowTeamVerificationPanel();
}
catch (System.Exception e)
{
Debug.LogError($"Error in ReceiveExternalTeamData: {e.Message}");
if (mobileDebugText != null) mobileDebugText.text = $"ERROR processing team data: {e.Message}";
}
}
// Resume game from existing session data (called by FirebaseRTDBFetcher)
public void ResumeFromSession(TeamData teamData, SessionData sessionData)
{
try
{
if (teamData == null || sessionData == null)
{
Debug.LogError("Cannot resume: missing team data or session data");
if (mobileDebugText != null) mobileDebugText.text = "ERROR: Cannot resume game - missing data";
return;
}
// Set team data
currentTeamData = teamData;
teamNumber = teamData.teamNumber;
isTeamVerified = true;
// Calculate team assignment (needed for clue cycling)
CalculateTeamAssignment();
// Override clue index with session data (convert from 1-based to 0-based)
clueIndex = Mathf.Max(0, sessionData.currentClueNumber - 1);
// Set collected treasures count from session
cluesFound = sessionData.cluesCompleted;
Debug.Log($"ResumeFromSession: cluesFound set to {cluesFound}, clueIndex set to {clueIndex} from session data");
// Restore inventory visual states - use completedClueIndices if available, otherwise assume sequential
if (inventoryManager != null)
{
int[] collectedClues;
if (sessionData.completedClueIndices != null && sessionData.completedClueIndices.Length > 0)
{
// Use actual completed clue indices from session data
collectedClues = sessionData.completedClueIndices;
Debug.Log($"Restoring inventory from session data: {collectedClues.Length} completed clues");
}
else
{
// Fallback to sequential assumption for backward compatibility
collectedClues = new int[cluesFound];
int teamStartIndex = (teamNumber - 1) % totalClues;
for (int i = 0; i < cluesFound; i++)
{
collectedClues[i] = (teamStartIndex + i) % totalClues;
}
Debug.Log($"Restoring inventory using sequential assumption: {collectedClues.Length} completed clues");
}
inventoryManager.RestoreFromProgress(collectedClues);
// Also restore completed clues tracking for duplicate protection
completedClueIndices.Clear();
foreach (int completedClue in collectedClues)
{
completedClueIndices.Add(completedClue);
}
}
// Check if we need to resume to physical game instead of next clue
// Enhanced logic to use physicalGamePending for better detection
bool shouldResumeToPhysicalGame = sessionData.physicalGamePending &&
!sessionData.physicalGamePlayed;
if (shouldResumeToPhysicalGame)
{
Debug.Log($"Resuming to physical game for clue {clueIndex} (physicalGamePending detected)");
if (mobileDebugText != null) mobileDebugText.text = $"Resuming to physical game for clue {clueIndex + 1}";
// Show brief resuming message then go directly to physical game
ShowResumingMessage();
StartCoroutine(ResumeToPhysicalGame());
}
else
{
// Normal resume flow
Debug.Log($"Resuming to next clue: Team {teamNumber}, {sessionData.cluesCompleted} clues completed, current clue: {sessionData.currentClueNumber}");
if (mobileDebugText != null) mobileDebugText.text = $"Resuming: {sessionData.cluesCompleted} clues completed, current clue: {sessionData.currentClueNumber}";
// Show brief resuming message then go to clue panel for next treasure
ShowResumingMessage();
StartCoroutine(ResumeToCluePanel());
}
}
catch (System.Exception e)
{
Debug.LogError($"Error in ResumeFromSession: {e.Message}");
if (mobileDebugText != null) mobileDebugText.text = $"ERROR resuming game: {e.Message}";
// Fallback to normal verification flow
ShowTeamVerificationPanel();
}
}
private void ShowResumingMessage()
{
// Show a brief "Resuming..." message using the team verification panel
if (teamVerificationPanel != null)
{
teamVerificationPanel.SetActive(true);
// Use the existing team verification text fields to show resuming message
if (teamDetailsText != null)
{
teamDetailsText.text = "Resuming your treasure hunt...";
}
if (teamMembersText != null)
{
teamMembersText.text = "Please wait while we restore your progress.";
}
if (teamNumberDisplayText != null)
{
teamNumberDisplayText.text = "Loading saved data...";
}
}
// Hide all other panels
registrationPanel.SetActive(false);
timerPanel.SetActive(false);
cluePanel.SetActive(false);
if (arScanPanel != null) arScanPanel.SetActive(false);
}
private IEnumerator ResumeToCluePanel()
{
// Wait 2 seconds to show the resuming message
yield return new WaitForSeconds(2f);
// Check if game is complete (all clues found)
if (cluesFound >= totalClues)
{
// Show completion screen
ShowGameCompletePanel();
}
else
{
// Resume to clue panel for next treasure
ShowCluePanel();
}
}
private IEnumerator ResumeToPhysicalGame()
{
// Wait 2 seconds to show the resuming message
yield return new WaitForSeconds(2f);
// Get current treasure to verify it has a physical game
TreasureLocation currentTreasure = GetCurrentTreasureLocation();
if (currentTreasure != null && currentTreasure.hasPhysicalGame)
{
// Show congratulations panel with physical game
congratsPanel.SetActive(true);
int remaining = GetRemainingClues();
// Set appropriate message for resumed physical game
if (remaining <= 0)
{
congratsMessage.text = "🎉 Final treasure found!\nComplete the physical game to finish the hunt!";
if (nextTreasureButton != null)
nextTreasureButton.gameObject.SetActive(false);
}
else
{
congratsMessage.text = $"Congrats on finding the treasure!\n{remaining} clue{(remaining > 1 ? "s" : "")} remaining.";
if (nextTreasureButton != null)
nextTreasureButton.gameObject.SetActive(false); // Hidden until physical game complete
}
// Show physical game instructions
if (physicalGameText != null)
{
physicalGameText.gameObject.SetActive(true);
physicalGameText.text = currentTreasure.physicalGameInstruction;
}
// Show verification UI
ShowPhysicalGameVerificationUI();
if (physicalGameStatusText != null)
physicalGameStatusText.text = "Complete the physical game and get the verification code from the volunteer.";
Debug.Log($"Resumed to physical game for clue {clueIndex}");
if (mobileDebugText != null)
mobileDebugText.text = $"Physical game resumed for clue {clueIndex + 1}";
}
else
{
// Fallback to normal clue panel if no physical game
Debug.LogWarning($"Tried to resume to physical game but clue {clueIndex} has no physical game");
ShowCluePanel();
}
}
private void ShowGameCompletePanel()
{
// Show congratulations panel with completion message
congratsPanel.SetActive(true);
congratsMessage.text = "🎉 Congrats on completing the Treasure Hunt!\n\nYou have found all treasures!";
// Hide next button since game is complete
if (nextTreasureButton != null)
nextTreasureButton.gameObject.SetActive(false);
// Hide physical game elements
if (physicalGameText != null)
physicalGameText.gameObject.SetActive(false);
HidePhysicalGameVerificationUI();
// Hide all other panels
registrationPanel.SetActive(false);
timerPanel.SetActive(false);
cluePanel.SetActive(false);
if (teamVerificationPanel != null) teamVerificationPanel.SetActive(false);
if (arScanPanel != null) arScanPanel.SetActive(false);
Debug.Log("Game complete - showing completion screen");
if (mobileDebugText != null) mobileDebugText.text = "Game complete - all treasures found!";
}
// NEW: Resume methods for ProgressData-based system
public void ResumeToPhysicalGame(TeamData teamData, ProgressData progressData)
{
try
{
if (teamData == null || progressData == null)
{
Debug.LogError("Cannot resume to physical game: missing team data or progress data");
if (mobileDebugText != null) mobileDebugText.text = "ERROR: Cannot resume to physical game - missing data";
return;
}
// Set team data
currentTeamData = teamData;
teamNumber = teamData.teamNumber;
isTeamVerified = true;
// Calculate team assignment (needed for clue cycling)
CalculateTeamAssignment();
// Set clue index to the physical game clue
clueIndex = progressData.physicalGameClueIndex;
// Set collected treasures count from progress
cluesFound = progressData.totalTreasuresCollected;
Debug.Log($"ResumeToPhysicalGame: cluesFound set to {cluesFound}, clueIndex set to {clueIndex} for physical game");
if (mobileDebugText != null) mobileDebugText.text = $"Resuming physical game: clue {clueIndex + 1}";
// Restore inventory visual states
if (inventoryManager != null)
{
inventoryManager.RestoreFromProgress(progressData.collectedTreasures);
// Also restore completed clues tracking for duplicate protection
completedClueIndices.Clear();
foreach (int completedClue in progressData.collectedTreasures)
{
completedClueIndices.Add(completedClue);
}
}
// Show brief resuming message then go directly to physical game
ShowResumingMessage();
StartCoroutine(ResumeToPhysicalGamePanel());
}
catch (System.Exception e)
{
Debug.LogError($"Error in ResumeToPhysicalGame: {e.Message}");
if (mobileDebugText != null) mobileDebugText.text = $"ERROR resuming to physical game: {e.Message}";
// Fallback to normal verification flow
ShowTeamVerificationPanel();
}
}
public void ResumeFromProgress(TeamData teamData, ProgressData progressData)
{
try
{
if (teamData == null || progressData == null)
{
Debug.LogError("Cannot resume from progress: missing team data or progress data");
if (mobileDebugText != null) mobileDebugText.text = "ERROR: Cannot resume from progress - missing data";
return;
}
// Set team data
currentTeamData = teamData;
teamNumber = teamData.teamNumber;
isTeamVerified = true;
// Calculate team assignment (needed for clue cycling)
CalculateTeamAssignment();
// Set clue index to next clue
clueIndex = progressData.nextClueIndex;
// Set collected treasures count from progress
cluesFound = progressData.totalTreasuresCollected;
Debug.Log($"ResumeFromProgress: cluesFound set to {cluesFound}, clueIndex set to {clueIndex} from progress data");
if (mobileDebugText != null) mobileDebugText.text = $"Resuming: {cluesFound} treasures found, next clue {clueIndex + 1}";
// Restore inventory visual states
if (inventoryManager != null)
{
inventoryManager.RestoreFromProgress(progressData.collectedTreasures);
// Also restore completed clues tracking for duplicate protection
completedClueIndices.Clear();
foreach (int completedClue in progressData.collectedTreasures)
{
completedClueIndices.Add(completedClue);
}
}
// Show brief resuming message then go to clue panel for next treasure
ShowResumingMessage();
StartCoroutine(ResumeToCluePanel());
}
catch (System.Exception e)
{
Debug.LogError($"Error in ResumeFromProgress: {e.Message}");
if (mobileDebugText != null) mobileDebugText.text = $"ERROR resuming from progress: {e.Message}";
// Fallback to normal verification flow
ShowTeamVerificationPanel();
}
}
private IEnumerator ResumeToPhysicalGamePanel()
{
// Wait 2 seconds to show the resuming message
yield return new WaitForSeconds(2f);
// Get current treasure to verify it has a physical game
TreasureLocation currentTreasure = GetCurrentTreasureLocation();
if (currentTreasure != null && currentTreasure.hasPhysicalGame)
{
// Show congratulations panel with physical game
congratsPanel.SetActive(true);
int remaining = GetRemainingClues();
// Set appropriate message for resumed physical game
if (remaining <= 0)
{
congratsMessage.text = "🎉 Final treasure found!\nComplete the physical game to finish the hunt!";
if (nextTreasureButton != null)
nextTreasureButton.gameObject.SetActive(false);
}
else
{
congratsMessage.text = $"Congrats on finding the treasure!\n{remaining} clue{(remaining > 1 ? "s" : "")} remaining.";
if (nextTreasureButton != null)
nextTreasureButton.gameObject.SetActive(false); // Hidden until physical game complete
}
// Show physical game instructions
if (physicalGameText != null)
{
physicalGameText.gameObject.SetActive(true);
physicalGameText.text = currentTreasure.physicalGameInstruction;
}
// Show verification UI
ShowPhysicalGameVerificationUI();
if (physicalGameStatusText != null)
physicalGameStatusText.text = "Complete the physical game and get the verification code from the volunteer.";
Debug.Log($"Resumed to physical game panel for clue {clueIndex}");
if (mobileDebugText != null)
mobileDebugText.text = $"Physical game panel shown for clue {clueIndex + 1}";
}
else
{
// Fallback to normal clue panel if no physical game
Debug.LogWarning($"Tried to resume to physical game but clue {clueIndex} has no physical game");
ShowCluePanel();
}
}
// OnTeamDataFetchFailed method removed - now handled by FirebaseRTDBFetcher
public void OnVerifyTeam()
{
if (currentTeamData == null)
{
Debug.LogWarning("No team data to verify");
return;
}
// Set the team number from Firebase data
teamNumber = currentTeamData.teamNumber;
isTeamVerified = true;
Debug.Log($"Team verified: {currentTeamData.teamName} (#{teamNumber})");
if (mobileDebugText != null) mobileDebugText.text = $"Team verified: {currentTeamData.teamName} (#{teamNumber})";
// Now calculate team assignment using Firebase team number
CalculateTeamAssignment();
// No progress initialization needed - session tracking will handle it
if (delayMinutes > 0)
{
ShowTimerPanel();
StartTimer();
}
else
{
// No delay - go straight to clue
ShowCluePanel();
}
}
private void CalculateTeamAssignment()
{
// Calculate wave, clue index, and delay using dynamic total clues count
wave = (teamNumber - 1) / totalClues;
clueIndex = (teamNumber - 1) % totalClues; // 0-based index for array access
delayMinutes = wave * 1;
string teamInfo = currentTeamData != null ? $"{currentTeamData.teamName} (#{teamNumber})" : $"Team {teamNumber}";
Debug.Log($"{teamInfo}: Wave {wave}, Clue Index {clueIndex + 1}, Delay {delayMinutes} minutes");
if (mobileDebugText != null) mobileDebugText.text = $"{teamInfo}: Wave {wave}, Clue {clueIndex + 1}, Delay {delayMinutes}min";
}
private void StartTimer()
{
// Calculate when the team should start (current time + delay)
startTime = DateTime.Now.AddMinutes(delayMinutes);
isTimerActive = true;
// Update team info display
string teamDisplayName = currentTeamData != null ? $"{currentTeamData.teamName} (#{teamNumber})" : $"Team {teamNumber}";
teamInfoText.text = $"{teamDisplayName}, Wave {wave + 1}";
waitingMessage.text = "Waiting for your turn...";
Debug.Log($"Timer started. Team will begin at: {startTime:HH:mm:ss}");
if (mobileDebugText != null) mobileDebugText.text = $"Timer started. Begin at: {startTime:HH:mm:ss}";
}
private void UpdateTimer()
{
DateTime currentTime = DateTime.Now;
TimeSpan timeRemaining = startTime - currentTime;
if (timeRemaining.TotalSeconds <= 0)
{
// Timer complete
OnTimerComplete();
}
else
{
// Update display with MM:SS format
int minutes = (int)timeRemaining.TotalMinutes;
int seconds = timeRemaining.Seconds;
timerDisplay.text = $"{minutes:D2}:{seconds:D2}";
}
}
private void OnTimerComplete()
{
isTimerActive = false;
// Play completion sound
if (timerCompleteSound != null)
{
timerCompleteSound.Play();
}
// Show clue panel
ShowCluePanel();
Debug.Log("Timer complete! Starting treasure hunt.");
if (mobileDebugText != null) mobileDebugText.text = "Timer complete! Starting treasure hunt.";
}
private void ShowRegistrationPanel()
{
registrationPanel.SetActive(true);
timerPanel.SetActive(false);
cluePanel.SetActive(false);
if (arScanPanel != null) arScanPanel.SetActive(false);
if (teamVerificationPanel != null) teamVerificationPanel.SetActive(false);
// Hide inventory button during registration
if (inventoryButton != null) inventoryButton.gameObject.SetActive(false);
// Reset verification state
isTeamVerified = false;
currentTeamData = null;
}
private void ShowTeamVerificationPanel()
{
if (currentTeamData == null) return;
registrationPanel.SetActive(false);
teamVerificationPanel.SetActive(true);
timerPanel.SetActive(false);
cluePanel.SetActive(false);
if (arScanPanel != null) arScanPanel.SetActive(false);
// Display team information
if (teamDetailsText != null)
teamDetailsText.text = $"Team: {currentTeamData.teamName}\nEmail: {currentTeamData.email}";
if (teamMembersText != null)
teamMembersText.text = $"Player 1: {currentTeamData.player1}\nPlayer 2: {currentTeamData.player2}";
if (teamNumberDisplayText != null)
teamNumberDisplayText.text = $"Team Number: {currentTeamData.teamNumber}";
}
private void ShowTimerPanel()
{
registrationPanel.SetActive(false);
if (teamVerificationPanel != null) teamVerificationPanel.SetActive(false);
timerPanel.SetActive(true);
cluePanel.SetActive(false);
if (arScanPanel != null) arScanPanel.SetActive(false);
// Hide inventory button during timer
if (inventoryButton != null) inventoryButton.gameObject.SetActive(false);
}
private void ShowCluePanel()
{
registrationPanel.SetActive(false);
if (teamVerificationPanel != null) teamVerificationPanel.SetActive(false);
timerPanel.SetActive(false);
cluePanel.SetActive(true);
if (arScanPanel != null) arScanPanel.SetActive(false);
// Reset GPS tracking state for new clue
isNearTreasure = false;
startHuntButton.interactable = true;
// Display the clue for this team
DisplayCurrentClue();
}
private void DisplayCurrentClue()
{
if (clueIndex >= 0 && clueIndex < treasureLocations.Length)
{
clueDisplayText.text = treasureLocations[clueIndex].clueText;
Debug.Log($"Displaying clue {clueIndex + 1}: {treasureLocations[clueIndex].clueText}");
if (mobileDebugText != null) mobileDebugText.text = $"Displaying clue {clueIndex + 1}: {treasureLocations[clueIndex].clueText}";
}
else
{
Debug.LogError($"Invalid clue index: {clueIndex}");
if (mobileDebugText != null) mobileDebugText.text = $"ERROR: Invalid clue index: {clueIndex}";
clueDisplayText.text = "Error: Clue not found";
}
}
public void OnStartHunt()
{
Debug.Log($"Team {teamNumber} started hunting for treasure at location: {GetCurrentTreasureLocation().latitude}, {GetCurrentTreasureLocation().longitude}");
if (mobileDebugText != null) mobileDebugText.text = $"Team {teamNumber} started hunting - GPS tracking enabled";
// Hide the start hunt button completely
startHuntButton.gameObject.SetActive(false);
// Show inventory button once hunt starts
if (inventoryButton != null) inventoryButton.gameObject.SetActive(true);
// Enable GPS tracking
EnableGPSTracking();
}
private void EnableGPSTracking()
{
if (cameraHelper != null)
{
isGPSTrackingActive = true;
Debug.Log("GPS tracking enabled. Looking for treasure location...");
if (mobileDebugText != null) mobileDebugText.text = "GPS tracking enabled. Looking for treasure location...";
}
else
{
Debug.LogError("Cannot enable GPS tracking - ARWorldPositioningCameraHelper not available");
if (mobileDebugText != null) mobileDebugText.text = "ERROR: Cannot enable GPS tracking - ARWorldPositioningCameraHelper not available";
}
}
private void CheckProximityToTreasure()
{
TreasureLocation currentTreasure = GetCurrentTreasureLocation();
if (currentTreasure == null) return;
// Temporarily disabled WPS check - calculate distance directly
// if (wpsManager == null || wpsManager.Status.ToString() != "Available")
// {
// string statusMessage = GetWPSStatusMessage();
// if (distanceDebugText != null)
// {
// distanceDebugText.text = statusMessage;
// }
// return;
// }
// Get current device location from Lightship
float deviceLatitude = (float)cameraHelper.Latitude;
float deviceLongitude = (float)cameraHelper.Longitude;
// Calculate distance to treasure
double distance = CalculateDistanceInMeters(
cameraHelper.Latitude, cameraHelper.Longitude,
currentTreasure.latitude, currentTreasure.longitude
);
if (distanceDebugText != null)
{
distanceDebugText.text = $"Distance to treasure: {distance:F1}m";
}
else
{
Debug.Log($"Distance to treasure: {distance:F1}m");
if (mobileDebugText != null) mobileDebugText.text = $"Distance to treasure: {distance:F1}m";
}
// Check if within proximity threshold
if (distance <= proximityThreshold)
{
if (!isNearTreasure)
{
OnArrivedAtTreasure();
}
}
else
{
if (isNearTreasure)
{
OnLeftTreasureArea();
}
}
}
private string GetWPSStatusMessage()
{
if (wpsManager == null)
{
return "GPS system not configured...";
}
string status = wpsManager.Status.ToString();
switch (status)
{
case "Initializing":
return "Speaking to satellites...";
case "Localizing":
return "Data travelling across the atmosphere...";
case "Limited":
return "Weak GPS signal, getting better location...";
case "Failed":
return "GPS connection failed, retrying...";
default:
return $"Connecting to GPS... ({status})";
}
}
private void OnArrivedAtTreasure()
{
isNearTreasure = true;
Debug.Log("Arrived at treasure location! Switching to AR mode.");
if (mobileDebugText != null) mobileDebugText.text = "ARRIVED AT TREASURE! Switching to AR mode.";
// Hide clue panel and show AR scan panel
ShowARScanPanel();
}
private void OnLeftTreasureArea()
{
isNearTreasure = false;
Debug.Log("Left treasure area. Returning to clue mode.");
if (mobileDebugText != null) mobileDebugText.text = "Left treasure area. Returning to clue mode.";
// Return to clue panel and hide AR scan panel
ShowCluePanelFromAR();
}
private void ShowCluePanelFromAR()
{
registrationPanel.SetActive(false);
timerPanel.SetActive(false);
cluePanel.SetActive(true);
if (arScanPanel != null) arScanPanel.SetActive(false);
// Disable AR image tracking when leaving AR mode
// Use web server version if available, otherwise use StreamingAssets version
if (webServerClueARImageManager != null)
{
webServerClueARImageManager.DisableARTracking();
}
else if (runtimeClueARImageManager != null)
{
runtimeClueARImageManager.DisableARTracking();
}
// Keep GPS tracking active but don't reset states since hunt is ongoing
startHuntButton.interactable = false; // Keep disabled since hunt is ongoing
// Show inventory button when returning from AR mode
if (inventoryButton != null) inventoryButton.gameObject.SetActive(true);