forked from shobhit-pathak/MatchZy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MatchZy.cs
616 lines (529 loc) · 25.8 KB
/
MatchZy.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
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace MatchZy
{
[MinimumApiVersion(107)]
public partial class MatchZy : BasePlugin
{
public override string ModuleName => "MatchZy";
public override string ModuleVersion => "0.5.1-alpha";
public override string ModuleAuthor => "WD- (https://github.com/shobhit-pathak/)";
public override string ModuleDescription => "A plugin for running and managing CS2 practice/pugs/scrims/matches!";
public string chatPrefix = $"[{ChatColors.Green}MatchZy{ChatColors.Default}]";
public string adminChatPrefix = $"[{ChatColors.Red}ADMIN{ChatColors.Default}]";
// Plugin start phase data
public bool isPractice = false;
public bool isSleep = false;
public bool readyAvailable = false;
public bool matchStarted = false;
public bool isWarmup = false;
public bool isKnifeRound = false;
public bool isSideSelectionPhase = false;
public bool isMatchLive = false;
public long liveMatchId = -1;
public int autoStartMode = 1;
// Pause Data
public bool isPaused = false;
public Dictionary<string, object> unpauseData = new Dictionary<string, object> {
{ "ct", false },
{ "t", false },
{ "pauseTeam", "" }
};
bool isPauseCommandForTactical = false;
// Knife Data
public int knifeWinner = 0;
public string knifeWinnerName = "";
// Players Data (including admins)
public int connectedPlayers = 0;
private Dictionary<int, bool> playerReadyStatus = new Dictionary<int, bool>();
private Dictionary<int, CCSPlayerController> playerData = new Dictionary<int, CCSPlayerController>();
// Admin Data
private Dictionary<string, string> loadedAdmins = new Dictionary<string, string>();
// Timers
public CounterStrikeSharp.API.Modules.Timers.Timer? unreadyPlayerMessageTimer = null;
public CounterStrikeSharp.API.Modules.Timers.Timer? sideSelectionMessageTimer = null;
public CounterStrikeSharp.API.Modules.Timers.Timer? pausedStateTimer = null;
// Each message is kept in chat display for ~13 seconds, hence setting default chat timer to 13 seconds.
// Configurable using matchzy_chat_messages_timer_delay <seconds>
public int chatTimerDelay = 13;
// Game Config
public bool isKnifeRequired = true;
public int minimumReadyRequired = 2; // Number of ready players required start the match. If set to 0, all connected players have to ready-up to start the match.
public bool isWhitelistRequired = false;
public bool isSaveNadesAsGlobalEnabled = false;
public bool isPlayOutEnabled = false;
// User command - action map
public Dictionary<string, Action<CCSPlayerController?, CommandInfo?>>? commandActions;
// SQLite/MySQL Database
private Database database = new();
public override void Load(bool hotReload) {
LoadAdmins();
database.InitializeDatabase(ModuleDirectory);
// This sets default config ConVars
Server.ExecuteCommand("execifexists MatchZy/config.cfg");
teamSides[matchzyTeam1] = "CT";
teamSides[matchzyTeam2] = "TERRORIST";
reverseTeamSides["CT"] = matchzyTeam1;
reverseTeamSides["TERRORIST"] = matchzyTeam2;
if (!hotReload) {
AutoStart();
} else {
// Pluign should not be reloaded while a match is live (this would messup with the match flags which were set)
// Only hot-reload the plugin if you are testing something and don't want to restart the server time and again.
UpdatePlayersMap();
}
commandActions = new Dictionary<string, Action<CCSPlayerController?, CommandInfo?>> {
{ ".ready", OnPlayerReady },
{ ".r", OnPlayerReady },
{ ".unready", OnPlayerUnReady },
{ ".ur", OnPlayerUnReady },
{ ".stay", OnTeamStay },
{ ".switch", OnTeamSwitch },
{ ".swap", OnTeamSwitch },
{ ".tech", OnTechCommand },
{ ".pause", OnPauseCommand },
{ ".unpause", OnUnpauseCommand },
{ ".forcepause", OnForcePauseCommand },
{ ".fp", OnForcePauseCommand },
{ ".forceunpause", OnForceUnpauseCommand },
{ ".fup", OnForceUnpauseCommand },
{ ".tac", OnTacCommand },
{ ".roundknife", OnKifeCommand },
{ ".rk", OnKifeCommand },
{ ".playout", OnPlayoutCommand },
{ ".start", OnStartCommand },
{ ".restart", OnRestartMatchCommand },
{ ".reloadmap", OnMapReloadCommand },
{ ".settings", OnMatchSettingsCommand },
{ ".whitelist", OnWLCommand },
{ ".globalnades", OnSaveNadesAsGlobalCommand },
{ ".reload_admins", OnReloadAdmins },
{ ".prac", OnPracCommand },
{ ".bot", OnBotCommand },
{ ".crouchbot", OnCrouchBotCommand },
{ ".boost", OnBoostBotCommand },
{ ".crouchboost", OnCrouchBoostBotCommand },
{ ".nobots", OnNoBotsCommand },
{ ".god", OnGodCommand },
{ ".ff", OnFastForwardCommand },
{ ".fastforward", OnFastForwardCommand },
{ ".clear", OnClearCommand },
{ ".match", OnMatchCommand },
{ ".uncoach", OnUnCoachCommand },
{ ".exitprac", OnMatchCommand },
{ ".stop", OnStopCommand },
{ ".help", OnHelpCommand },
{ ".t", OnTCommand },
{ ".ct", OnCTCommand },
{ ".spec", OnSpecCommand },
{ ".fas", OnFASCommand },
{ ".watchme", OnFASCommand }
};
RegisterEventHandler<EventPlayerConnectFull>((@event, info) => {
try
{
Log($"[FULL CONNECT] Player ID: {@event.Userid.UserId}, Name: {@event.Userid.PlayerName} has connected!");
CCSPlayerController player = @event.Userid;
// Handling whitelisted players
if(!player.IsBot || !player.IsHLTV)
{
var steamId = player.SteamID;
string whitelistfileName = "MatchZy/whitelist.cfg";
string whitelistPath = Path.Join(Server.GameDirectory + "/csgo/cfg", whitelistfileName);
string? directoryPath = Path.GetDirectoryName(whitelistPath);
if (directoryPath != null)
{
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
if(!File.Exists(whitelistPath)) File.WriteAllLines(whitelistPath, new []{"Steamid1", "Steamid2"});
var whiteList = File.ReadAllLines(whitelistPath);
if (isWhitelistRequired == true)
{
if (!whiteList.Contains(steamId.ToString()))
{
Log($"[EventPlayerConnectFull] KICKING PLAYER STEAMID: {steamId}, Name: {player.PlayerName} (Not whitelisted!)");
Server.ExecuteCommand($"kickid {(ushort)player.UserId}");
return HookResult.Continue;
}
}
if (isMatchSetup || matchModeOnly) {
CsTeam team = GetPlayerTeam(player);
Log($"[EventPlayerConnectFull] KICKING PLAYER STEAMID: {steamId}, Name: {player.PlayerName} (NOT ALLOWED!)");
if (team == CsTeam.None) {
Server.ExecuteCommand($"kickid {(ushort)player.UserId}");
return HookResult.Continue;
}
}
}
if (player.UserId.HasValue) {
playerData[player.UserId.Value] = player;
connectedPlayers++;
if (readyAvailable && !matchStarted) {
playerReadyStatus[player.UserId.Value] = false;
} else {
playerReadyStatus[player.UserId.Value] = true;
}
}
// May not be required, but just to be on safe side so that player data is properly updated in dictionaries
UpdatePlayersMap();
if (readyAvailable && !matchStarted) {
// Start Warmup when first player connect and match is not started.
if (GetRealPlayersCount() == 1) {
Log($"[FULL CONNECT] First player has connected, starting warmup!");
ExecUnpracCommands();
AutoStart();
}
}
return HookResult.Continue;
}
catch (Exception e)
{
Log($"[EventPlayerConnectFull FATAL] An error occurred: {e.Message}");
return HookResult.Continue;
}
});
RegisterEventHandler<EventPlayerDisconnect>((@event, info) => {
try
{
CCSPlayerController player = @event.Userid;
if (player.UserId.HasValue) {
if (playerReadyStatus.ContainsKey(player.UserId.Value)) {
playerReadyStatus.Remove(player.UserId.Value);
connectedPlayers--;
}
if (playerData.ContainsKey(player.UserId.Value)) {
playerData.Remove(player.UserId.Value);
}
if (matchzyTeam1.coach == player) {
matchzyTeam1.coach = null;
player.Clan = "";
} else if (matchzyTeam2.coach == player) {
matchzyTeam2.coach = null;
player.Clan = "";
}
}
return HookResult.Continue;
}
catch (Exception e)
{
Log($"[EventPlayerDisconnect FATAL] An error occurred: {e.Message}");
return HookResult.Continue;
}
});
RegisterListener<Listeners.OnClientDisconnectPost>(playerSlot => {
// May not be required, but just to be on safe side so that player data is properly updated in dictionaries
UpdatePlayersMap();
});
RegisterEventHandler<EventCsWinPanelRound>((@event, info) => {
Log($"[EventCsWinPanelRound PRE] finalEvent: {@event.FinalEvent}");
if (isKnifeRound && matchStarted) {
HandleKnifeWinner(@event);
}
return HookResult.Continue;
}, HookMode.Pre);
RegisterEventHandler<EventCsWinPanelMatch>((@event, info) => {
try
{
Log($"[EventCsWinPanelMatch]");
HandleMatchEnd();
// ResetMatch();
return HookResult.Continue;
}
catch (Exception e)
{
Log($"[EventCsWinPanelMatch FATAL] An error occurred: {e.Message}");
return HookResult.Continue;
}
});
RegisterEventHandler<EventRoundStart>((@event, info) => {
try
{
HandlePostRoundStartEvent(@event);
return HookResult.Continue;
}
catch (Exception e)
{
Log($"[EventRoundStart FATAL] An error occurred: {e.Message}");
return HookResult.Continue;
}
});
RegisterEventHandler<EventRoundFreezeEnd>((@event, info) => {
try
{
HandlePostRoundFreezeEndEvent(@event);
return HookResult.Continue;
}
catch (Exception e)
{
Log($"[EventRoundFreezeEnd FATAL] An error occurred: {e.Message}");
return HookResult.Continue;
}
});
RegisterEventHandler<EventPlayerTeam>((@event, info) => {
CCSPlayerController player = @event.Userid;
if (matchzyTeam1.coach == player || matchzyTeam2.coach == player) {
@event.Silent = true;
return HookResult.Changed;
}
return HookResult.Continue;
}, HookMode.Pre);
RegisterEventHandler<EventPlayerTeam>((@event, info) =>
{
CCSPlayerController player = @event.Userid;
if (player.IsHLTV || player.IsBot || !isMatchSetup)
{
return HookResult.Continue;
}
CsTeam playerTeam = GetPlayerTeam(player);
Log($"[EventPlayerTeam] PLAYER TEAM DETERMINED: {(int)playerTeam}");
if (@event.Team != (int)playerTeam)
{
if (player.IsValid)
{
Server.NextFrame(() =>
{
player.SwitchTeam(playerTeam);
// Server.NextFrame(() =>
// {
// player.PlayerPawn.Value.CommitSuicide(explode: true, force: true);
// });
});
}
}
return HookResult.Continue;
});
AddCommandListener("jointeam", (player, info) =>
{
if (isMatchSetup && player != null && player.IsValid) {
if (int.TryParse(info.ArgByIndex(1), out int joiningTeam)) {
int playerTeam = (int)GetPlayerTeam(player);
Log($"[jointeam] PLAYER TEAM DETERMINED: PlayerName: {player.PlayerName}, PlayerTeam: {playerTeam}");
if (joiningTeam != playerTeam) {
return HookResult.Stop;
}
}
}
return HookResult.Continue;
});
RegisterEventHandler<EventRoundEnd>((@event, info) => {
if (isKnifeRound) {
Log($"[EventRoundEnd PRE] Winner: {@event.Winner}, Reason: {@event.Reason}");
@event.Winner = knifeWinner;
int finalEvent = 10;
if (knifeWinner == 3) {
finalEvent = 8;
} else if (knifeWinner == 2) {
finalEvent = 9;
}
@event.Reason = finalEvent;
Log($"[EventRoundEnd Updated] Winner: {@event.Winner}, Reason: {@event.Reason}");
isSideSelectionPhase = true;
isKnifeRound = false;
StartAfterKnifeWarmup();
}
return HookResult.Continue;
}, HookMode.Pre);
RegisterEventHandler<EventRoundEnd>((@event, info) => {
try
{
if (!isMatchLive) return HookResult.Continue;
Log($"[EventRoundEnd POST] Winner: {@event.Winner}, Reason: {@event.Reason}");
HandlePostRoundEndEvent(@event);
return HookResult.Continue;
}
catch (Exception e)
{
Log($"[EventRoundEnd FATAL] An error occurred: {e.Message}");
return HookResult.Continue;
}
}, HookMode.Post);
// RegisterEventHandler<EventMapShutdown>((@event, info) => {
// Log($"[EventMapShutdown] Resetting match!");
// ResetMatch();
// return HookResult.Continue;
// });
RegisterListener<Listeners.OnMapStart>(mapName => {
Log($"[Listeners.OnMapStart]");
if (isWarmup) StartWarmup();
});
// RegisterListener<Listeners.OnMapEnd>(() => {
// Log($"[Listeners.OnMapEnd] Resetting match!");
// ResetMatch();
// });
RegisterEventHandler<EventPlayerDeath>((@event, info) => {
// Setting money back to 16000 when a player dies in warmup
var player = @event.Userid;
if (isWarmup) {
if (player.InGameMoneyServices != null) player.InGameMoneyServices.Account = 16000;
}
return HookResult.Continue;
});
RegisterEventHandler<EventPlayerHurt>((@event, info) =>
{
CCSPlayerController attacker = @event.Attacker;
CCSPlayerController victim = @event.Userid;
if (isPractice)
{
if (victim.IsBot) {
int damage = @event.DmgHealth;
int postDamageHealth = @event.Health;
@event.Attacker.PrintToChat($"{chatPrefix} {damage} damage to BOT {victim.PlayerName}({postDamageHealth} health)");
}
return HookResult.Continue;
}
if (!attacker.IsValid || attacker.IsBot && !(@event.DmgHealth > 0 || @event.DmgArmor > 0))
return HookResult.Continue;
if (matchStarted) {
if (@event.Userid.TeamNum != attacker.TeamNum)
{
int targetId = (int)@event.Userid.UserId!;
UpdatePlayerDamageInfo(@event, targetId);
}
}
return HookResult.Continue;
});
RegisterEventHandler<EventPlayerChat>((@event, info) => {
int currentVersion = Api.GetVersion();
int index = @event.Userid;
// From APIVersion 50 and above, EventPlayerChat userid property will be a "slot", rather than an entity index
// Player index is slot + 1
if (currentVersion >= 50)
{
index += 1;
}
var playerUserId = NativeAPI.GetUseridFromIndex(index);
Log($"[EventPlayerChat] UserId(Index): {index} playerUserId: {playerUserId} Message: {@event.Text}");
var originalMessage = @event.Text.Trim();
var message = @event.Text.Trim().ToLower();
CCSPlayerController? player = null;
if (playerData.ContainsKey(playerUserId)) {
player = playerData[playerUserId];
}
if (player == null) {
// Somehow we did not had the player in playerData, hence updating the maps again before getting the player
UpdatePlayersMap();
player = playerData[playerUserId];
}
// Handling player commands
if (commandActions.ContainsKey(message)) {
commandActions[message](player, null);
}
if (message.StartsWith(".map")) {
string command = ".map";
string mapName = message.Substring(command.Length).Trim();
HandleMapChangeCommand(player, mapName);
}
if (message.StartsWith(".readyrequired")) {
string command = ".readyrequired";
string commandArg = message.Substring(command.Length).Trim();
HandleReadyRequiredCommand(player, commandArg);
}
if (message.StartsWith(".restore")) {
string command = ".restore";
string commandArg = message.Substring(command.Length).Trim();
HandleRestoreCommand(player, commandArg);
}
if (originalMessage.StartsWith(".asay")) {
string command = ".asay";
string commandArg = originalMessage.Substring(command.Length).Trim();
if (IsPlayerAdmin(player, "css_asay", "@css/chat")) {
if (commandArg != "") {
Server.PrintToChatAll($"{adminChatPrefix} {commandArg}");
} else {
ReplyToUserCommand(player, "Usage: .asay <message>");
}
} else {
SendPlayerNotAdminMessage(player);
}
}
if (message.StartsWith(".savenade"))
{
string command = ".savenade";
string commandArg = message.Substring(command.Length).Trim();
HandleSaveNadeCommand(player, commandArg);
}
if (message.StartsWith(".delnade"))
{
string command = ".delnade";
string commandArg = message.Substring(command.Length).Trim();
HandleDeleteNadeCommand(player, commandArg);
}
if (message.StartsWith(".importnade"))
{
string command = ".importnade";
string commandArg = message.Substring(command.Length).Trim();
HandleImportNadeCommand(player, commandArg);
}
if (message.StartsWith(".listnades"))
{
string command = ".listnades";
string commandArg = message.Substring(command.Length).Trim();
HandleListNadesCommand(player, commandArg);
}
if (message.StartsWith(".loadnade"))
{
string command = ".loadnade";
string commandArg = message.Substring(command.Length).Trim();
HandleLoadNadeCommand(player, commandArg);
}
if (message.StartsWith(".spawn")) {
string command = ".spawn";
string commandArg = message.Substring(command.Length).Trim();
HandleSpawnCommand(player, commandArg, player.TeamNum, "spawn");
}
if (message.StartsWith(".ctspawn")) {
string command = ".ctspawn";
string commandArg = message.Substring(command.Length).Trim();
HandleSpawnCommand(player, commandArg, (byte)CsTeam.CounterTerrorist, "ctspawn");
}
if (message.StartsWith(".tspawn")) {
string command = ".tspawn";
string commandArg = message.Substring(command.Length).Trim();
HandleSpawnCommand(player, commandArg, (byte)CsTeam.Terrorist, "tspawn");
}
if (originalMessage.StartsWith(".team1")) {
string command = ".team1";
string commandArg = originalMessage.Substring(command.Length).Trim();
HandleTeamNameChangeCommand(player, commandArg, 1);
}
if (originalMessage.StartsWith(".team2")) {
string command = ".team2";
string commandArg = originalMessage.Substring(command.Length).Trim();
HandleTeamNameChangeCommand(player, commandArg, 2);
}
if (originalMessage.StartsWith(".rcon")) {
string command = ".rcon";
string commandArg = originalMessage.Substring(command.Length).Trim();
if (IsPlayerAdmin(player, "css_rcon", "@css/rcon")) {
Server.ExecuteCommand(commandArg);
ReplyToUserCommand(player, "Command sent successfully!");
} else {
SendPlayerNotAdminMessage(player);
}
}
if (message.StartsWith(".coach")) {
string command = ".coach";
string coachSide = message.Substring(command.Length).Trim();
HandleCoachCommand(player, coachSide);
}
return HookResult.Continue;
});
RegisterEventHandler<EventPlayerBlind>((@event, info) =>
{
if (isPractice && @event.Userid.SteamID != @event.Attacker.SteamID)
{
double roundedBlindDuration = Math.Round(@event.BlindDuration, 2);
@event.Attacker.PrintToChat($"{chatPrefix} Flashed {@event.Userid.PlayerName}. Blind time: {roundedBlindDuration} seconds");
}
return HookResult.Continue;
});
Console.WriteLine("[MatchZy LOADED] MatchZy by WD- (https://github.com/shobhit-pathak/)");
}
}
}