forked from shobhit-pathak/MatchZy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MatchManagement.cs
586 lines (511 loc) · 23.6 KB
/
MatchManagement.cs
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
using System.Text.Json;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Cvars;
using CounterStrikeSharp.API.Modules.Utils;
using Newtonsoft.Json.Linq;
namespace MatchZy
{
public partial class MatchZy
{
public MatchConfig matchConfig = new();
public bool isMatchSetup = false;
public bool matchModeOnly = false;
public bool resetCvarsOnSeriesEnd = true;
public Team matchzyTeam1 = new() {
teamName = "COUNTER-TERRORISTS"
};
public Team matchzyTeam2 = new() {
teamName = "TERRORISTS"
};
public Dictionary<Team, string> teamSides = new();
public Dictionary<string, Team> reverseTeamSides = new();
[ConsoleCommand("css_team1", "Sets team name for team1")]
public void OnTeam1Command(CCSPlayerController? player, CommandInfo command) {
HandleTeamNameChangeCommand(player, command.ArgString, 1);
}
[ConsoleCommand("css_team2", "Sets team name for team1")]
public void OnTeam2Command(CCSPlayerController? player, CommandInfo command) {
HandleTeamNameChangeCommand(player, command.ArgString, 2);
}
[ConsoleCommand("matchzy_loadmatch", "Loads a match from the given JSON file path (relative to the csgo/ directory)")]
public void LoadMatch(CCSPlayerController? player, CommandInfo command)
{
try
{
if (player != null) return;
if (isMatchSetup)
{
command.ReplyToCommand($"[LoadMatch] A match is already setup with id: {liveMatchId}, cannot load a new match!");
Log($"[LoadMatch] A match is already setup with id: {liveMatchId}, cannot load a new match!");
return;
}
string fileName = command.ArgString;
string filePath = Path.Join(Server.GameDirectory + "/csgo", fileName);
if (!File.Exists(filePath))
{
command.ReplyToCommand($"[LoadMatch] Provided file does not exist! Usage: matchzy_loadmatch <filename>");
Log($"[LoadMatch] Provided file does not exist! Usage: matchzy_loadmatch <filename>");
return;
}
string jsonData = File.ReadAllText(filePath);
bool success = LoadMatchFromJSON(jsonData);
if (!success)
{
command.ReplyToCommand("Match load failed! Resetting current match");
ResetMatch();
}
}
catch (Exception e)
{
Log($"[LoadMatch - FATAL] An error occured: {e.Message}");
return;
}
}
[ConsoleCommand("get5_loadmatch_url", "Loads a match from the given URL")]
[ConsoleCommand("matchzy_loadmatch_url", "Loads a match from the given URL")]
public void LoadMatchFromURL(CCSPlayerController? player, CommandInfo command)
{
if (player != null) return;
if (isMatchSetup)
{
command.ReplyToCommand($"[LoadMatchDataCommand] A match is already setup with id: {liveMatchId}, cannot load a new match!");
Log($"[LoadMatchDataCommand] A match is already setup with id: {liveMatchId}, cannot load a new match!");
return;
}
string url = command.ArgByIndex(1);
string headerName = command.ArgCount > 3 ? command.ArgByIndex(2) : "";
string headerValue = command.ArgCount > 3 ? command.ArgByIndex(3) : "";
Log($"[LoadMatchDataCommand] Match setup request received with URL: {url} headerName: {headerName} and headerValue: {headerValue}");
if (!IsValidUrl(url))
{
command.ReplyToCommand($"[LoadMatchDataCommand] Invalid URL: {url}. Please provide a valid URL to load the match!");
Log($"[LoadMatchDataCommand] Invalid URL: {url}. Please provide a valid URL to load the match!");
return;
}
try
{
HttpClient httpClient = new();
if (headerName != "")
{
httpClient.DefaultRequestHeaders.Add(headerName, headerValue);
}
HttpResponseMessage response = httpClient.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
string jsonData = response.Content.ReadAsStringAsync().Result;
Log($"[LoadMatchFromURL] Received following data: {jsonData}");
bool success = LoadMatchFromJSON(jsonData);
if (!success)
{
command.ReplyToCommand("Match load failed! Resetting current match");
ResetMatch();
}
}
else
{
command.ReplyToCommand($"[LoadMatchFromURL] HTTP request failed with status code: {response.StatusCode}");
Log($"[LoadMatchFromURL] HTTP request failed with status code: {response.StatusCode}");
}
}
catch (Exception e)
{
Log($"[LoadMatchFromURL - FATAL] An error occured: {e.Message}");
return;
}
}
static string ValidateMatchJsonStructure(JObject jsonData)
{
string[] requiredFields = { "maplist", "team1", "team2", "num_maps" };
// Check if any required field is missing
foreach (string field in requiredFields)
{
if (jsonData[field] == null)
{
return $"Missing mandatory field: {field}";
}
}
foreach (var property in jsonData.Properties())
{
string field = property.Name;
switch (field)
{
case "matchid":
case "players_per_team":
case "min_players_to_ready":
case "min_spectators_to_ready":
case "num_maps":
int numMaps;
if (!int.TryParse(jsonData[field]!.ToString(), out numMaps))
{
return $"{field} should be an integer!";
}
if (field == "num_maps" && numMaps > jsonData["maplist"]!.ToObject<List<string>>()!.Count)
{
return $"{field} should be equal to or greater than maplist!";
}
break;
case "cvars":
if (jsonData[field]!.Type != JTokenType.Object)
{
return $"{field} should be a JSON structure!";
}
break;
case "team1":
case "team2":
case "spectators":
if (jsonData[field]!.Type != JTokenType.Object)
{
return $"{field} should be a JSON structure!";
}
if ((field != "spectators") && (jsonData[field]!["players"] == null || jsonData[field]!["players"]!.Type != JTokenType.Object))
{
return $"{field} should have 'players' JSON!";
}
break;
case "veto_mode":
if (jsonData[field]!.Type != JTokenType.Array)
{
return $"{field} should be an Array!";
}
break;
case "maplist":
if (jsonData[field]!.Type != JTokenType.Array)
{
return $"{field} should be an Array!";
}
if (!jsonData[field]!.Any())
{
return $"{field} should contain atleast 1 map!";
}
break;
case "map_sides":
if (jsonData[field]!.Type != JTokenType.Array)
{
return $"{field} should be an Array!";
}
string[] allowedValues = { "team1_ct", "team1_t", "team2_ct", "team2_t", "knife" };
bool allElementsValid = jsonData[field]!.All(element => allowedValues.Contains(element.ToString()));
if (!allElementsValid) {
return $"{field} should be \"team1_ct\", \"team1_t\", or \"knife\"!";
}
if (jsonData[field]!.ToObject<List<string>>()!.Count < jsonData["num_maps"]!.Value<int>()) {
return $"{field} should be equal to or greater than num_maps!";
}
break;
case "skip_veto":
case "clinch_series":
if (!bool.TryParse(jsonData[field]!.ToString(), out bool result))
{
return $"{field} should be a boolean!";
}
break;
}
}
return "";
}
public bool LoadMatchFromJSON(string jsonData)
{
JObject jsonDataObject = JObject.Parse(jsonData);
string validationError = ValidateMatchJsonStructure(jsonDataObject);
if (validationError != "")
{
Log($"[LoadMatchDataCommand] {validationError}");
return false;
}
if(jsonDataObject["matchid"] != null)
{
liveMatchId = (long)jsonDataObject["matchid"]!;
}
JToken team1 = jsonDataObject["team1"]!;
JToken team2 = jsonDataObject["team2"]!;
JToken maplist = jsonDataObject["maplist"]!;
if (team1["id"] != null) matchzyTeam1.id = team1["id"]!.ToString();
if (team2["id"] != null) matchzyTeam2.id = team2["id"]!.ToString();
matchzyTeam1.teamName = RemoveSpecialCharacters(team1["name"]!.ToString());
matchzyTeam2.teamName = RemoveSpecialCharacters(team2["name"]!.ToString());
matchzyTeam1.teamPlayers = team1["players"];
matchzyTeam2.teamPlayers = team2["players"];
matchConfig = new()
{
MatchId = liveMatchId,
MapsPool = maplist.ToObject<List<string>>()!,
MapsLeftInVetoPool = maplist.ToObject<List<string>>()!,
NumMaps = jsonDataObject["num_maps"]!.Value<int>(),
MinPlayersToReady = minimumReadyRequired
};
GetOptionalMatchValues(jsonDataObject);
if (matchConfig.MapsPool.Count == matchConfig.NumMaps)
{
matchConfig.SkipVeto = true;
isPreVeto = false;
}
else if (matchConfig.MapsPool.Count < matchConfig.NumMaps)
{
Log($"[LOADMATCH] The map pool {matchConfig.MapsPool.Count} is not large enough to play a series of {matchConfig.NumMaps} maps.");
return false;
}
if (!matchConfig.SkipVeto)
{
if (matchConfig.MapBanOrder.Count != 0)
{
if (!ValidateMapBanLogic()) return false;
}
else
{
GenerateDefaultVetoSetup();
}
}
GetCvarValues(jsonDataObject);
Log($"[LOADMATCH] MinPlayersToReady: {matchConfig.MinPlayersToReady} SeriesClinch: {matchConfig.SeriesCanClinch}");
Log($"[LOADMATCH] MapsPool: {string.Join(", ", matchConfig.MapsPool)} MapsLeftInVetoPool: {string.Join(", ", matchConfig.MapsLeftInVetoPool)}");
LoadClientNames();
if (matchConfig.SkipVeto)
{
// Copy the first k maps from the maplist to the final match maps.
for (int i = 0; i < matchConfig.NumMaps; i++)
{
matchConfig.Maplist.Add(matchConfig.MapsPool[i]);
// Push a map side if one hasn't been set yet.
if (matchConfig.MapSides.Count < matchConfig.Maplist.Count) {
if (matchConfig.MatchSideType == "standard" || matchConfig.MatchSideType == "always_knife") {
matchConfig.MapSides.Add("knife");
} else if (matchConfig.MatchSideType == "random") {
matchConfig.MapSides.Add(new Random().Next(0, 2) == 0 ? "team1_ct" : "team1_t");
} else {
matchConfig.MapSides.Add("team1_ct");
}
}
}
string mapName = matchConfig.Maplist[0].ToString();
if (long.TryParse(mapName, out _)) {
Server.ExecuteCommand($"bot_kick");
Server.ExecuteCommand($"host_workshop_map \"{mapName}\"");
} else if (Server.IsMapValid(mapName)) {
Server.ExecuteCommand($"bot_kick");
Server.ExecuteCommand($"changelevel \"{mapName}\"");
} else {
Log($"[LoadMatchFromJSON] Invalid map name: {mapName}, cannot setup match!");
ResetMatch(false);
return false;
}
}
else
{
isPreVeto = true;
}
readyAvailable = true;
// This is done before starting warmup so that cvars like get5_remote_log_url are set properly to send the events
ExecuteChangedConvars();
StartWarmup();
isMatchSetup = true;
if(matchConfig.SkipVeto) SetMapSides();
SetTeamNames();
UpdatePlayersMap();
var seriesStartedEvent = new MatchZySeriesStartedEvent
{
MatchId = liveMatchId.ToString(),
NumberOfMaps = matchConfig.NumMaps,
Team1 = new(matchzyTeam1.id, matchzyTeam1.teamName),
Team2 = new(matchzyTeam2.id, matchzyTeam2.teamName),
};
Task.Run(async () => {
await SendEventAsync(seriesStartedEvent);
});
Log($"[LoadMatchFromJSON] Success with matchid: {liveMatchId}!");
return true;
}
public void SetMapSides() {
int mapNumber = matchConfig.CurrentMapNumber;
if (matchConfig.MapSides[mapNumber] == "team1_ct" || matchConfig.MapSides[mapNumber] == "team2_t")
{
teamSides[matchzyTeam1] = "CT";
teamSides[matchzyTeam2] = "TERRORIST";
reverseTeamSides["CT"] = matchzyTeam1;
reverseTeamSides["TERRORIST"] = matchzyTeam2;
isKnifeRequired = false;
}
else if (matchConfig.MapSides[mapNumber] == "team2_ct" || matchConfig.MapSides[mapNumber] == "team1_t")
{
teamSides[matchzyTeam2] = "CT";
teamSides[matchzyTeam1] = "TERRORIST";
reverseTeamSides["CT"] = matchzyTeam2;
reverseTeamSides["TERRORIST"] = matchzyTeam1;
isKnifeRequired = false;
}
else if (matchConfig.MapSides[mapNumber] == "knife")
{
isKnifeRequired = true;
}
SetTeamNames();
}
public void SetTeamNames()
{
Server.ExecuteCommand($"mp_teamname_1 {reverseTeamSides["CT"].teamName}");
Server.ExecuteCommand($"mp_teamname_2 {reverseTeamSides["TERRORIST"].teamName}");
}
public void GetCvarValues(JObject jsonDataObject)
{
try
{
if (jsonDataObject["cvars"] != null)
{
foreach (JProperty cvarData in jsonDataObject["cvars"]!)
{
string cvarName = cvarData.Name;
string cvarValue = cvarData.Value.ToString();
var cvar = ConVar.Find(cvarName);
matchConfig.ChangedCvars[cvarName] = cvarValue;
if (cvar != null)
{
matchConfig.OriginalCvars[cvarName] = GetConvarStringValue(cvar);
}
}
}
}
catch (Exception e)
{
Log($"[GetCvarValues FATAL] An error occurred: {e.Message}");
}
}
public void GetOptionalMatchValues(JObject jsonDataObject)
{
if(jsonDataObject["map_sides"] != null)
{
matchConfig.MapSides = jsonDataObject["map_sides"]!.ToObject<List<string>>()!;
}
if(jsonDataObject["players_per_team"] != null)
{
matchConfig.PlayersPerTeam = jsonDataObject["players_per_team"]!.Value<int>();
}
if(jsonDataObject["min_players_to_ready"] != null)
{
matchConfig.MinPlayersToReady = jsonDataObject["min_players_to_ready"]!.Value<int>();
}
if(jsonDataObject["min_spectators_to_ready"] != null)
{
matchConfig.MinSpectatorsToReady = jsonDataObject["min_spectators_to_ready"]!.Value<int>();
}
if (jsonDataObject["spectators"] != null && jsonDataObject["spectators"]!["players"] != null)
{
matchConfig.Spectators = jsonDataObject["spectators"]!["players"];
if (matchConfig.Spectators is JArray spectatorsArray && spectatorsArray.Count == 0)
{
// Convert the empty JArray to an empty JObject
matchConfig.Spectators = new JObject();
}
}
if (jsonDataObject["clinch_series"] != null)
{
matchConfig.SeriesCanClinch = bool.Parse(jsonDataObject["clinch_series"]!.ToString());
}
if (jsonDataObject["skip_veto"] != null)
{
matchConfig.SkipVeto = bool.Parse(jsonDataObject["skip_veto"]!.ToString());
}
if (jsonDataObject["veto_mode"] != null)
{
matchConfig.MapBanOrder = jsonDataObject["veto_mode"]!.ToObject<List<string>>()!;
}
}
public void HandleTeamNameChangeCommand(CCSPlayerController? player, string teamName, int teamNum) {
if (!IsPlayerAdmin(player, "css_team", "@css/config")) {
SendPlayerNotAdminMessage(player);
return;
}
if (matchStarted) {
ReplyToUserCommand(player, "Team names cannot be changed once the match is started!");
return;
}
teamName = RemoveSpecialCharacters(teamName.Trim());
if (teamName == "") {
ReplyToUserCommand(player, $"Usage: !team{teamNum} <name>");
}
if (teamNum == 1) {
matchzyTeam1.teamName = teamName;
teamSides[matchzyTeam1] = "CT";
reverseTeamSides["CT"] = matchzyTeam1;
if (matchzyTeam1.coach != null) matchzyTeam1.coach.Clan = $"[{matchzyTeam1.teamName} COACH]";
} else if (teamNum == 2) {
matchzyTeam2.teamName = teamName;
teamSides[matchzyTeam2] = "TERRORIST";
reverseTeamSides["TERRORIST"] = matchzyTeam2;
if (matchzyTeam2.coach != null) matchzyTeam2.coach.Clan = $"[{matchzyTeam2.teamName} COACH]";
}
Server.ExecuteCommand($"mp_teamname_{teamNum} {teamName};");
}
public void SwapSidesInTeamData(bool swapTeams) {
// if (swapTeams) {
// // Here, we sync matchzyTeam1 and matchzyTeam2 with the actual team1 and team2
// (matchzyTeam2, matchzyTeam1) = (matchzyTeam1, matchzyTeam2);
// }
(teamSides[matchzyTeam1], teamSides[matchzyTeam2]) = (teamSides[matchzyTeam2], teamSides[matchzyTeam1]);
(reverseTeamSides["CT"], reverseTeamSides["TERRORIST"]) = (reverseTeamSides["TERRORIST"], reverseTeamSides["CT"]);
}
private CsTeam GetPlayerTeam(CCSPlayerController player)
{
CsTeam playerTeam = CsTeam.None;
var steamId = player.SteamID;
try
{
if (matchzyTeam1.teamPlayers != null && matchzyTeam1.teamPlayers[steamId.ToString()] != null)
{
if (teamSides[matchzyTeam1] == "CT")
{
playerTeam = CsTeam.CounterTerrorist;
}
else if (teamSides[matchzyTeam1] == "TERRORIST")
{
playerTeam = CsTeam.Terrorist;
}
}
else if (matchzyTeam2.teamPlayers != null && matchzyTeam2.teamPlayers[steamId.ToString()] != null)
{
if (teamSides[matchzyTeam2] == "CT")
{
playerTeam = CsTeam.CounterTerrorist;
}
else if (teamSides[matchzyTeam2] == "TERRORIST")
{
playerTeam = CsTeam.Terrorist;
}
}
else if (matchConfig.Spectators != null && matchConfig.Spectators[steamId.ToString()] != null)
{
playerTeam = CsTeam.Spectator;
}
}
catch (Exception ex)
{
Log($"[GetPlayerTeam - FATAL] Exception occurred: {ex.Message}");
}
return playerTeam;
}
public void EndSeries(string winnerName, int restartDelay)
{
Server.PrintToChatAll($"{chatPrefix} {ChatColors.Green}{winnerName}{ChatColors.Default} has won the match");
(int t1score, int t2score) = GetTeamsScore();
var seriesResultEvent = new MatchZySeriesResultEvent()
{
MatchId = liveMatchId.ToString(),
Winner = new Winner(t1score > t2score && reverseTeamSides["CT"] == matchzyTeam1 ? "3" : "2", matchzyTeam1.seriesScore > matchzyTeam2.seriesScore ? "team1" : "team2"),
Team1SeriesScore = matchzyTeam1.seriesScore,
Team2SeriesScore = matchzyTeam2.seriesScore,
TimeUntilRestore = 10,
};
Task.Run(async () => {
// Making sure that map end event is fired first
await Task.Delay(2000);
await SendEventAsync(seriesResultEvent);
});
database.SetMatchEndData(liveMatchId, winnerName, matchzyTeam1.seriesScore, matchzyTeam2.seriesScore);
if (resetCvarsOnSeriesEnd) ResetChangedConvars();
isMatchLive = false;
AddTimer(restartDelay, () => {
ResetMatch(false);
});
}
}
}