-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleaderboardManager.cs
More file actions
271 lines (230 loc) · 8.21 KB
/
leaderboardManager.cs
File metadata and controls
271 lines (230 loc) · 8.21 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
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;
using TMPro;
public class LeaderboardManager : MonoBehaviour
{
private const string SERVER_URL = "localhost:80/new_sql";
private const string GET_LEADERBOARD_URL = "get_leaderboard.php";
[Header("UI Elements")]
[SerializeField] private Transform leaderboardContainer;
[SerializeField] private GameObject leaderboardEntryPrefab;
[SerializeField] private TextMeshProUGUI statusText;
[SerializeField] private TMP_Dropdown difficultyDropdown;
[Header("Leaderboard Settings")]
[SerializeField] private int topScoresToShow = 10;
private string currentDifficulty = "NORMAL";
private void Start()
{
// Setup difficulty dropdown if available
if (difficultyDropdown != null)
{
difficultyDropdown.onValueChanged.AddListener(OnDifficultyChanged);
// Set initial value based on player's current difficulty
string savedDifficulty = PlayerPrefs.GetString("GameDifficulty", "NORMAL");
int difficultyIndex = 1; // Default to NORMAL (index 1)
if (savedDifficulty == "EASY") difficultyIndex = 0;
else if (savedDifficulty == "HARD") difficultyIndex = 2;
difficultyDropdown.value = difficultyIndex;
}
else
{
// Use the player's current difficulty setting
currentDifficulty = PlayerPrefs.GetString("GameDifficulty", "NORMAL");
}
LoadLeaderboard();
}
private void OnDifficultyChanged(int index)
{
// Convert dropdown index to difficulty string
switch (index)
{
case 0:
currentDifficulty = "EASY";
break;
case 1:
currentDifficulty = "NORMAL";
break;
case 2:
currentDifficulty = "HARD";
break;
default:
currentDifficulty = "NORMAL";
break;
}
LoadLeaderboard();
}
public void LoadLeaderboard()
{
StartCoroutine(FetchLeaderboardData());
}
private IEnumerator FetchLeaderboardData()
{
if (statusText != null)
{
statusText.text = "Loading leaderboard...";
}
// Clear existing entries
foreach (Transform child in leaderboardContainer)
{
Destroy(child.gameObject);
}
// Create request data
LeaderboardRequest requestData = new LeaderboardRequest
{
difficulty = currentDifficulty,
limit = topScoresToShow
};
string jsonData = JsonUtility.ToJson(requestData);
using (UnityWebRequest request = new UnityWebRequest($"{SERVER_URL}/{GET_LEADERBOARD_URL}", "POST"))
{
byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
if (statusText != null)
{
statusText.text = "Failed to load leaderboard. Please try again.";
}
yield break;
}
try
{
LeaderboardResponse response = JsonUtility.FromJson<LeaderboardResponse>(request.downloadHandler.text);
if (response != null && response.success)
{
if (response.scores != null && response.scores.Length > 0)
{
DisplayLeaderboard(response.scores);
if (statusText != null)
{
statusText.text = $"Top {response.scores.Length} scores for {currentDifficulty} difficulty";
}
}
else
{
if (statusText != null)
{
statusText.text = $"No scores available for {currentDifficulty} difficulty";
}
}
}
else
{
if (statusText != null)
{
statusText.text = "Error loading leaderboard. Please try again.";
}
}
}
catch
{
if (statusText != null)
{
statusText.text = "Error loading leaderboard. Please try again.";
}
}
}
}
private void DisplayLeaderboard(LeaderboardEntry[] scores)
{
// Clear any existing entries
foreach (Transform child in leaderboardContainer)
{
Destroy(child.gameObject);
}
// Apply merge sort to the scores
LeaderboardEntry[] sortedScores = MergeSortLeaderboard(scores);
// Dynamically generate UI elements for each leaderboard entry
for (int i = 0; i < sortedScores.Length; i++)
{
GameObject entryObject = Instantiate(leaderboardEntryPrefab, leaderboardContainer);
LeaderboardEntryUI entryUI = entryObject.GetComponent<LeaderboardEntryUI>();
if (entryUI != null)
{
entryUI.SetEntryData(i + 1, sortedScores[i].username, sortedScores[i].completion_time);
}
}
}
// Merge sort for leaderboard entries
private LeaderboardEntry[] MergeSortLeaderboard(LeaderboardEntry[] entries)
{
// IF the array has 0 or 1 element, it's already sorted
if (entries.Length <= 1)
return entries;
int middle = entries.Length / 2;
// Create arrays for the two halves
LeaderboardEntry[] leftArray = new LeaderboardEntry[middle];
LeaderboardEntry[] rightArray = new LeaderboardEntry[entries.Length - middle];
// Fill the left and right arrays
for (int i = 0; i < middle; i++)
leftArray[i] = entries[i];
for (int i = middle; i < entries.Length; i++)
rightArray[i - middle] = entries[i];
// Recursively sort both halves
leftArray = MergeSortLeaderboard(leftArray);
rightArray = MergeSortLeaderboard(rightArray);
return MergeArrays(leftArray, rightArray);
}
private LeaderboardEntry[] MergeArrays(LeaderboardEntry[] leftArray, LeaderboardEntry[] rightArray)
{
LeaderboardEntry[] result = new LeaderboardEntry[leftArray.Length + rightArray.Length];
int leftIndex = 0, rightIndex = 0, resultIndex = 0;
// Compare elements from both arrays and merge them in sorted order
// Sort by ascending order
while (leftIndex < leftArray.Length && rightIndex < rightArray.Length)
{
if (leftArray[leftIndex].completion_time <= rightArray[rightIndex].completion_time)
{
result[resultIndex] = leftArray[leftIndex];
leftIndex++;
}
else
{
result[resultIndex] = rightArray[rightIndex];
rightIndex++;
}
resultIndex++;
}
while (leftIndex < leftArray.Length)
{
result[resultIndex] = leftArray[leftIndex];
leftIndex++;
resultIndex++;
}
while (rightIndex < rightArray.Length)
{
result[resultIndex] = rightArray[rightIndex];
rightIndex++;
resultIndex++;
}
return result;
}
}
// Data classes for leaderboard requests and responses
[System.Serializable]
public class LeaderboardRequest
{
public string difficulty;
public int limit;
}
[System.Serializable]
public class LeaderboardResponse
{
public bool success;
public string message;
public LeaderboardEntry[] scores;
}
[System.Serializable]
public class LeaderboardEntry
{
public string username;
public float completion_time;
public string difficulty;
public string timestamp;
}