-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
PracticeMode.cs
1805 lines (1569 loc) · 88.1 KB
/
PracticeMode.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 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.Entities.Constants;
using CounterStrikeSharp.API.Modules.Timers;
using CounterStrikeSharp.API.Modules.Utils;
using System.Drawing;
using System.Text.Json;
namespace MatchZy
{
public class Position
{
public Vector PlayerPosition { get; private set; }
public QAngle PlayerAngle { get; private set; }
public Position(Vector playerPosition, QAngle playerAngle)
{
// Create deep copies of the Vector and QAngle objects
PlayerPosition = new Vector(playerPosition.X, playerPosition.Y, playerPosition.Z);
PlayerAngle = new QAngle(playerAngle.X, playerAngle.Y, playerAngle.Z);
}
public override bool Equals(object? obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
Position otherPosition = (Position)obj;
return PlayerPosition.X == otherPosition.PlayerPosition.X &&
PlayerPosition.Y == otherPosition.PlayerPosition.Y &&
PlayerAngle.X == otherPosition.PlayerAngle.X &&
PlayerAngle.Y == otherPosition.PlayerAngle.Y &&
PlayerAngle.Z == otherPosition.PlayerAngle.Z;
}
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = hash * 23 + PlayerPosition.X.GetHashCode();
hash = hash * 23 + PlayerPosition.Y.GetHashCode();
hash = hash * 23 + PlayerPosition.Z.GetHashCode();
hash = hash * 23 + PlayerAngle.X.GetHashCode();
hash = hash * 23 + PlayerAngle.Y.GetHashCode();
hash = hash * 23 + PlayerAngle.Z.GetHashCode();
return hash;
}
}
}
public static class StringSimilarity
{
// Dice coefficient function
public static double DiceCoefficient(string s1, string s2)
{
var bigrams1 = GetBigrams(s1);
var bigrams2 = GetBigrams(s2);
int intersection = bigrams1.Intersect(bigrams2).Count();
return (2.0 * intersection) / (bigrams1.Count + bigrams2.Count);
}
// Get bigrams function
private static List<string> GetBigrams(string input)
{
var bigrams = new List<string>();
for (int i = 0; i < input.Length - 1; i++)
{
bigrams.Add(input.Substring(i, 2));
}
return bigrams;
}
/// <summary>
/// Finds the name from a list of names that is nearest to the input name using the Dice coefficient.
/// </summary>
/// <param name="inputName">The input name to match.</param>
/// <param name="names">The list of names to search from.</param>
/// <returns>The nearest matching name from the list.</returns>
public static string FindNearestName(string inputName, List<string> names)
{
if (inputName.Length == 1)
{
// If input name is a single character, find the name that starts with the same character
var matchingName = names.FirstOrDefault(name => name.StartsWith(inputName, StringComparison.OrdinalIgnoreCase));
if (matchingName != null)
{
return matchingName;
}
}
// Otherwise, use the Dice coefficient to find the nearest name
string nearestName = names.OrderByDescending(name => DiceCoefficient(inputName, name)).FirstOrDefault() ?? inputName;
return nearestName;
}
}
public partial class MatchZy
{
int maxLastGrenadesSavedLimit = 512;
Dictionary<int, List<GrenadeThrownData>> lastGrenadesData = new();
Dictionary<int, Dictionary<string, GrenadeThrownData>> nadeSpecificLastGrenadeData = new();
Dictionary<int, DateTime> lastGrenadeThrownTime = new();
Dictionary<int, PlayerPracticeTimer> playerTimers = new();
public Dictionary<byte, List<Position>> spawnsData = GetEmptySpawnsData();
public Dictionary<byte, List<Position>> coachSpawns = GetEmptySpawnsData();
public const string practiceCfgPath = "MatchZy/prac.cfg";
public const string dryrunCfgPath = "MatchZy/dryrun.cfg";
// This map stores the bots which are being used in prac (probably spawned using .bot). Key is the userid of the bot.
public Dictionary<int, Dictionary<string, object>> pracUsedBots = new Dictionary<int, Dictionary<string, object>>();
private CounterStrikeSharp.API.Modules.Timers.Timer? collisionGroupTimer;
public bool isSpawningBot;
public bool isDryRun = false;
public List<int> noFlashList = new List<int>();
public static Dictionary<byte, List<Position>> GetEmptySpawnsData()
{
return new Dictionary<byte, List<Position>>
{
{ (byte)CsTeam.CounterTerrorist, new List<Position>() },
{ (byte)CsTeam.Terrorist, new List<Position>() }
};
}
public void StartPracticeMode()
{
if (matchStarted) return;
isPractice = true;
isDryRun = false;
isWarmup = false;
readyAvailable = false;
var absolutePath = Path.Join(Server.GameDirectory + "/csgo/cfg", practiceCfgPath);
if (File.Exists(Path.Join(Server.GameDirectory + "/csgo/cfg", practiceCfgPath)))
{
Log($"[StartWarmup] Starting Practice Mode! Executing Practice CFG from {practiceCfgPath}");
Server.ExecuteCommand($"exec {practiceCfgPath}");
}
else
{
Log($"[StartWarmup] Starting Practice Mode! Practice CFG not found in {absolutePath}, using default CFG!");
Server.ExecuteCommand("""sv_cheats "true"; mp_force_pick_time "0"; bot_quota "0"; sv_showimpacts "1"; mp_limitteams "0"; sv_deadtalk "true"; sv_full_alltalk "true"; sv_ignoregrenaderadio "false"; mp_forcecamera "0"; sv_grenade_trajectory_prac_pipreview "true"; sv_grenade_trajectory_prac_trailtime "3"; sv_infinite_ammo "1"; weapon_auto_cleanup_time "15"; weapon_max_before_cleanup "30"; mp_buy_anywhere "1"; mp_maxmoney "9999999"; mp_startmoney "9999999";""");
Server.ExecuteCommand("""mp_weapons_allow_typecount "-1"; mp_death_drop_breachcharge "false"; mp_death_drop_defuser "false"; mp_death_drop_taser "false"; mp_drop_knife_enable "true"; mp_death_drop_grenade "0"; ammo_grenade_limit_total "5"; mp_defuser_allocation "2"; mp_free_armor "2"; mp_ct_default_grenades "weapon_incgrenade weapon_hegrenade weapon_smokegrenade weapon_flashbang weapon_decoy"; mp_ct_default_primary "weapon_m4a1";""");
Server.ExecuteCommand("""mp_t_default_grenades "weapon_molotov weapon_hegrenade weapon_smokegrenade weapon_flashbang weapon_decoy"; mp_t_default_primary "weapon_ak47"; mp_warmup_online_enabled "true"; mp_warmup_pausetimer "1"; mp_warmup_start; bot_quota_mode fill; mp_solid_teammates 2; mp_autoteambalance false; mp_teammates_are_enemies false; buddha 1; buddha_ignore_bots 1; buddha_reset_hp 100;""");
}
GetSpawns();
PrintToAllChat($"Practice mode loaded!");
Server.PrintToChatAll($" {ChatColors.Green}Spawns: {ChatColors.Default}.spawn, .ctspawn, .tspawn, .bestspawn, .worstspawn");
Server.PrintToChatAll($" {ChatColors.Green}Bots: {ChatColors.Default}.bot, .nobots, .crouchbot, .boost, .crouchboost");
Server.PrintToChatAll($" {ChatColors.Green}Nades: {ChatColors.Default}.loadnade, .savenade, .importnade, .listnades");
Server.PrintToChatAll($" {ChatColors.Green}Nade Throw: {ChatColors.Default}.rethrow, .throwindex <index>, .lastindex, .delay <number>");
Server.PrintToChatAll($" {ChatColors.Green}Utility & Toggles: {ChatColors.Default}.clear, .fastforward, .last, .back, .solid, .impacts, .traj");
Server.PrintToChatAll($" {ChatColors.Green}Sides & Others: {ChatColors.Default}.ct, .t, .spec, .fas, .god, .dryrun, .break, .exitprac");
}
public void GetSpawns()
{
// Resetting spawn data to avoid any glitches
spawnsData = GetEmptySpawnsData();
int minPriority = 1;
var spawnsct = Utilities.FindAllEntitiesByDesignerName<SpawnPoint>("info_player_counterterrorist");
foreach (var spawn in spawnsct)
{
if (spawn.IsValid && spawn.Enabled && spawn.Priority < minPriority)
{
minPriority = spawn.Priority;
}
}
foreach (var spawn in spawnsct)
{
if (spawn.IsValid && spawn.Enabled && spawn.Priority == minPriority)
{
spawnsData[(byte)CsTeam.CounterTerrorist].Add(new Position(spawn.CBodyComponent?.SceneNode?.AbsOrigin!, spawn.CBodyComponent?.SceneNode?.AbsRotation!));
}
}
var spawnst = Utilities.FindAllEntitiesByDesignerName<SpawnPoint>("info_player_terrorist");
foreach (var spawn in spawnst)
{
if (spawn.IsValid && spawn.Enabled && spawn.Priority == minPriority)
{
spawnsData[(byte)CsTeam.Terrorist].Add(new Position(spawn.CBodyComponent?.SceneNode?.AbsOrigin!, spawn.CBodyComponent?.SceneNode?.AbsRotation!));
}
}
GetCoachSpawns();
}
private void HandleSpawnCommand(CCSPlayerController? player, string commandArg, byte teamNum, string command)
{
if (!isPractice || !IsPlayerValid(player)) return;
if (teamNum != 2 && teamNum != 3) return;
if (!string.IsNullOrWhiteSpace(commandArg))
{
if (int.TryParse(commandArg, out int spawnNumber) && spawnNumber >= 1)
{
// Adjusting the spawnNumber according to the array index.
spawnNumber -= 1;
if (spawnsData.ContainsKey(teamNum) && spawnsData[teamNum].Count <= spawnNumber) return;
player!.PlayerPawn.Value!.Teleport(spawnsData[teamNum][spawnNumber].PlayerPosition, spawnsData[teamNum][spawnNumber].PlayerAngle, new Vector(0, 0, 0));
// ReplyToUserCommand(player, $"Moved to spawn: {spawnNumber+1}/{spawnsData[teamNum].Count}");
ReplyToUserCommand(player, Localizer["matchzy.pm.movedtospawn", $"{spawnNumber + 1}/{spawnsData[teamNum].Count}"]);
}
else
{
// ReplyToUserCommand(player, $"Invalid value for {command} command. Please specify a valid non-negative number. Usage: !{command} <number>");
ReplyToUserCommand(player, Localizer["matchzy.pm.negativenumber"]);
return;
}
}
else
{
// ReplyToUserCommand(player, $"Usage: !{command} <number>");
ReplyToUserCommand(player, Localizer["matchzy.cc.usage", $"!{command} <number>"]);
}
}
private string GetNadeType(string nadeName)
{
switch (nadeName)
{
case "weapon_flashbang":
return "Flash";
case "weapon_smokegrenade":
return "Smoke";
case "weapon_hegrenade":
return "HE";
case "weapon_decoy":
return "Decoy";
case "weapon_molotov":
return "Molly";
case "weapon_incgrenade":
return "Molly";
default:
return "";
}
}
private void HandleSaveNadeCommand(CCSPlayerController? player, string saveNadeName)
{
if (!isPractice || !IsPlayerValid(player)) return;
if (!string.IsNullOrWhiteSpace(saveNadeName))
{
// Split string into 2 parts
string[] lineupUserString = saveNadeName.Split(' ');
string lineupName = lineupUserString[0];
string lineupDesc = string.Join(" ", lineupUserString, 1, lineupUserString.Length - 1);
// Get player info: steamid, pos, ang
string playerSteamID;
if(isSaveNadesAsGlobalEnabled == false)
{
playerSteamID = player!.SteamID.ToString();
}
else
{
playerSteamID = "default";
}
QAngle playerAngle = player!.PlayerPawn.Value!.EyeAngles;
Vector playerPos = player.Pawn.Value!.CBodyComponent!.SceneNode!.AbsOrigin;
string currentMapName = Server.MapName;
string nadeType = GetNadeType(player.PlayerPawn.Value.WeaponServices!.ActiveWeapon.Value!.DesignerName);
// Define the file path
string savednadesfileName = "MatchZy/savednades.json";
string savednadesPath = Path.Join(Server.GameDirectory + "/csgo/cfg", savednadesfileName);
// Check if the file exists, if not, create it with an empty JSON object
if (!File.Exists(savednadesPath))
{
File.WriteAllText(savednadesPath, "{}");
}
try
{
// Read existing JSON content
string existingJson = File.ReadAllText(savednadesPath);
// Deserialize the existing JSON content
var savedNadesDict = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, Dictionary<string, string>>>>(existingJson)
?? new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
// Check if the lineup name already exists for the given SteamID
if (savedNadesDict.ContainsKey(playerSteamID) && savedNadesDict[playerSteamID].ContainsKey(lineupName))
{
// Check if the lineup already exists on the same map
if (savedNadesDict[playerSteamID][lineupName]["Map"] == currentMapName)
{
// Lineup already exists on the same map, reply to the user and return
// ReplyToUserCommand(player, $"Lineup already exists! Please use a different name or use .delnade <nade>");
ReplyToUserCommand(player, Localizer["matchzy.pm.lineupissaved"]);
return;
}
}
// Update or add the new lineup information
if (!savedNadesDict.ContainsKey(playerSteamID))
{
savedNadesDict[playerSteamID] = new Dictionary<string, Dictionary<string, string>>();
}
savedNadesDict[playerSteamID][lineupName] = new Dictionary<string, string>
{
{ "LineupPos", $"{playerPos.X} {playerPos.Y} {playerPos.Z+4}" },
{ "LineupAng", $"{playerAngle.X} {playerAngle.Y} {playerAngle.Z}" },
{ "Desc", lineupDesc },
{ "Map", currentMapName },
{ "Type", nadeType }
};
// Serialize the updated dictionary back to JSON
string updatedJson = JsonSerializer.Serialize(savedNadesDict, new JsonSerializerOptions { WriteIndented = true });
// Write the updated JSON content back to the file
File.WriteAllText(savednadesPath, updatedJson);
PrintToPlayerChat(player, Localizer["matchzy.pm.lineupsavedsucces", lineupName]);
PrintToAllChat(Localizer["matchzy.pm.playersavedlineup", player.PlayerName, $"{lineupName} {playerPos} {playerAngle}"]);
}
catch (JsonException ex)
{
Log($"Error handling JSON: {ex.Message}");
}
}
else
{
// ReplyToUserCommand(player, $"Usage: .savenade <name>");
ReplyToUserCommand(player, Localizer["matchzy.cc.usage", $".savenade <name>"]);
}
}
private void HandleDeleteNadeCommand(CCSPlayerController? player, string saveNadeName)
{
if (!isPractice || player == null) return;
if (!string.IsNullOrWhiteSpace(saveNadeName))
{
// Grab player steamid
string playerSteamID;
if(isSaveNadesAsGlobalEnabled == false)
{
playerSteamID = player.SteamID.ToString();
}
else
{
playerSteamID = "default";
}
// Define the file path
string savednadesfileName = "MatchZy/savednades.json";
string savednadesPath = Path.Join(Server.GameDirectory + "/csgo/cfg", savednadesfileName);
try
{
// Read existing JSON content
string existingJson = File.ReadAllText(savednadesPath);
//Console.WriteLine($"Existing JSON Content: {existingJson}");
// Deserialize the existing JSON content
var savedNadesDict = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, Dictionary<string, string>>>>(existingJson)
?? new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
// Check if the lineup exists for the given SteamID and name
if (savedNadesDict.ContainsKey(playerSteamID) && savedNadesDict[playerSteamID].ContainsKey(saveNadeName))
{
var lineupInfo = savedNadesDict[playerSteamID][saveNadeName];
// Check if the lineup is for the current maps
if (lineupInfo.ContainsKey("Map") && lineupInfo["Map"] == Server.MapName)
{
// Remove the specified lineup
savedNadesDict[playerSteamID].Remove(saveNadeName);
// Serialize the updated dictionary back to JSON
string updatedJson = JsonSerializer.Serialize(savedNadesDict, new JsonSerializerOptions { WriteIndented = true });
// Write the updated JSON content back to the file
File.WriteAllText(savednadesPath, updatedJson);
// ReplyToUserCommand(player, $"Lineup '{saveNadeName}' deleted successfully.");
ReplyToUserCommand(player, Localizer["matchzy.pm.lineupdeletesuccess", saveNadeName]);
}
else
{
// ReplyToUserCommand(player, $"Lineup '{saveNadeName}' not found on the current map!");
ReplyToUserCommand(player, Localizer["matchzy.pm.nadenotfoundonmap", saveNadeName]);
}
}
else
{
// ReplyToUserCommand(player, $"Lineup '{saveNadeName}' not found!");
ReplyToUserCommand(player, Localizer["matchzy.pm.lineupnotfound", saveNadeName]);
}
}
catch (JsonException ex)
{
Log($"Error handling JSON: {ex.Message}");
}
}
else
{
// ReplyToUserCommand(player, $"Usage: .delnade <name>");
ReplyToUserCommand(player, Localizer["matchzy.cc.usage", $".delnade <name>"]);
}
}
private void HandleImportNadeCommand(CCSPlayerController? player, string saveNadeCode)
{
if (!isPractice || player == null) return;
if (!string.IsNullOrWhiteSpace(saveNadeCode))
{
try
{
// Split the code into parts
string[] parts = saveNadeCode.Split(' ');
// Check if there are enough parts
if (parts.Length == 7)
{
// Extract name, pos, and ang from the parts
string lineupName = parts[0].Trim();
string[] posAng = parts.Skip(1).Select(p => p.Replace(",", "")).ToArray(); // Replace ',' with '' for proper parsing
// Get player info: steamid
string playerSteamID = player.SteamID.ToString();
string currentMapName = Server.MapName;
// Define the file path
string savednadesfileName = "MatchZy/savednades.json";
string savednadesPath = Path.Join(Server.GameDirectory + "/csgo/cfg", savednadesfileName);
// Read existing JSON content
string existingJson = File.ReadAllText(savednadesPath);
//Console.WriteLine($"Existing JSON Content: {existingJson}");
// Deserialize the existing JSON content
var savedNadesDict = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, Dictionary<string, string>>>>(existingJson)
?? new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
// Check if the lineup name already exists for the given SteamID on the same map
if (savedNadesDict.ContainsKey(playerSteamID) && savedNadesDict[playerSteamID].ContainsKey(lineupName))
{
var existingLineup = savedNadesDict[playerSteamID][lineupName];
if (existingLineup.ContainsKey("Map") && existingLineup["Map"] == currentMapName)
{
// Lineup already exists on the same map, reply to the user and return
// ReplyToUserCommand(player, $"Lineup '{lineupName}' already exists! Please use a different name or use .delnade <nade>");
ReplyToUserCommand(player, Localizer["matchzy.pm.lineupalreadyexists", lineupName]);
return;
}
}
// Update or add the new lineup information
if (!savedNadesDict.ContainsKey(playerSteamID))
{
savedNadesDict[playerSteamID] = new Dictionary<string, Dictionary<string, string>>();
}
savedNadesDict[playerSteamID][lineupName] = new Dictionary<string, string>
{
{ "LineupPos", $"{posAng[0]} {posAng[1]} {posAng[2]}" },
{ "LineupAng", $"{posAng[3]} {posAng[4]} {posAng[5]}" },
{ "Desc", "" },
{ "Map", currentMapName }
};
// Serialize the updated dictionary back to JSON
string updatedJson = JsonSerializer.Serialize(savedNadesDict, new JsonSerializerOptions { WriteIndented = true });
// Write the updated JSON content back to the file
File.WriteAllText(savednadesPath, updatedJson);
// ReplyToUserCommand(player, $"Lineup '{lineupName}' imported and saved successfully.");
ReplyToUserCommand(player, Localizer["matchzy.pm.lineupimportedsuccess"]);
}
else
{
// ReplyToUserCommand(player, $"Invalid code format. Please provide a valid code with name, pos, and ang.");
ReplyToUserCommand(player, Localizer["matchzy.pm.lineupinvalidcode"]);
}
}
catch (JsonException ex)
{
Log($"Error handling JSON: {ex.Message}");
}
}
else
{
// ReplyToUserCommand(player, $"Usage: .importnade <code>");
ReplyToUserCommand(player, Localizer["matchzy.cc.usage", $".importnade <code>"]);
}
}
private void HandleListNadesCommand(CCSPlayerController? player, string nadeFilter)
{
if (!isPractice || player == null) return;
// Define the file path
string savednadesfileName = "MatchZy/savednades.json";
string savednadesPath = Path.Join(Server.GameDirectory + "/csgo/cfg", savednadesfileName);
try
{
// Read existing JSON content
string existingJson = File.ReadAllText(savednadesPath);
//Console.WriteLine($"Existing JSON Content: {existingJson}");
// Deserialize the existing JSON content
var savedNadesDict = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, Dictionary<string, string>>>>(existingJson)
?? new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
ReplyToUserCommand(player, $"\x0D-----All Saved Lineups for \x06{Server.MapName}\x0D-----");
// List lineups for the specified player
ListLineups(player, "default", Server.MapName, savedNadesDict, nadeFilter);
// List lineups for the current player
ListLineups(player, player.SteamID.ToString(), Server.MapName, savedNadesDict, nadeFilter);
}
catch (JsonException ex)
{
Log($"Error handling JSON: {ex.Message}");
ReplyToUserCommand(player, $"Error handling JSON. Please check the server logs.");
}
}
private void ListLineups(CCSPlayerController player, string steamID, string mapName, Dictionary<string, Dictionary<string, Dictionary<string, string>>> savedNadesDict, string nadeFilter)
{
if (savedNadesDict.ContainsKey(steamID))
{
foreach (var kvp in savedNadesDict[steamID])
{
// Check if a filter is provided, and if so, apply the filter
if ((string.IsNullOrWhiteSpace(nadeFilter) || kvp.Key.Contains(nadeFilter, StringComparison.OrdinalIgnoreCase))
&& kvp.Value.ContainsKey("Map") && kvp.Value["Map"] == mapName)
{
// Format and reply with the lineup name
ReplyToUserCommand(player, $"\x06[{kvp.Value["Type"]}] \x0D.loadnade \x06{kvp.Key}");
}
}
}
else
{
// ReplyToUserCommand(player, $"No saved lineups found for the specified SteamID: ({steamID}).");
ReplyToUserCommand(player, Localizer["matchzy.pm.nosavedlineups", steamID]);
}
}
private void HandleLoadNadeCommand(CCSPlayerController? player, string loadNadeName)
{
if (!isPractice || player == null || !IsPlayerValid(player)) return;
if (!string.IsNullOrWhiteSpace(loadNadeName))
{
// Get player info: steamid
string playerSteamID = player.SteamID.ToString();
// Define the file path
string savednadesfileName = "MatchZy/savednades.json";
string savednadesPath = Path.Join(Server.GameDirectory + "/csgo/cfg", savednadesfileName);
try
{
// Read existing JSON content
string existingJson = File.ReadAllText(savednadesPath);
//Console.WriteLine($"Existing JSON Content: {existingJson}");
// Deserialize the existing JSON content
var savedNadesDict = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, Dictionary<string, string>>>>(existingJson)
?? new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
bool lineupFound = false;
bool lineupOnWrongMap = false;
// Check for the lineup in the player's steamID and the fixed steamID
foreach (string currentSteamID in new[] { playerSteamID, "default" })
{
if (savedNadesDict.ContainsKey(currentSteamID))
{
// Filter nade names based on the current map
var nadeNamesOnCurrentMap = savedNadesDict[currentSteamID]
.Where(n => n.Value.ContainsKey("Map") && n.Value["Map"] == Server.MapName)
.Select(n => n.Key)
.ToList();
// Find the nearest matching name
string nearestName = StringSimilarity.FindNearestName(loadNadeName, nadeNamesOnCurrentMap);
if (savedNadesDict[currentSteamID].ContainsKey(nearestName))
{
var lineupInfo = savedNadesDict[currentSteamID][nearestName];
// Check if the lineup contains the "Map" key and if it matches the current map
if (lineupInfo.ContainsKey("Map") && lineupInfo["Map"] == Server.MapName)
{
// Extract position and angle from the lineup information
string[] posArray = lineupInfo["LineupPos"].Split(' ');
string[] angArray = lineupInfo["LineupAng"].Split(' ');
// Parse position and angle
Vector loadedPlayerPos = new Vector(float.Parse(posArray[0]), float.Parse(posArray[1]), float.Parse(posArray[2]));
QAngle loadedPlayerAngle = new QAngle(float.Parse(angArray[0]), float.Parse(angArray[1]), float.Parse(angArray[2]));
// Teleport player
player!.PlayerPawn!.Value!.Teleport(loadedPlayerPos, loadedPlayerAngle, new Vector(0, 0, 0));
// Change player inv slot
switch (lineupInfo["Type"])
{
case "Flash":
player.ExecuteClientCommand("slot7");
break;
case "Smoke":
player.ExecuteClientCommand("slot8");
break;
case "HE":
player.ExecuteClientCommand("slot6");
break;
case "Decoy":
player.ExecuteClientCommand("slot9");
break;
case "Molly":
player.ExecuteClientCommand("slot10");
break;
case "":
player.ExecuteClientCommand("slot8");
break;
}
// Extract description, if available
string lineupDesc = lineupInfo.ContainsKey("Desc") ? lineupInfo["Desc"] : null;
// Print messages
// ReplyToUserCommand(player, $"Lineup {ChatColors.Green}{nearestName}{ChatColors.Default} loaded successfully!");
ReplyToUserCommand(player, Localizer["matchzy.pm.lineuploadedsuccess", nearestName]);
if (!string.IsNullOrWhiteSpace(lineupDesc))
{
player.PrintToCenter($"{lineupDesc}");
// ReplyToUserCommand(player, $"Description: {ChatColors.Green}{lineupDesc}{ChatColors.Default}");
ReplyToUserCommand(player, Localizer["matchzy.pm.lineupdesc", lineupDesc]);
}
lineupFound = true;
break;
}
else
{
// ReplyToUserCommand(player, $"Nade {ChatColor.Green}{nearestName}{ChatColor.Default} not found on the current map!");
ReplyToUserCommand(player, Localizer["matchzy.pm.nadenotfoundonmap", nearestName]);
lineupOnWrongMap = true;
}
}
}
}
if (!lineupFound && !lineupOnWrongMap)
{
// Lineup not found
// ReplyToUserCommand(player, $"Nade {ChatColor.Green}{loadNadeName}{ChatColor.Default} not found!");
ReplyToUserCommand(player, Localizer["matchzy.pm.nadenotfound", loadNadeName]);
}
}
catch (JsonException ex)
{
Log($"Error handling JSON: {ex.Message}");
}
}
else
{
// ReplyToUserCommand(player, $"Nade not found! Usage: .loadnade <name>");
ReplyToUserCommand(player, Localizer["matchzy.pm.loadnadenotfound"]);
}
}
public void ShowSpawnBeam(Position spawn, Color color)
{
CBeam? beam = Utilities.CreateEntityByName<CBeam>("beam");
if (beam == null)
{
Log($"Failed to create beam for the spawn");
return;
}
beam.LifeState = 1;
beam.Width = 5;
beam.Render = color;
beam.EndPos.X = spawn.PlayerPosition.X;
beam.EndPos.Y = spawn.PlayerPosition.Y;
beam.EndPos.Z = spawn.PlayerPosition.Z + 100.0f;
beam.Teleport(spawn.PlayerPosition, new QAngle(0, 0, 0), new Vector(0, 0, 0));
beam.DispatchSpawn();
}
public void RemoveSpawnBeams()
{
var beams = Utilities.FindAllEntitiesByDesignerName<CEntityInstance>("beam");
foreach (var beam in beams)
{
if (beam == null) continue;
beam.Remove();
}
}
[ConsoleCommand("css_god", "Sets Infinite health for player")]
public void OnGodCommand(CCSPlayerController? player, CommandInfo? command)
{
if (!isPractice || player == null || !IsPlayerValid(player)) return;
int currentHP = player!.PlayerPawn!.Value!.Health;
if(currentHP > 100)
{
player.PlayerPawn.Value.Health = 100;
// ReplyToUserCommand(player, $"God mode disabled!");
ReplyToUserCommand(player, "God is " + Localizer["matchzy.cc.disabled"]);
return;
}
else
{
player.PlayerPawn.Value.Health = 2147483647; // max 32bit int
// ReplyToUserCommand(player, $"God mode enabled!");
ReplyToUserCommand(player, "God is " + Localizer["matchzy.cc.enabled"]);
return;
}
}
[ConsoleCommand("css_prac", "Starts practice mode")]
[ConsoleCommand("css_tactics", "Starts practice mode")]
public void OnPracCommand(CCSPlayerController? player, CommandInfo? command)
{
if (!IsPlayerAdmin(player, "css_prac", "@css/map", "@custom/prac")) {
SendPlayerNotAdminMessage(player);
return;
}
if (matchStarted)
{
// ReplyToUserCommand(player, "Practice Mode cannot be started when a match has been started!");
ReplyToUserCommand(player, Localizer["matchzy.pm.pracmatchstarted"]);
return;
}
// if (isPractice)
// {
// StartMatchMode();
// return;
// }
StartPracticeMode();
}
[ConsoleCommand("css_dry", "Starts dryrun in practice mode")]
[ConsoleCommand("css_dryrun", "Starts dryrun in practice mode")]
public void OnDryRunCommand(CCSPlayerController? player, CommandInfo? command)
{
if (!IsPlayerAdmin(player, "css_prac", "@css/map", "@custom/prac")) {
SendPlayerNotAdminMessage(player);
return;
}
if (matchStarted)
{
// ReplyToUserCommand(player, "Dryrun cannot be started when a match has been started!");
ReplyToUserCommand(player, Localizer["matchzy.pm.dryrunmatchstarted"]);
return;
}
if (!isPractice)
{
// ReplyToUserCommand(player, "Dryrun can only be started in practice mode!");
ReplyToUserCommand(player, Localizer["matchzy.pm.dryrunnopractice"]);
return;
}
Server.ExecuteCommand("bot_kick");
pracUsedBots = new Dictionary<int, Dictionary<string, object>>();
noFlashList = new();
ExecUnpracCommands();
ExecDryRunCFG();
isDryRun = true;
}
[ConsoleCommand("css_spawn", "Teleport to provided spawn")]
public void OnSpawnCommand(CCSPlayerController? player, CommandInfo command)
{
if (!isPractice) return;
// Checking if any of the Position List is empty
if (spawnsData.Values.Any(list => list.Count == 0)) GetSpawns();
if (player == null || !player.PlayerPawn.IsValid) return;
if (command.ArgCount >= 2)
{
string commandArg = command.ArgByIndex(1);
HandleSpawnCommand(player, commandArg, player.TeamNum, "spawn");
}
else
{
// ReplyToUserCommand(player, $"Usage: !spawn <round>");
ReplyToUserCommand(player, Localizer["matchzy.cc.usage", $"!spawn <round>"]);
}
}
[ConsoleCommand("css_ctspawn", "Teleport to provided CT spawn")]
public void OnCtSpawnCommand(CCSPlayerController? player, CommandInfo command)
{
if (!isPractice) return;
// Checking if any of the Position List is empty
if (spawnsData.Values.Any(list => list.Count == 0)) GetSpawns();
if (player == null || !player.PlayerPawn.IsValid) return;
if (command.ArgCount >= 2)
{
string commandArg = command.ArgByIndex(1);
HandleSpawnCommand(player, commandArg, (byte)CsTeam.CounterTerrorist, "ctspawn");
}
else
{
// ReplyToUserCommand(player, $"Usage: !ctspawn <round>");
ReplyToUserCommand(player, Localizer["matchzy.cc.usage", $"!ctspawn <round>"]);
}
}
[ConsoleCommand("css_tspawn", "Teleport to provided T spawn")]
public void OnTSpawnCommand(CCSPlayerController? player, CommandInfo command)
{
if (!isPractice) return;
// Checking if any of the Position List is empty
if (spawnsData.Values.Any(list => list.Count == 0)) GetSpawns();
if (player == null || !player.PlayerPawn.IsValid) return;
if (command.ArgCount >= 2)
{
string commandArg = command.ArgByIndex(1);
HandleSpawnCommand(player, commandArg, (byte)CsTeam.Terrorist, "tspawn");
}
else
{
// ReplyToUserCommand(player, $"Usage: !ctspawn <round>");
ReplyToUserCommand(player, Localizer["matchzy.cc.usage", $"!ctspawn <round>"]);
}
}
[ConsoleCommand("css_bot", "Spawns a bot at the player's position")]
public void OnBotCommand(CCSPlayerController? player, CommandInfo? command)
{
AddBot(player, false);
}
[ConsoleCommand("css_cbot", "Spawns a crouched bot at the player's position")]
[ConsoleCommand("css_crouchbot", "Spawns a crouched bot at the player's position")]
public void OnCrouchBotCommand(CCSPlayerController? player, CommandInfo? command)
{
AddBot(player, true);
}
[ConsoleCommand("css_boost", "Spawns a bot at the player's position and boost the player on it")]
public void OnBoostBotCommand(CCSPlayerController? player, CommandInfo? command)
{
if (!isPractice) return;
AddBot(player, false);
AddTimer(0.2f, () => ElevatePlayer(player));
}
[ConsoleCommand("css_crouchboost", "Spawns a crouched bot at the player's position and boost the player on it")]
public void OnCrouchBoostBotCommand(CCSPlayerController? player, CommandInfo? command)
{
if (!isPractice) return;
AddBot(player, true);
AddTimer(0.2f, () => ElevatePlayer(player));
}
private void AddBot(CCSPlayerController? player, bool crouch)
{
try
{
if (!isPractice || player == null || !player.IsValid || !player.PlayerPawn.IsValid || player.PlayerPawn.Value == null) return;
CCSPlayer_MovementServices movementService = new(player.PlayerPawn.Value.MovementServices!.Handle);
if ((int)movementService.DuckAmount == 1)
{
// Player was crouching while using .bot command
crouch = true;
}
isSpawningBot = true;
// !bot/.bot command is made using a lot of workarounds, as there is no direct way to create a bot entity and spawn it in CSSharp
// Hence there can be some issues with this approach. This will be revamped when we will be able to fake clients.
if (player.TeamNum == (byte)CsTeam.CounterTerrorist)
{
Server.ExecuteCommand("bot_join_team T");
Server.ExecuteCommand("bot_add_t");
}
else if (player.TeamNum == (byte)CsTeam.Terrorist)
{
Server.ExecuteCommand("bot_join_team CT");
Server.ExecuteCommand("bot_add_ct");
}
// Once bot is added, we teleport it to the requested position
AddTimer(0.1f, () => SpawnBot(player, crouch));
Server.ExecuteCommand("bot_stop 1");
Server.ExecuteCommand("bot_freeze 1");
Server.ExecuteCommand("bot_zombie 1");
}
catch (JsonException ex)
{
Log($"[AddBot - FATAL] Error: {ex.Message}");
}
}
private void SpawnBot(CCSPlayerController botOwner, bool crouch)
{
try
{
if (!IsPlayerValid(botOwner)) return;
var playerEntities = Utilities.FindAllEntitiesByDesignerName<CCSPlayerController>("cs_player_controller");
bool unusedBotFound = false;
foreach (var tempPlayer in playerEntities)
{
if (!IsPlayerValid(tempPlayer)) continue;
if (!tempPlayer.IsBot || tempPlayer.IsHLTV) continue;
if (tempPlayer.UserId.HasValue)
{
if (!pracUsedBots.ContainsKey(tempPlayer.UserId.Value) && unusedBotFound)
{
Log($"UNUSED BOT FOUND: {tempPlayer.UserId.Value} EXECUTING: kickid {tempPlayer.UserId.Value}");
// Kicking the unused bot. We have to do this because bot_add_t/bot_add_ct may add multiple bots but we need only 1, so we kick the remaining unused ones
Server.ExecuteCommand($"kickid {tempPlayer.UserId.Value}");
continue;
}
if (pracUsedBots.ContainsKey(tempPlayer.UserId.Value))
{
continue;
}
pracUsedBots[tempPlayer.UserId.Value] = new Dictionary<string, object>();
Position botOwnerPosition = new Position(botOwner.PlayerPawn.Value!.CBodyComponent?.SceneNode?.AbsOrigin!, botOwner.PlayerPawn.Value!.CBodyComponent?.SceneNode?.AbsRotation!);
// Add key-value pairs to the inner dictionary
pracUsedBots[tempPlayer.UserId.Value]["controller"] = tempPlayer;
pracUsedBots[tempPlayer.UserId.Value]["position"] = botOwnerPosition;
pracUsedBots[tempPlayer.UserId.Value]["owner"] = botOwner;
pracUsedBots[tempPlayer.UserId.Value]["crouchstate"] = crouch;
if (crouch)
{
CCSPlayer_MovementServices movementService = new(tempPlayer.PlayerPawn.Value!.MovementServices!.Handle);
AddTimer(0.1f, () => movementService.DuckAmount = 1);
AddTimer(0.2f, () => tempPlayer.PlayerPawn.Value!.Bot!.IsCrouching = true);
}
tempPlayer.PlayerPawn.Value!.Teleport(botOwnerPosition.PlayerPosition, botOwnerPosition.PlayerAngle, new Vector(0, 0, 0));
TemporarilyDisableCollisions(botOwner, tempPlayer);
unusedBotFound = true;
}
}
if (!unusedBotFound) {
// Server.PrintToChatAll($"{chatPrefix} Cannot add bots, the team is full! Use .nobots to remove the current bots.");
PrintToAllChat(Localizer["matchzy.pm.botlimit"]);
}
isSpawningBot = false;
}
catch (JsonException ex)
{
Log($"[SpawnBot - FATAL] Error: {ex.Message}");
}
}
public void TemporarilyDisableCollisions(CCSPlayerController p1, CCSPlayerController p2)
{