-
-
Notifications
You must be signed in to change notification settings - Fork 79
/
Utility.cs
2057 lines (1823 loc) · 88.9 KB
/
Utility.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
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.Text.Json;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Modules.Timers;
using CounterStrikeSharp.API.Modules.Cvars;
using CounterStrikeSharp.API.Modules.Admin;
using System.Text.RegularExpressions;
using System.Text;
using Newtonsoft.Json.Linq;
using System.Drawing;
namespace MatchZy
{
public partial class MatchZy
{
public const string warmupCfgPath = "MatchZy/warmup.cfg";
public const string knifeCfgPath = "MatchZy/knife.cfg";
public const string liveCfgPath = "MatchZy/live.cfg";
public const string liveWingmanCfgPath = "MatchZy/live_wingman.cfg";
private void PrintToAllChat(string message)
{
Server.PrintToChatAll($"{chatPrefix} {message}");
}
private void PrintToPlayerChat(CCSPlayerController player, string message)
{
player.PrintToChat($"{chatPrefix} {message}");
}
private void ReplyToUserCommand(CCSPlayerController? player, string message, bool console = false)
{
if (player == null)
{
Server.PrintToConsole($"{chatPrefix} {message}");
}
else
{
if (console)
{
player.PrintToConsole($"{chatPrefix} {message}");
}
else
{
player.PrintToChat($"{chatPrefix} {message}");
}
}
}
private void LoadAdmins()
{
string fileName = "MatchZy/admins.json";
string filePath = Path.Join(Server.GameDirectory + "/csgo/cfg", fileName);
if (File.Exists(filePath))
{
try
{
using (StreamReader fileReader = File.OpenText(filePath))
{
string jsonContent = fileReader.ReadToEnd();
if (!string.IsNullOrEmpty(jsonContent))
{
JsonSerializerOptions options = new()
{
AllowTrailingCommas = true,
};
loadedAdmins = JsonSerializer.Deserialize<Dictionary<string, string>>(jsonContent, options) ?? new Dictionary<string, string>();
}
else
{
// Handle the case where the JSON content is empty or null
loadedAdmins = new Dictionary<string, string>();
}
}
foreach (var kvp in loadedAdmins)
{
Log($"[ADMIN] Username: {kvp.Key}, Role: {kvp.Value}");
}
}
catch (Exception e)
{
Log($"[LoadAdmins FATAL] An error occurred: {e.Message}");
}
}
else
{
Log("[LoadAdmins] The JSON file does not exist. Creating one with default content");
Dictionary<string, string> defaultAdmins = new()
{
{ "steamid", "" }
};
try
{
JsonSerializerOptions options = new()
{
WriteIndented = true,
};
string defaultJson = JsonSerializer.Serialize(defaultAdmins, options);
string? directoryPath = Path.GetDirectoryName(filePath);
if (directoryPath != null)
{
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
File.WriteAllText(filePath, defaultJson);
Log("[LoadAdmins] Created a new JSON file with default content.");
}
catch (Exception e)
{
Log($"[LoadAdmins FATAL] Error creating the JSON file: {e.Message}");
}
}
}
private bool IsPlayerAdmin(CCSPlayerController? player, string command = "", params string[] permissions)
{
if (everyoneIsAdmin.Value) return true; // Everyone is treated as admin if matchzy_everyone_is_admin is true.
string[] updatedPermissions = permissions.Concat(new[] { "@css/root" }).ToArray();
RequiresPermissionsOr attr = new(updatedPermissions)
{
Command = command
};
if (attr.CanExecuteCommand(player)) return true; // Admin exists in admins.json of CSSharp
if (player == null) return true; // Sent via server, hence should be treated as an admin.
if (loadedAdmins.ContainsKey(player.SteamID.ToString())) return true; // Admin exists in admins.json of MatchZy
return false;
}
private int GetRealPlayersCount()
{
return playerData.Count;
}
private void SendUnreadyPlayersMessage()
{
if (!isWarmup || matchStarted) return;
List<string> unreadyPlayers = new();
foreach (var key in playerReadyStatus.Keys)
{
if (playerReadyStatus[key] == false)
{
unreadyPlayers.Add(playerData[key].PlayerName);
}
}
if (unreadyPlayers.Count > 0)
{
string unreadyPlayerList = string.Join(", ", unreadyPlayers);
string minimumReadyRequiredMessage = isMatchSetup ? "" : $"[Minimum ready players required: {ChatColors.Green}{minimumReadyRequired}{ChatColors.Default}]";
// Server.PrintToChatAll($"{chatPrefix} Unready players: {unreadyPlayerList}. Please type .ready to ready up! {minimumReadyRequiredMessage}");
if (isRoundRestorePending)
{
PrintToAllChat(Localizer["matchzy.ready.readytotestorebackupinfomessage", unreadyPlayerList, minimumReadyRequiredMessage]);
}
else
{
PrintToAllChat(Localizer["matchzy.utility.unreadyplayers", unreadyPlayerList, minimumReadyRequiredMessage]);
}
}
else
{
int countOfReadyPlayers = playerReadyStatus.Count(kv => kv.Value == true);
if (isMatchSetup)
{
// Server.PrintToChatAll($"{chatPrefix} Current ready players: {ChatColors.Green}{countOfReadyPlayers}{ChatColors.Default}");
PrintToAllChat(Localizer["matchzy.utility.readyplayers", countOfReadyPlayers]);
}
else
{
// Server.PrintToChatAll($"{chatPrefix} Minimum ready players required {ChatColors.Green}{minimumReadyRequired}{ChatColors.Default}, current ready players: {ChatColors.Green}{countOfReadyPlayers}{ChatColors.Default}");
PrintToAllChat(Localizer["matchzy.utility.minimumreadyplayers", minimumReadyRequired, countOfReadyPlayers]);
}
}
}
private void SendPausedStateMessage()
{
if (isPaused && matchStarted)
{
var pauseTeamName = unpauseData["pauseTeam"];
if ((string)pauseTeamName == "Admin")
{
PrintToAllChat(Localizer["matchzy.pause.adminpausedthematch"]);
}
else if ((string)pauseTeamName == "RoundRestore" && !(bool)unpauseData["t"] && !(bool)unpauseData["ct"])
{
PrintToAllChat(Localizer["matchzy.pause.pausedbecauserestore"]);
}
else if ((bool)unpauseData["t"] && !(bool)unpauseData["ct"])
{
PrintToAllChat(Localizer["matchzy.pause.teamwantstounpause", reverseTeamSides["TERRORIST"].teamName, reverseTeamSides["CT"].teamName]);
}
else if (!(bool)unpauseData["t"] && (bool)unpauseData["ct"])
{
PrintToAllChat(Localizer["matchzy.pause.teamwantstounpause", reverseTeamSides["CT"].teamName, reverseTeamSides["TERRORIST"].teamName]);
}
else if (!(bool)unpauseData["t"] && !(bool)unpauseData["ct"])
{
PrintToAllChat(Localizer["matchzy.pause.pausedthematch", pauseTeamName]);
}
}
}
private void ExecWarmupCfg()
{
var absolutePath = Path.Join(Server.GameDirectory + "/csgo/cfg", warmupCfgPath);
if (File.Exists(Path.Join(Server.GameDirectory + "/csgo/cfg", warmupCfgPath)))
{
Log($"[StartWarmup] Starting warmup! Executing Warmup CFG from {warmupCfgPath}");
Server.ExecuteCommand($"exec {warmupCfgPath}");
}
else
{
Log($"[StartWarmup] Starting warmup! Warmup CFG not found in {absolutePath}, using default CFG!");
Server.ExecuteCommand("bot_kick;bot_quota 0;mp_autokick 0;mp_autoteambalance 0;mp_buy_anywhere 0;mp_buytime 15;mp_death_drop_gun 0;mp_free_armor 0;mp_ignore_round_win_conditions 0;mp_limitteams 0;mp_radar_showall 0;mp_respawn_on_death_ct 0;mp_respawn_on_death_t 0;mp_solid_teammates 0;mp_spectators_max 20;mp_maxmoney 16000;mp_startmoney 16000;mp_timelimit 0;sv_alltalk 0;sv_auto_full_alltalk_during_warmup_half_end 0;sv_deadtalk 1;sv_full_alltalk 0;sv_grenade_trajectory 0;sv_hibernate_when_empty 0;mp_weapons_allow_typecount -1;sv_infinite_ammo 0;sv_showimpacts 0;sv_voiceenable 1;sm_cvar sv_mute_players_with_social_penalties 0;sv_mute_players_with_social_penalties 0;tv_relayvoice 1;sv_cheats 0;mp_ct_default_melee weapon_knife;mp_ct_default_secondary weapon_hkp2000;mp_ct_default_primary \"\";mp_t_default_melee weapon_knife;mp_t_default_secondary weapon_glock;mp_t_default_primary;mp_maxrounds 24;mp_warmup_start;mp_warmup_pausetimer 1;mp_warmuptime 9999;cash_team_bonus_shorthanded 0;");
}
}
private void StartWarmup()
{
unreadyPlayerMessageTimer?.Kill();
unreadyPlayerMessageTimer = null;
unreadyPlayerMessageTimer ??= AddTimer(chatTimerDelay, SendUnreadyPlayersMessage, TimerFlags.REPEAT);
isWarmup = true;
ExecWarmupCfg();
}
private void StartKnifeRound()
{
// Kills unready players message timer
if (unreadyPlayerMessageTimer != null)
{
unreadyPlayerMessageTimer.Kill();
unreadyPlayerMessageTimer = null;
}
// Setting match phases bools
matchStarted = true;
isKnifeRound = true;
readyAvailable = false;
isWarmup = false;
var absolutePath = Path.Join(Server.GameDirectory + "/csgo/cfg", knifeCfgPath);
if (File.Exists(Path.Join(Server.GameDirectory + "/csgo/cfg", knifeCfgPath)))
{
Log($"[StartKnifeRound] Starting Knife! Executing Knife CFG from {knifeCfgPath}");
Server.ExecuteCommand($"exec {knifeCfgPath}");
Server.ExecuteCommand("mp_restartgame 1;mp_warmup_end;");
}
else
{
Log($"[StartKnifeRound] Starting Knife! Knife CFG not found in {absolutePath}, using default CFG!");
Server.ExecuteCommand("mp_ct_default_secondary \"\";mp_free_armor 1;mp_freezetime 10;mp_give_player_c4 0;mp_maxmoney 0;mp_respawn_immunitytime 0;mp_respawn_on_death_ct 0;mp_respawn_on_death_t 0;mp_roundtime 1.92;mp_roundtime_defuse 1.92;mp_roundtime_hostage 1.92;mp_t_default_secondary \"\";mp_round_restart_delay 3;mp_team_intro_time 0;mp_restartgame 1;mp_warmup_end;");
}
PrintToAllChat($"{ChatColors.Olive}KNIFE!");
PrintToAllChat($"{ChatColors.Lime}KNIFE!");
PrintToAllChat($"{ChatColors.Green}KNIFE!");
}
private void SendSideSelectionMessage()
{
if (!isSideSelectionPhase) return;
PrintToAllChat(Localizer["matchzy.knife.sidedecisionpending", knifeWinnerName]);
// Server.PrintToChatAll($"{chatPrefix} {ChatColors.Green}{knifeWinnerName}{ChatColors.Default} Won the knife. Waiting for them to type {ChatColors.Green}.stay{ChatColors.Default} or {ChatColors.Green}.switch{ChatColors.Default}");
}
private void StartAfterKnifeWarmup()
{
isWarmup = true;
ExecWarmupCfg();
knifeWinnerName = knifeWinner == 3 ? reverseTeamSides["CT"].teamName : reverseTeamSides["TERRORIST"].teamName;
ShowDamageInfo();
PrintToAllChat(Localizer["matchzy.knife.sidedecisionpending", knifeWinnerName]);
// Server.PrintToChatAll($"{chatPrefix} {ChatColors.Green}{knifeWinnerName}{ChatColors.Default} Won the knife. Waiting for them to type {ChatColors.Green}.stay{ChatColors.Default} or {ChatColors.Green}.switch{ChatColors.Default}");
sideSelectionMessageTimer ??= AddTimer(chatTimerDelay, SendSideSelectionMessage, TimerFlags.REPEAT);
}
private void SetLiveFlags()
{
// Setting match phases bools
isWarmup = false;
isSideSelectionPhase = false;
matchStarted = true;
isMatchLive = true;
readyAvailable = false;
isKnifeRound = false;
}
private void SetupLiveFlagsAndCfg()
{
SetLiveFlags();
KillPhaseTimers();
ExecLiveCFG();
// Adding timer here to make sure that CFG execution is completed till then
AddTimer(1, () =>
{
HandlePlayoutConfig();
ExecuteChangedConvars();
});
}
private void StartLive()
{
SetupLiveFlagsAndCfg();
StartDemoRecording();
// Storing 0-0 score backup file as lastBackupFileName, so that .stop functions properly in first round.
lastBackupFileName = $"matchzy_{liveMatchId}_{matchConfig.CurrentMapNumber}_round00.txt";
lastMatchZyBackupFileName = $"matchzy_{liveMatchId}_{matchConfig.CurrentMapNumber}_round00.json";
// This is to reload the map once it is over so that all flags are reset accordingly
Server.ExecuteCommand("mp_match_end_restart true");
PrintToAllChat($"{ChatColors.Olive}LIVE!");
PrintToAllChat($"{ChatColors.Lime}LIVE!");
PrintToAllChat($"{ChatColors.Green}LIVE!");
var goingLiveEvent = new GoingLiveEvent
{
MatchId = liveMatchId,
MapNumber = matchConfig.CurrentMapNumber,
};
Task.Run(async () =>
{
await SendEventAsync(goingLiveEvent);
});
}
private void KillPhaseTimers()
{
unreadyPlayerMessageTimer?.Kill();
sideSelectionMessageTimer?.Kill();
pausedStateTimer?.Kill();
unreadyPlayerMessageTimer = null;
sideSelectionMessageTimer = null;
pausedStateTimer = null;
}
private (int alivePlayers, int totalHealth) GetAlivePlayers(int team)
{
int count = 0;
int totalHealth = 0;
foreach (var key in playerData.Keys)
{
CCSPlayerController player = playerData[key];
if (team == 2 && reverseTeamSides["TERRORIST"].coach.Contains(player)) continue;
if (team == 3 && reverseTeamSides["CT"].coach.Contains(player)) continue;
if (!IsPlayerValid(player)) continue;
if (player.TeamNum == team)
{
if (player.PlayerPawn.Value!.Health > 0) count++;
totalHealth += player.PlayerPawn.Value!.Health;
}
}
return (count, totalHealth);
}
private void ResetMatch(bool warmupCfgRequired = true)
{
try
{
// We stop demo recording if a live match was restarted
if (matchStarted && isDemoRecording)
{
Server.ExecuteCommand($"tv_stoprecord");
isDemoRecording = false;
}
// Reset match data
matchStarted = false;
readyAvailable = true;
isPaused = false;
isMatchSetup = false;
isWarmup = true;
isKnifeRound = false;
isSideSelectionPhase = false;
isMatchLive = false;
liveMatchId = -1;
isPractice = false;
isDryRun = false;
isVeto = false;
isPreVeto = false;
lastBackupFileName = "";
lastMatchZyBackupFileName = "";
isRoundRestorePending = false;
playerHasTakenDamage = false;
// Unready all players
foreach (var key in playerReadyStatus.Keys)
{
playerReadyStatus[key] = false;
}
teamReadyOverride = new()
{
{CsTeam.Terrorist, false},
{CsTeam.CounterTerrorist, false},
{CsTeam.Spectator, false}
};
HandleClanTags();
// Reset unpause data
Dictionary<string, object> unpauseData = new()
{
{ "ct", false },
{ "t", false },
{ "pauseTeam", "" }
};
// Reset stop data
stopData["ct"] = false;
stopData["t"] = false;
// Reset owned bots data
pracUsedBots = new Dictionary<int, Dictionary<string, object>>();
noFlashList = new();
lastGrenadesData = new();
nadeSpecificLastGrenadeData = new();
UnpauseMatch();
matchzyTeam1.teamName = "COUNTER-TERRORISTS";
matchzyTeam2.teamName = "TERRORISTS";
matchzyTeam1.teamPlayers = null;
matchzyTeam2.teamPlayers = null;
HashSet<CCSPlayerController> coaches = GetAllCoaches();
foreach (var coach in coaches)
{
if (!IsPlayerValid(coach)) continue;
coach.Clan = "";
SetPlayerVisible(coach);
}
matchzyTeam1.coach = new();
matchzyTeam2.coach = new();
coachKillTimer?.Kill();
coachKillTimer = null;
matchzyTeam1.seriesScore = 0;
matchzyTeam2.seriesScore = 0;
Server.ExecuteCommand($"mp_teamname_1 {matchzyTeam1.teamName}");
Server.ExecuteCommand($"mp_teamname_2 {matchzyTeam2.teamName}");
teamSides[matchzyTeam1] = "CT";
teamSides[matchzyTeam2] = "TERRORIST";
reverseTeamSides["CT"] = matchzyTeam1;
reverseTeamSides["TERRORIST"] = matchzyTeam2;
// Keeping the log URLs to avoid their reset on match start.
matchConfig = new()
{
RemoteLogURL = matchConfig.RemoteLogURL,
RemoteLogHeaderKey = matchConfig.RemoteLogHeaderKey,
RemoteLogHeaderValue = matchConfig.RemoteLogURL
};
KillPhaseTimers();
UpdatePlayersMap();
if (warmupCfgRequired)
{
StartWarmup();
}
else
{
// Since we should be already in warmup phase by this point, we are just setting up the SendUnreadyPlayersMessage timer
unreadyPlayerMessageTimer?.Kill();
unreadyPlayerMessageTimer = null;
unreadyPlayerMessageTimer ??= AddTimer(chatTimerDelay, SendUnreadyPlayersMessage, TimerFlags.REPEAT);
}
}
catch (Exception ex)
{
Log($"[ResetMatch - FATAL] [ERROR]: {ex.Message}");
}
}
private void UpdatePlayersMap()
{
try
{
var playerEntities = Utilities.FindAllEntitiesByDesignerName<CCSPlayerController>("cs_player_controller");
Log($"[UpdatePlayersMap] CCSPlayerController count: {playerEntities.Count<CCSPlayerController>()} matchModeOnly: {matchModeOnly}");
connectedPlayers = 0;
// Clear the playerData dictionary by creating a new instance to add fresh data.
playerData = new Dictionary<int, CCSPlayerController>();
foreach (var player in playerEntities)
{
if (player == null) continue;
if (!player.IsValid || player.IsBot || player.IsHLTV) continue;
if (isMatchSetup || matchModeOnly)
{
CsTeam team = GetPlayerTeam(player);
if (team == CsTeam.None && player.UserId.HasValue)
{
Server.ExecuteCommand($"kickid {(ushort)player.UserId}");
continue;
}
}
// A player controller still exists after a player disconnects
// Hence checking whether the player is actually in the server or not
if (player.Connected != PlayerConnectedState.PlayerConnected) continue;
if (player.UserId.HasValue)
{
// Updating playerData and playerReadyStatus
playerData[player.UserId.Value] = player;
// Adding missing player in playerReadyStatus
if (!playerReadyStatus.ContainsKey(player.UserId.Value))
{
playerReadyStatus[player.UserId.Value] = false;
}
}
connectedPlayers++;
}
// Removing disconnected players from playerReadyStatus
foreach (var key in playerReadyStatus.Keys.ToList())
{
if (!playerData.ContainsKey(key))
{
// Key is not present in playerData, so remove it from playerReadyStatus
playerReadyStatus.Remove(key);
}
}
Log($"[UpdatePlayersMap] CCSPlayerController count: {playerEntities.Count<CCSPlayerController>()}, RealPlayersCount: {GetRealPlayersCount()}");
}
catch (Exception e)
{
Log($"[UpdatePlayersMap FATAL] An error occurred: {e.Message}");
}
}
public void DetermineKnifeWinner()
{
// Knife Round code referred from Get5, thanks to the Get5 team for their amazing job!
(int tAlive, int tHealth) = GetAlivePlayers(2);
(int ctAlive, int ctHealth) = GetAlivePlayers(3);
Log($"[KNIFE OVER] CT Alive: {ctAlive} with Total Health: {ctHealth}, T Alive: {tAlive} with Total Health: {tHealth}");
if (ctAlive > tAlive)
{
knifeWinner = 3;
}
else if (tAlive > ctAlive)
{
knifeWinner = 2;
}
else if (ctHealth > tHealth)
{
knifeWinner = 3;
}
else if (tHealth > ctHealth)
{
knifeWinner = 2;
}
else
{
// Choosing a winner randomly
Random random = new();
knifeWinner = random.Next(2, 4);
}
}
private void HandleKnifeWinner(EventCsWinPanelRound @event)
{
DetermineKnifeWinner();
// Below code is working partially (Winner audio plays correctly for knife winner team, but may display round winner incorrectly)
// Hence we restart the game with StartAfterKnifeWarmup and allow the winning team to choose side
@event.FunfactToken = "";
// Commenting these assignments as they were crashing the server.
// long empty = 0;
// @event.FunfactPlayer = null;
// @event.FunfactData1 = empty;
// @event.FunfactData2 = empty;
// @event.FunfactData3 = empty;
int finalEvent = 10;
if (knifeWinner == 3)
{
finalEvent = 8;
}
else if (knifeWinner == 2)
{
finalEvent = 9;
}
Log($"[KNIFE WINNER] Won by: {knifeWinner}, finalEvent: {@event.FinalEvent}, newFinalEvent: {finalEvent}");
@event.FinalEvent = finalEvent;
}
private void HandleMapChangeCommand(CCSPlayerController? player, string mapName)
{
if (!IsPlayerAdmin(player, "css_map", "@css/map"))
{
SendPlayerNotAdminMessage(player);
return;
}
if (matchStarted)
{
// ReplyToUserCommand(player, $"Map cannot be changed once the match is started!");
ReplyToUserCommand(player, Localizer["matchzy.utility.matchstarted"]);
return;
}
if (!long.TryParse(mapName, out _) && !mapName.Contains('_'))
{
mapName = "de_" + mapName;
}
if (long.TryParse(mapName, out _))
{ // Check if mapName is a long for workshop map ids
Server.ExecuteCommand($"bot_kick");
Server.ExecuteCommand($"host_workshop_map \"{mapName}\"");
}
else if (Server.IsMapValid(mapName))
{
Server.ExecuteCommand($"bot_kick");
Server.ExecuteCommand($"changelevel \"{mapName}\"");
}
else
{
ReplyToUserCommand(player, $"Invalid map name!");
}
}
private void HandleReadyRequiredCommand(CCSPlayerController? player, string commandArg)
{
if (!IsPlayerAdmin(player, "css_readyrequired", "@css/config"))
{
SendPlayerNotAdminMessage(player);
return;
}
if (!string.IsNullOrWhiteSpace(commandArg))
{
if (int.TryParse(commandArg, out int readyRequired) && readyRequired >= 0 && readyRequired <= 32)
{
minimumReadyRequired = readyRequired;
string minimumReadyRequiredFormatted = (player == null) ? $"{minimumReadyRequired}" : $"{ChatColors.Green}{minimumReadyRequired}{ChatColors.Default}";
// ReplyToUserCommand(player, $"Minimum ready players required to start the match are now set to: {minimumReadyRequiredFormatted}");
ReplyToUserCommand(player, Localizer["matchzy.utility.minreadyplayers", minimumReadyRequiredFormatted]);
CheckLiveRequired();
}
else
{
// ReplyToUserCommand(player, $"Invalid value for readyrequired. Please specify a valid non-negative number. Usage: !readyrequired <number_of_ready_players_required>");
ReplyToUserCommand(player, Localizer["matchzy.utility.rrinvalidvalue"]);
}
}
else
{
string minimumReadyRequiredFormatted = (player == null) ? $"{minimumReadyRequired}" : $"{ChatColors.Green}{minimumReadyRequired}{ChatColors.Default}";
// ReplyToUserCommand(player, $"Current Ready Required: {minimumReadyRequiredFormatted} .Usage: !readyrequired <number_of_ready_players_required>");
ReplyToUserCommand(player, Localizer["matchzy.utility.currentreadyrequired", minimumReadyRequiredFormatted]);
}
}
private void CheckLiveRequired()
{
if (!readyAvailable || matchStarted) return;
// Todo: Implement a same ready system for both pug and match
int countOfReadyPlayers = playerReadyStatus.Count(kv => kv.Value == true);
bool liveRequired = false;
if (isMatchSetup)
{
if (IsTeamsReady() && IsSpectatorsReady())
{
liveRequired = true;
}
}
else if (minimumReadyRequired == 0)
{
if (countOfReadyPlayers >= connectedPlayers && connectedPlayers > 0)
{
liveRequired = true;
}
}
else if (countOfReadyPlayers >= minimumReadyRequired)
{
liveRequired = true;
}
if (liveRequired)
{
HandleMatchStart();
}
}
private void HandleMatchStart()
{
isPractice = false;
isDryRun = false;
if (isRoundRestorePending)
{
RestoreRoundBackup(null, pendingRestoreFileName);
isRoundRestorePending = false;
pendingRestoreFileName = "";
return;
}
// If default names, we pick a player and use their name as their team name
if (matchzyTeam1.teamName == "COUNTER-TERRORISTS")
{
// matchzyTeam1.teamName = teamName;
teamSides[matchzyTeam1] = "CT";
reverseTeamSides["CT"] = matchzyTeam1;
foreach (var key in playerData.Keys)
{
if (playerData[key].TeamNum == 3)
{
matchzyTeam1.teamName = "team_" + RemoveSpecialCharacters(playerData[key].PlayerName.Replace(" ", "_"));
foreach (var coach in matchzyTeam1.coach) {
coach.Clan = $"[{matchzyTeam1.teamName} COACH]";
}
break;
}
}
// Server.ExecuteCommand($"mp_teamname_1 {matchzyTeam1.teamName}");
}
if (matchzyTeam2.teamName == "TERRORISTS")
{
// matchzyTeam2.teamName = teamName;
teamSides[matchzyTeam2] = "TERRORIST";
reverseTeamSides["TERRORIST"] = matchzyTeam2;
foreach (var key in playerData.Keys)
{
if (playerData[key].TeamNum == 2)
{
matchzyTeam2.teamName = "team_" + RemoveSpecialCharacters(playerData[key].PlayerName.Replace(" ", "_"));
foreach (var coach in matchzyTeam2.coach) {
coach.Clan = $"[{matchzyTeam2.teamName} COACH]";
}
break;
}
}
// Server.ExecuteCommand($"mp_teamname_2 {matchzyTeam2.teamName}");
}
Server.ExecuteCommand($"mp_teamname_1 {reverseTeamSides["CT"].teamName}");
Server.ExecuteCommand($"mp_teamname_2 {reverseTeamSides["TERRORIST"].teamName}");
HandleClanTags();
string seriesType = "BO" + matchConfig.NumMaps.ToString();
liveMatchId = database.InitMatch(matchzyTeam1.teamName, matchzyTeam2.teamName, "-", isMatchSetup, liveMatchId, matchConfig.CurrentMapNumber, seriesType);
SetupRoundBackupFile();
GetSpawns();
if (isPreVeto)
{
CreateVeto();
}
else if (isKnifeRequired)
{
StartKnifeRound();
}
else
{
StartDemoRecording();
StartLive();
}
if (showCreditsOnMatchStart.Value)
{
Server.PrintToChatAll($"{chatPrefix} {ChatColors.Green}MatchZy{ChatColors.Default} Plugin by {ChatColors.Green}WD-{ChatColors.Default}");
}
if (matchStartMessage.Value.Trim() != "" && matchStartMessage.Value.Trim() != "\"\"")
{
List<string> matchStartMessages = [.. matchStartMessage.Value.Split("$$$")];
foreach (string message in matchStartMessages)
{
PrintToAllChat(GetColorTreatedString(FormatCvarValue(message.Trim())));
}
}
}
public void HandleClanTags()
{
// Currently it is not possible to keep updating player tags while in warmup without restarting the match
// Hence returning from here until we find a proper solution
return;
if (readyAvailable && !matchStarted)
{
foreach (var key in playerData.Keys)
{
if (playerReadyStatus[key])
{
playerData[key].Clan = "[Ready]";
}
else
{
playerData[key].Clan = "[Unready]";
}
Server.PrintToChatAll($"PlayerName: {playerData[key].PlayerName} Clan: {playerData[key].Clan}");
}
}
else if (matchStarted)
{
foreach (var key in playerData.Keys)
{
if (playerData[key].TeamNum == 2)
{
playerData[key].Clan = reverseTeamSides["TERRORIST"].teamTag;
}
else if (playerData[key].TeamNum == 3)
{
playerData[key].Clan = reverseTeamSides["CT"].teamTag;
}
Server.PrintToChatAll($"PlayerName: {playerData[key].PlayerName} Clan: {playerData[key].Clan}");
}
}
}
private void HandleMatchEnd()
{
if (!isMatchLive) return;
// This ensures that the mp_match_restart_delay is not shorter than what is required for the GOTV recording to finish.
// Ref: Get5
int restartDelay = ConVar.Find("mp_match_restart_delay")!.GetPrimitiveValue<int>();
int tvDelay = GetTvDelay();
int requiredDelay = tvDelay + 15;
int tvFlushDelay = requiredDelay;
if (tvDelay > 0.0)
{
requiredDelay += 10;
}
if (requiredDelay > restartDelay)
{
Log($"Extended mp_match_restart_delay from {restartDelay} to {requiredDelay} to ensure GOTV broadcast can finish.");
ConVar.Find("mp_match_restart_delay")!.SetValue(requiredDelay);
restartDelay = requiredDelay;
}
int currentMapNumber = matchConfig.CurrentMapNumber;
Log($"[HandleMatchEnd] MAP ENDED, isMatchSetup: {isMatchSetup} matchid: {liveMatchId} currentMapNumber: {currentMapNumber} tvFlushDelay: {tvFlushDelay}");
StopDemoRecording(tvFlushDelay - 0.5f, activeDemoFile, liveMatchId, currentMapNumber);
string winnerName = GetMatchWinnerName();
(int t1score, int t2score) = GetTeamsScore();
int team1SeriesScore = matchzyTeam1.seriesScore;
int team2SeriesScore = matchzyTeam2.seriesScore;
string statsPath = Server.GameDirectory + "/csgo/MatchZy_Stats/" + liveMatchId.ToString();
var mapResultEvent = new MapResultEvent
{
MatchId = liveMatchId,
MapNumber = currentMapNumber,
Winner = new Winner(t1score > t2score && reverseTeamSides["CT"] == matchzyTeam1 ? "3" : "2", team1SeriesScore > team2SeriesScore ? "team1" : "team2"),
StatsTeam1 = new MatchZyStatsTeam(matchzyTeam1.id, matchzyTeam1.teamName, team1SeriesScore, t1score, 0, 0, new List<StatsPlayer>()),
StatsTeam2 = new MatchZyStatsTeam(matchzyTeam2.id, matchzyTeam2.teamName, team2SeriesScore, t2score, 0, 0, new List<StatsPlayer>())
};
Task.Run(async () =>
{
await SendEventAsync(mapResultEvent);
await database.SetMapEndData(liveMatchId, currentMapNumber, winnerName, t1score, t2score, team1SeriesScore, team2SeriesScore);
await database.WritePlayerStatsToCsv(statsPath, liveMatchId, currentMapNumber);
});
// If a match is not setup, it was supposed to be a pug/scrim with 1 map
// Hence we reset the match once it is over
// Todo: Support BO3/BO5 in pugs as well
if (!isMatchSetup)
{
EndSeries(winnerName, restartDelay - 1, t1score, t2score);
return;
}
int remainingMaps = matchConfig.NumMaps - matchzyTeam1.seriesScore - matchzyTeam2.seriesScore;
Log($"[HandleMatchEnd] MATCH ENDED, remainingMaps: {remainingMaps}, NumMaps: {matchConfig.NumMaps}, Team1SeriesScore: {matchzyTeam1.seriesScore}, Team2SeriesScore: {matchzyTeam2.seriesScore}");
if (matchzyTeam1.seriesScore == matchzyTeam2.seriesScore && remainingMaps <= 0)
{
EndSeries(null, restartDelay - 1, t1score, t2score);
}
else if (matchConfig.SeriesCanClinch)
{
int mapsToWinSeries = (matchConfig.NumMaps / 2) + 1;
if (matchzyTeam1.seriesScore == mapsToWinSeries)
{
EndSeries(winnerName, restartDelay - 1, t1score, t2score);
return;
}
else if (matchzyTeam2.seriesScore == mapsToWinSeries)
{
EndSeries(winnerName, restartDelay - 1, t1score, t2score);
return;
}
}
else if (remainingMaps <= 0)
{
EndSeries(winnerName, restartDelay - 1, t1score, t2score);
return;
}
if (matchzyTeam1.seriesScore > matchzyTeam2.seriesScore)
{
Server.PrintToChatAll($"{chatPrefix} {ChatColors.Green}{matchzyTeam1.teamName}{ChatColors.Default} is winning the series {ChatColors.Green}{matchzyTeam1.seriesScore}-{matchzyTeam2.seriesScore}{ChatColors.Default}");
}
else if (matchzyTeam2.seriesScore > matchzyTeam1.seriesScore)
{
Server.PrintToChatAll($"{chatPrefix} {ChatColors.Green}{matchzyTeam2.teamName}{ChatColors.Default} is winning the series {ChatColors.Green}{matchzyTeam2.seriesScore}-{matchzyTeam1.seriesScore}{ChatColors.Default}");
}
else
{
Server.PrintToChatAll($"{chatPrefix} The series is tied at {ChatColors.Green}{matchzyTeam1.seriesScore}-{matchzyTeam2.seriesScore}{ChatColors.Default}");
}
matchConfig.CurrentMapNumber += 1;
string nextMap = matchConfig.Maplist[matchConfig.CurrentMapNumber];
if (isPaused)
UnpauseMatch();
stopData["ct"] = false;
stopData["t"] = false;
KillPhaseTimers();
AddTimer(restartDelay - 4, () =>
{
if (!isMatchSetup) return;
ChangeMap(nextMap, 3.0f);
matchStarted = false;
readyAvailable = true;
isPaused = false;
isWarmup = true;
isKnifeRound = false;
isSideSelectionPhase = false;
isMatchLive = false;
isPractice = false;
isDryRun = false;
StartWarmup();
SetMapSides();
});
}
private void ChangeMap(string mapName, float delay)
{
Log($"[ChangeMap] Changing map to {mapName} with delay {delay}");
AddTimer(delay, () =>
{
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}\"");
}
});
}
private string GetMatchWinnerName()
{
(int t1score, int t2score) = GetTeamsScore();
if (t1score > t2score)
{
matchzyTeam1.seriesScore++;
return matchzyTeam1.teamName;
}
else if (t2score > t1score)
{
matchzyTeam2.seriesScore++;
return matchzyTeam2.teamName;
}
else
{
return "Draw";