Skip to content

Commit

Permalink
Merge pull request #226 from shobhit-pathak/dev
Browse files Browse the repository at this point in the history
0.8.6
  • Loading branch information
shobhit-pathak authored Sep 13, 2024
2 parents 87420fb + 9e663f0 commit 1fb8c7d
Show file tree
Hide file tree
Showing 18 changed files with 337 additions and 97 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
obj/*
bin/*
bin/*
/.vs
155 changes: 105 additions & 50 deletions Coach.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Modules.Cvars;
using System.Text.Json;

namespace MatchZy;

Expand All @@ -26,6 +27,11 @@ public void HandleCoachCommand(CCSPlayerController? player, string side)
ReplyToUserCommand(player, "Coach command can only be used in match mode!");
return;
}
if (IsWingmanMode())
{
ReplyToUserCommand(player, "Coach command cannot be used in wingman!");
return;
}

side = side.Trim().ToLower();

Expand Down Expand Up @@ -73,13 +79,21 @@ public void HandleCoaches()
coachKillTimer?.Kill();
coachKillTimer = null;
HashSet<CCSPlayerController> coaches = GetAllCoaches();
if (coaches.Count == 0) return;
if (IsWingmanMode() || coaches.Count == 0) return;
if (spawnsData.Values.Any(list => list.Count == 0)) GetSpawns();
if (coachSpawns.Count == 0 ||
coachSpawns[(byte)CsTeam.CounterTerrorist].Count == 0 ||
coachSpawns[(byte)CsTeam.Terrorist].Count == 0)
{
Log($"[HandleCoaches] No coach spawns found, player positions will not be swapped!");
return;
}

int freezeTime = ConVar.Find("mp_freezetime")!.GetPrimitiveValue<int>();
freezeTime = freezeTime > 2 ? freezeTime: 2;
coachKillTimer ??= AddTimer(freezeTime - 1.5f, KillCoaches);
HashSet<CCSPlayerController> competitiveSpawnCoaches = new();
if (spawnsData.Values.Any(list => list.Count == 0)) GetSpawns();
coachKillTimer ??= AddTimer(freezeTime - 1f, KillCoaches);

Random random = new();
foreach (CCSPlayerController coach in coaches)
{
if (!IsPlayerValid(coach)) continue;
Expand All @@ -94,64 +108,72 @@ public void HandleCoaches()
coach.ActionTrackingServices!.MatchStats.Assists = 0;
coach.ActionTrackingServices!.MatchStats.Damage = 0;

List<Position> teamPositions = spawnsData[coach.TeamNum];
SetPlayerInvisible(player: coach, setWeaponsInvisible: false);
// Stopping the coaches from moving, so that they don't block the players.
coach.PlayerPawn.Value!.MoveType = MoveType_t.MOVETYPE_NONE;
coach.PlayerPawn.Value!.ActualMoveType = MoveType_t.MOVETYPE_NONE;

List<Position> coachTeamSpawns = coachSpawns[coach.TeamNum];
Position coachPosition = new(coach.PlayerPawn.Value!.CBodyComponent!.SceneNode!.AbsOrigin, coach.PlayerPawn.Value!.CBodyComponent!.SceneNode!.AbsRotation);

foreach (Position position in teamPositions)
{
if (position.Equals(coachPosition))
{
competitiveSpawnCoaches.Add(coach);
break;
}
}
SetPlayerInvisible(player: coach, setWeaponsInvisible: false);
// Picking a random position for the coach (from coachSpawns) to teleport them.
Position newPosition = coachTeamSpawns[random.Next(0, coachTeamSpawns.Count)];

// Elevating coach before dropping the C4 to prevent it going inside the ground.
AddTimer(0.05f, () =>
{
coach!.PlayerPawn.Value!.Teleport(new Vector(coachPosition.PlayerPosition.X, coachPosition.PlayerPosition.Y, coachPosition.PlayerPosition.Z + 20.0f), coachPosition.PlayerAngle, new Vector(0, 0, 0));
HandleCoachWeapons(coach);
coach!.PlayerPawn.Value.Teleport(coachPosition.PlayerPosition, coachPosition.PlayerAngle, new Vector(0, 0, 0));
coach!.PlayerPawn.Value.Teleport(newPosition.PlayerPosition, newPosition.PlayerAngle, new Vector(0, 0, 0));
});

}

var playerEntities = Utilities.FindAllEntitiesByDesignerName<CCSPlayerController>("cs_player_controller");
List<CCSPlayerController> players = Utilities.GetPlayers();
HashSet<Position> occupiedSpawns = new();
HashSet<CCSPlayerController> incorrectSpawnedPlayers = new();

// We will loop on the players 2 times, first loop is to get all the players who are on a non-competitive spawn, and to get all the non-occupied competitive spawn.
// In the next loop, we will teleport the non-competitive spawned players to an available competitive spawn.

// foreach (var key in playerData.Keys)
// {
foreach (var player in playerEntities)
foreach (CCSPlayerController player in players)
{
if (!IsPlayerValid(player)) continue;
// CCSPlayerController player = playerData[key];
if (!IsPlayerValid(player) || coaches.Contains(player)) continue;

List<Position> teamPositions = spawnsData[player.TeamNum];
Position playerPosition = new(player.PlayerPawn.Value!.CBodyComponent!.SceneNode!.AbsOrigin, player.PlayerPawn.Value!.CBodyComponent!.SceneNode!.AbsRotation);
bool isCompetitiveSpawn = false;
foreach (Position position in teamPositions)
{
if (position.Equals(playerPosition))
{
occupiedSpawns.Add(position);
isCompetitiveSpawn = true;
break;
}
}
// Player is already on a competitive spawn, no need to swap.
if (isCompetitiveSpawn) continue;

CCSPlayerController? coach = competitiveSpawnCoaches.FirstOrDefault((CCSPlayerController coach) => coach.Team == player.Team);
if (coach is null) continue;
competitiveSpawnCoaches.Remove(coach);
// The player is not on a competitive spawn, we will put them on one in the next loop.
incorrectSpawnedPlayers.Add(player);
}

Position coachPosition = new(coach.PlayerPawn.Value!.CBodyComponent!.SceneNode!.AbsOrigin, coach.PlayerPawn.Value!.CBodyComponent!.SceneNode!.AbsRotation);
AddTimer(0.1f, () =>
{
coach!.PlayerPawn.Value!.Teleport(new Vector(playerPosition.PlayerPosition.X, playerPosition.PlayerPosition.Y, playerPosition.PlayerPosition.Z), playerPosition.PlayerAngle, new Vector(0, 0, 0));
player!.PlayerPawn.Value.Teleport(coachPosition.PlayerPosition, coachPosition.PlayerAngle, new Vector(0, 0, 0));
});
foreach (CCSPlayerController player in incorrectSpawnedPlayers)
{
if (!IsPlayerValid(player) || coaches.Contains(player)) continue;

// Stopping the coaches from moving, so that they don't block the players.
coach.PlayerPawn.Value!.MoveType = MoveType_t.MOVETYPE_NONE;
coach.PlayerPawn.Value!.ActualMoveType = MoveType_t.MOVETYPE_NONE;
List<Position> teamPositions = spawnsData[player.TeamNum];
Position playerPosition = new(player.PlayerPawn.Value!.CBodyComponent!.SceneNode!.AbsOrigin, player.PlayerPawn.Value!.CBodyComponent!.SceneNode!.AbsRotation);
foreach (Position position in teamPositions)
{
if (occupiedSpawns.Contains(position)) continue;
occupiedSpawns.Add(position);
AddTimer(0.1f, () =>
{
player!.PlayerPawn.Value.Teleport(position.PlayerPosition, position.PlayerAngle, new Vector(0, 0, 0));
});
break;
}
}
}

Expand Down Expand Up @@ -204,29 +226,62 @@ private void KillCoaches()
{
if (isPaused || IsTacticalTimeoutActive()) return;
HashSet<CCSPlayerController> coaches = GetAllCoaches();
if (coaches.Count == 0) return;
if (IsWingmanMode() || coaches.Count == 0) return;
string suicidePenalty = GetConvarStringValue(ConVar.Find("mp_suicide_penalty"));
string deathDropGunEnabled = GetConvarStringValue(ConVar.Find("mp_death_drop_gun"));
string specFreezeTime = GetConvarStringValue(ConVar.Find("spec_freeze_time"));
string specFreezeTimeLock = GetConvarStringValue(ConVar.Find("spec_freeze_time_lock"));
string specFreezeDeathanim = GetConvarStringValue(ConVar.Find("spec_freeze_deathanim_time"));
Server.ExecuteCommand("mp_suicide_penalty 0;spec_freeze_time 0; spec_freeze_time_lock 0; spec_freeze_deathanim_time 0;");

// Adding timer to make sure above commands are executed successfully.
AddTimer(0.5f, () =>
foreach (var coach in coaches)
{
if (!IsPlayerValid(coach)) continue;
if (isPaused || IsTacticalTimeoutActive()) continue;

Position coachPosition = new(coach.PlayerPawn.Value!.CBodyComponent!.SceneNode!.AbsOrigin, coach.PlayerPawn.Value!.CBodyComponent!.SceneNode!.AbsRotation);
coach!.PlayerPawn.Value!.Teleport(new Vector(coachPosition.PlayerPosition.X, coachPosition.PlayerPosition.Y, coachPosition.PlayerPosition.Z + 20.0f), coachPosition.PlayerAngle, new Vector(0, 0, 0));
// Dropping the C4 if it was picked up or passed to the coach.
DropWeaponByDesignerName(coach, "weapon_c4");
coach.PlayerPawn.Value!.CommitSuicide(explode: false, force: true);
}
Server.ExecuteCommand($"mp_suicide_penalty {suicidePenalty}; spec_freeze_time {specFreezeTime}; spec_freeze_time_lock {specFreezeTimeLock}; spec_freeze_deathanim_time {specFreezeDeathanim};");
}

private void GetCoachSpawns()
{
coachSpawns = GetEmptySpawnsData();
try
{
foreach (var coach in coaches)
string spawnsConfigPath = Path.Combine(ModuleDirectory, "spawns", "coach", $"{Server.MapName}.json");
string spawnsConfig = File.ReadAllText(spawnsConfigPath);

var jsonDictionary = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(spawnsConfig);
if (jsonDictionary is null) return;
foreach (var entry in jsonDictionary)
{
if (!IsPlayerValid(coach)) continue;
if (isPaused || IsTacticalTimeoutActive()) continue;
byte team = byte.Parse(entry.Key);
List<Position> positionList = new();

Position coachPosition = new(coach.PlayerPawn.Value!.CBodyComponent!.SceneNode!.AbsOrigin, coach.PlayerPawn.Value!.CBodyComponent!.SceneNode!.AbsRotation);
coach!.PlayerPawn.Value!.Teleport(new Vector(coachPosition.PlayerPosition.X, coachPosition.PlayerPosition.Y, coachPosition.PlayerPosition.Z + 20.0f), coachPosition.PlayerAngle, new Vector(0, 0, 0));
// Dropping the C4 if it was picked up or passed to the coach.
DropWeaponByDesignerName(coach, "weapon_c4");
coach.PlayerPawn.Value!.CommitSuicide(explode: false, force: true);
foreach (var positionData in entry.Value)
{
string[] vectorArray = positionData["Vector"].Split(' ');
string[] angleArray = positionData["QAngle"].Split(' ');

// Parse position and angle
Vector vector = new(float.Parse(vectorArray[0]), float.Parse(vectorArray[1]), float.Parse(vectorArray[2]));
QAngle qAngle = new(float.Parse(angleArray[0]), float.Parse(angleArray[1]), float.Parse(angleArray[2]));

Position position = new(vector, qAngle);

positionList.Add(position);
}
coachSpawns[team] = positionList;
}
Server.ExecuteCommand($"mp_suicide_penalty {suicidePenalty}; spec_freeze_time {specFreezeTime}; spec_freeze_time_lock {specFreezeTimeLock}; spec_freeze_deathanim_time {specFreezeDeathanim};");
});
Log($"[GetCoachSpawns] Loaded {coachSpawns.Count} coach spawns");
}
catch (Exception ex)
{
Log($"[GetCoachSpawns - FATAL] Error getting coach spawns. [ERROR]: {ex.Message}");
}
}
}
}
1 change: 1 addition & 0 deletions ConsoleCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,7 @@ public void OnEndMatchCommand(CCSPlayerController? player, CommandInfo? command)
}

[ConsoleCommand("css_restart", "Restarts the match")]
[ConsoleCommand("css_rr", "Restarts the match")]
public void OnRestartMatchCommand(CCSPlayerController? player, CommandInfo? command)
{
if (IsPlayerAdmin(player, "css_restart", "@css/config"))
Expand Down
4 changes: 0 additions & 4 deletions EventHandlers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,6 @@ public HookResult EventPlayerConnectFullHandler(EventPlayerConnectFull @event, G
KickPlayer(player);
return HookResult.Continue;
}
else
{
SwitchPlayerTeam(player, team);
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions MapVeto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ public void HandeMapBanCommand(CCSPlayerController player, string map)
if (player.UserId != vetoCaptains[currentTeamToBan]) return;

if (!BanMap(map, playerTeam)) {
player.PrintToChat($"{chatPrefix} {map} is not a valid map.");
PrintToPlayerChat(player, $"{map} is not a valid map.");
} else {
HandleVetoStep();
}
Expand Down Expand Up @@ -229,7 +229,7 @@ public void HandeMapPickCommand(CCSPlayerController player, string map)
if (player.UserId != vetoCaptains[currentTeamToPick]) return;

if (!PickMap(map, playerTeam)) {
player.PrintToChat($"{chatPrefix} {map} is not a valid map.");
PrintToPlayerChat(player, $"{map} is not a valid map.");
} else {
HandleVetoStep();
}
Expand Down
18 changes: 10 additions & 8 deletions MatchZy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public partial class MatchZy : BasePlugin
{

public override string ModuleName => "MatchZy";
public override string ModuleVersion => "0.8.5";
public override string ModuleVersion => "0.8.6";

public override string ModuleAuthor => "WD- (https://github.com/shobhit-pathak/)";

Expand Down Expand Up @@ -135,6 +135,7 @@ public override void Load(bool hotReload) {
{ ".skipveto", OnSkipVetoCommand },
{ ".sv", OnSkipVetoCommand },
{ ".restart", OnRestartMatchCommand },
{ ".rr", OnRestartMatchCommand },
{ ".endmatch", OnEndMatchCommand },
{ ".forceend", OnEndMatchCommand },
{ ".reloadmap", OnMapReloadCommand },
Expand All @@ -144,6 +145,8 @@ public override void Load(bool hotReload) {
{ ".reload_admins", OnReloadAdmins },
{ ".tactics", OnPracCommand },
{ ".prac", OnPracCommand },
{ ".showspawns", OnShowSpawnsCommand },
{ ".hidespawns", OnHideSpawnsCommand },
{ ".dryrun", OnDryRunCommand },
{ ".dry", OnDryRunCommand },
{ ".noflash", OnNoFlashCommand },
Expand Down Expand Up @@ -212,7 +215,6 @@ public override void Load(bool hotReload) {
// UpdatePlayersMap();
});
RegisterListener<Listeners.OnEntitySpawned>(OnEntitySpawnedHandler);

RegisterEventHandler<EventPlayerTeam>((@event, info) => {
CCSPlayerController? player = @event.Userid;
if (!IsPlayerValid(player)) return HookResult.Continue;
Expand Down Expand Up @@ -366,13 +368,13 @@ public override void Load(bool hotReload) {
var originalMessage = @event.Text.Trim();
var message = @event.Text.Trim().ToLower();

var parts = message.Split(' ');
var parts = originalMessage.Split(' ');
var messageCommand = parts.Length > 0 ? parts[0] : string.Empty;
var messageCommandArg = parts.Length > 1 ? string.Join(' ', parts.Skip(1)) : string.Empty;

CCSPlayerController? player = null;
if (playerData.ContainsKey(playerUserId)) {
player = playerData[playerUserId];
if (playerData.TryGetValue(playerUserId, out CCSPlayerController? value)) {
player = value;
}

if (player == null) {
Expand Down Expand Up @@ -454,15 +456,15 @@ public override void Load(bool hotReload) {
{
HandleSpawnCommand(player, messageCommandArg, (byte)CsTeam.Terrorist, "tspawn");
}
if (originalMessage.StartsWith(".team1"))
if (message.StartsWith(".team1"))
{
HandleTeamNameChangeCommand(player, messageCommandArg, 1);
}
if (originalMessage.StartsWith(".team2"))
if (message.StartsWith(".team2"))
{
HandleTeamNameChangeCommand(player, messageCommandArg, 2);
}
if (originalMessage.StartsWith(".rcon"))
if (message.StartsWith(".rcon"))
{
if (IsPlayerAdmin(player, "css_rcon", "@css/rcon"))
{
Expand Down
3 changes: 2 additions & 1 deletion MatchZy.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="CounterStrikeSharp.API" Version="1.0.253">
<PackageReference Include="CounterStrikeSharp.API" Version="1.0.263">
<PrivateAssets>none</PrivateAssets>
<ExcludeAssets>runtime</ExcludeAssets>
<IncludeAssets>compile; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand All @@ -21,5 +21,6 @@
</ItemGroup>
<ItemGroup>
<None Update="lang\**\*.*" CopyToOutputDirectory="PreserveNewest" />
<None Update="spawns\**\*.*" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
Loading

0 comments on commit 1fb8c7d

Please sign in to comment.