diff --git a/.editorconfig b/.editorconfig index 45a4da5aa..1f3fff443 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,10 +1,10 @@ [*.cs] # CA2211: Non-constant fields should not be visible -dotnet_diagnostic.CA2211.severity = none +dotnet_diagnostic.ca2211.severity = none # IDE0060: Remove unused parameter -dotnet_diagnostic.IDE0060.severity = none +dotnet_diagnostic.ide0060.severity = none csharp_using_directive_placement = outside_namespace:silent csharp_prefer_simple_using_statement = true:suggestion csharp_prefer_braces = true:silent @@ -49,9 +49,27 @@ csharp_style_prefer_pattern_matching = true:silent csharp_style_pattern_matching_over_as_with_null_check = true:suggestion csharp_style_prefer_not_pattern = true:suggestion csharp_style_prefer_extended_property_pattern = true:suggestion -csharp_style_var_for_built_in_types = false:silent -csharp_style_var_when_type_is_apparent = false:silent -csharp_style_var_elsewhere = false:silent +csharp_style_var_for_built_in_types = false:none +csharp_style_var_when_type_is_apparent = true:none +csharp_style_var_elsewhere = false:none + +# ReSharper properties +resharper_braces_for_dowhile = required_for_multiline +resharper_braces_for_fixed = required_for_multiline +resharper_braces_for_for = required_for_multiline +resharper_braces_for_foreach = required_for_multiline +resharper_braces_for_ifelse = required_for_multiline +resharper_braces_for_lock = required_for_multiline +resharper_braces_for_using = required_for_multiline +resharper_braces_for_while = required_for_multiline +resharper_braces_redundant = true +resharper_for_built_in_types = use_var_when_evident + +# Microsoft .NET properties +dotnet_style_qualification_for_event = false:none +dotnet_style_qualification_for_field = true:none +dotnet_style_qualification_for_method = false:none +dotnet_style_qualification_for_property = true:none [*.{cs,vb}] #### Naming styles #### diff --git a/EHR.sln.DotSettings b/EHR.sln.DotSettings index 2a394860e..6e7e96eea 100644 --- a/EHR.sln.DotSettings +++ b/EHR.sln.DotSettings @@ -1,8 +1,14 @@  + xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xml:space="preserve"> SOLUTION + 1 + 1 + 1 + TOGETHER_SAME_LINE AFK ATK AU diff --git a/GameMode/CTFManager.cs b/GameMode/CTFManager.cs index f85d7b793..0c3729576 100644 --- a/GameMode/CTFManager.cs +++ b/GameMode/CTFManager.cs @@ -109,10 +109,7 @@ namespace EHR public static bool KnowTargetRoleColor(PlayerControl seer, PlayerControl target, ref string color) { - if (!ValidTag) - { - return false; - } + if (!ValidTag) return false; Color32 teamColor = PlayerTeams[target.PlayerId].GetTeamColor(); color = $"#{teamColor.r:x2}{teamColor.g:x2}{teamColor.b:x2}{teamColor.a:x2}"; @@ -121,15 +118,9 @@ namespace EHR public static string GetSuffixText(PlayerControl seer, PlayerControl target) { - if (!ValidTag) - { - return string.Empty; - } + if (!ValidTag) return string.Empty; - if (seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId) return string.Empty; string arrows = TargetArrow.GetAllArrows(seer); arrows = arrows.Length > 0 ? $"{arrows}\n" : string.Empty; @@ -138,10 +129,7 @@ namespace EHR public static string GetStatistics(byte id) { - if (!PlayerData.TryGetValue(id, out CTFPlayerData stats)) - { - return string.Empty; - } + if (!PlayerData.TryGetValue(id, out CTFPlayerData stats)) return string.Empty; return string.Format(Translator.GetString("CTF_PlayerStats"), Math.Round(stats.FlagTime, 1), stats.TagCount); } @@ -156,10 +144,7 @@ namespace EHR reason = GameOverReason.ImpostorByKill; PlayerControl[] aapc = Main.AllAlivePlayerControls; - if (!ValidTag) - { - return false; - } + if (!ValidTag) return false; switch (aapc.Length) { @@ -209,10 +194,7 @@ namespace EHR ValidTag = false; // Check if the current game mode is Capture The Flag - if (Options.CurrentGameMode != CustomGameMode.CaptureTheFlag) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.CaptureTheFlag) return; LateTask.New(() => { @@ -220,10 +202,7 @@ namespace EHR // Assign players to teams List players = Main.AllAlivePlayerControls.Shuffle().ToList(); - if (Main.GM.Value) - { - players.RemoveAll(x => x.IsHost()); - } + if (Main.GM.Value) players.RemoveAll(x => x.IsHost()); int blueCount = players.Count / 2; HashSet bluePlayers = []; @@ -231,7 +210,7 @@ namespace EHR NetworkedPlayerInfo.PlayerOutfit blueOutfit = BlueOutfit; NetworkedPlayerInfo.PlayerOutfit yellowOutfit = YellowOutfit; - for (int i = 0; i < blueCount; i++) + for (var i = 0; i < blueCount; i++) { PlayerControl player = players.FirstOrDefault(p => p.Data.DefaultOutfit.ColorId == 1) ?? players.FirstOrDefault(x => x.Data.DefaultOutfit.ColorId != 5) ?? players.RandomElement(); players.Remove(player); @@ -292,20 +271,14 @@ namespace EHR public static void OnCheckMurder(PlayerControl killer, PlayerControl target) { CTFTeam targetTeam = PlayerTeams[target.PlayerId]; - if (!ValidTag || PlayerTeams[killer.PlayerId] == targetTeam || TeamData.Values.Any(x => x.FlagCarrier == killer.PlayerId)) - { - return; - } + if (!ValidTag || PlayerTeams[killer.PlayerId] == targetTeam || TeamData.Values.Any(x => x.FlagCarrier == killer.PlayerId)) return; new[] { killer, target }.Do(x => x.SetKillCooldown(TagCooldown.GetFloat())); if (TeamData.FindFirst(x => x.Value.FlagCarrier == target.PlayerId, out KeyValuePair kvp)) { kvp.Value.DropFlag(); - if (WhenFlagCarrierGetsTagged.GetValue() == 1) - { - kvp.Value.Flag.TP(kvp.Key.GetFlagBase().Position); - } + if (WhenFlagCarrierGetsTagged.GetValue() == 1) kvp.Value.Flag.TP(kvp.Key.GetFlagBase().Position); } switch (TaggedPlayersGet.GetValue()) @@ -328,19 +301,13 @@ namespace EHR public static void TryPickUpFlag(PlayerControl pc) { - if (!ValidTag) - { - return; - } + if (!ValidTag) return; Logger.Info($"Received flag pickup request from {pc.GetRealName()}", "CTF"); // If the player is near the enemy's flag, pick it up Vector2 pos = pc.Pos(); CTFTeamData enemy = TeamData[PlayerTeams[pc.PlayerId].GetOppositeTeam()]; - if (enemy.IsNearFlag(pos)) - { - enemy.PickUpFlag(pc.PlayerId); - } + if (enemy.IsNearFlag(pos)) enemy.PickUpFlag(pc.PlayerId); } public static void ApplyGameOptions(IGameOptions opt) @@ -411,12 +378,10 @@ namespace EHR { try { - if (FlagCarrier == byte.MaxValue) - { - return; - } + if (FlagCarrier == byte.MaxValue) return; PlayerControl flagCarrierPc = FlagCarrier.GetPlayer(); + if (flagCarrierPc == null || !flagCarrierPc.IsAlive()) { DropFlag(); @@ -428,22 +393,14 @@ namespace EHR Utils.NotifyRoles(SpecifySeer: flagCarrierPc, SpecifyTarget: flagCarrierPc); CTFTeam enemy = team.GetOppositeTeam(); - if (Translator.GetString(Flag.playerControl.GetPlainShipRoom().RoomId.ToString()) == enemy.GetFlagBase().RoomName) - { - TeamData[enemy].SetAsWinner(); - } - } - catch - { + if (Translator.GetString(Flag.playerControl.GetPlainShipRoom().RoomId.ToString()) == enemy.GetFlagBase().RoomName) TeamData[enemy].SetAsWinner(); } + catch { } } public void PickUpFlag(byte id) { - if (FlagCarrier == id) - { - return; - } + if (FlagCarrier == id) return; FlagCarrier = id; Update(); @@ -456,14 +413,12 @@ namespace EHR if (AlertTeamMembersOfFlagTaken.GetBool()) { bool arrow = ArrowToEnemyFlagCarrier.GetBool(); + TeamData[team].Players .Select(x => x.GetPlayer()) .DoIf(x => x != null, x => { - if (arrow) - { - TargetArrow.Add(x.PlayerId, id); - } + if (arrow) TargetArrow.Add(x.PlayerId, id); x.Notify(Utils.ColorString(Color.yellow, Translator.GetString("CTF_FlagTaken"))); }); @@ -472,14 +427,12 @@ namespace EHR if (AlertTeamMembersOfEnemyFlagTaken.GetBool()) { bool arrow = ArrowToOwnFlagCarrier.GetBool(); + TeamData[team.GetOppositeTeam()].Players .Select(x => x.GetPlayer()) .DoIf(x => x != null, x => { - if (arrow) - { - TargetArrow.Add(x.PlayerId, id); - } + if (arrow) TargetArrow.Add(x.PlayerId, id); x.Notify(Translator.GetString("CTF_EnemyFlagTaken")); }); @@ -489,10 +442,7 @@ namespace EHR public void DropFlag() { Logger.Info($"{FlagCarrier.ColoredPlayerName().RemoveHtmlTags()} dropped the {team} flag", "CTF"); - if (ArrowToEnemyFlagCarrier.GetBool() || ArrowToOwnFlagCarrier.GetBool()) - { - TeamData.Values.SelectMany(x => x.Players).Do(x => TargetArrow.Remove(x, FlagCarrier)); - } + if (ArrowToEnemyFlagCarrier.GetBool() || ArrowToOwnFlagCarrier.GetBool()) TeamData.Values.SelectMany(x => x.Players).Do(x => TargetArrow.Remove(x, FlagCarrier)); FlagCarrier = byte.MaxValue; Utils.NotifyRoles(); @@ -515,10 +465,7 @@ namespace EHR { public static void Postfix(PlayerControl __instance) { - if (!AmongUsClient.Instance.AmHost || !GameStates.IsInTask || Options.CurrentGameMode != CustomGameMode.CaptureTheFlag || Main.HasJustStarted || !__instance.IsHost()) - { - return; - } + if (!AmongUsClient.Instance.AmHost || !GameStates.IsInTask || Options.CurrentGameMode != CustomGameMode.CaptureTheFlag || Main.HasJustStarted || !__instance.IsHost()) return; TeamData.Values.Do(x => x.Update()); } diff --git a/GameMode/FFAManager.cs b/GameMode/FFAManager.cs index 9ea5fc690..e8bef57d4 100644 --- a/GameMode/FFAManager.cs +++ b/GameMode/FFAManager.cs @@ -60,53 +60,68 @@ namespace EHR .SetColor(new Color32(0, 255, 165, byte.MaxValue)) .SetValueFormat(OptionFormat.Seconds) .SetHeader(true); + FFAKcd = new FloatOptionItem(67_223_002, "FFA_KCD", new(1f, 60f, 1f), 10f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA) .SetColor(new Color32(0, 255, 165, byte.MaxValue)) .SetValueFormat(OptionFormat.Seconds); + FFADisableVentingWhenTwoPlayersAlive = new BooleanOptionItem(67_223_003, "FFA_DisableVentingWhenTwoPlayersAlive", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA) .SetColor(new Color32(0, 255, 165, byte.MaxValue)); + FFADisableVentingWhenKcdIsUp = new BooleanOptionItem(67_223_004, "FFA_DisableVentingWhenKCDIsUp", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA) .SetColor(new Color32(0, 255, 165, byte.MaxValue)); + FFAEnableRandomAbilities = new BooleanOptionItem(67_223_005, "FFA_EnableRandomAbilities", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA) .SetColor(new Color32(0, 255, 165, byte.MaxValue)); + FFAShieldDuration = new FloatOptionItem(67_223_006, "FFA_ShieldDuration", new(1f, 70f, 1f), 7f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA) .SetColor(new Color32(0, 255, 165, byte.MaxValue)) .SetValueFormat(OptionFormat.Seconds); + FFAIncreasedSpeed = new FloatOptionItem(67_223_007, "FFA_IncreasedSpeed", new(0.1f, 5f, 0.1f), 1.5f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA) .SetColor(new Color32(0, 255, 165, byte.MaxValue)) .SetValueFormat(OptionFormat.Multiplier); + FFADecreasedSpeed = new FloatOptionItem(67_223_008, "FFA_DecreasedSpeed", new(0.1f, 5f, 0.1f), 1f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA) .SetColor(new Color32(0, 255, 165, byte.MaxValue)) .SetValueFormat(OptionFormat.Multiplier); + FFAModifiedSpeedDuration = new FloatOptionItem(67_223_009, "FFA_ModifiedSpeedDuration", new(1f, 60f, 1f), 10f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA).SetColor(new Color32(0, 255, 165, byte.MaxValue)) .SetValueFormat(OptionFormat.Seconds); + FFALowerVision = new FloatOptionItem(67_223_010, "FFA_LowerVision", new(0f, 1f, 0.05f), 0.5f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA).SetColor(new Color32(0, 255, 165, byte.MaxValue)) .SetValueFormat(OptionFormat.Multiplier); + FFAModifiedVisionDuration = new FloatOptionItem(67_223_011, "FFA_ModifiedVisionDuration", new(1f, 70f, 1f), 5f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA).SetColor(new Color32(0, 255, 165, byte.MaxValue)) .SetValueFormat(OptionFormat.Seconds); + FFAEnableRandomTwists = new BooleanOptionItem(67_223_012, "FFA_EnableRandomTwists", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA) .SetColor(new Color32(0, 255, 165, byte.MaxValue)); + FFAShieldIsOneTimeUse = new BooleanOptionItem(67_223_013, "FFA_ShieldIsOneTimeUse", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA) .SetColor(new Color32(0, 255, 165, byte.MaxValue)); + FFAChatDuringGame = new BooleanOptionItem(67_223_014, "FFA_ChatDuringGame", false, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA) .SetColor(new Color32(0, 255, 165, byte.MaxValue)); + FFATeamMode = new BooleanOptionItem(67_223_015, "FFA_TeamMode", false, TabGroup.GameSettings) .SetGameMode(CustomGameMode.FFA) .SetHeader(true) .SetColor(new Color32(0, 255, 165, byte.MaxValue)); + FFATeamNumber = new IntegerOptionItem(67_223_016, "FFA_TeamNumber", new(2, 8, 1), 2, TabGroup.GameSettings) .SetParent(FFATeamMode) .SetGameMode(CustomGameMode.FFA) @@ -115,10 +130,7 @@ namespace EHR public static void Init() { - if (Options.CurrentGameMode != CustomGameMode.FFA) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.FFA) return; FFADecreasedSpeedList = []; FFAIncreasedSpeedList = []; @@ -132,15 +144,9 @@ namespace EHR PlayerTeams = []; PlayerControl[] allPlayers = Main.AllAlivePlayerControls; - if (Main.GM.Value && AmongUsClient.Instance.AmHost) - { - allPlayers = allPlayers.Without(PlayerControl.LocalPlayer).ToArray(); - } + if (Main.GM.Value && AmongUsClient.Instance.AmHost) allPlayers = allPlayers.Without(PlayerControl.LocalPlayer).ToArray(); - foreach (PlayerControl pc in allPlayers) - { - KillCount[pc.PlayerId] = 0; - } + foreach (PlayerControl pc in allPlayers) KillCount[pc.PlayerId] = 0; if (FFATeamMode.GetBool()) { @@ -149,13 +155,9 @@ namespace EHR int memberNum = (teamNum > 5 && playerNum >= 15) || playerNum % teamNum == 0 ? playerNum / teamNum : (playerNum / teamNum) + 1; List teamMembers = allPlayers.Select(x => x.PlayerId).Shuffle().Chunk(memberNum).ToList(); - for (int i = 0; i < teamMembers.Count; i++) - { + for (var i = 0; i < teamMembers.Count; i++) foreach (byte id in teamMembers[i]) - { PlayerTeams.Add(id, i); - } - } LateTask.New(() => Utils.NotifyRoles(NoCache: true, ForceLoop: true), 10f, log: false); } @@ -183,10 +185,7 @@ namespace EHR public static void OnPlayerAttack(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null || Options.CurrentGameMode != CustomGameMode.FFA) - { - return; - } + if (killer == null || target == null || Options.CurrentGameMode != CustomGameMode.FFA) return; if (target.inVent) { @@ -201,10 +200,12 @@ namespace EHR } int totalalive = Main.AllAlivePlayerControls.Length; + if (FFAShieldedList.TryGetValue(target.PlayerId, out long dur)) { killer.Notify(GetString("FFA_TargetIsShielded")); Logger.Info($"{killer.GetRealName().RemoveHtmlTags()} attacked shielded player {target.GetRealName().RemoveHtmlTags()}, their shield expires in {FFAShieldDuration.GetInt() - (Utils.TimeStamp - dur)}s", "FFA"); + if (FFAShieldIsOneTimeUse.GetBool()) { FFAShieldedList.Remove(target.PlayerId); @@ -220,6 +221,7 @@ namespace EHR if (totalalive == 3) { PlayerControl otherPC = null; + foreach (PlayerControl pc in Main.AllAlivePlayerControls.Where(a => a.PlayerId != killer.PlayerId && a.PlayerId != target.PlayerId && a.IsAlive())) { TargetArrow.Add(killer.PlayerId, pc.PlayerId); @@ -232,29 +234,23 @@ namespace EHR if (FFAEnableRandomAbilities.GetBool()) { - bool sync = false; - bool mark = false; + var sync = false; + var mark = false; float nowKCD = Main.AllPlayerKillCooldown[killer.PlayerId]; byte EffectType; + if (Main.NormalOptions.MapId != 4) - { EffectType = (byte)IRandom.Instance.Next(0, 10); - } else - { EffectType = (byte)IRandom.Instance.Next(4, 10); - } switch (EffectType) { // Buff case <= 7: { - byte EffectID = (byte)IRandom.Instance.Next(0, 3); - if (Main.NormalOptions.MapId == 4) - { - EffectID = 2; - } + var EffectID = (byte)IRandom.Instance.Next(0, 3); + if (Main.NormalOptions.MapId == 4) EffectID = 2; switch (EffectID) { @@ -295,11 +291,8 @@ namespace EHR // De-Buff case 8: { - byte EffectID = (byte)IRandom.Instance.Next(0, 3); - if (Main.NormalOptions.MapId == 4) - { - EffectID = 1; - } + var EffectID = (byte)IRandom.Instance.Next(0, 3); + if (Main.NormalOptions.MapId == 4) EffectID = 1; switch (EffectID) { @@ -352,10 +345,7 @@ namespace EHR killer.SyncSettings(); } - if (mark) - { - killer.MarkDirtySettings(); - } + if (mark) killer.MarkDirtySettings(); } killer.Kill(target); @@ -363,38 +353,23 @@ namespace EHR private static void OnPlayerKill(PlayerControl killer) { - if (PlayerControl.LocalPlayer.Is(CustomRoles.GM)) - { - PlayerControl.LocalPlayer.KillFlash(); - } + if (PlayerControl.LocalPlayer.Is(CustomRoles.GM)) PlayerControl.LocalPlayer.KillFlash(); KillCount[killer.PlayerId]++; } public static string GetPlayerArrow(PlayerControl seer, PlayerControl target = null) { - if (GameStates.IsMeeting) - { - return string.Empty; - } + if (GameStates.IsMeeting) return string.Empty; - if (target != null && seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (target != null && seer.PlayerId != target.PlayerId) return string.Empty; - if (Main.AllAlivePlayerControls.Length != 2) - { - return string.Empty; - } + if (Main.AllAlivePlayerControls.Length != 2) return string.Empty; - string arrows = string.Empty; + var arrows = string.Empty; PlayerControl otherPlayer = Main.AllAlivePlayerControls.FirstOrDefault(pc => pc.IsAlive() && pc.PlayerId != seer.PlayerId); - if (otherPlayer == null) - { - return string.Empty; - } + if (otherPlayer == null) return string.Empty; string arrow = TargetArrow.GetArrows(seer, otherPlayer.PlayerId); arrows += Utils.ColorString(Utils.GetRoleColor(CustomRoles.Killer), arrow); @@ -405,10 +380,7 @@ namespace EHR public static void UpdateLastChatMessage(string playerName, string message) { LatestChatMessage = string.Format(GetString("FFAChatMessageNotify"), playerName, message); - foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { - pc.Notify(LatestChatMessage); - } + foreach (PlayerControl pc in Main.AllAlivePlayerControls) pc.Notify(LatestChatMessage); } [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.FixedUpdate))] @@ -419,24 +391,18 @@ namespace EHR [SuppressMessage("ReSharper", "UnusedMember.Local")] public static void Postfix() { - if (!GameStates.IsInTask || ExileController.Instance || Options.CurrentGameMode != CustomGameMode.FFA || !AmongUsClient.Instance.AmHost) - { - return; - } + if (!GameStates.IsInTask || ExileController.Instance || Options.CurrentGameMode != CustomGameMode.FFA || !AmongUsClient.Instance.AmHost) return; long now = Utils.TimeStamp; - if (LastFixedUpdate == now) - { - return; - } + if (LastFixedUpdate == now) return; LastFixedUpdate = now; RoundTime--; - IRandom rd = IRandom.Instance; - byte FFAdoTPdecider = (byte)rd.Next(0, 100); + var rd = IRandom.Instance; + var FFAdoTPdecider = (byte)rd.Next(0, 100); bool FFAdoTP = FFAdoTPdecider == 0; if (FFAEnableRandomTwists.GetBool() && FFAdoTP) @@ -447,24 +413,16 @@ namespace EHR foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (changePositionPlayers.Contains(pc.PlayerId) || !pc.IsAlive() || pc.onLadder || pc.inVent || pc.inMovingPlat) - { - continue; - } + if (changePositionPlayers.Contains(pc.PlayerId) || !pc.IsAlive() || pc.onLadder || pc.inVent || pc.inMovingPlat) continue; PlayerControl[] filtered = Main.AllAlivePlayerControls.Where(a => pc.IsAlive() && !pc.inVent && a.PlayerId != pc.PlayerId && !changePositionPlayers.Contains(a.PlayerId)).ToArray(); - if (filtered.Length == 0) - { - break; - } + + if (filtered.Length == 0) break; PlayerControl target = filtered.RandomElement(); - if (pc.inVent || target.inVent) - { - continue; - } + if (pc.inVent || target.inVent) continue; changePositionPlayers.Add(target.PlayerId); changePositionPlayers.Add(pc.PlayerId); @@ -482,19 +440,13 @@ namespace EHR changePositionPlayers.Clear(); } - if (Main.NormalOptions.MapId == 4) - { - return; - } + if (Main.NormalOptions.MapId == 4) return; foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (pc == null) - { - return; - } + if (pc == null) return; - bool sync = false; + var sync = false; if (FFADecreasedSpeedList.TryGetValue(pc.PlayerId, out long dstime) && dstime + FFAModifiedSpeedDuration.GetInt() < now) { @@ -527,10 +479,7 @@ namespace EHR FFAShieldedList.Remove(pc.PlayerId); } - if (sync) - { - pc.MarkDirtySettings(); - } + if (sync) pc.MarkDirtySettings(); } } } diff --git a/GameMode/HideAndSeekRoles/Agent.cs b/GameMode/HideAndSeekRoles/Agent.cs index 0bad56aa8..0236bec4a 100644 --- a/GameMode/HideAndSeekRoles/Agent.cs +++ b/GameMode/HideAndSeekRoles/Agent.cs @@ -17,11 +17,13 @@ public override void SetupCustomOption() { Options.SetupRoleOptions(69_211_2001, TabGroup.ImpostorRoles, CustomRoles.Agent, CustomGameMode.HideAndSeek); + Vision = new FloatOptionItem(69_211_2003, "AgentVision", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(255, 143, 143, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Agent]); + Speed = new FloatOptionItem(69_213_2004, "AgentSpeed", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) diff --git a/GameMode/HideAndSeekRoles/Dasher.cs b/GameMode/HideAndSeekRoles/Dasher.cs index bea57a35f..1a403f555 100644 --- a/GameMode/HideAndSeekRoles/Dasher.cs +++ b/GameMode/HideAndSeekRoles/Dasher.cs @@ -25,31 +25,37 @@ namespace EHR.GameMode.HideAndSeekRoles public override void SetupCustomOption() { Options.SetupRoleOptions(69_211_801, TabGroup.ImpostorRoles, CustomRoles.Dasher, CustomGameMode.HideAndSeek); + Vision = new FloatOptionItem(69_211_803, "DasherVision", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(245, 66, 176, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Dasher]); + Speed = new FloatOptionItem(69_213_804, "DasherSpeed", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(245, 66, 176, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Dasher]); + DashCooldown = new FloatOptionItem(69_213_805, "DasherCooldown", new(0f, 60f, 0.5f), 20f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(245, 66, 176, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Dasher]); + DashDuration = new FloatOptionItem(69_213_806, "DasherDuration", new(1f, 30f, 1f), 5f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(245, 66, 176, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Dasher]); + DashSpeed = new FloatOptionItem(69_213_807, "DasherSpeedIncreased", new(0.05f, 5f, 0.05f), 1.5f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(245, 66, 176, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Dasher]); + UseLimit = new IntegerOptionItem(69_213_808, "AbilityUseLimit", new(0, 60, 1), 3, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetColor(new(245, 66, 176, byte.MaxValue)) @@ -60,6 +66,7 @@ namespace EHR.GameMode.HideAndSeekRoles { On = true; playerId.SetAbilityUseLimit(UseLimit.GetFloat()); + DashStatus = new() { Cooldown = DashCooldown.GetInt(), @@ -84,12 +91,10 @@ namespace EHR.GameMode.HideAndSeekRoles public override void OnFixedUpdate(PlayerControl pc) { - if (!DashStatus.IsDashing) - { - return; - } + if (!DashStatus.IsDashing) return; long now = Utils.TimeStamp; + if (DashStatus.DashEndTime <= now) { DashStatus.IsDashing = false; @@ -99,10 +104,7 @@ namespace EHR.GameMode.HideAndSeekRoles public override void OnPet(PlayerControl pc) { - if (pc.HasAbilityCD() || DashStatus.IsDashing || pc.GetAbilityUseLimit() < 1f) - { - return; - } + if (pc.HasAbilityCD() || DashStatus.IsDashing || pc.GetAbilityUseLimit() < 1f) return; DashStatus.IsDashing = true; DashStatus.DashEndTime = Utils.TimeStamp + DashStatus.Duration; diff --git a/GameMode/HideAndSeekRoles/Detector.cs b/GameMode/HideAndSeekRoles/Detector.cs index 121611450..9665bba0a 100644 --- a/GameMode/HideAndSeekRoles/Detector.cs +++ b/GameMode/HideAndSeekRoles/Detector.cs @@ -22,16 +22,19 @@ namespace EHR.GameMode.HideAndSeekRoles public override void SetupCustomOption() { Options.SetupRoleOptions(69_211_601, TabGroup.CrewmateRoles, CustomRoles.Detector, CustomGameMode.HideAndSeek); + Vision = new FloatOptionItem(69_211_603, "DetectorVision", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(66, 221, 245, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Detector]); + Speed = new FloatOptionItem(69_213_604, "DetectorSpeed", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(66, 221, 245, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Detector]); + InfoFrequency = new IntegerOptionItem(69_213_605, "DetectorFrequency", new(0, 60, 1), 20, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) @@ -52,15 +55,14 @@ namespace EHR.GameMode.HideAndSeekRoles public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive()) - { - return; - } + if (!pc.IsAlive()) return; long now = Utils.TimeStamp; + if (LastInfoTime + InfoFrequency.GetInt() <= now) { PlayerControl[] imps = HnSManager.PlayerRoles.Where(x => x.Value.Interface.Team == Team.Impostor).Select(x => Utils.GetPlayerById(x.Key)).Where(x => x != null && x.GetPlainShipRoom() != null).ToArray(); + if (imps.Length > 0) { PlayerControl imp = imps.RandomElement(); diff --git a/GameMode/HideAndSeekRoles/Fox.cs b/GameMode/HideAndSeekRoles/Fox.cs index bda3b4560..9579a429f 100644 --- a/GameMode/HideAndSeekRoles/Fox.cs +++ b/GameMode/HideAndSeekRoles/Fox.cs @@ -17,11 +17,13 @@ public override void SetupCustomOption() { Options.SetupRoleOptions(69_211_301, TabGroup.NeutralRoles, CustomRoles.Fox, CustomGameMode.HideAndSeek); + Vision = new FloatOptionItem(69_211_303, "FoxVision", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.NeutralRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(0, 255, 0, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Fox]); + Speed = new FloatOptionItem(69_213_304, "FoxSpeed", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.NeutralRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) diff --git a/GameMode/HideAndSeekRoles/Hider.cs b/GameMode/HideAndSeekRoles/Hider.cs index d754cb3da..7ae7cc7d2 100644 --- a/GameMode/HideAndSeekRoles/Hider.cs +++ b/GameMode/HideAndSeekRoles/Hider.cs @@ -30,26 +30,32 @@ .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(52, 94, 235, byte.MaxValue)); + Speed = new FloatOptionItem(69_211_102, "HiderSpeed", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(52, 94, 235, byte.MaxValue)); + TimeDecreaseOnShortTaskComplete = new IntegerOptionItem(69_211_103, "TimeDecreaseOnShortTaskComplete", new(0, 60, 1), 5, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(52, 94, 235, byte.MaxValue)); + TimeDecreaseOnCommonTaskComplete = new IntegerOptionItem(69_211_104, "TimeDecreaseOnCommonTaskComplete", new(0, 60, 1), 10, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(52, 94, 235, byte.MaxValue)); + TimeDecreaseOnLongTaskComplete = new IntegerOptionItem(69_211_105, "TimeDecreaseOnLongTaskComplete", new(0, 60, 1), 15, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(52, 94, 235, byte.MaxValue)); + TimeDecreaseOnSituationalTaskComplete = new IntegerOptionItem(69_211_106, "TimeDecreaseOnSituationalTaskComplete", new(0, 60, 1), 20, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(52, 94, 235, byte.MaxValue)); + TimeDecreaseOnOtherTaskComplete = new IntegerOptionItem(69_211_107, "TimeDecreaseOnOtherTaskComplete", new(0, 60, 1), 5, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) @@ -81,10 +87,7 @@ HnSManager.TimeLeft -= time; pc.Notify(string.Format(Translator.GetString("TimeDecreased"), time)); - if (60 - (HnSManager.TimeLeft % 60) <= time) - { - Utils.NotifyRoles(); - } + if (60 - (HnSManager.TimeLeft % 60) <= time) Utils.NotifyRoles(); } } } \ No newline at end of file diff --git a/GameMode/HideAndSeekRoles/Jet.cs b/GameMode/HideAndSeekRoles/Jet.cs index 8ea2ed255..48429e5aa 100644 --- a/GameMode/HideAndSeekRoles/Jet.cs +++ b/GameMode/HideAndSeekRoles/Jet.cs @@ -25,31 +25,37 @@ namespace EHR.GameMode.HideAndSeekRoles public override void SetupCustomOption() { Options.SetupRoleOptions(69_211_701, TabGroup.CrewmateRoles, CustomRoles.Jet, CustomGameMode.HideAndSeek); + Vision = new FloatOptionItem(69_211_703, "JetVision", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(66, 245, 75, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Jet]); + Speed = new FloatOptionItem(69_213_704, "JetSpeed", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(66, 245, 75, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Jet]); + DashCooldown = new FloatOptionItem(69_213_705, "JetCooldown", new(0f, 60f, 0.5f), 20f, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(66, 245, 75, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Jet]); + DashDuration = new FloatOptionItem(69_213_706, "JetDuration", new(1f, 30f, 1f), 5f, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(66, 245, 75, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Jet]); + DashSpeed = new FloatOptionItem(69_213_707, "JetSpeedIncreased", new(0.05f, 5f, 0.05f), 1.5f, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(66, 245, 75, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Jet]); + UseLimit = new IntegerOptionItem(69_213_708, "AbilityUseLimit", new(0, 60, 1), 3, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetColor(new(66, 245, 75, byte.MaxValue)) @@ -60,6 +66,7 @@ namespace EHR.GameMode.HideAndSeekRoles { On = true; playerId.SetAbilityUseLimit(UseLimit.GetFloat()); + DashStatus = new() { Cooldown = DashCooldown.GetInt(), @@ -79,10 +86,7 @@ namespace EHR.GameMode.HideAndSeekRoles public override void OnPet(PlayerControl pc) { - if (pc.HasAbilityCD() || DashStatus.IsDashing || pc.GetAbilityUseLimit() < 1f) - { - return; - } + if (pc.HasAbilityCD() || DashStatus.IsDashing || pc.GetAbilityUseLimit() < 1f) return; DashStatus.IsDashing = true; DashStatus.DashEndTime = Utils.TimeStamp + DashStatus.Duration; @@ -93,12 +97,10 @@ namespace EHR.GameMode.HideAndSeekRoles public override void OnFixedUpdate(PlayerControl pc) { - if (!DashStatus.IsDashing) - { - return; - } + if (!DashStatus.IsDashing) return; long now = Utils.TimeStamp; + if (DashStatus.DashEndTime <= now) { DashStatus.IsDashing = false; diff --git a/GameMode/HideAndSeekRoles/Jumper.cs b/GameMode/HideAndSeekRoles/Jumper.cs index 1f036c578..6272d113c 100644 --- a/GameMode/HideAndSeekRoles/Jumper.cs +++ b/GameMode/HideAndSeekRoles/Jumper.cs @@ -22,26 +22,31 @@ namespace EHR.GameMode.HideAndSeekRoles public override void SetupCustomOption() { Options.SetupRoleOptions(69_211_501, TabGroup.CrewmateRoles, CustomRoles.Jumper, CustomGameMode.HideAndSeek); + Vision = new FloatOptionItem(69_211_503, "JumperVision", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(221, 245, 66, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Jumper]); + Speed = new FloatOptionItem(69_213_504, "JumperSpeed", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(221, 245, 66, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Jumper]); + VentCooldown = new FloatOptionItem(69_213_505, "VentCooldown", new(0f, 60f, 0.5f), 20f, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(221, 245, 66, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Jumper]); + MaxInVentTime = new FloatOptionItem(69_213_506, "MaxInVentTime", new(0f, 60f, 0.5f), 3f, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(221, 245, 66, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Jumper]); + UseLimit = new IntegerOptionItem(69_213_507, "AbilityUseLimit", new(0, 60, 1), 3, TabGroup.CrewmateRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetColor(new(221, 245, 66, byte.MaxValue)) @@ -68,13 +73,9 @@ namespace EHR.GameMode.HideAndSeekRoles public override void OnCoEnterVent(PlayerPhysics physics, int ventId) { if (physics.myPlayer.GetAbilityUseLimit() < 1f) - { LateTask.New(() => { physics.RpcBootFromVent(ventId); }, 0.5f, "Jumper no uses boot from vent"); - } else - { physics.myPlayer.RpcRemoveAbilityUse(); - } } } } \ No newline at end of file diff --git a/GameMode/HideAndSeekRoles/Locator.cs b/GameMode/HideAndSeekRoles/Locator.cs index 269ad4564..a05cd63b5 100644 --- a/GameMode/HideAndSeekRoles/Locator.cs +++ b/GameMode/HideAndSeekRoles/Locator.cs @@ -25,26 +25,31 @@ namespace EHR.GameMode.HideAndSeekRoles public override void SetupCustomOption() { Options.SetupRoleOptions(69_211_901, TabGroup.ImpostorRoles, CustomRoles.Locator, CustomGameMode.HideAndSeek); + Vision = new FloatOptionItem(69_211_903, "LocatorVision", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(245, 158, 66, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Locator]); + Speed = new FloatOptionItem(69_213_904, "LocatorSpeed", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(245, 158, 66, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Locator]); + ArrowFrequency = new IntegerOptionItem(69_213_905, "LocatorFrequency", new(0, 60, 1), 20, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(245, 158, 66, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Locator]); + ArrowDuration = new FloatOptionItem(69_213_906, "LocatorDuration", new(1f, 30f, 1f), 5f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(245, 158, 66, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Locator]); + HidersKnowTheyAreLocated = new BooleanOptionItem(69_213_907, "LocatorTargetKnows", true, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetColor(new(245, 158, 66, byte.MaxValue)) @@ -65,26 +70,21 @@ namespace EHR.GameMode.HideAndSeekRoles public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive()) - { - return; - } + if (!pc.IsAlive()) return; if (Status.TargetId == byte.MaxValue) { if (Status.LastArrowEndTime + ArrowFrequency.GetInt() < Utils.TimeStamp) { PlayerControl target = HnSManager.PlayerRoles.Where(x => x.Value.Interface.Team != Team.Impostor).Select(x => Utils.GetPlayerById(x.Key)).Where(x => x != null && x.IsAlive()).Shuffle().FirstOrDefault(); + if (target != null) { Status.TargetId = target.PlayerId; Status.LastArrowEndTime = Utils.TimeStamp + ArrowDuration.GetInt(); TargetArrow.Add(pc.PlayerId, target.PlayerId); Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - if (HidersKnowTheyAreLocated.GetBool()) - { - target.Notify(Translator.GetString("LocatorNotify")); - } + if (HidersKnowTheyAreLocated.GetBool()) target.Notify(Translator.GetString("LocatorNotify")); } } } @@ -98,10 +98,7 @@ namespace EHR.GameMode.HideAndSeekRoles public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || hud || seer.PlayerId != LocatorId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || hud || seer.PlayerId != LocatorId) return string.Empty; return Status.TargetId == byte.MaxValue ? string.Empty : TargetArrow.GetArrows(seer, Status.TargetId); } diff --git a/GameMode/HideAndSeekRoles/Seeker.cs b/GameMode/HideAndSeekRoles/Seeker.cs index 78c8e4207..1c44694a7 100644 --- a/GameMode/HideAndSeekRoles/Seeker.cs +++ b/GameMode/HideAndSeekRoles/Seeker.cs @@ -28,17 +28,21 @@ .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(255, 25, 25, byte.MaxValue)); + Speed = new FloatOptionItem(69_211_202, "SeekerSpeed", new(0.05f, 5f, 0.05f), 1.5f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(255, 25, 25, byte.MaxValue)); + CanVent = new BooleanOptionItem(69_211_204, "CanVent", false, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetColor(new(255, 25, 25, byte.MaxValue)); + BlindTime = new FloatOptionItem(69_211_206, "BlindTime", new(0f, 60f, 1f), 10f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) .SetColor(new(255, 25, 25, byte.MaxValue)); + KillCooldown = new IntegerOptionItem(69_211_207, "KillCooldown", new(0, 60, 1), 10, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Seconds) diff --git a/GameMode/HideAndSeekRoles/Taskinator.cs b/GameMode/HideAndSeekRoles/Taskinator.cs index 3efb3a898..2bcc3f20b 100644 --- a/GameMode/HideAndSeekRoles/Taskinator.cs +++ b/GameMode/HideAndSeekRoles/Taskinator.cs @@ -18,20 +18,24 @@ public override void SetupCustomOption() { Options.SetupRoleOptions(69_211_3001, TabGroup.NeutralRoles, CustomRoles.Taskinator, CustomGameMode.HideAndSeek); + Vision = new FloatOptionItem(69_211_3003, "TaskinatorVision", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.NeutralRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(86, 29, 209, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Taskinator]); + Speed = new FloatOptionItem(69_213_3004, "TaskinatorSpeed", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.NeutralRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(86, 29, 209, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Taskinator]); + CanWinWhenDead = new BooleanOptionItem(69_213_3005, "TaskinatorCanWinAfterDeath", true, TabGroup.NeutralRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetColor(new(86, 29, 209, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Taskinator]); + Options.OverrideTasksData.Create(69_213_3006, TabGroup.NeutralRoles, CustomRoles.Taskinator); } diff --git a/GameMode/HideAndSeekRoles/Troll.cs b/GameMode/HideAndSeekRoles/Troll.cs index 68110e67e..7d6db0bbb 100644 --- a/GameMode/HideAndSeekRoles/Troll.cs +++ b/GameMode/HideAndSeekRoles/Troll.cs @@ -17,11 +17,13 @@ public override void SetupCustomOption() { Options.SetupRoleOptions(69_211_401, TabGroup.NeutralRoles, CustomRoles.Troll, CustomGameMode.HideAndSeek); + Vision = new FloatOptionItem(69_211_403, "TrollVision", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.NeutralRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(255, 0, 255, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Troll]); + Speed = new FloatOptionItem(69_211_404, "TrollSpeed", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.NeutralRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) diff --git a/GameMode/HideAndSeekRoles/Venter.cs b/GameMode/HideAndSeekRoles/Venter.cs index 6b9ec7ba6..bf626341e 100644 --- a/GameMode/HideAndSeekRoles/Venter.cs +++ b/GameMode/HideAndSeekRoles/Venter.cs @@ -18,16 +18,19 @@ public override void SetupCustomOption() { Options.SetupRoleOptions(69_211_1001, TabGroup.ImpostorRoles, CustomRoles.Venter, CustomGameMode.HideAndSeek); + Vision = new FloatOptionItem(69_211_1003, "VenterVision", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(105, 65, 65, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Venter]); + Speed = new FloatOptionItem(69_213_1004, "VenterSpeed", new(0.05f, 5f, 0.05f), 1.25f, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new(105, 65, 65, byte.MaxValue)) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Venter]); + UseLimit = new IntegerOptionItem(69_213_1007, "AbilityUseLimit", new(0, 60, 1), 3, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.HideAndSeek) .SetColor(new(105, 65, 65, byte.MaxValue)) @@ -53,13 +56,9 @@ public override void OnCoEnterVent(PlayerPhysics physics, int ventId) { if (physics.myPlayer.GetAbilityUseLimit() < 1f) - { LateTask.New(() => { physics.RpcBootFromVent(ventId); }, 0.5f, "Venter no uses boot from vent"); - } else - { physics.myPlayer.RpcRemoveAbilityUse(); - } } } } \ No newline at end of file diff --git a/GameMode/HnSManager.cs b/GameMode/HnSManager.cs index 76737adf1..e8a9b5778 100644 --- a/GameMode/HnSManager.cs +++ b/GameMode/HnSManager.cs @@ -44,6 +44,7 @@ namespace EHR MinNeutrals = new IntegerOptionItem(id + 1, "HNS.MinNeutrals", new(0, 13, 1), 0, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HideAndSeek) .SetColor(color); + MaxNeutrals = new IntegerOptionItem(id + 2, "HNS.MaxNeutrals", new(0, 13, 1), 2, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HideAndSeek) .SetColor(color); @@ -84,6 +85,7 @@ namespace EHR Main.AllPlayerKillCooldown.SetAllValues(Seeker.KillCooldown.GetFloat()); IsBlindTime = true; Utils.MarkEveryoneDirtySettingsV4(); + LateTask.New(() => { IsBlindTime = false; @@ -134,6 +136,7 @@ namespace EHR [Team.Neutral] = IRandom.Instance.Next(MinNeutrals.GetInt(), MaxNeutrals.GetInt() + 1), [Team.Impostor] = SeekerNum }; + memberNum[Team.Crewmate] = allPlayers.Count - memberNum.Values.Sum(); Logger.Warn($"Number of impostors: {memberNum[Team.Impostor]}", "HnsRoleAssigner"); @@ -143,10 +146,7 @@ namespace EHR try { PlayerControl pc = allPlayers.FirstOrDefault(x => x.PlayerId == item.Key); - if (pc == null) - { - continue; - } + if (pc == null) continue; result[pc] = item.Value; allPlayers.Remove(pc); @@ -171,19 +171,13 @@ namespace EHR .GroupBy(x => x.First, x => x.Second) .ToDictionary(x => x.Key, x => x.ToArray()); - if (memberNum[Team.Neutral] > 0 && HideAndSeekRoles.TryGetValue(Team.Neutral, out Dictionary neutrals)) - { - HideAndSeekRoles[Team.Neutral] = neutrals.Shuffle().ToDictionary(x => x.Key, x => x.Value); - } + if (memberNum[Team.Neutral] > 0 && HideAndSeekRoles.TryGetValue(Team.Neutral, out Dictionary neutrals)) HideAndSeekRoles[Team.Neutral] = neutrals.Shuffle().ToDictionary(x => x.Key, x => x.Value); foreach ((Team team, Dictionary roleCounts) in HideAndSeekRoles) { try { - if (playerTeams[team].Length == 0 || memberNum[team] <= 0) - { - continue; - } + if (playerTeams[team].Length == 0 || memberNum[team] <= 0) continue; } catch (KeyNotFoundException) { @@ -192,41 +186,29 @@ namespace EHR foreach ((CustomRoles role, int count) in roleCounts) { - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { try { PlayerControl pc = playerTeams[team][0]; - if (pc == null) - { - continue; - } + if (pc == null) continue; result[pc] = role; allPlayers.Remove(pc); playerTeams[team] = playerTeams[team][1..]; memberNum[team]--; - if (memberNum[team] <= 0) - { - break; - } + if (memberNum[team] <= 0) break; } catch (Exception e) { - if (e is IndexOutOfRangeException) - { - break; - } + if (e is IndexOutOfRangeException) break; Utils.ThrowException(e); } } - if (playerTeams[team].Length == 0 || memberNum[team] <= 0) - { - break; - } + if (playerTeams[team].Length == 0 || memberNum[team] <= 0) break; } } @@ -238,10 +220,7 @@ namespace EHR allPlayers.Remove(pc); } - if (allPlayers.Count > 0) - { - Logger.Error($"Some players were not assigned a role: {allPlayers.Join(x => x.GetRealName())}", "HnsRoleAssigner"); - } + if (allPlayers.Count > 0) Logger.Error($"Some players were not assigned a role: {allPlayers.Join(x => x.GetRealName())}", "HnsRoleAssigner"); Logger.Msg($"Roles: {result.Join(x => $"{x.Key.GetRealName()} => {x.Value}")}", "HnsRoleAssigner"); @@ -250,6 +229,7 @@ namespace EHR .Select(x => (IHideAndSeekRole)Activator.CreateInstance(x)) .Where(x => x != null) .ToDictionary(x => x.GetType().Name, x => x); + PlayerRoles = result.ToDictionary(x => x.Key.PlayerId, x => (roleInterfaces[x.Value.ToString()], x.Value)); LateTask.New(() => result.IntersectBy(Main.PlayerStates.Keys, x => x.Key.PlayerId).Do(x => x.Key.RpcSetCustomRole(x.Value)), 5f, log: false); @@ -275,28 +255,16 @@ namespace EHR public static bool KnowTargetRoleColor(PlayerControl seer, PlayerControl target, ref string color) { - if (seer.PlayerId == target.PlayerId) - { - return true; - } + if (seer.PlayerId == target.PlayerId) return true; - if (!PlayerRoles.TryGetValue(target.PlayerId, out (IHideAndSeekRole Interface, CustomRoles Role) targetRole)) - { - return false; - } + if (!PlayerRoles.TryGetValue(target.PlayerId, out (IHideAndSeekRole Interface, CustomRoles Role) targetRole)) return false; - if (!PlayerRoles.TryGetValue(seer.PlayerId, out (IHideAndSeekRole Interface, CustomRoles Role) seerRole)) - { - return false; - } + if (!PlayerRoles.TryGetValue(seer.PlayerId, out (IHideAndSeekRole Interface, CustomRoles Role) seerRole)) return false; if (PlayersSeeRoles.GetBool()) { color = Main.RoleColors[targetRole.Role]; - if (targetRole.Role == CustomRoles.Agent) - { - color = Main.RoleColors[CustomRoles.Hider]; - } + if (targetRole.Role == CustomRoles.Agent) color = Main.RoleColors[CustomRoles.Hider]; return true; } @@ -312,50 +280,29 @@ namespace EHR public static bool HasTasks(NetworkedPlayerInfo playerInfo) { - if (!AmongUsClient.Instance.AmHost && playerInfo.PlayerId == PlayerControl.LocalPlayer.PlayerId) - { - return PlayerControl.LocalPlayer.GetCustomRole() is CustomRoles.Taskinator or CustomRoles.Hider or CustomRoles.Jet or CustomRoles.Detector or CustomRoles.Jumper; - } + if (!AmongUsClient.Instance.AmHost && playerInfo.PlayerId == PlayerControl.LocalPlayer.PlayerId) return PlayerControl.LocalPlayer.GetCustomRole() is CustomRoles.Taskinator or CustomRoles.Hider or CustomRoles.Jet or CustomRoles.Detector or CustomRoles.Jumper; - if (!PlayerRoles.TryGetValue(playerInfo.PlayerId, out (IHideAndSeekRole Interface, CustomRoles Role) role)) - { - return false; - } + if (!PlayerRoles.TryGetValue(playerInfo.PlayerId, out (IHideAndSeekRole Interface, CustomRoles Role) role)) return false; return role.Interface.Team == Team.Crewmate || role.Role == CustomRoles.Taskinator; } public static bool IsRoleTextEnabled(PlayerControl seer, PlayerControl target) { - if (seer.PlayerId == target.PlayerId || PlayersSeeRoles.GetBool()) - { - return true; - } + if (seer.PlayerId == target.PlayerId || PlayersSeeRoles.GetBool()) return true; - if (!PlayerRoles.TryGetValue(target.PlayerId, out (IHideAndSeekRole Interface, CustomRoles Role) targetRole)) - { - return false; - } + if (!PlayerRoles.TryGetValue(target.PlayerId, out (IHideAndSeekRole Interface, CustomRoles Role) targetRole)) return false; - if (!PlayerRoles.TryGetValue(seer.PlayerId, out (IHideAndSeekRole Interface, CustomRoles Role) seerRole)) - { - return false; - } + if (!PlayerRoles.TryGetValue(seer.PlayerId, out (IHideAndSeekRole Interface, CustomRoles Role) seerRole)) return false; return targetRole.Interface.Team == Team.Impostor && (targetRole.Role != CustomRoles.Agent || seerRole.Interface.Team == Team.Impostor); } public static string GetSuffixText(PlayerControl seer, PlayerControl target, bool hud = false) { - if (GameStates.IsLobby || Options.CurrentGameMode != CustomGameMode.HideAndSeek || Main.HasJustStarted) - { - return string.Empty; - } + if (GameStates.IsLobby || Options.CurrentGameMode != CustomGameMode.HideAndSeek || Main.HasJustStarted) return string.Empty; - if (seer.PlayerId != target.PlayerId || (seer.IsHost() && !hud) || TimeLeft < 0) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || (seer.IsHost() && !hud) || TimeLeft < 0) return string.Empty; string dangerMeter = GetDangerMeter(seer); @@ -365,10 +312,7 @@ namespace EHR dangerMeter += TargetArrow.GetArrows(seer, agent); } - if (TimeLeft <= 60) - { - return $"{dangerMeter}\n{Translator.GetString("TimeLeft")}: {TimeLeft}s"; - } + if (TimeLeft <= 60) return $"{dangerMeter}\n{Translator.GetString("TimeLeft")}: {TimeLeft}s"; int minutes = TimeLeft / 60; int seconds = TimeLeft % 60; @@ -446,15 +390,14 @@ namespace EHR public static void AddFoxesToWinners() { List foxes = Main.PlayerStates.Where(x => x.Value.MainRole == CustomRoles.Fox).Select(x => x.Key).ToList(); + foxes.RemoveAll(x => { PlayerControl pc = Utils.GetPlayerById(x); return pc == null || !pc.IsAlive(); }); - if (foxes.Count == 0) - { - return; - } + + if (foxes.Count == 0) return; CustomWinnerHolder.AdditionalWinnerTeams.Add(AdditionalWinners.Fox); CustomWinnerHolder.WinnerIds.UnionWith(foxes); @@ -474,20 +417,13 @@ namespace EHR bool alive = !state.Value.IsDead; TaskState ts = state.Value.TaskState; - string stateText = string.Empty; - if (PlayersSeeRoles.GetBool()) - { - stateText = $" ({GetRole().ToColoredString()}){GetTaskCount()}"; - } - else if (isSeeker) - { - stateText = $" ({CustomRoles.Seeker.ToColoredString()})"; - } + var stateText = string.Empty; - if (!alive) - { - stateText += $" {Translator.GetString("Dead")}"; - } + if (PlayersSeeRoles.GetBool()) + stateText = $" ({GetRole().ToColoredString()}){GetTaskCount()}"; + else if (isSeeker) stateText = $" ({CustomRoles.Seeker.ToColoredString()})"; + + if (!alive) stateText += $" {Translator.GetString("Dead")}"; stateText = $"{name}{stateText}"; return stateText; @@ -507,6 +443,7 @@ namespace EHR { StringBuilder sb = new(); bool flag = PlayerControl.LocalPlayer.Data.Role != null && PlayerControl.LocalPlayer.Data.Role.IsImpostor; + foreach (PlayerTask task in PlayerControl.LocalPlayer.myTasks) { if (task != null) @@ -528,10 +465,7 @@ namespace EHR public static void OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null || PlayerRoles[killer.PlayerId].Interface.Team != Team.Impostor || PlayerRoles[target.PlayerId].Interface.Team == Team.Impostor) - { - return; - } + if (killer == null || target == null || PlayerRoles[killer.PlayerId].Interface.Team != Team.Impostor || PlayerRoles[target.PlayerId].Interface.Team == Team.Impostor) return; killer.Kill(target); @@ -544,25 +478,17 @@ namespace EHR } } - public static void OnCoEnterVent(PlayerPhysics physics, int ventId) - { - } + public static void OnCoEnterVent(PlayerPhysics physics, int ventId) { } [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.FixedUpdate))] private class FixedUpdatePatch { public static void Postfix() { - if (!AmongUsClient.Instance.AmHost || !GameStates.IsInTask || Options.CurrentGameMode != CustomGameMode.HideAndSeek || Main.HasJustStarted) - { - return; - } + if (!AmongUsClient.Instance.AmHost || !GameStates.IsInTask || Options.CurrentGameMode != CustomGameMode.HideAndSeek || Main.HasJustStarted) return; long now = Utils.TimeStamp; - if (LastUpdate == now) - { - return; - } + if (LastUpdate == now) return; LastUpdate = now; @@ -578,14 +504,9 @@ namespace EHR ClosestImpostor = nonImps.ToDictionary(x => x.Key, x => imps.MinBy(y => Vector2.Distance(y.Value, idPosPairs[x.Key])).Key); Danger = nonImps.ToDictionary(x => x.Key, x => Math.Clamp(((1 + (int)Math.Ceiling(Vector2.Distance(idPosPairs[x.Key], idPosPairs[ClosestImpostor[x.Key]]))) / 3) - 1, 0, 5)); } - catch - { - } + catch { } - if (DangerMeter.GetBool() || (TimeLeft + 1) % 60 == 0 || TimeLeft <= 60) - { - Utils.NotifyRoles(); - } + if (DangerMeter.GetBool() || (TimeLeft + 1) % 60 == 0 || TimeLeft <= 60) Utils.NotifyRoles(); } } } diff --git a/GameMode/HotPotatoManager.cs b/GameMode/HotPotatoManager.cs index 49218b528..fd30bd8c5 100644 --- a/GameMode/HotPotatoManager.cs +++ b/GameMode/HotPotatoManager.cs @@ -29,10 +29,12 @@ namespace EHR .SetGameMode(CustomGameMode.HotPotato) .SetValueFormat(OptionFormat.Seconds) .SetColor(new Color32(232, 205, 70, byte.MaxValue)); + HolderSpeed = new FloatOptionItem(69_213_002, "HotPotato_HolderSpeed", new(0.1f, 5f, 0.1f), 2f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HotPotato) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new Color32(232, 205, 70, byte.MaxValue)); + Range = new FloatOptionItem(69_213_004, "HotPotato_Range", new(0.25f, 5f, 0.25f), 1f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.HotPotato) .SetValueFormat(OptionFormat.Multiplier) @@ -45,10 +47,7 @@ namespace EHR HotPotatoState = (byte.MaxValue, byte.MaxValue, Time.GetInt() + 50, 1); SurvivalTimes = []; - foreach (PlayerControl pc in Main.AllPlayerControls) - { - SurvivalTimes[pc.PlayerId] = 0; - } + foreach (PlayerControl pc in Main.AllPlayerControls) SurvivalTimes[pc.PlayerId] = 0; DefaultSpeed = Main.AllPlayerSpeed[0]; } @@ -84,12 +83,10 @@ namespace EHR [SuppressMessage("ReSharper", "UnusedMember.Local")] public static void Postfix(PlayerControl __instance) { - if (Options.CurrentGameMode != CustomGameMode.HotPotato || Return || !AmongUsClient.Instance.AmHost || !GameStates.IsInTask) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.HotPotato || Return || !AmongUsClient.Instance.AmHost || !GameStates.IsInTask) return; PlayerControl Holder = Utils.GetPlayerById(HotPotatoState.HolderID); + if (Holder == null || Holder.Data.Disconnected || !Holder.IsAlive()) { PassHotPotato(); @@ -97,6 +94,7 @@ namespace EHR } long now = Utils.TimeStamp; + if (now > LastFixedUpdate) { HotPotatoState.TimeLeft--; @@ -113,35 +111,23 @@ namespace EHR } PlayerControl[] aapc = Main.AllAlivePlayerControls; - if (HotPotatoState.HolderID != __instance.PlayerId || !aapc.Any(x => x.PlayerId != HotPotatoState.HolderID && (x.PlayerId != HotPotatoState.LastHolderID || aapc.Length == 2) && Vector2.Distance(x.Pos(), Holder.Pos()) <= Range.GetFloat())) - { - return; - } + if (HotPotatoState.HolderID != __instance.PlayerId || !aapc.Any(x => x.PlayerId != HotPotatoState.HolderID && (x.PlayerId != HotPotatoState.LastHolderID || aapc.Length == 2) && Vector2.Distance(x.Pos(), Holder.Pos()) <= Range.GetFloat())) return; float wait = aapc.Length <= 2 ? 0.4f : 0.05f; UpdateDelay += UnityEngine.Time.fixedDeltaTime; - if (UpdateDelay < wait) - { - return; - } + if (UpdateDelay < wait) return; UpdateDelay = 0; PlayerControl Target = aapc.OrderBy(x => Vector2.Distance(x.Pos(), Holder.Pos())).FirstOrDefault(x => x.PlayerId != HotPotatoState.HolderID && (x.PlayerId != HotPotatoState.LastHolderID || aapc.Length == 2)); - if (Target == null) - { - return; - } + if (Target == null) return; PassHotPotato(Target, false); } private static void PassHotPotato(PlayerControl target = null, bool resetTime = true) { - if (Return || Main.AllAlivePlayerControls.Length < 2) - { - return; - } + if (Return || Main.AllAlivePlayerControls.Length < 2) return; if (resetTime) { @@ -160,6 +146,7 @@ namespace EHR target.MarkDirtySettings(); PlayerControl LastHolder = Utils.GetPlayerById(HotPotatoState.LastHolderID); + if (LastHolder != null) { Main.AllPlayerSpeed[HotPotatoState.LastHolderID] = DefaultSpeed; diff --git a/GameMode/MoveAndStopManager.cs b/GameMode/MoveAndStopManager.cs index 1d77c3fc5..0912fb22a 100644 --- a/GameMode/MoveAndStopManager.cs +++ b/GameMode/MoveAndStopManager.cs @@ -62,15 +62,9 @@ namespace EHR { string result = IsYellow || (Timer == TotalGreenTime && !IsRed && !IsYellow) || (Timer == TotalRedTime && IsRed) ? Utils.ColorString(Color.clear, "00") : Utils.ColorString(IsRed ? Color.red : Color.green, Timer < 10 ? $" {Timer}" : Timer.ToString()); - if (Timer is <= 19 and >= 10 && !IsYellow) - { - result = $" {result}"; - } + if (Timer is <= 19 and >= 10 && !IsYellow) result = $" {result}"; - if (Timer % 10 == 1 && !IsYellow) - { - result = result.Insert(result.Length - 9, " "); - } + if (Timer % 10 == 1 && !IsYellow) result = result.Insert(result.Length - 9, " "); return $"{result}"; } @@ -147,8 +141,8 @@ namespace EHR string middleTimer = MiddleCounter.ColoredTimerString; string rightTimer = RightCounter.ColoredTimerString; - string arrowRow = $"{LeftCounter.ColoredArrow} {MiddleCounter.ColoredArrow} {RightCounter.ColoredArrow}"; - string counterRow = $"{leftTimer} {middleTimer} {rightTimer}"; + var arrowRow = $"{LeftCounter.ColoredArrow} {MiddleCounter.ColoredArrow} {RightCounter.ColoredArrow}"; + var counterRow = $"{leftTimer} {middleTimer} {rightTimer}"; return $"{counterRow}\n{arrowRow}"; } @@ -269,6 +263,7 @@ namespace EHR .SetColor(new Color32(0, 255, 255, byte.MaxValue)) .SetValueFormat(OptionFormat.Seconds) .SetHeader(true); + MoveAndStop_RightCounterGreenMin = CreateSetting(68_213_002, "Right", false, true); MoveAndStop_RightCounterRedMin = CreateSetting(68_213_003, "Right", true, true); MoveAndStop_RightCounterGreenMax = CreateSetting(68_213_004, "Right", false, false); @@ -283,6 +278,7 @@ namespace EHR MoveAndStop_MiddleCounterRedMax = CreateSetting(68_213_013, "Middle", true, false); MoveAndStop_ExtraGreenTimeOnAirhip = CreateExtraTimeSetting(68_213_014, "Airship", 20); MoveAndStop_ExtraGreenTimeOnFungle = CreateExtraTimeSetting(68_213_015, "Fungle", 10); + MoveAndStop_EnableTutorial = new BooleanOptionItem(68_213_016, "MoveAndStop_EnableTutorial", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.MoveAndStop) .SetHeader(true) @@ -291,10 +287,7 @@ namespace EHR public static void Init() { - if (Options.CurrentGameMode != CustomGameMode.MoveAndStop) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.MoveAndStop) return; FixedUpdatePatch.LastSuffix = []; FixedUpdatePatch.Limit = []; @@ -315,6 +308,7 @@ namespace EHR pc.Pos().x, pc.Pos().y)); float limit; + try { limit = pc.GetClient().PlatformData.Platform is Platforms.Unknown or Platforms.IPhone or Platforms.Android or Platforms.Switch or Platforms.Xbox or Platforms.Playstation @@ -347,17 +341,11 @@ namespace EHR public static string GetSuffixText(PlayerControl pc) { - if (!pc.IsAlive() || !AllPlayerTimers.TryGetValue(pc.PlayerId, out MoveAndStopPlayerData timers)) - { - return string.Empty; - } + if (!pc.IsAlive() || !AllPlayerTimers.TryGetValue(pc.PlayerId, out MoveAndStopPlayerData timers)) return string.Empty; - string text = timers.ToString(); + var text = timers.ToString(); - if (HasJustStarted && Tutorial && !HasPlayed.Contains(pc.FriendCode)) - { - text += $"\n\n{GetString("MoveAndStop_Tutorial")}"; - } + if (HasJustStarted && Tutorial && !HasPlayed.Contains(pc.FriendCode)) text += $"\n\n{GetString("MoveAndStop_Tutorial")}"; return text; } @@ -372,10 +360,7 @@ namespace EHR public static void Postfix(PlayerControl __instance) { - if (!GameStates.IsInTask || Options.CurrentGameMode != CustomGameMode.MoveAndStop || !__instance.IsAlive() || !AmongUsClient.Instance.AmHost || !DoChecks) - { - return; - } + if (!GameStates.IsInTask || Options.CurrentGameMode != CustomGameMode.MoveAndStop || !__instance.IsAlive() || !AmongUsClient.Instance.AmHost || !DoChecks) return; PlayerControl pc = __instance; @@ -456,17 +441,11 @@ namespace EHR data.UpdateCounters(); - if (!pc.IsAlive()) - { - goto NoSuffix; // If the player is dead, there's no need to get them a suffix and notify them - } + if (!pc.IsAlive()) goto NoSuffix; // If the player is dead, there's no need to get them a suffix and notify them string suffix = GetSuffixText(pc); - if (!LastSuffix.TryGetValue(pc.PlayerId, out string beforeSuffix) || beforeSuffix != suffix) - { - Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - } + if (!LastSuffix.TryGetValue(pc.PlayerId, out string beforeSuffix) || beforeSuffix != suffix) Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); LastSuffix[pc.PlayerId] = suffix; } @@ -474,10 +453,7 @@ namespace EHR NoSuffix: long now = Utils.TimeStamp; - if (LastFixedUpdate == now) - { - return; - } + if (LastFixedUpdate == now) return; LastFixedUpdate = now; diff --git a/GameMode/NaturalDisasters.cs b/GameMode/NaturalDisasters.cs index 9379267dd..870709599 100644 --- a/GameMode/NaturalDisasters.cs +++ b/GameMode/NaturalDisasters.cs @@ -41,7 +41,7 @@ namespace EHR public static void SetupCustomOption() { - int id = 69_216_001; + var id = 69_216_001; Color color = Utils.GetRoleColor(CustomRoles.NDPlayer); const CustomGameMode gameMode = CustomGameMode.NaturalDisasters; @@ -105,16 +105,10 @@ namespace EHR BuildingCollapse.CollapsedRooms.Clear(); BuildingCollapse.LastPosition.Clear(); - if (Options.CurrentGameMode != CustomGameMode.NaturalDisasters) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.NaturalDisasters) return; Dictionary.ValueCollection rooms = RoomLocations()?.Values; - if (rooms == null) - { - return; - } + if (rooms == null) return; float[] x = rooms.Select(r => r.x).ToArray(); float[] y = rooms.Select(r => r.y).ToArray(); @@ -209,14 +203,12 @@ namespace EHR [SuppressMessage("ReSharper", "UnusedMember.Local")] public static void Postfix(PlayerControl __instance) { - if (!AmongUsClient.Instance.AmHost || !GameStates.IsInTask || Options.CurrentGameMode != CustomGameMode.NaturalDisasters || Main.HasJustStarted || GameStartTimeStamp + 5 > Utils.TimeStamp || !__instance.IsHost()) - { - return; - } + if (!AmongUsClient.Instance.AmHost || !GameStates.IsInTask || Options.CurrentGameMode != CustomGameMode.NaturalDisasters || Main.HasJustStarted || GameStartTimeStamp + 5 > Utils.TimeStamp || !__instance.IsHost()) return; foreach (NaturalDisaster naturalDisaster in PreparingDisasters.ToArray()) { naturalDisaster.Update(); + if (float.IsNaN(naturalDisaster.SpawnTimer)) { Type type = AllDisasters.Find(d => d.Name == naturalDisaster.DisasterName); @@ -232,6 +224,7 @@ namespace EHR if (LimitMaximumDisastersAtOnce.GetBool()) { int numDisasters = ActiveDisasters.Count + PreparingDisasters.Count; + if (numDisasters > MaximumDisastersAtOnce.GetInt()) { switch (WhenLimitIsReached.GetValue()) @@ -250,10 +243,7 @@ namespace EHR } Disaster remove = PreferRemovingThunderstorm.GetBool() ? ActiveDisasters.Find(x => x is Thunderstorm) : ActiveDisasters.RandomElement(); - if (remove != null) - { - remove.Duration = 0; - } + if (remove != null) remove.Duration = 0; remove?.RemoveIfExpired(); break; @@ -270,17 +260,16 @@ namespace EHR } long now = Utils.TimeStamp; + if (now - LastDisaster >= DisasterFrequency.GetInt()) { LastDisaster = now; List disasters = AllDisasters.ToList(); - if (ActiveDisasters.Exists(x => x is Thunderstorm)) - { - disasters.RemoveAll(x => x.Name == "Thunderstorm"); - } + if (ActiveDisasters.Exists(x => x is Thunderstorm)) disasters.RemoveAll(x => x.Name == "Thunderstorm"); Type disaster = disasters.SelectMany(x => Enumerable.Repeat(x, DisasterSpawnChances[x.Name].GetInt() / 5)).RandomElement(); KeyValuePair roomKvp = RoomLocations().RandomElement(); + Vector2 position = disaster.Name switch { "BuildingCollapse" => roomKvp.Value, @@ -289,6 +278,7 @@ namespace EHR ? Main.AllAlivePlayerControls.RandomElement().Pos() : new(Random.Range(MapBounds.X.Left, MapBounds.X.Right), Random.Range(MapBounds.Y.Top, MapBounds.Y.Bottom)) }; + SystemTypes? room = disaster.Name == "BuildingCollapse" ? roomKvp.Key : null; PreparingDisasters.Add(new(position, DisasterWarningTime.GetFloat(), Sprite(disaster.Name), disaster.Name, room)); } @@ -328,19 +318,13 @@ namespace EHR public abstract void Update(); - public virtual void ApplyOwnGameOptions(IGameOptions opt, byte id) - { - } + public virtual void ApplyOwnGameOptions(IGameOptions opt, byte id) { } protected void KillNearbyPlayers(PlayerState.DeathReason deathReason, float range = Range) { foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { if (Vector2.Distance(pc.Pos(), Position) <= range) - { pc.Suicide(deathReason); - } - } } } @@ -379,10 +363,7 @@ namespace EHR public override void Update() { - if (RemoveIfExpired()) - { - return; - } + if (RemoveIfExpired()) return; foreach (PlayerControl pc in Main.AllAlivePlayerControls) { @@ -392,6 +373,7 @@ namespace EHR false when AffectedPlayers.Remove(pc.PlayerId) => Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod), _ => float.NaN }; + if (!float.IsNaN(speed) && !Mathf.Approximately(Main.AllPlayerSpeed[pc.PlayerId], speed)) { Main.AllPlayerSpeed[pc.PlayerId] = speed; @@ -475,20 +457,15 @@ namespace EHR public override void Update() { - if (RemoveIfExpired()) - { - return; - } + if (RemoveIfExpired()) return; Timer += Time.deltaTime; + if (Timer >= FlowStepDelay.GetFloat()) { Timer = 0f; Phase++; - if (Phase > Phases) - { - return; - } + if (Phase > Phases) return; string newSprite = Phase switch { @@ -549,10 +526,7 @@ namespace EHR public override void Update() { - if (RemoveIfExpired()) - { - return; - } + if (RemoveIfExpired()) return; const float eyeRange = Range / 4f; const float dragRange = Range * 1.25f; @@ -560,6 +534,7 @@ namespace EHR foreach (PlayerControl pc in Main.AllAlivePlayerControls) { Vector2 pos = pc.Pos(); + switch (Vector2.Distance(pos, Position)) { case <= eyeRange: @@ -573,15 +548,13 @@ namespace EHR } } - if (Count++ < 3) - { - return; - } + if (Count++ < 3) return; Count = 0; float angle; long now = Utils.TimeStamp; + if (LastAngleChange + 7 <= now) { angle = RandomAngle(); @@ -589,9 +562,7 @@ namespace EHR Angle = angle; } else - { angle = Angle; - } Vector2 newPos = Position + (new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * MovingSpeed.GetFloat()); @@ -653,30 +624,23 @@ namespace EHR public override void Update() { - if (RemoveIfExpired()) - { - return; - } + if (RemoveIfExpired()) return; long now = Utils.TimeStamp; + if (now - LastHit >= HitFrequency.GetInt()) { LastHit = now; - Vector2 hit = new Vector2(Random.Range(MapBounds.X.Left, MapBounds.X.Right), Random.Range(MapBounds.Y.Bottom, MapBounds.Y.Top)); - Lightning cno = new Lightning(hit); + var hit = new Vector2(Random.Range(MapBounds.X.Left, MapBounds.X.Right), Random.Range(MapBounds.Y.Bottom, MapBounds.Y.Top)); + var cno = new Lightning(hit); + if (cno.playerControl.GetPlainShipRoom() != default(PlainShipRoom)) - { cno.Despawn(); - } else { foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { if (Vector2.Distance(pc.Pos(), hit) <= Range / 2f) - { pc.Suicide(PlayerState.DeathReason.Lightning); - } - } } } } @@ -728,18 +692,12 @@ namespace EHR public override void Update() { - if (RemoveIfExpired()) - { - return; - } + if (RemoveIfExpired()) return; foreach (PlayerControl pc in Main.AllAlivePlayerControls) { bool inRange = Vector2.Distance(pc.Pos(), Position) <= Range; - if ((inRange && AffectedPlayers.Add(pc.PlayerId)) || (!inRange && AffectedPlayers.Remove(pc.PlayerId))) - { - pc.MarkDirtySettings(); - } + if ((inRange && AffectedPlayers.Add(pc.PlayerId)) || (!inRange && AffectedPlayers.Remove(pc.PlayerId))) pc.MarkDirtySettings(); } } @@ -748,12 +706,8 @@ namespace EHR if (base.RemoveIfExpired()) { foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { if (AffectedPlayers.Remove(pc.PlayerId)) - { pc.MarkDirtySettings(); - } - } return true; } @@ -814,14 +768,12 @@ namespace EHR public override void Update() { - if (RemoveIfExpired()) - { - return; - } + if (RemoveIfExpired()) return; foreach (PlayerControl pc in Main.AllAlivePlayerControls) { Vector2 pos = pc.Pos(); + bool inWay = Direction switch { MovingDirection.LeftToRight => pos.x >= Position.x, @@ -831,21 +783,16 @@ namespace EHR _ => false }; - if (Vector2.Distance(pos, Position) <= Range && inWay) - { - pc.Suicide(PlayerState.DeathReason.Drowned); - } + if (Vector2.Distance(pos, Position) <= Range && inWay) pc.Suicide(PlayerState.DeathReason.Drowned); } - if (Count++ < 2) - { - return; - } + if (Count++ < 2) return; Count = 0; float speed = MovingSpeed.GetFloat(); Vector2 newPos = Position; + switch (Direction) { case MovingDirection.LeftToRight: @@ -905,22 +852,16 @@ namespace EHR public static void OnFixedUpdate() { - if (Sinkholes.Count == 0) - { - return; - } + if (Sinkholes.Count == 0) return; foreach (PlayerControl pc in Main.AllAlivePlayerControls) { Vector2 pos = pc.Pos(); + // ReSharper disable once ForCanBeConvertedToForeach - for (int i = 0; i < Sinkholes.Count; i++) - { + for (var i = 0; i < Sinkholes.Count; i++) if (Vector2.Distance(pos, Sinkholes[i].Position) <= Range) - { pc.Suicide(PlayerState.DeathReason.Sunken); - } - } } } @@ -944,18 +885,11 @@ namespace EHR Update(); PlainShipRoom room = ShipStatus.Instance.AllRooms.FirstOrDefault(x => x.RoomId == naturalDisaster.Room); - if (room == default(PlainShipRoom)) - { - return; - } + if (room == default(PlainShipRoom)) return; foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { if (pc.GetPlainShipRoom() == room) - { pc.Suicide(PlayerState.DeathReason.Collapsed); - } - } CollapsedRooms.Add(room); Utils.NotifyRoles(); @@ -973,36 +907,25 @@ namespace EHR public static void OnFixedUpdate() { - if (CollapsedRooms.Count == 0) - { - return; - } + if (CollapsedRooms.Count == 0) return; - if (Count++ < 10) - { - return; - } + if (Count++ < 10) return; Count = 0; foreach (PlayerControl pc in Main.AllAlivePlayerControls) { PlainShipRoom room = pc.GetPlainShipRoom(); + if (room != default(PlainShipRoom) && CollapsedRooms.Exists(x => x == room)) { if (LastPosition.TryGetValue(pc.PlayerId, out Vector2 lastPos)) - { pc.TP(lastPos); - } else - { pc.Suicide(PlayerState.DeathReason.Collapsed); - } } else - { LastPosition[pc.PlayerId] = pc.Pos(); - } } } } diff --git a/GameMode/RoomRush.cs b/GameMode/RoomRush.cs index d70cf607f..6f8e8974b 100644 --- a/GameMode/RoomRush.cs +++ b/GameMode/RoomRush.cs @@ -122,7 +122,7 @@ namespace EHR public static void SetupCustomOption() { - int id = 69_217_001; + var id = 69_217_001; Color color = Utils.GetRoleColor(CustomRoles.RRPlayer); const CustomGameMode gameMode = CustomGameMode.RoomRush; @@ -152,15 +152,9 @@ namespace EHR public static int GetSurvivalTime(byte id) { - if (!Main.PlayerStates.TryGetValue(id, out PlayerState state)) - { - return -1; - } + if (!Main.PlayerStates.TryGetValue(id, out PlayerState state)) return -1; - if (!state.IsDead) - { - return 0; - } + if (!state.IsDead) return 0; DateTime died = state.RealKiller.TimeStamp; TimeSpan time = died - GameStartDateTime; @@ -169,10 +163,7 @@ namespace EHR public static void OnGameStart() { - if (Options.CurrentGameMode != CustomGameMode.RoomRush) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.RoomRush) return; Main.Instance.StartCoroutine(GameStartTasks()); } @@ -208,9 +199,11 @@ namespace EHR aapc.Do(x => x.RpcSetCustomRole(CustomRoles.RRPlayer)); bool showTutorial = aapc.ExceptBy(HasPlayedFriendCodes, x => x.FriendCode).Count() >= aapc.Length / 3; + if (showTutorial) { string[] notifies = [Translator.GetString("RR_Tutorial_1"), Translator.GetString("RR_Tutorial_2"), Translator.GetString("RR_Tutorial_3"), Translator.GetString("RR_Tutorial_4")]; + foreach (string notify in notifies) { aapc.Do(x => x.Notify(notify, 8f)); @@ -225,7 +218,7 @@ namespace EHR yield return new WaitForSeconds(2f); - for (int i = 3; i > 0; i--) + for (var i = 3; i > 0; i--) { int time = i; NameNotifyManager.Reset(); @@ -233,10 +226,7 @@ namespace EHR yield return new WaitForSeconds(1f); } - if (ventLimit > 0) - { - aapc.Without(PlayerControl.LocalPlayer).DoIf(x => !x.IsNonHostModClient(), x => x.RpcChangeRoleBasis(CustomRoles.EngineerEHR)); - } + if (ventLimit > 0) aapc.Without(PlayerControl.LocalPlayer).DoIf(x => !x.IsNonHostModClient(), x => x.RpcChangeRoleBasis(CustomRoles.EngineerEHR)); Utils.SendRPC(CustomRPC.RoomRushDataSync, 1); @@ -248,10 +238,7 @@ namespace EHR private static void StartNewRound(bool initial = false) { - if (GameStates.IsEnded) - { - return; - } + if (GameStates.IsEnded) return; SystemTypes previous = !initial ? RoomGoal @@ -265,34 +252,31 @@ namespace EHR MapNames.Fungle => SystemTypes.Dropship, _ => throw new ArgumentOutOfRangeException(Main.CurrentMap.ToString(), "Invalid map") }; + DonePlayers.Clear(); RoomGoal = AllRooms.Without(previous).RandomElement(); Vector2 goalPos = Map.Positions.GetValueOrDefault(RoomGoal, RoomGoal.GetRoomClass().transform.position); Vector2 previousPos = Map.Positions.GetValueOrDefault(previous, initial ? Main.AllAlivePlayerControls.RandomElement().Pos() : previous.GetRoomClass().transform.position); float distance = initial ? 50 : Vector2.Distance(goalPos, previousPos); float speed = Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod); - int time = (int)Math.Ceiling(distance / speed); + var time = (int)Math.Ceiling(distance / speed); MapNames map = Main.CurrentMap; Dictionary<(SystemTypes, SystemTypes), int> multipliers = Multipliers[map == MapNames.Dleks ? MapNames.Skeld : map]; time *= multipliers.GetValueOrDefault((previous, RoomGoal), multipliers.GetValueOrDefault((RoomGoal, previous), 1)); + bool involvesDecontamination = Main.CurrentMap switch { MapNames.Mira => !(previous is SystemTypes.Laboratory or SystemTypes.Reactor && RoomGoal is SystemTypes.Laboratory or SystemTypes.Reactor) && (previous is SystemTypes.Laboratory or SystemTypes.Reactor || RoomGoal is SystemTypes.Laboratory or SystemTypes.Reactor), MapNames.Polus => previous == SystemTypes.Specimens || RoomGoal == SystemTypes.Specimens, _ => false }; - if (involvesDecontamination) - { - time += 15; - } + + if (involvesDecontamination) time += 15; switch (Main.CurrentMap) { case MapNames.Airship: - if (RoomGoal == SystemTypes.Ventilation) - { - time = (int)(time * 0.4f); - } + if (RoomGoal == SystemTypes.Ventilation) time = (int)(time * 0.4f); break; case MapNames.Fungle when RoomGoal == SystemTypes.Laboratory || previous == SystemTypes.Laboratory: @@ -306,15 +290,13 @@ namespace EHR TimeLeft = Math.Max((int)Math.Round(time * GlobalTimeMultiplier.GetFloat()), 4); Logger.Info($"Starting a new round - Goal = from: {Translator.GetString(previous.ToString())}, to: {Translator.GetString(RoomGoal.ToString())} - Time: {TimeLeft} ({Main.CurrentMap})", "RoomRush"); Main.AllPlayerControls.Do(x => LocateArrow.RemoveAllTarget(x.PlayerId)); - if (DisplayArrowToRoom.GetBool()) - { - Main.AllPlayerControls.Do(x => LocateArrow.Add(x.PlayerId, goalPos)); - } + if (DisplayArrowToRoom.GetBool()) Main.AllPlayerControls.Do(x => LocateArrow.Add(x.PlayerId, goalPos)); Utils.NotifyRoles(); Main.AllPlayerSpeed[PlayerControl.LocalPlayer.PlayerId] = Main.MinSpeed; PlayerControl.LocalPlayer.SyncSettings(); + LateTask.New(() => { Main.AllPlayerSpeed[PlayerControl.LocalPlayer.PlayerId] = speed; @@ -329,32 +311,20 @@ namespace EHR public static string GetSuffix(PlayerControl seer) { - if (!GameGoing || Main.HasJustStarted || seer == null) - { - return string.Empty; - } + if (!GameGoing || Main.HasJustStarted || seer == null) return string.Empty; StringBuilder sb = new(); bool dead = !seer.IsAlive(); bool done = dead || DonePlayers.Contains(seer.PlayerId); Color color = done ? Color.green : Color.yellow; - if (DisplayRoomName.GetBool()) - { - sb.AppendLine(Utils.ColorString(color, Translator.GetString(RoomGoal.ToString()))); - } + if (DisplayRoomName.GetBool()) sb.AppendLine(Utils.ColorString(color, Translator.GetString(RoomGoal.ToString()))); - if (DisplayArrowToRoom.GetBool()) - { - sb.AppendLine(Utils.ColorString(color, LocateArrow.GetArrows(seer))); - } + if (DisplayArrowToRoom.GetBool()) sb.AppendLine(Utils.ColorString(color, LocateArrow.GetArrows(seer))); color = done ? Color.white : Color.yellow; sb.AppendLine(Utils.ColorString(color, TimeLeft.ToString())); - if (VentTimes.GetInt() == 0 || dead) - { - return sb.ToString(); - } + if (VentTimes.GetInt() == 0 || dead) return sb.ToString(); sb.AppendLine(); @@ -388,10 +358,7 @@ namespace EHR [SuppressMessage("ReSharper", "UnusedMember.Local")] public static void Postfix(PlayerControl __instance) { - if (!GameGoing || Main.HasJustStarted || Options.CurrentGameMode != CustomGameMode.RoomRush || !AmongUsClient.Instance.AmHost || !GameStates.IsInTask || !__instance.IsHost()) - { - return; - } + if (!GameGoing || Main.HasJustStarted || Options.CurrentGameMode != CustomGameMode.RoomRush || !AmongUsClient.Instance.AmHost || !GameStates.IsInTask || !__instance.IsHost()) return; long now = Utils.TimeStamp; PlayerControl[] aapc = Main.AllAlivePlayerControls; @@ -399,11 +366,13 @@ namespace EHR foreach (PlayerControl pc in aapc) { PlainShipRoom room = pc.GetPlainShipRoom(); + if (pc.IsAlive() && !pc.inMovingPlat && room != null && room.RoomId == RoomGoal && DonePlayers.Add(pc.PlayerId)) { Logger.Info($"{pc.GetRealName()} entered the correct room", "RoomRush"); int timeLeft = TimeWhenFirstPlayerEntersRoom.GetInt(); + if (DonePlayers.Count == 2 && timeLeft < TimeLeft) { Logger.Info($"Two players entered the correct room, setting the timer to {timeLeft}", "RoomRush"); @@ -421,16 +390,10 @@ namespace EHR return; } } - else if (room == null || room.RoomId != RoomGoal) - { - DonePlayers.Remove(pc.PlayerId); - } + else if (room == null || room.RoomId != RoomGoal) DonePlayers.Remove(pc.PlayerId); } - if (LastUpdate == now) - { - return; - } + if (LastUpdate == now) return; LastUpdate = now; @@ -442,10 +405,7 @@ namespace EHR Logger.Info("Time is up, killing everyone who didn't enter the correct room", "RoomRush"); PlayerControl[] lateAapc = Main.AllAlivePlayerControls; PlayerControl[] playersOutsideRoom = lateAapc.ExceptBy(DonePlayers, x => x.PlayerId).ToArray(); - if (playersOutsideRoom.Length == lateAapc.Length) - { - CustomWinnerHolder.ResetAndSetWinner(CustomWinner.None); - } + if (playersOutsideRoom.Length == lateAapc.Length) CustomWinnerHolder.ResetAndSetWinner(CustomWinner.None); playersOutsideRoom.Do(x => x.Suicide()); StartNewRound(); @@ -458,26 +418,17 @@ namespace EHR { public override bool IsEnable => Options.CurrentGameMode == CustomGameMode.RoomRush; - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } - public override void SetupCustomOption() - { - } + public override void SetupCustomOption() { } public override void OnExitVent(PlayerControl pc, Vent vent) { RoomRush.VentLimit[pc.PlayerId]--; Utils.SendRPC(CustomRPC.RoomRushDataSync, 2, RoomRush.VentLimit[pc.PlayerId], pc.PlayerId); - if (RoomRush.VentLimit[pc.PlayerId] <= 0) - { - pc.RpcChangeRoleBasis(CustomRoles.RRPlayer); - } + if (RoomRush.VentLimit[pc.PlayerId] <= 0) pc.RpcChangeRoleBasis(CustomRoles.RRPlayer); } public override bool CanUseImpostorVentButton(PlayerControl pc) diff --git a/GameMode/SoloKombatManager.cs b/GameMode/SoloKombatManager.cs index da409be15..c3b062745 100644 --- a/GameMode/SoloKombatManager.cs +++ b/GameMode/SoloKombatManager.cs @@ -38,34 +38,42 @@ namespace EHR .SetColor(new Color32(245, 82, 82, byte.MaxValue)) .SetValueFormat(OptionFormat.Seconds) .SetHeader(true); + KB_ATKCooldown = new FloatOptionItem(66_223_008, "KB_ATKCooldown", new(1f, 10f, 0.1f), 1f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.SoloKombat) .SetColor(new Color32(245, 82, 82, byte.MaxValue)) .SetValueFormat(OptionFormat.Seconds); + KB_HPMax = new FloatOptionItem(66_233_002, "KB_HPMax", new(10f, 990f, 5f), 100f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.SoloKombat) .SetColor(new Color32(245, 82, 82, byte.MaxValue)) .SetValueFormat(OptionFormat.Health); + KB_ATK = new FloatOptionItem(66_233_003, "KB_ATK", new(1f, 100f, 1f), 8f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.SoloKombat) .SetColor(new Color32(245, 82, 82, byte.MaxValue)) .SetValueFormat(OptionFormat.Health); + KB_RecoverPerSecond = new FloatOptionItem(66_233_005, "KB_RecoverPerSecond", new(1f, 180f, 1f), 2f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.SoloKombat) .SetColor(new Color32(245, 82, 82, byte.MaxValue)) .SetValueFormat(OptionFormat.Health); + KB_RecoverAfterSecond = new IntegerOptionItem(66_233_004, "KB_RecoverAfterSecond", new(0, 60, 1), 8, TabGroup.GameSettings) .SetGameMode(CustomGameMode.SoloKombat) .SetColor(new Color32(245, 82, 82, byte.MaxValue)) .SetValueFormat(OptionFormat.Seconds); + KB_ResurrectionWaitingTime = new IntegerOptionItem(66_233_006, "KB_ResurrectionWaitingTime", new(3, 990, 1), 15, TabGroup.GameSettings) .SetGameMode(CustomGameMode.SoloKombat) .SetColor(new Color32(245, 82, 82, byte.MaxValue)) .SetValueFormat(OptionFormat.Seconds); + KB_KillBonusMultiplier = new FloatOptionItem(66_233_007, "KB_KillBonusMultiplier", new(0.25f, 5f, 0.25f), 1.25f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.SoloKombat) .SetColor(new Color32(245, 82, 82, byte.MaxValue)) .SetValueFormat(OptionFormat.Multiplier); + KB_BootVentWhenDead = new BooleanOptionItem(66_233_009, "KB_BootVentWhenDead", false, TabGroup.GameSettings) .SetGameMode(CustomGameMode.SoloKombat) .SetColor(new Color32(245, 82, 82, byte.MaxValue)); @@ -73,10 +81,7 @@ namespace EHR public static void Init() { - if (Options.CurrentGameMode != CustomGameMode.SoloKombat) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.SoloKombat) return; PlayerHPMax = []; PlayerHP = []; @@ -111,28 +116,22 @@ namespace EHR private static Color32 GetHealthColor(PlayerControl pc) { - int x = (int)(PlayerHP[pc.PlayerId] / PlayerHPMax[pc.PlayerId] * 10 * 50); - int R = 255; - int G = 255; - int B = 0; + var x = (int)(PlayerHP[pc.PlayerId] / PlayerHPMax[pc.PlayerId] * 10 * 50); + var R = 255; + var G = 255; + var B = 0; + if (x > 255) - { R -= x - 255; - } else - { G = x; - } return new((byte)R, (byte)G, (byte)B, byte.MaxValue); } public static void GetNameNotify(PlayerControl player, ref string name) { - if (Options.CurrentGameMode != CustomGameMode.SoloKombat || player == null) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.SoloKombat || player == null) return; if (BackCountdown.TryGetValue(player.PlayerId, out int value)) { @@ -141,10 +140,7 @@ namespace EHR return; } - if (NameNotify.TryGetValue(player.PlayerId, out (string Text, long TimeStamp) value1)) - { - name = value1.Text; - } + if (NameNotify.TryGetValue(player.PlayerId, out (string Text, long TimeStamp) value1)) name = value1.Text; } public static int GetRankOfScore(byte playerId) @@ -169,15 +165,9 @@ namespace EHR public static void OnPlayerAttack(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null || Options.CurrentGameMode != CustomGameMode.SoloKombat) - { - return; - } + if (killer == null || target == null || Options.CurrentGameMode != CustomGameMode.SoloKombat) return; - if (!killer.SoloAlive() || !target.SoloAlive() || target.inVent) - { - return; - } + if (!killer.SoloAlive() || !target.SoloAlive() || target.inVent) return; float dmg = PlayerATK[killer.PlayerId] - PlayerDF[target.PlayerId]; PlayerHP[target.PlayerId] = Math.Max(0f, PlayerHP[target.PlayerId] - dmg); @@ -191,18 +181,12 @@ namespace EHR LastHurt[target.PlayerId] = Utils.TimeStamp; float kcd = KB_ATKCooldown.GetFloat(); - if (killer.IsHost()) - { - kcd += AmongUsClient.Instance.Ping / 1000f * 4f; - } + if (killer.IsHost()) kcd += AmongUsClient.Instance.Ping / 1000f * 4f; killer.SetKillCooldown(kcd, target); RPC.PlaySoundRPC(killer.PlayerId, Sounds.KillSound); RPC.PlaySoundRPC(target.PlayerId, Sounds.KillSound); - if (!target.IsModClient() && !target.AmOwner) - { - target.RpcGuardAndKill(); - } + if (!target.IsModClient() && !target.AmOwner) target.RpcGuardAndKill(); Utils.NotifyRoles(SpecifySeer: killer, SpecifyTarget: target); Utils.NotifyRoles(SpecifySeer: target, SpecifyTarget: killer); @@ -254,21 +238,16 @@ namespace EHR private static void OnPlayerKill(PlayerControl killer) { killer.KillFlash(); - if (PlayerControl.LocalPlayer.Is(CustomRoles.GM)) - { - PlayerControl.LocalPlayer.KillFlash(); - } + if (PlayerControl.LocalPlayer.Is(CustomRoles.GM)) PlayerControl.LocalPlayer.KillFlash(); KBScore[killer.PlayerId]++; float addRate = IRandom.Instance.Next(3, 5 + GetRankOfScore(killer.PlayerId)) / 100f; addRate *= KB_KillBonusMultiplier.GetFloat(); - if (killer.IsHost()) - { - addRate /= 2f; - } + if (killer.IsHost()) addRate /= 2f; float addin; + switch (IRandom.Instance.Next(0, 4)) { case 0: @@ -308,33 +287,21 @@ namespace EHR public static void Postfix( /*PlayerControl __instance*/) { - if (!GameStates.IsInTask || Options.CurrentGameMode != CustomGameMode.SoloKombat || !AmongUsClient.Instance.AmHost) - { - return; - } + if (!GameStates.IsInTask || Options.CurrentGameMode != CustomGameMode.SoloKombat || !AmongUsClient.Instance.AmHost) return; foreach (PlayerControl pc in Main.AllPlayerControls) { if (!pc.SoloAlive()) { - if (pc.inVent && KB_BootVentWhenDead.GetBool()) - { - pc.MyPhysics.RpcExitVent(2); - } + if (pc.inVent && KB_BootVentWhenDead.GetBool()) pc.MyPhysics.RpcExitVent(2); Vector2 pos = Pelican.GetBlackRoomPS(); float dis = Vector2.Distance(pos, pc.Pos()); - if (dis > 1f) - { - pc.TP(pos); - } + if (dis > 1f) pc.TP(pos); } } - if (LastFixedUpdate == Utils.TimeStamp) - { - return; - } + if (LastFixedUpdate == Utils.TimeStamp) return; LastFixedUpdate = Utils.TimeStamp; @@ -342,7 +309,8 @@ namespace EHR foreach (PlayerControl pc in Main.AllPlayerControls) { - bool notifyRoles = false; + var notifyRoles = false; + if (LastHurt[pc.PlayerId] + KB_RecoverAfterSecond.GetInt() < Utils.TimeStamp && PlayerHP[pc.PlayerId] < PlayerHPMax[pc.PlayerId] && pc.SoloAlive() && !pc.inVent) { PlayerHP[pc.PlayerId] += PlayerHPReco[pc.PlayerId]; @@ -354,19 +322,13 @@ namespace EHR { Vector2 pos = Pelican.GetBlackRoomPS(); float dis = Vector2.Distance(pos, pc.Pos()); - if (dis < 1.1f) - { - PlayerRandomSpwan(pc); - } + if (dis < 1.1f) PlayerRandomSpwan(pc); } if (BackCountdown.ContainsKey(pc.PlayerId)) { BackCountdown[pc.PlayerId]--; - if (BackCountdown[pc.PlayerId] <= 0) - { - OnPlayerBack(pc); - } + if (BackCountdown[pc.PlayerId] <= 0) OnPlayerBack(pc); notifyRoles = true; } @@ -377,10 +339,7 @@ namespace EHR notifyRoles = true; } - if (notifyRoles) - { - Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - } + if (notifyRoles) Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); } } } diff --git a/GameMode/SpeedrunManager.cs b/GameMode/SpeedrunManager.cs index 4951faef5..b689317eb 100644 --- a/GameMode/SpeedrunManager.cs +++ b/GameMode/SpeedrunManager.cs @@ -54,23 +54,16 @@ namespace EHR public static void ResetTimer(PlayerControl pc) { if (TimeStacksUp.GetBool()) - { Timers[pc.PlayerId] += TimeLimit.GetInt(); - } else - { Timers[pc.PlayerId] = TimeLimit.GetInt(); - } Logger.Info($" Timer for {pc.GetRealName()} set to {Timers[pc.PlayerId]}", "Speedrun"); } public static void OnTaskFinish(PlayerControl pc) { - if (TaskFinishWins.GetBool()) - { - return; - } + if (TaskFinishWins.GetBool()) return; CanKill.Add(pc.PlayerId); Main.AllPlayerKillCooldown[pc.PlayerId] = KillCooldown.GetInt(); @@ -94,10 +87,7 @@ namespace EHR public static string GetSuffixText(PlayerControl pc) { - if (!pc.IsAlive()) - { - return string.Empty; - } + if (!pc.IsAlive()) return string.Empty; int time = Timers[pc.PlayerId]; int alive = Main.AllAlivePlayerControls.Length; @@ -105,10 +95,7 @@ namespace EHR int killers = CanKill.Count; // ReSharper disable once ConvertIfStatementToReturnStatement - if (CanKill.Contains(pc.PlayerId)) - { - return string.Format(Translator.GetString("Speedrun_CanKillSuffixInfo"), alive, apc, killers - 1, time); - } + if (CanKill.Contains(pc.PlayerId)) return string.Format(Translator.GetString("Speedrun_CanKillSuffixInfo"), alive, apc, killers - 1, time); return string.Format(Translator.GetString("Speedrun_DoTasksSuffixInfo"), pc.GetTaskState().RemainingTasksCount, alive, apc, killers, time); } @@ -120,6 +107,7 @@ namespace EHR if (TaskFinishWins.GetBool()) { PlayerControl player = aapc.FirstOrDefault(x => x.GetTaskState().IsTaskFinished); + if (player != null) { CustomWinnerHolder.WinnerIds = [player.PlayerId]; @@ -141,16 +129,13 @@ namespace EHR } reason = GameOverReason.ImpostorByKill; - KeyCode[] keys = new[] { KeyCode.LeftShift, KeyCode.L, KeyCode.Return }; + KeyCode[] keys = { KeyCode.LeftShift, KeyCode.L, KeyCode.Return }; return keys.Any(Input.GetKeyDown) && keys.All(Input.GetKey); } public static bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!CanKill.Contains(killer.PlayerId)) - { - return false; - } + if (!CanKill.Contains(killer.PlayerId)) return false; return CanKill.Contains(target.PlayerId) || KillersCanKillTaskingPlayers.GetBool(); } @@ -162,21 +147,12 @@ namespace EHR public static void Postfix(PlayerControl __instance) { - if (!AmongUsClient.Instance.AmHost || !GameStates.IsInTask || Options.CurrentGameMode != CustomGameMode.Speedrun || Main.HasJustStarted) - { - return; - } + if (!AmongUsClient.Instance.AmHost || !GameStates.IsInTask || Options.CurrentGameMode != CustomGameMode.Speedrun || Main.HasJustStarted) return; - if (__instance.IsAlive() && Timers[__instance.PlayerId] <= 0) - { - __instance.Suicide(); - } + if (__instance.IsAlive() && Timers[__instance.PlayerId] <= 0) __instance.Suicide(); long now = Utils.TimeStamp; - if (LastUpdate == now) - { - return; - } + if (LastUpdate == now) return; LastUpdate = now; @@ -192,17 +168,11 @@ namespace EHR { public override bool IsEnable => false; - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } - public override void SetupCustomOption() - { - } + public override void SetupCustomOption() { } public override bool CanUseVent(PlayerControl pc, int ventId) { diff --git a/Modules/AFKDetector.cs b/Modules/AFKDetector.cs index 419c4d51a..9ed424226 100644 --- a/Modules/AFKDetector.cs +++ b/Modules/AFKDetector.cs @@ -22,14 +22,18 @@ namespace EHR.Modules new TextOptionItem(100080, "MenuTitle.AFKDetection", TabGroup.GameSettings) .SetColor(new Color32(0, 255, 165, 255)) .SetHeader(true); + EnableDetector = new BooleanOptionItem(90, "EnableAFKDetector", true, TabGroup.GameSettings) .SetColor(new Color32(0, 255, 165, 255)); + ConsequenceOption = new StringOptionItem(91, "AFKConsequence", Enum.GetNames().Select(x => $"AFKConsequence.{x}").ToArray(), 0, TabGroup.GameSettings) .SetParent(EnableDetector) .SetColor(new Color32(0, 255, 165, 255)); + MinPlayersToActivate = new IntegerOptionItem(92, "AFKMinPlayersToActivate", new(3, 15, 1), 7, TabGroup.GameSettings) .SetParent(EnableDetector) .SetColor(new Color32(0, 255, 165, 255)); + ActivateOnStart = new BooleanOptionItem(93, "AFKActivateOnStart", false, TabGroup.GameSettings) .SetParent(EnableDetector) .SetColor(new Color32(0, 255, 165, 255)); @@ -37,10 +41,7 @@ namespace EHR.Modules public static void RecordPosition(PlayerControl pc) { - if (!EnableDetector.GetBool() || !GameStates.IsInTask || pc == null || ExemptedPlayers.Contains(pc.PlayerId)) - { - return; - } + if (!EnableDetector.GetBool() || !GameStates.IsInTask || pc == null || ExemptedPlayers.Contains(pc.PlayerId)) return; PlayerData[pc.PlayerId] = new() { @@ -51,10 +52,7 @@ namespace EHR.Modules public static void OnFixedUpdate(PlayerControl pc) { - if (!EnableDetector.GetBool() || !GameStates.IsInTask || Main.AllAlivePlayerControls.Length < MinPlayersToActivate.GetInt() || pc == null || !PlayerData.TryGetValue(pc.PlayerId, out Data data)) - { - return; - } + if (!EnableDetector.GetBool() || !GameStates.IsInTask || Main.AllAlivePlayerControls.Length < MinPlayersToActivate.GetInt() || pc == null || !PlayerData.TryGetValue(pc.PlayerId, out Data data)) return; if (Vector2.Distance(pc.Pos(), data.LastPosition) > 0.1f) { @@ -63,19 +61,16 @@ namespace EHR.Modules return; } - int lastTimer = (int)Math.Round(data.Timer); + var lastTimer = (int)Math.Round(data.Timer); data.Timer -= Time.fixedDeltaTime; - int currentTimer = (int)Math.Round(data.Timer); + var currentTimer = (int)Math.Round(data.Timer); if (data.Timer <= 0f) { switch (data.CurrentPhase) { case Data.Phase.Detection: - if (!pc.IsModClient()) - { - NumAFK++; - } + if (!pc.IsModClient()) NumAFK++; data.CurrentPhase = Data.Phase.Warning; data.Timer = 15f; @@ -93,23 +88,14 @@ namespace EHR.Modules } } - if (data.CurrentPhase == Data.Phase.Warning && lastTimer != currentTimer) - { - Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - } + if (data.CurrentPhase == Data.Phase.Warning && lastTimer != currentTimer) Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); } public static string GetSuffix(PlayerControl seer, PlayerControl target) { - if (seer.PlayerId == target.PlayerId && seer.IsAlive() && PlayerData.TryGetValue(seer.PlayerId, out Data seerData) && seerData.CurrentPhase > Data.Phase.Detection) - { - return seerData.CurrentPhase == Data.Phase.Warning ? string.Format(Translator.GetString("AFKWarning"), (int)Math.Round(seerData.Timer)) : Translator.GetString("AFKSuffix"); - } + if (seer.PlayerId == target.PlayerId && seer.IsAlive() && PlayerData.TryGetValue(seer.PlayerId, out Data seerData) && seerData.CurrentPhase > Data.Phase.Detection) return seerData.CurrentPhase == Data.Phase.Warning ? string.Format(Translator.GetString("AFKWarning"), (int)Math.Round(seerData.Timer)) : Translator.GetString("AFKSuffix"); - if (target.IsAlive() && PlayerData.TryGetValue(target.PlayerId, out Data targetData) && targetData.CurrentPhase > Data.Phase.Detection) - { - return Translator.GetString("AFKSuffix"); - } + if (target.IsAlive() && PlayerData.TryGetValue(target.PlayerId, out Data targetData) && targetData.CurrentPhase > Data.Phase.Detection) return Translator.GetString("AFKSuffix"); return string.Empty; } diff --git a/Modules/AntiBlackout.cs b/Modules/AntiBlackout.cs index fcb6a6ce0..db6a4bb8e 100644 --- a/Modules/AntiBlackout.cs +++ b/Modules/AntiBlackout.cs @@ -55,18 +55,13 @@ namespace EHR SkipTasks = true; RevivePlayersAndSetDummyImp(); Logger.Info($"SetIsDead is called from {callerMethodName}"); - if (IsCached) - { - return; - } + if (IsCached) return; IsDeadCache.Clear(); + foreach (NetworkedPlayerInfo info in GameData.Instance.AllPlayers) { - if (info == null) - { - continue; - } + if (info == null) continue; IsDeadCache[info.PlayerId] = (info.IsDead, info.Disconnected); info.IsDead = false; @@ -74,27 +69,18 @@ namespace EHR } IsCached = true; - if (doSend) - { - SendGameData(); - } + if (doSend) SendGameData(); } private static void RevivePlayersAndSetDummyImp() { - if (CustomWinnerHolder.WinnerTeam != CustomWinner.Default) - { - return; - } + if (CustomWinnerHolder.WinnerTeam != CustomWinner.Default) return; PlayerControl dummyImp = Main.AllAlivePlayerControls.First(x => x.PlayerId != ExilePlayerId); foreach (PlayerControl seer in Main.AllPlayerControls) { - if (seer.IsHost() || seer.IsModClient()) - { - continue; - } + if (seer.IsHost() || seer.IsModClient()) continue; foreach (PlayerControl target in Main.AllPlayerControls) { @@ -107,12 +93,10 @@ namespace EHR public static void RestoreIsDead(bool doSend = true, [CallerMemberName] string callerMethodName = "") { Logger.Info($"RestoreIsDead is called from {callerMethodName}"); + foreach (NetworkedPlayerInfo info in GameData.Instance.AllPlayers) { - if (info == null) - { - continue; - } + if (info == null) continue; if (IsDeadCache.TryGetValue(info.PlayerId, out (bool IsDead, bool Disconnected) val)) { @@ -123,28 +107,30 @@ namespace EHR IsDeadCache.Clear(); IsCached = false; - if (doSend) - { - SendGameData(); - } + if (doSend) SendGameData(); } public static void SendGameData([CallerMemberName] string callerMethodName = "") { Logger.Info($"SendGameData is called from {callerMethodName}"); + foreach (NetworkedPlayerInfo playerinfo in GameData.Instance.AllPlayers) { MessageWriter writer = MessageWriter.Get(SendOption.Reliable); writer.StartMessage(5); //0x05 GameData + { writer.Write(AmongUsClient.Instance.GameId); writer.StartMessage(1); //0x01 Data + { writer.WritePacked(playerinfo.NetId); playerinfo.Serialize(writer, true); } + writer.EndMessage(); } + writer.EndMessage(); AmongUsClient.Instance.SendOrDisconnect(writer); @@ -155,10 +141,7 @@ namespace EHR public static void OnDisconnect(NetworkedPlayerInfo player) { // Execution conditions: Client is the host, IsDead is overridden, player is already disconnected - if (!AmongUsClient.Instance.AmHost || !IsCached || !player.Disconnected) - { - return; - } + if (!AmongUsClient.Instance.AmHost || !IsCached || !player.Disconnected) return; IsDeadCache[player.PlayerId] = (true, true); RevivePlayersAndSetDummyImp(); @@ -168,33 +151,22 @@ namespace EHR public static void SetRealPlayerRoles() { - if (CustomWinnerHolder.WinnerTeam != CustomWinner.Default) - { - return; - } + if (CustomWinnerHolder.WinnerTeam != CustomWinner.Default) return; foreach (((byte seerId, byte targetId), (RoleTypes roletype, _)) in StartGameHostPatch.RpcSetRoleReplacer.RoleMap) { - if (seerId == 0) - { - continue; // Skip the host - } + if (seerId == 0) continue; // Skip the host PlayerControl seer = Utils.GetPlayerById(seerId); PlayerControl target = Utils.GetPlayerById(targetId); - if (seer == null || target == null) - { - continue; - } + if (seer == null || target == null) continue; - if (seer.IsModClient()) - { - continue; - } + if (seer.IsModClient()) continue; bool self = seerId == targetId; RoleTypes changedRoleType = roletype; + if (target.Data.IsDead) { if (self) @@ -202,29 +174,20 @@ namespace EHR target.RpcExile(); if (target.GetCustomRole().IsGhostRole() || target.HasGhostRole()) - { changedRoleType = RoleTypes.GuardianAngel; - } else if (target.Is(Team.Impostor) || target.HasDesyncRole()) - { changedRoleType = RoleTypes.ImpostorGhost; - } else - { changedRoleType = RoleTypes.CrewmateGhost; - } } else { bool seerIsKiller = seer.Is(Team.Impostor) || seer.HasDesyncRole(); + if (!seerIsKiller && target.Is(Team.Impostor)) - { changedRoleType = RoleTypes.ImpostorGhost; - } else - { changedRoleType = RoleTypes.CrewmateGhost; - } } } @@ -241,15 +204,9 @@ namespace EHR seer.RpcResetAbilityCooldown(); seer.ResetKillCooldown(); - if (Main.AllPlayerKillCooldown.TryGetValue(seer.PlayerId, out float kcd) && kcd >= 2f) - { - seer.SetKillCooldown(kcd - 2f); - } - } - else if (seer.HasGhostRole()) - { - seer.RpcResetAbilityCooldown(); + if (Main.AllPlayerKillCooldown.TryGetValue(seer.PlayerId, out float kcd) && kcd >= 2f) seer.SetKillCooldown(kcd - 2f); } + else if (seer.HasGhostRole()) seer.RpcResetAbilityCooldown(); } } diff --git a/Modules/BanManager.cs b/Modules/BanManager.cs index 200bd92ee..82b67ed54 100644 --- a/Modules/BanManager.cs +++ b/Modules/BanManager.cs @@ -59,12 +59,10 @@ namespace EHR stream.Position = 0; using StreamReader sr = new(stream, Encoding.UTF8); string line; + while ((line = sr.ReadLine()) != null) { - if (line == "" || line.StartsWith("#")) - { - continue; - } + if (line == "" || line.StartsWith("#")) continue; EACList.Add(line); } @@ -85,13 +83,10 @@ namespace EHR public static string GetHashedPuid(this ClientData player) { - if (player == null) - { - return string.Empty; - } + if (player == null) return string.Empty; string puid = player.ProductUserId; - using SHA256 sha256 = SHA256.Create(); + using var sha256 = SHA256.Create(); // get sha-256 hash byte[] sha256Bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(puid)); string sha256Hash = BitConverter.ToString(sha256Bytes).Replace("-", "").ToLower(); @@ -102,10 +97,7 @@ namespace EHR public static void AddBanPlayer(ClientData player) { - if (!AmongUsClient.Instance.AmHost || player == null) - { - return; - } + if (!AmongUsClient.Instance.AmHost || player == null) return; if (!CheckBanList(player.FriendCode, player.GetHashedPuid()) && !TempBanWhiteList.Contains(player.GetHashedPuid())) { @@ -115,34 +107,24 @@ namespace EHR Logger.SendInGame(string.Format(GetString("Message.AddedPlayerToBanList"), player.PlayerName)); } else - { Logger.Info($"Failed to add player {player.PlayerName.RemoveHtmlTags()}/{player.FriendCode}/{player.GetHashedPuid()} to ban list!", "AddBanPlayer"); - } } } public static bool CheckDenyNamePlayer(PlayerControl player, string name) { - if (!AmongUsClient.Instance.AmHost || !Options.ApplyDenyNameList.GetBool()) - { - return false; - } + if (!AmongUsClient.Instance.AmHost || !Options.ApplyDenyNameList.GetBool()) return false; try { Directory.CreateDirectory("EHR_DATA"); - if (!File.Exists(DenyNameListPath)) - { - File.Create(DenyNameListPath).Close(); - } + if (!File.Exists(DenyNameListPath)) File.Create(DenyNameListPath).Close(); using StreamReader sr = new(DenyNameListPath); + while (sr.ReadLine() is { } line) { - if (line == "") - { - continue; - } + if (line == "") continue; if (line.Contains("Amogus") || line.Contains("Amogus V") || Regex.IsMatch(name, line)) { @@ -164,12 +146,10 @@ namespace EHR public static void CheckBanPlayer(ClientData player) { - if (!AmongUsClient.Instance.AmHost || !Options.ApplyBanList.GetBool()) - { - return; - } + if (!AmongUsClient.Instance.AmHost || !Options.ApplyBanList.GetBool()) return; string friendcode = player?.FriendCode; + if (friendcode?.Length < 7) // #1234 is 5 chars, and it's impossible for a friend code to only have 3 { AmongUsClient.Instance.KickPlayer(player.Id, true); @@ -189,6 +169,7 @@ namespace EHR // Contains any non-word character or digits const string pattern = @"[\W\d]"; + if (Regex.IsMatch(friendcode[..friendcode.IndexOf("#", StringComparison.Ordinal)], pattern)) { AmongUsClient.Instance.KickPlayer(player.Id, true); @@ -222,45 +203,29 @@ namespace EHR public static bool CheckBanList(string code, string hashedpuid = "") { - bool OnlyCheckPuid = false; + var OnlyCheckPuid = false; + if (code == "" && hashedpuid != "") - { OnlyCheckPuid = true; - } - else if (code == "") - { - return false; - } + else if (code == "") return false; try { Directory.CreateDirectory("EHR_DATA"); - if (!File.Exists(BanListPath)) - { - File.Create(BanListPath).Close(); - } + if (!File.Exists(BanListPath)) File.Create(BanListPath).Close(); using StreamReader sr = new(BanListPath); string line; + while ((line = sr.ReadLine()) != null) { - if (line == "") - { - continue; - } + if (line == "") continue; if (!OnlyCheckPuid) - { if (line.Contains(code)) - { return true; - } - } - if (line.Contains(hashedpuid)) - { - return true; - } + if (line.Contains(hashedpuid)) return true; } } catch (Exception ex) @@ -273,7 +238,8 @@ namespace EHR public static bool CheckEACList(string code, string hashedPuid) { - bool OnlyCheckPuid = false; + var OnlyCheckPuid = false; + switch (code) { case "" when hashedPuid == "": @@ -293,15 +259,9 @@ namespace EHR public static void Postfix(BanMenu __instance, int clientId) { ClientData recentClient = AmongUsClient.Instance.GetRecentClient(clientId); - if (recentClient == null) - { - return; - } + if (recentClient == null) return; - if (!BanManager.CheckBanList(recentClient.FriendCode, recentClient.GetHashedPuid())) - { - __instance.BanButton.GetComponent().SetEnabledColors(); - } + if (!BanManager.CheckBanList(recentClient.FriendCode, recentClient.GetHashedPuid())) __instance.BanButton.GetComponent().SetEnabledColors(); } } } \ No newline at end of file diff --git a/Modules/Camouflague.cs b/Modules/Camouflague.cs index 475885351..819ff79b7 100644 --- a/Modules/Camouflague.cs +++ b/Modules/Camouflague.cs @@ -77,10 +77,7 @@ namespace EHR public static bool CheckCamouflage() { - if (!AmongUsClient.Instance.AmHost || (!Options.CommsCamouflage.GetBool() && !Camouflager.On)) - { - return false; - } + if (!AmongUsClient.Instance.AmHost || (!Options.CommsCamouflage.GetBool() && !Camouflager.On)) return false; bool oldIsCamouflage = IsCamouflage; @@ -102,10 +99,7 @@ namespace EHR RpcSetSkin(pc); - if (!IsCamouflage && !pc.IsAlive()) - { - PetsPatch.RpcRemovePet(pc); - } + if (!IsCamouflage && !pc.IsAlive()) PetsPatch.RpcRemovePet(pc); } Utils.NotifyRoles(NoCache: true); @@ -117,33 +111,22 @@ namespace EHR public static void RpcSetSkin(PlayerControl target, bool ForceRevert = false, bool RevertToDefault = false, bool GameEnd = false) { - if (!AmongUsClient.Instance.AmHost || (!Options.CommsCamouflage.GetBool() && !Camouflager.On) || target == null || (BlockCamouflage && !ForceRevert && !RevertToDefault && !GameEnd)) - { - return; - } + if (!AmongUsClient.Instance.AmHost || (!Options.CommsCamouflage.GetBool() && !Camouflager.On) || target == null || (BlockCamouflage && !ForceRevert && !RevertToDefault && !GameEnd)) return; Logger.Info($"New outfit for {target.GetNameWithRole()}", "Camouflage.RpcSetSkin"); byte id = target.PlayerId; - if (IsCamouflage && Main.PlayerStates[id].IsDead) - { - return; - } + if (IsCamouflage && Main.PlayerStates[id].IsDead) return; NetworkedPlayerInfo.PlayerOutfit newOutfit = CamouflageOutfit; if (!IsCamouflage || ForceRevert) { - if (id.IsPlayerShifted() && !RevertToDefault) - { - id = Main.ShapeshiftTarget[id]; - } + if (id.IsPlayerShifted() && !RevertToDefault) id = Main.ShapeshiftTarget[id]; if (!GameEnd && Doppelganger.DoppelPresentSkin.TryGetValue(id, out NetworkedPlayerInfo.PlayerOutfit value)) - { newOutfit = value; - } else { if (GameEnd && Doppelganger.DoppelVictim.TryGetValue(id, out string value1)) @@ -167,9 +150,10 @@ namespace EHR Logger.Info($"Setting new outfit: {newOutfit.GetString()}", "Camouflage.RpcSetSkin"); - CustomRpcSender sender = CustomRpcSender.Create($"Camouflage.RpcSetSkin({target.Data.PlayerName})"); + var sender = CustomRpcSender.Create($"Camouflage.RpcSetSkin({target.Data.PlayerName})"); target.SetColor(newOutfit.ColorId); + sender.AutoStartRpc(target.NetId, (byte)RpcCalls.SetColor) .Write(target.Data.NetId) .Write((byte)newOutfit.ColorId) @@ -177,6 +161,7 @@ namespace EHR target.SetHat(newOutfit.HatId, newOutfit.ColorId); target.Data.DefaultOutfit.HatSequenceId += 10; + sender.AutoStartRpc(target.NetId, (byte)RpcCalls.SetHatStr) .Write(newOutfit.HatId) .Write(target.GetNextRpcSequenceId(RpcCalls.SetHatStr)) @@ -184,6 +169,7 @@ namespace EHR target.SetSkin(newOutfit.SkinId, newOutfit.ColorId); target.Data.DefaultOutfit.SkinSequenceId += 10; + sender.AutoStartRpc(target.NetId, (byte)RpcCalls.SetSkinStr) .Write(newOutfit.SkinId) .Write(target.GetNextRpcSequenceId(RpcCalls.SetSkinStr)) @@ -191,6 +177,7 @@ namespace EHR target.SetVisor(newOutfit.VisorId, newOutfit.ColorId); target.Data.DefaultOutfit.VisorSequenceId += 10; + sender.AutoStartRpc(target.NetId, (byte)RpcCalls.SetVisorStr) .Write(newOutfit.VisorId) .Write(target.GetNextRpcSequenceId(RpcCalls.SetVisorStr)) @@ -198,6 +185,7 @@ namespace EHR target.SetPet(newOutfit.PetId); target.Data.DefaultOutfit.PetSequenceId += 10; + sender.AutoStartRpc(target.NetId, (byte)RpcCalls.SetPetStr) .Write(newOutfit.PetId) .Write(target.GetNextRpcSequenceId(RpcCalls.SetPetStr)) @@ -208,18 +196,12 @@ namespace EHR public static void OnFixedUpdate(PlayerControl pc) { - if (!WaitingForSkinChange.Contains(pc.PlayerId) || pc.inVent || pc.walkingToVent || pc.onLadder || pc.inMovingPlat) - { - return; - } + if (!WaitingForSkinChange.Contains(pc.PlayerId) || pc.inVent || pc.walkingToVent || pc.onLadder || pc.inMovingPlat) return; RpcSetSkin(pc); WaitingForSkinChange.Remove(pc.PlayerId); - if (!IsCamouflage && !pc.IsAlive()) - { - PetsPatch.RpcRemovePet(pc); - } + if (!IsCamouflage && !pc.IsAlive()) PetsPatch.RpcRemovePet(pc); Utils.NotifyRoles(SpecifySeer: pc, NoCache: true); Utils.NotifyRoles(SpecifyTarget: pc, NoCache: true); diff --git a/Modules/CheckAUVersion.cs b/Modules/CheckAUVersion.cs index 989dd70b9..b8e20424c 100644 --- a/Modules/CheckAUVersion.cs +++ b/Modules/CheckAUVersion.cs @@ -19,10 +19,7 @@ namespace EHR.Modules IsSupported = AmongUsVersion >= SupportedVersion; Logger.Info($" {IsSupported}", "Version Is Supported?"); - if (!IsSupported) - { - ErrorText.Instance.AddError(ErrorCode.UnsupportedVersion); - } + if (!IsSupported) ErrorText.Instance.AddError(ErrorCode.UnsupportedVersion); } } } \ No newline at end of file diff --git a/Modules/ClientOptionItem.cs b/Modules/ClientOptionItem.cs index 558dca72b..9aaf6dcc2 100644 --- a/Modules/ClientOptionItem.cs +++ b/Modules/ClientOptionItem.cs @@ -38,19 +38,17 @@ namespace EHR closeButton.name = "Back"; closeButton.Text.text = Translator.GetString("Back"); closeButton.Background.color = Palette.DisabledGrey; - PassiveButton closePassiveButton = closeButton.GetComponent(); + var closePassiveButton = closeButton.GetComponent(); closePassiveButton.OnClick = new(); closePassiveButton.OnClick.AddListener(new Action(() => { CustomBackground.gameObject.SetActive(false); })); UiElement[] selectableButtons = optionsMenuBehaviour.ControllerSelectable.ToArray(); PassiveButton leaveButton = null; PassiveButton returnButton = null; + foreach (UiElement button in selectableButtons) { - if (button == null) - { - continue; - } + if (button == null) continue; switch (button.name) { @@ -70,41 +68,36 @@ namespace EHR modOptionsButton.name = "EHROptions"; modOptionsButton.Text.text = Translator.GetString("EHROptions"); modOptionsButton.Background.color = new Color32(0, 165, 255, byte.MaxValue); - PassiveButton modOptionsPassiveButton = modOptionsButton.GetComponent(); + var modOptionsPassiveButton = modOptionsButton.GetComponent(); modOptionsPassiveButton.OnClick = new(); modOptionsPassiveButton.OnClick.AddListener(new Action(() => CustomBackground.gameObject.SetActive(true))); - if (leaveButton != null && leaveButton.transform != null) - { - leaveButton.transform.localPosition = new(-1.35f, -2.411f, -1f); - } + if (leaveButton != null && leaveButton.transform != null) leaveButton.transform.localPosition = new(-1.35f, -2.411f, -1f); - if (returnButton != null) - { - returnButton.transform.localPosition = new(1.35f, -2.411f, -1f); - } + if (returnButton != null) returnButton.transform.localPosition = new(1.35f, -2.411f, -1f); } ToggleButton = Object.Instantiate(mouseMoveToggle, CustomBackground.transform); + ToggleButton.transform.localPosition = new( NumOptions % 2 == 0 ? -1.3f : 1.3f, // ReSharper disable once PossibleLossOfFraction 2.2f - (0.5f * (NumOptions / 2)), -6f); + ToggleButton.name = name; ToggleButton.Text.text = Translator.GetString(name); - PassiveButton passiveButton = ToggleButton.GetComponent(); + var passiveButton = ToggleButton.GetComponent(); passiveButton.OnClick = new(); + passiveButton.OnClick.AddListener(new Action(() => { - if (config != null) - { - config.Value = !config.Value; - } + if (config != null) config.Value = !config.Value; UpdateToggle(); additionalOnClickAction?.Invoke(); })); + UpdateToggle(); } finally @@ -124,10 +117,7 @@ namespace EHR public void UpdateToggle() { - if (ToggleButton == null) - { - return; - } + if (ToggleButton == null) return; Color32 color = Config is { Value: true } ? new(0, 165, 255, byte.MaxValue) : new Color32(77, 77, 77, byte.MaxValue); ToggleButton.Background.color = color; diff --git a/Modules/Cloud.cs b/Modules/Cloud.cs index e8cb42e23..541fa18bd 100644 --- a/Modules/Cloud.cs +++ b/Modules/Cloud.cs @@ -80,12 +80,10 @@ namespace EHR public static void StartConnect() { - if (connecting || (EacClientSocket != null && EacClientSocket.Connected)) - { - return; - } + if (connecting || (EacClientSocket != null && EacClientSocket.Connected)) return; connecting = true; + LateTask.New(() => { if (!AmongUsClient.Instance.AmHost || !GameData.Instance || AmongUsClient.Instance.NetworkMode == NetworkModes.LocalGame) @@ -96,10 +94,7 @@ namespace EHR try { - if (IP == null || EAC_PORT == 0) - { - throw new("Has no ip or port"); - } + if (IP == null || EAC_PORT == 0) throw new("Has no ip or port"); LastRepotTimeStamp = Utils.TimeStamp; EacClientSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); @@ -119,15 +114,13 @@ namespace EHR public static void StopConnect() { - if (EacClientSocket != null && EacClientSocket.Connected) - { - EacClientSocket.Close(); - } + if (EacClientSocket != null && EacClientSocket.Connected) EacClientSocket.Close(); } public static void SendData(string msg) { StartConnect(); + if (EacClientSocket == null || !EacClientSocket.Connected) { Logger.Warn("未连接至EHR服务器,报告被取消", "EAC Cloud"); diff --git a/Modules/CustomNetObject.cs b/Modules/CustomNetObject.cs index 2f860ef5a..d65ca22a5 100644 --- a/Modules/CustomNetObject.cs +++ b/Modules/CustomNetObject.cs @@ -29,12 +29,10 @@ namespace EHR public void RpcChangeSprite(string sprite) { - if (this is not DisasterWarningTimer) - { - Logger.Info($" Change Custom Net Object {GetType().Name} (ID {Id}) sprite", "CNO.RpcChangeSprite"); - } + if (this is not DisasterWarningTimer) Logger.Info($" Change Custom Net Object {GetType().Name} (ID {Id}) sprite", "CNO.RpcChangeSprite"); Sprite = sprite; + LateTask.New(() => { playerControl.RawSetName(sprite); @@ -44,7 +42,7 @@ namespace EHR string skinId = PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].SkinId; string petId = PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PetId; string visorId = PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].VisorId; - CustomRpcSender sender = CustomRpcSender.Create("SetFakeData"); + var sender = CustomRpcSender.Create("SetFakeData"); MessageWriter writer = sender.stream; sender.StartMessage(); PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PlayerName = "
" + sprite; @@ -54,15 +52,19 @@ namespace EHR PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PetId = ""; PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].VisorId = ""; writer.StartMessage(1); + { writer.WritePacked(PlayerControl.LocalPlayer.Data.NetId); PlayerControl.LocalPlayer.Data.Serialize(writer, false); } + writer.EndMessage(); + sender.StartRpc(playerControl.NetId, (byte)RpcCalls.Shapeshift) .WriteNetObject(PlayerControl.LocalPlayer) .Write(false) .EndRpc(); + PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PlayerName = name; PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].ColorId = colorId; PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].HatId = hatId; @@ -70,10 +72,12 @@ namespace EHR PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PetId = petId; PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].VisorId = visorId; writer.StartMessage(1); + { writer.WritePacked(PlayerControl.LocalPlayer.Data.NetId); PlayerControl.LocalPlayer.Data.Serialize(writer, false); } + writer.EndMessage(); sender.EndMessage(); sender.SendMessage(); @@ -89,6 +93,7 @@ namespace EHR public void Despawn() { Logger.Info($" Despawn Custom Net Object {GetType().Name} (ID {Id})", "CNO.Despawn"); + try { playerControl.Despawn(); @@ -98,10 +103,7 @@ namespace EHR { if (Options.CurrentGameMode == CustomGameMode.NaturalDisasters) { - if (HiddenList.Contains(PlayerControl.LocalPlayer.PlayerId)) - { - return; - } + if (HiddenList.Contains(PlayerControl.LocalPlayer.PlayerId)) return; Logger.Warn("Error during despawn, hiding instead", "CNO.Despawn"); Main.AllPlayerControls.Do(Hide); @@ -117,6 +119,7 @@ namespace EHR Logger.Info($" Hide Custom Net Object {GetType().Name} (ID {Id}) from {player.GetNameWithRole()}", "CNO.Hide"); HiddenList.Add(player.PlayerId); + if (player.AmOwner) { LateTask.New(() => playerControl.transform.FindChild("Names").FindChild("NameText_TMP").gameObject.SetActive(false), 0.1f); @@ -126,11 +129,13 @@ namespace EHR LateTask.New(() => { - CustomRpcSender sender = CustomRpcSender.Create("FixModdedClientCNOText", SendOption.Reliable); + var sender = CustomRpcSender.Create("FixModdedClientCNOText", SendOption.Reliable); + sender.AutoStartRpc(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.FixModdedClientCNO, player.GetClientId()) .WriteNetObject(playerControl) .Write(false) .EndRpc(); + sender.SendMessage(); }, 0.4f); @@ -149,6 +154,7 @@ namespace EHR protected virtual void OnFixedUpdate() { PlayerControlTimer += Time.fixedDeltaTime; + if (PlayerControlTimer > 20f) { Logger.Info($" Recreate Custom Net Object {GetType().Name} (ID {Id})", "CNO.OnFixedUpdate"); @@ -166,6 +172,7 @@ namespace EHR msg.StartMessage(6); msg.Write(AmongUsClient.Instance.GameId); msg.WritePacked(int.MaxValue); + for (uint i = 1; i <= 3; ++i) { msg.StartMessage(4); @@ -182,10 +189,7 @@ namespace EHR msg.EndMessage(); AmongUsClient.Instance.SendOrDisconnect(msg); msg.Recycle(); - if (PlayerControl.AllPlayerControls.Contains(playerControl)) - { - PlayerControl.AllPlayerControls.Remove(playerControl); - } + if (PlayerControl.AllPlayerControls.Contains(playerControl)) PlayerControl.AllPlayerControls.Remove(playerControl); LateTask.New(() => { @@ -197,7 +201,7 @@ namespace EHR string skinId = PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].SkinId; string petId = PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PetId; string visorId = PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].VisorId; - CustomRpcSender sender = CustomRpcSender.Create("SetFakeData"); + var sender = CustomRpcSender.Create("SetFakeData"); MessageWriter writer = sender.stream; sender.StartMessage(); PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PlayerName = "
" + Sprite; @@ -207,15 +211,19 @@ namespace EHR PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PetId = ""; PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].VisorId = ""; writer.StartMessage(1); + { writer.WritePacked(PlayerControl.LocalPlayer.Data.NetId); PlayerControl.LocalPlayer.Data.Serialize(writer, false); } + writer.EndMessage(); + sender.StartRpc(playerControl.NetId, (byte)RpcCalls.Shapeshift) .WriteNetObject(PlayerControl.LocalPlayer) .Write(false) .EndRpc(); + PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PlayerName = name; PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].ColorId = colorId; PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].HatId = hatId; @@ -223,44 +231,51 @@ namespace EHR PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PetId = petId; PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].VisorId = visorId; writer.StartMessage(1); + { writer.WritePacked(PlayerControl.LocalPlayer.Data.NetId); PlayerControl.LocalPlayer.Data.Serialize(writer, false); } + writer.EndMessage(); sender.EndMessage(); sender.SendMessage(); }, 0.2f); + LateTask.New(() => oldPlayerControl.Despawn(), 0.3f); + //playerControl.cosmetics.currentBodySprite.BodySprite.color = Color.clear; //playerControl.cosmetics.colorBlindText.color = Color.clear; foreach (PlayerControl pc in Main.AllPlayerControls) { - if (pc.AmOwner) - { - continue; - } + if (pc.AmOwner) continue; LateTask.New(() => { - CustomRpcSender sender = CustomRpcSender.Create("SetFakeData"); + var sender = CustomRpcSender.Create("SetFakeData"); MessageWriter writer = sender.stream; sender.StartMessage(pc.GetClientId()); writer.StartMessage(1); + { writer.WritePacked(playerControl.NetId); writer.Write(pc.PlayerId); } + writer.EndMessage(); + sender.StartRpc(playerControl.NetId, (byte)RpcCalls.MurderPlayer) .WriteNetObject(playerControl) .Write((int)MurderResultFlags.FailedError) .EndRpc(); + writer.StartMessage(1); + { writer.WritePacked(playerControl.NetId); writer.Write((byte)255); } + writer.EndMessage(); sender.EndMessage(); sender.SendMessage(); @@ -268,31 +283,27 @@ namespace EHR } foreach (PlayerControl pc in Main.AllPlayerControls) - { if (HiddenList.Contains(pc.PlayerId)) - { Hide(pc); - } - } LateTask.New(() => { // Fix for Host - if (!HiddenList.Contains(PlayerControl.LocalPlayer.PlayerId)) - { - playerControl.transform.FindChild("Names").FindChild("NameText_TMP").gameObject.SetActive(true); - } + if (!HiddenList.Contains(PlayerControl.LocalPlayer.PlayerId)) playerControl.transform.FindChild("Names").FindChild("NameText_TMP").gameObject.SetActive(true); }, 0.1f); + LateTask.New(() => { // Fix for Non-Host Modded foreach (PlayerControl visiblePC in Main.AllPlayerControls.ExceptBy(HiddenList, x => x.PlayerId)) { - CustomRpcSender sender = CustomRpcSender.Create("FixModdedClientCNOText", SendOption.Reliable); + var sender = CustomRpcSender.Create("FixModdedClientCNOText", SendOption.Reliable); + sender.AutoStartRpc(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.FixModdedClientCNO, visiblePC.GetClientId()) .WriteNetObject(playerControl) .Write(true) .EndRpc(); + sender.SendMessage(); } }, 0.4f); @@ -327,6 +338,7 @@ namespace EHR msg.StartMessage(6); msg.Write(AmongUsClient.Instance.GameId); msg.WritePacked(int.MaxValue); + for (uint i = 1; i <= 3; ++i) { msg.StartMessage(4); @@ -343,10 +355,7 @@ namespace EHR msg.EndMessage(); AmongUsClient.Instance.SendOrDisconnect(msg); msg.Recycle(); - if (PlayerControl.AllPlayerControls.Contains(playerControl)) - { - PlayerControl.AllPlayerControls.Remove(playerControl); - } + if (PlayerControl.AllPlayerControls.Contains(playerControl)) PlayerControl.AllPlayerControls.Remove(playerControl); LateTask.New(() => { @@ -358,7 +367,7 @@ namespace EHR string skinId = PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].SkinId; string petId = PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PetId; string visorId = PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].VisorId; - CustomRpcSender sender = CustomRpcSender.Create("SetFakeData"); + var sender = CustomRpcSender.Create("SetFakeData"); MessageWriter writer = sender.stream; sender.StartMessage(); PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PlayerName = "
" + sprite; @@ -368,15 +377,19 @@ namespace EHR PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PetId = ""; PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].VisorId = ""; writer.StartMessage(1); + { writer.WritePacked(PlayerControl.LocalPlayer.Data.NetId); PlayerControl.LocalPlayer.Data.Serialize(writer, false); } + writer.EndMessage(); + sender.StartRpc(playerControl.NetId, (byte)RpcCalls.Shapeshift) .WriteNetObject(PlayerControl.LocalPlayer) .Write(false) .EndRpc(); + PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PlayerName = name; PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].ColorId = colorId; PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].HatId = hatId; @@ -384,14 +397,17 @@ namespace EHR PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].PetId = petId; PlayerControl.LocalPlayer.Data.Outfits[PlayerOutfitType.Default].VisorId = visorId; writer.StartMessage(1); + { writer.WritePacked(PlayerControl.LocalPlayer.Data.NetId); PlayerControl.LocalPlayer.Data.Serialize(writer, false); } + writer.EndMessage(); sender.EndMessage(); sender.SendMessage(); }, 0.2f); + Position = position; PlayerControlTimer = 0f; //playerControl.cosmetics.currentBodySprite.BodySprite.color = Color.clear; @@ -399,39 +415,40 @@ namespace EHR Sprite = sprite; ++MaxId; Id = MaxId; - if (MaxId == int.MaxValue) - { - MaxId = int.MinValue; - } + if (MaxId == int.MaxValue) MaxId = int.MinValue; AllObjects.Add(this); + foreach (PlayerControl pc in Main.AllPlayerControls) { - if (pc.AmOwner) - { - continue; - } + if (pc.AmOwner) continue; LateTask.New(() => { - CustomRpcSender sender = CustomRpcSender.Create("SetFakeData"); + var sender = CustomRpcSender.Create("SetFakeData"); MessageWriter writer = sender.stream; sender.StartMessage(pc.GetClientId()); writer.StartMessage(1); + { writer.WritePacked(playerControl.NetId); writer.Write(pc.PlayerId); } + writer.EndMessage(); + sender.StartRpc(playerControl.NetId, (byte)RpcCalls.MurderPlayer) .WriteNetObject(playerControl) .Write((int)MurderResultFlags.FailedError) .EndRpc(); + writer.StartMessage(1); + { writer.WritePacked(playerControl.NetId); writer.Write((byte)255); } + writer.EndMessage(); sender.EndMessage(); sender.SendMessage(); @@ -444,10 +461,7 @@ namespace EHR public static void FixedUpdate() { - foreach (CustomNetObject cno in AllObjects.ToArray()) - { - cno?.OnFixedUpdate(); - } + foreach (CustomNetObject cno in AllObjects.ToArray()) cno?.OnFixedUpdate(); } public static CustomNetObject Get(int id) @@ -579,10 +593,7 @@ namespace EHR try { - if (Gone) - { - return; - } + if (Gone) return; if (SpawnTimeStamp + Tornado.TornadoDuration.GetInt() < Utils.TimeStamp) { @@ -705,10 +716,7 @@ namespace EHR base.OnFixedUpdate(); int oldTime = Time; Timer -= UnityEngine.Time.fixedDeltaTime; - if (Time != oldTime) - { - RpcChangeSprite($"{Time:N0}\n{Disaster}"); - } + if (Time != oldTime) RpcChangeSprite($"{Time:N0}\n{Disaster}"); } } @@ -730,12 +738,10 @@ namespace EHR public void Update() { - if (float.IsNaN(SpawnTimer)) - { - return; - } + if (float.IsNaN(SpawnTimer)) return; SpawnTimer -= Time.fixedDeltaTime; + if (SpawnTimer <= 0f) { WarningTimer.Despawn(); @@ -758,10 +764,7 @@ namespace EHR { base.OnFixedUpdate(); Timer -= Time.fixedDeltaTime; - if (Timer <= 0) - { - Despawn(); - } + if (Timer <= 0) Despawn(); } } } @@ -771,12 +774,9 @@ internal static class RawSetNamePatch { public static bool Prefix(PlayerControl __instance, [HarmonyArgument(0)] string name) { - if (Options.CurrentGameMode != CustomGameMode.NaturalDisasters) - { - return true; - } + if (Options.CurrentGameMode != CustomGameMode.NaturalDisasters) return true; - bool exception = false; + var exception = false; try { diff --git a/Modules/CustomRoleSelector.cs b/Modules/CustomRoleSelector.cs index 214dc9269..9ca92c633 100644 --- a/Modules/CustomRoleSelector.cs +++ b/Modules/CustomRoleSelector.cs @@ -23,27 +23,18 @@ namespace EHR.Modules private static void GetNeutralCounts(int NKmaxOpt, int NKminOpt, int NNKmaxOpt, int NNKminOpt, ref int ResultNKnum, ref int ResultNNKnum) { - IRandom rd = IRandom.Instance; + var rd = IRandom.Instance; - if (NNKmaxOpt > 0 && NNKmaxOpt >= NNKminOpt) - { - ResultNNKnum = rd.Next(NNKminOpt, NNKmaxOpt + 1); - } + if (NNKmaxOpt > 0 && NNKmaxOpt >= NNKminOpt) ResultNNKnum = rd.Next(NNKminOpt, NNKmaxOpt + 1); - if (NKmaxOpt > 0 && NKmaxOpt >= NKminOpt) - { - ResultNKnum = rd.Next(NKminOpt, NKmaxOpt + 1); - } + if (NKmaxOpt > 0 && NKmaxOpt >= NKminOpt) ResultNKnum = rd.Next(NKminOpt, NKmaxOpt + 1); } public static void SelectCustomRoles() { RoleResult = []; - if (Main.GM.Value && Main.AllPlayerControls.Length == 1) - { - return; - } + if (Main.GM.Value && Main.AllPlayerControls.Length == 1) return; switch (Options.CurrentGameMode) { @@ -77,28 +68,25 @@ namespace EHR.Modules return; } - IRandom rd = IRandom.Instance; + var rd = IRandom.Instance; int playerCount = Main.AllAlivePlayerControls.Length; int optImpNum = Main.RealOptionsData.GetInt(Int32OptionNames.NumImpostors); - int optNonNeutralKillingNum = 0; - int optNeutralKillingNum = 0; + var optNonNeutralKillingNum = 0; + var optNeutralKillingNum = 0; GetNeutralCounts(Options.NeutralKillingRolesMaxPlayer.GetInt(), Options.NeutralKillingRolesMinPlayer.GetInt(), Options.NonNeutralKillingRolesMaxPlayer.GetInt(), Options.NonNeutralKillingRolesMinPlayer.GetInt(), ref optNeutralKillingNum, ref optNonNeutralKillingNum); - int readyRoleNum = 0; - int readyImpNum = 0; - int readyNonNeutralKillingNum = 0; - int readyNeutralKillingNum = 0; + var readyRoleNum = 0; + var readyImpNum = 0; + var readyNonNeutralKillingNum = 0; + var readyNeutralKillingNum = 0; List FinalRolesList = []; Dictionary> Roles = []; Enum.GetValues().Do(x => Roles[x] = []); - foreach (byte id in Main.SetRoles.Keys.Where(id => Utils.GetPlayerById(id) == null).ToArray()) - { - Main.SetRoles.Remove(id); - } + foreach (byte id in Main.SetRoles.Keys.Where(id => Utils.GetPlayerById(id) == null).ToArray()) Main.SetRoles.Remove(id); (bool Spawning, bool OneIsImp) LoversData = (Lovers.LegacyLovers.GetBool(), rd.Next(100) < Lovers.LovingImpostorSpawnChance.GetInt()); LoversData.Spawning &= rd.Next(100) < Options.CustomAdtRoleSpawnRate[CustomRoles.Lovers].GetInt(); @@ -106,10 +94,7 @@ namespace EHR.Modules foreach (CustomRoles role in Enum.GetValues()) { int chance = role.GetMode(); - if (role.IsVanilla() || chance == 0 || role.IsAdditionRole() || (role.OnlySpawnsWithPets() && !Options.UsePets.GetBool()) || (role != CustomRoles.Randomizer && role.IsCrewmate() && Options.AprilFoolsMode.GetBool()) || HnSManager.AllHnSRoles.Contains(role)) - { - continue; - } + if (role.IsVanilla() || chance == 0 || role.IsAdditionRole() || (role.OnlySpawnsWithPets() && !Options.UsePets.GetBool()) || (role != CustomRoles.Randomizer && role.IsCrewmate() && Options.AprilFoolsMode.GetBool()) || HnSManager.AllHnSRoles.Contains(role)) continue; switch (role) { @@ -140,21 +125,13 @@ namespace EHR.Modules RoleAssignInfo info = new(role, chance, count); if (role.IsImpostor()) - { Roles[RoleAssignType.Impostor].Add(info); - } else if (role.IsNK()) - { Roles[RoleAssignType.NeutralKilling].Add(info); - } else if (role.IsNonNK()) - { Roles[RoleAssignType.NonKillingNeutral].Add(info); - } else - { Roles[RoleAssignType.Crewmate].Add(info); - } } LoversData.OneIsImp &= Roles[RoleAssignType.Impostor].Count(x => x.SpawnChance == 100) < optImpNum; @@ -167,9 +144,7 @@ namespace EHR.Modules Roles[RoleAssignType.Impostor].Add(new(CustomRoles.LovingImpostor, 100, 1)); } else - { Roles[RoleAssignType.Crewmate].Add(new(CustomRoles.LovingCrewmate, 100, 2)); - } } if (Roles[RoleAssignType.Impostor].Count == 0 && optNeutralKillingNum == 0 && optNonNeutralKillingNum == 0 && !Main.SetRoles.Values.Any(x => x.IsImpostor() || x.IsNK())) @@ -243,10 +218,7 @@ namespace EHR.Modules foreach ((byte id, CustomRoles role) in Main.SetRoles.AddRange(ChatCommands.DraftResult, false)) { PlayerControl pc = AllPlayers.FirstOrDefault(x => x.PlayerId == id); - if (pc == null) - { - continue; - } + if (pc == null) continue; RoleResult[pc.PlayerId] = role; AllPlayers.Remove(pc); @@ -267,9 +239,7 @@ namespace EHR.Modules readyNonNeutralKillingNum++; } else - { Roles[RoleAssignType.Crewmate].DoIf(x => x.Role == role, x => x.AssignedCount++); - } readyRoleNum++; @@ -287,25 +257,19 @@ namespace EHR.Modules { List AlwaysImpRoles = []; List ChanceImpRoles = []; - for (int i = 0; i < Roles[RoleAssignType.Impostor].Count; i++) + + for (var i = 0; i < Roles[RoleAssignType.Impostor].Count; i++) { RoleAssignInfo item = Roles[RoleAssignType.Impostor][i]; + if (item.SpawnChance == 100) - { - for (int j = 0; j < item.MaxCount - item.AssignedCount; j++) - { + for (var j = 0; j < item.MaxCount - item.AssignedCount; j++) AlwaysImpRoles.Add(item.Role); - } - } else { - for (int j = 0; j < item.SpawnChance / 5; j++) - { - for (int k = 0; k < item.MaxCount - item.AssignedCount; k++) - { - ChanceImpRoles.Add(item.Role); - } - } + for (var j = 0; j < item.SpawnChance / 5; j++) + for (var k = 0; k < item.MaxCount - item.AssignedCount; k++) + ChanceImpRoles.Add(item.Role); } } @@ -320,10 +284,7 @@ namespace EHR.Modules CustomRoles selected = AlwaysImpRoles.RandomElement(); RoleAssignInfo info = ImpRoleCounts.FirstOrDefault(x => x.Role == selected); AlwaysImpRoles.Remove(selected); - if (info.AssignedCount >= info.MaxCount) - { - continue; - } + if (info.AssignedCount >= info.MaxCount) continue; FinalRolesList.Add(selected); info.AssignedCount++; @@ -332,15 +293,9 @@ namespace EHR.Modules Imps = ImpRoleCounts; - if (readyRoleNum >= playerCount) - { - goto EndOfAssign; - } + if (readyRoleNum >= playerCount) goto EndOfAssign; - if (readyImpNum >= optImpNum) - { - break; - } + if (readyImpNum >= optImpNum) break; } } @@ -351,10 +306,7 @@ namespace EHR.Modules { CustomRoles selected = ChanceImpRoles.RandomElement(); RoleAssignInfo info = ImpRoleCounts.FirstOrDefault(x => x.Role == selected); - for (int i = 0; i < info.SpawnChance / 5; i++) - { - ChanceImpRoles.Remove(selected); - } + for (var i = 0; i < info.SpawnChance / 5; i++) ChanceImpRoles.Remove(selected); FinalRolesList.Add(selected); info.AssignedCount++; @@ -364,22 +316,12 @@ namespace EHR.Modules Imps = ImpRoleCounts; if (info.AssignedCount >= info.MaxCount) - { while (ChanceImpRoles.Contains(selected)) - { ChanceImpRoles.Remove(selected); - } - } - if (readyRoleNum >= playerCount) - { - goto EndOfAssign; - } + if (readyRoleNum >= playerCount) goto EndOfAssign; - if (readyImpNum >= optImpNum) - { - break; - } + if (readyImpNum >= optImpNum) break; } } } @@ -390,25 +332,19 @@ namespace EHR.Modules { List AlwaysNNKRoles = []; List ChanceNNKRoles = []; - for (int i = 0; i < Roles[RoleAssignType.NonKillingNeutral].Count; i++) + + for (var i = 0; i < Roles[RoleAssignType.NonKillingNeutral].Count; i++) { RoleAssignInfo item = Roles[RoleAssignType.NonKillingNeutral][i]; + if (item.SpawnChance == 100) - { - for (int j = 0; j < item.MaxCount - item.AssignedCount; j++) - { + for (var j = 0; j < item.MaxCount - item.AssignedCount; j++) AlwaysNNKRoles.Add(item.Role); - } - } else { - for (int j = 0; j < item.SpawnChance / 5; j++) - { - for (int k = 0; k < item.MaxCount - item.AssignedCount; k++) - { - ChanceNNKRoles.Add(item.Role); - } - } + for (var j = 0; j < item.SpawnChance / 5; j++) + for (var k = 0; k < item.MaxCount - item.AssignedCount; k++) + ChanceNNKRoles.Add(item.Role); } } @@ -423,10 +359,7 @@ namespace EHR.Modules CustomRoles selected = AlwaysNNKRoles.RandomElement(); RoleAssignInfo info = NNKRoleCounts.FirstOrDefault(x => x.Role == selected); AlwaysNNKRoles.Remove(selected); - if (info.AssignedCount >= info.MaxCount) - { - continue; - } + if (info.AssignedCount >= info.MaxCount) continue; FinalRolesList.Add(selected); info.AssignedCount++; @@ -435,15 +368,9 @@ namespace EHR.Modules NNKs = NNKRoleCounts; - if (readyRoleNum >= playerCount) - { - goto EndOfAssign; - } + if (readyRoleNum >= playerCount) goto EndOfAssign; - if (readyNonNeutralKillingNum >= optNonNeutralKillingNum) - { - break; - } + if (readyNonNeutralKillingNum >= optNonNeutralKillingNum) break; } } @@ -454,10 +381,7 @@ namespace EHR.Modules { CustomRoles selected = ChanceNNKRoles.RandomElement(); RoleAssignInfo info = NNKRoleCounts.FirstOrDefault(x => x.Role == selected); - for (int i = 0; i < info.SpawnChance / 5; i++) - { - ChanceNNKRoles.Remove(selected); - } + for (var i = 0; i < info.SpawnChance / 5; i++) ChanceNNKRoles.Remove(selected); FinalRolesList.Add(selected); info.AssignedCount++; @@ -467,22 +391,12 @@ namespace EHR.Modules NNKs = NNKRoleCounts; if (info.AssignedCount >= info.MaxCount) - { while (ChanceNNKRoles.Contains(selected)) - { ChanceNNKRoles.Remove(selected); - } - } - if (readyRoleNum >= playerCount) - { - goto EndOfAssign; - } + if (readyRoleNum >= playerCount) goto EndOfAssign; - if (readyNonNeutralKillingNum >= optNonNeutralKillingNum) - { - break; - } + if (readyNonNeutralKillingNum >= optNonNeutralKillingNum) break; } } } @@ -491,25 +405,19 @@ namespace EHR.Modules { List AlwaysNKRoles = []; List ChanceNKRoles = []; - for (int i = 0; i < Roles[RoleAssignType.NeutralKilling].Count; i++) + + for (var i = 0; i < Roles[RoleAssignType.NeutralKilling].Count; i++) { RoleAssignInfo item = Roles[RoleAssignType.NeutralKilling][i]; + if (item.SpawnChance == 100) - { - for (int j = 0; j < item.MaxCount - item.AssignedCount; j++) - { + for (var j = 0; j < item.MaxCount - item.AssignedCount; j++) AlwaysNKRoles.Add(item.Role); - } - } else { - for (int j = 0; j < item.SpawnChance / 5; j++) - { - for (int k = 0; k < item.MaxCount - item.AssignedCount; k++) - { - ChanceNKRoles.Add(item.Role); - } - } + for (var j = 0; j < item.SpawnChance / 5; j++) + for (var k = 0; k < item.MaxCount - item.AssignedCount; k++) + ChanceNKRoles.Add(item.Role); } } @@ -524,10 +432,7 @@ namespace EHR.Modules CustomRoles selected = AlwaysNKRoles.RandomElement(); RoleAssignInfo info = NKRoleCounts.FirstOrDefault(x => x.Role == selected); AlwaysNKRoles.Remove(selected); - if (info.AssignedCount >= info.MaxCount) - { - continue; - } + if (info.AssignedCount >= info.MaxCount) continue; FinalRolesList.Add(selected); info.AssignedCount++; @@ -536,15 +441,9 @@ namespace EHR.Modules NKs = NKRoleCounts; - if (readyRoleNum >= playerCount) - { - goto EndOfAssign; - } + if (readyRoleNum >= playerCount) goto EndOfAssign; - if (readyNeutralKillingNum >= optNeutralKillingNum) - { - break; - } + if (readyNeutralKillingNum >= optNeutralKillingNum) break; } } @@ -555,10 +454,7 @@ namespace EHR.Modules { CustomRoles selected = ChanceNKRoles.RandomElement(); RoleAssignInfo info = NKRoleCounts.FirstOrDefault(x => x.Role == selected); - for (int i = 0; i < info.SpawnChance / 5; i++) - { - ChanceNKRoles.Remove(selected); - } + for (var i = 0; i < info.SpawnChance / 5; i++) ChanceNKRoles.Remove(selected); FinalRolesList.Add(selected); info.AssignedCount++; @@ -568,22 +464,12 @@ namespace EHR.Modules NKs = NKRoleCounts; if (info.AssignedCount >= info.MaxCount) - { while (ChanceNKRoles.Contains(selected)) - { ChanceNKRoles.Remove(selected); - } - } - if (readyRoleNum >= playerCount) - { - goto EndOfAssign; - } + if (readyRoleNum >= playerCount) goto EndOfAssign; - if (readyNeutralKillingNum >= optNeutralKillingNum) - { - break; - } + if (readyNeutralKillingNum >= optNeutralKillingNum) break; } } } @@ -593,25 +479,19 @@ namespace EHR.Modules { List AlwaysCrewRoles = []; List ChanceCrewRoles = []; - for (int i = 0; i < Roles[RoleAssignType.Crewmate].Count; i++) + + for (var i = 0; i < Roles[RoleAssignType.Crewmate].Count; i++) { RoleAssignInfo item = Roles[RoleAssignType.Crewmate][i]; + if (item.SpawnChance == 100) - { - for (int j = 0; j < item.MaxCount - item.AssignedCount; j++) - { + for (var j = 0; j < item.MaxCount - item.AssignedCount; j++) AlwaysCrewRoles.Add(item.Role); - } - } else { - for (int j = 0; j < item.SpawnChance / 5; j++) - { - for (int k = 0; k < item.MaxCount - item.AssignedCount; k++) - { - ChanceCrewRoles.Add(item.Role); - } - } + for (var j = 0; j < item.SpawnChance / 5; j++) + for (var k = 0; k < item.MaxCount - item.AssignedCount; k++) + ChanceCrewRoles.Add(item.Role); } } @@ -626,10 +506,7 @@ namespace EHR.Modules CustomRoles selected = AlwaysCrewRoles.RandomElement(); RoleAssignInfo info = CrewRoleCounts.FirstOrDefault(x => x.Role == selected); AlwaysCrewRoles.Remove(selected); - if (info.AssignedCount >= info.MaxCount) - { - continue; - } + if (info.AssignedCount >= info.MaxCount) continue; FinalRolesList.Add(selected); info.AssignedCount++; @@ -637,10 +514,7 @@ namespace EHR.Modules Crews = CrewRoleCounts; - if (readyRoleNum >= playerCount) - { - goto EndOfAssign; - } + if (readyRoleNum >= playerCount) goto EndOfAssign; } } @@ -651,10 +525,7 @@ namespace EHR.Modules { CustomRoles selected = ChanceCrewRoles.RandomElement(); RoleAssignInfo info = CrewRoleCounts.FirstOrDefault(x => x.Role == selected); - for (int i = 0; i < info.SpawnChance / 5; i++) - { - ChanceCrewRoles.Remove(selected); - } + for (var i = 0; i < info.SpawnChance / 5; i++) ChanceCrewRoles.Remove(selected); FinalRolesList.Add(selected); info.AssignedCount++; @@ -663,57 +534,29 @@ namespace EHR.Modules Crews = CrewRoleCounts; if (info.AssignedCount >= info.MaxCount) - { while (ChanceCrewRoles.Contains(selected)) - { ChanceCrewRoles.Remove(selected); - } - } - if (readyRoleNum >= playerCount) - { - goto EndOfAssign; - } + if (readyRoleNum >= playerCount) goto EndOfAssign; } } } EndOfAssign: - if (Imps.Length > 0) - { - Logger.Info(string.Join(", ", Imps.Select(x => $"{x.Role} - {x.AssignedCount}/{x.MaxCount} ({x.SpawnChance}%)")), "ImpRoleResult"); - } + if (Imps.Length > 0) Logger.Info(string.Join(", ", Imps.Select(x => $"{x.Role} - {x.AssignedCount}/{x.MaxCount} ({x.SpawnChance}%)")), "ImpRoleResult"); - if (NNKs.Length > 0) - { - Logger.Info(string.Join(", ", NNKs.Select(x => $"{x.Role} - {x.AssignedCount}/{x.MaxCount} ({x.SpawnChance}%)")), "NNKRoleResult"); - } + if (NNKs.Length > 0) Logger.Info(string.Join(", ", NNKs.Select(x => $"{x.Role} - {x.AssignedCount}/{x.MaxCount} ({x.SpawnChance}%)")), "NNKRoleResult"); - if (NKs.Length > 0) - { - Logger.Info(string.Join(", ", NKs.Select(x => $"{x.Role} - {x.AssignedCount}/{x.MaxCount} ({x.SpawnChance}%)")), "NKRoleResult"); - } + if (NKs.Length > 0) Logger.Info(string.Join(", ", NKs.Select(x => $"{x.Role} - {x.AssignedCount}/{x.MaxCount} ({x.SpawnChance}%)")), "NKRoleResult"); - if (Crews.Length > 0) - { - Logger.Info(string.Join(", ", Crews.Select(x => $"{x.Role} - {x.AssignedCount}/{x.MaxCount} ({x.SpawnChance}%)")), "CrewRoleResult"); - } + if (Crews.Length > 0) Logger.Info(string.Join(", ", Crews.Select(x => $"{x.Role} - {x.AssignedCount}/{x.MaxCount} ({x.SpawnChance}%)")), "CrewRoleResult"); - if (rd.Next(0, 100) < Jester.SunnyboyChance.GetInt() && FinalRolesList.Remove(CustomRoles.Jester)) - { - FinalRolesList.Add(CustomRoles.Sunnyboy); - } + if (rd.Next(0, 100) < Jester.SunnyboyChance.GetInt() && FinalRolesList.Remove(CustomRoles.Jester)) FinalRolesList.Add(CustomRoles.Sunnyboy); - if (rd.Next(0, 100) < Sans.BardChance.GetInt() && FinalRolesList.Remove(CustomRoles.Sans)) - { - FinalRolesList.Add(CustomRoles.Bard); - } + if (rd.Next(0, 100) < Sans.BardChance.GetInt() && FinalRolesList.Remove(CustomRoles.Sans)) FinalRolesList.Add(CustomRoles.Bard); - if (rd.Next(0, 100) < Bomber.NukerChance.GetInt() && FinalRolesList.Remove(CustomRoles.Bomber)) - { - FinalRolesList.Add(CustomRoles.Nuker); - } + if (rd.Next(0, 100) < Bomber.NukerChance.GetInt() && FinalRolesList.Remove(CustomRoles.Bomber)) FinalRolesList.Add(CustomRoles.Nuker); Logger.Info(string.Join(", ", FinalRolesList.Select(x => x.ToString())), "RoleResults"); @@ -721,10 +564,7 @@ namespace EHR.Modules RoleResult = AllPlayers.Zip(FinalRolesList.Shuffle()).ToDictionary(x => x.First.PlayerId, x => x.Second); RoleResult.AddRange(preResult); - if (RoleResult.Count < AllPlayers.Count) - { - Logger.Error("Role assignment error: There are players who have not been assigned a role", "CustomRoleSelector"); - } + if (RoleResult.Count < AllPlayers.Count) Logger.Error("Role assignment error: There are players who have not been assigned a role", "CustomRoleSelector"); return; @@ -786,23 +626,15 @@ namespace EHR.Modules public static void SelectAddonRoles() { - if (Options.CurrentGameMode != CustomGameMode.Standard) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.Standard) return; - foreach (byte id in Main.SetAddOns.Keys.Where(id => Utils.GetPlayerById(id) == null).ToArray()) - { - Main.SetAddOns.Remove(id); - } + foreach (byte id in Main.SetAddOns.Keys.Where(id => Utils.GetPlayerById(id) == null).ToArray()) Main.SetAddOns.Remove(id); AddonRolesList = []; + foreach (CustomRoles role in Enum.GetValues()) { - if (!role.IsAdditionRole() || role.IsGhostRole()) - { - continue; - } + if (!role.IsAdditionRole() || role.IsGhostRole()) continue; switch (role) { diff --git a/Modules/CustomRolesHelper.cs b/Modules/CustomRolesHelper.cs index 15d565283..1caf79b30 100644 --- a/Modules/CustomRolesHelper.cs +++ b/Modules/CustomRolesHelper.cs @@ -83,32 +83,18 @@ namespace EHR public static CustomRoles GetVNRole(this CustomRoles role, bool checkDesyncRole = false) { - if (role.IsGhostRole()) - { - return CustomRoles.GuardianAngel; - } + if (role.IsGhostRole()) return CustomRoles.GuardianAngel; - if (role.IsVanilla()) - { - return role; - } + if (role.IsVanilla()) return role; - if (checkDesyncRole && role.IsDesyncRole()) - { - return Enum.Parse(role.GetDYRole() + "EHR"); - } + if (checkDesyncRole && role.IsDesyncRole()) return Enum.Parse(role.GetDYRole() + "EHR"); - if (Options.UsePhantomBasis.GetBool() && role.SimpleAbilityTrigger()) - { - return CustomRoles.Phantom; - } + if (Options.UsePhantomBasis.GetBool() && role.SimpleAbilityTrigger()) return CustomRoles.Phantom; - if ((Options.UseUnshiftTrigger.GetBool() || role.AlwaysUsesUnshift()) && role.SimpleAbilityTrigger()) - { - return CustomRoles.Shapeshifter; - } + if ((Options.UseUnshiftTrigger.GetBool() || role.AlwaysUsesUnshift()) && role.SimpleAbilityTrigger()) return CustomRoles.Shapeshifter; bool UsePets = Options.UsePets.GetBool(); + return role switch { CustomRoles.Sniper => UsePets ? CustomRoles.Impostor : CustomRoles.Shapeshifter, @@ -366,12 +352,10 @@ namespace EHR public static CustomRoles GetErasedRole(this CustomRoles role) { - if (role.IsVanilla()) - { - return role; - } + if (role.IsVanilla()) return role; CustomRoles vnRole = role.GetVNRole(true); + return vnRole switch { CustomRoles.Crewmate => CustomRoles.CrewmateEHR, @@ -389,17 +373,12 @@ namespace EHR public static RoleTypes GetDYRole(this CustomRoles role, bool load = false) { - if (!load && Options.UsePhantomBasis.GetBool() && Options.UsePhantomBasisForNKs.GetBool() && !role.IsImpostor() && role.SimpleAbilityTrigger()) - { - return RoleTypes.Phantom; - } + if (!load && Options.UsePhantomBasis.GetBool() && Options.UsePhantomBasisForNKs.GetBool() && !role.IsImpostor() && role.SimpleAbilityTrigger()) return RoleTypes.Phantom; - if (!load && Options.UseUnshiftTrigger.GetBool() && Options.UseUnshiftTriggerForNKs.GetBool() && !role.IsImpostor() && role.SimpleAbilityTrigger()) - { - return RoleTypes.Shapeshifter; - } + if (!load && Options.UseUnshiftTrigger.GetBool() && Options.UseUnshiftTriggerForNKs.GetBool() && !role.IsImpostor() && role.SimpleAbilityTrigger()) return RoleTypes.Shapeshifter; bool UsePets = !load && Options.UsePets.GetBool(); + return role switch { // SoloKombat @@ -753,20 +732,11 @@ namespace EHR public static bool PetActivatedAbility(this CustomRoles role) { - if (Options.CurrentGameMode == CustomGameMode.CaptureTheFlag) - { - return true; - } + if (Options.CurrentGameMode == CustomGameMode.CaptureTheFlag) return true; - if (!Options.UsePets.GetBool()) - { - return false; - } + if (!Options.UsePets.GetBool()) return false; - if (role.UsesPetInsteadOfKill()) - { - return true; - } + if (role.UsesPetInsteadOfKill()) return true; Type type = role.GetRoleClass().GetType(); return type.GetMethod("OnPet")?.DeclaringType == type; @@ -1093,15 +1063,9 @@ namespace EHR public static Team GetTeam(this CustomRoles role) { - if (role.IsImpostorTeamV2()) - { - return Team.Impostor; - } + if (role.IsImpostorTeamV2()) return Team.Impostor; - if (role.IsNeutralTeamV2()) - { - return Team.Neutral; - } + if (role.IsNeutralTeamV2()) return Team.Neutral; return role.IsCrewmateTeamV2() ? Team.Crewmate : Team.None; } @@ -1120,10 +1084,7 @@ namespace EHR public static RoleTypes GetRoleTypes(this CustomRoles role) { - if (Enum.TryParse(role.GetVNRole(true).ToString().Replace("EHR", ""), true, out RoleTypes type)) - { - return type; - } + if (Enum.TryParse(role.GetVNRole(true).ToString().Replace("EHR", ""), true, out RoleTypes type)) return type; return role.IsImpostor() ? RoleTypes.Impostor : RoleTypes.Crewmate; } @@ -1194,21 +1155,12 @@ namespace EHR public static CustomRoleTypes GetCustomRoleTypes(this CustomRoles role) { - CustomRoleTypes type = CustomRoleTypes.Crewmate; - if (role.IsImpostor() || role.IsMadmate()) - { - type = CustomRoleTypes.Impostor; - } + var type = CustomRoleTypes.Crewmate; + if (role.IsImpostor() || role.IsMadmate()) type = CustomRoleTypes.Impostor; - if (role.IsNeutral()) - { - type = CustomRoleTypes.Neutral; - } + if (role.IsNeutral()) type = CustomRoleTypes.Neutral; - if (role.IsAdditionRole()) - { - type = CustomRoleTypes.Addon; - } + if (role.IsAdditionRole()) type = CustomRoleTypes.Addon; return type; } @@ -1222,12 +1174,10 @@ namespace EHR { if (role.IsVanilla()) { - if (Options.DisableVanillaRoles.GetBool()) - { - return 0; - } + if (Options.DisableVanillaRoles.GetBool()) return 0; IRoleOptionsCollection roleOpt = Main.NormalOptions.RoleOptions; + return role switch { CustomRoles.Engineer => roleOpt.GetNumPerGame(RoleTypes.Engineer), @@ -1256,6 +1206,7 @@ namespace EHR if (role.IsVanilla()) { IRoleOptionsCollection roleOpt = Main.NormalOptions.RoleOptions; + return role switch { CustomRoles.Engineer => roleOpt.GetChancePerGame(RoleTypes.Engineer), @@ -1329,20 +1280,11 @@ namespace EHR public static RoleOptionType GetRoleOptionType(this CustomRoles role) { - if (role.IsImpostor()) - { - return role.GetImpostorRoleCategory(); - } + if (role.IsImpostor()) return role.GetImpostorRoleCategory(); - if (role.IsCrewmate()) - { - return role.GetCrewmateRoleCategory(); - } + if (role.IsCrewmate()) return role.GetCrewmateRoleCategory(); - if (role.IsNeutral(true)) - { - return role.GetNeutralRoleCategory(); - } + if (role.IsNeutral(true)) return role.GetNeutralRoleCategory(); return RoleOptionType.Crewmate_Miscellaneous; } diff --git a/Modules/CustomRpcSender.cs b/Modules/CustomRpcSender.cs index 137a2020f..3944d1bb6 100644 --- a/Modules/CustomRpcSender.cs +++ b/Modules/CustomRpcSender.cs @@ -31,9 +31,7 @@ namespace EHR private State currentState = State.BeforeInit; - private CustomRpcSender() - { - } + private CustomRpcSender() { } public CustomRpcSender(string name, SendOption sendOption, bool isUnsafe) { @@ -54,13 +52,9 @@ namespace EHR set { if (isUnsafe) - { currentState = value; - } else - { Logger.Warn("CurrentState can only be overwritten when isUnsafe is true", "CustomRpcSender"); - } } } @@ -74,31 +68,22 @@ namespace EHR byte callId, int targetClientId = -1) { - if (targetClientId == -2) - { - targetClientId = -1; - } + if (targetClientId == -2) targetClientId = -1; if (currentState is not State.Ready and not State.InRootMessage) { - string errorMsg = $"Tried to start RPC automatically, but State is not Ready or InRootMessage (in: \"{name}\")"; + var errorMsg = $"Tried to start RPC automatically, but State is not Ready or InRootMessage (in: \"{name}\")"; + if (isUnsafe) - { Logger.Warn(errorMsg, "CustomRpcSender.Warn"); - } else - { throw new InvalidOperationException(errorMsg); - } } if (currentRpcTarget != targetClientId) { // StartMessage processing - if (currentState == State.InRootMessage) - { - EndMessage(); - } + if (currentState == State.InRootMessage) EndMessage(); StartMessage(targetClientId); } @@ -110,22 +95,16 @@ namespace EHR public void SendMessage() { - if (currentState == State.InRootMessage) - { - EndMessage(); - } + if (currentState == State.InRootMessage) EndMessage(); if (currentState != State.Ready) { - string errorMsg = $"Tried to send RPC but State is not Ready (in: \"{name}\")"; + var errorMsg = $"Tried to send RPC but State is not Ready (in: \"{name}\")"; + if (isUnsafe) - { Logger.Warn(errorMsg, "CustomRpcSender.Warn"); - } else - { throw new InvalidOperationException(errorMsg); - } } AmongUsClient.Instance.SendOrDisconnect(stream); @@ -139,15 +118,12 @@ namespace EHR { if (currentState != State.InRpc) { - string errorMsg = $"Tried to write RPC, but State is not Write (in: \"{name}\")"; + var errorMsg = $"Tried to write RPC, but State is not Write (in: \"{name}\")"; + if (isUnsafe) - { Logger.Warn(errorMsg, "CustomRpcSender.Warn"); - } else - { throw new InvalidOperationException(errorMsg); - } } action(stream); @@ -163,15 +139,12 @@ namespace EHR { if (currentState != State.Ready) { - string errorMsg = $"Tried to start Message but State is not Ready (in: \"{name}\")"; + var errorMsg = $"Tried to start Message but State is not Ready (in: \"{name}\")"; + if (isUnsafe) - { Logger.Warn(errorMsg, "CustomRpcSender.Warn"); - } else - { throw new InvalidOperationException(errorMsg); - } } if (targetClientId < 0) @@ -198,15 +171,12 @@ namespace EHR { if (currentState != State.InRootMessage) { - string errorMsg = $"Tried to exit Message but State is not InRootMessage (in: \"{name}\")"; + var errorMsg = $"Tried to exit Message but State is not InRootMessage (in: \"{name}\")"; + if (isUnsafe) - { Logger.Warn(errorMsg, "CustomRpcSender.Warn"); - } else - { throw new InvalidOperationException(errorMsg); - } } stream.EndMessage(); @@ -231,15 +201,12 @@ namespace EHR { if (currentState != State.InRootMessage) { - string errorMsg = $"Tried to start RPC but State is not InRootMessage (in: \"{name}\")"; + var errorMsg = $"Tried to start RPC but State is not InRootMessage (in: \"{name}\")"; + if (isUnsafe) - { Logger.Warn(errorMsg, "CustomRpcSender.Warn"); - } else - { throw new InvalidOperationException(errorMsg); - } } stream.StartMessage(2); @@ -254,15 +221,12 @@ namespace EHR { if (currentState != State.InRpc) { - string errorMsg = $"Tried to terminate RPC but State is not InRpc (in: \"{name}\")"; + var errorMsg = $"Tried to terminate RPC but State is not InRpc (in: \"{name}\")"; + if (isUnsafe) - { Logger.Warn(errorMsg, "CustomRpcSender.Warn"); - } else - { throw new InvalidOperationException(errorMsg); - } } stream.EndMessage(); diff --git a/Modules/CustomSounds.cs b/Modules/CustomSounds.cs index 4efbd1dd2..095d57227 100644 --- a/Modules/CustomSounds.cs +++ b/Modules/CustomSounds.cs @@ -13,12 +13,8 @@ namespace EHR.Modules public static void RPCPlayCustomSound(this PlayerControl pc, string sound, bool force = false) { if (!force) - { if (!AmongUsClient.Instance.AmHost || !pc.IsModClient()) - { return; - } - } if (pc == null || PlayerControl.LocalPlayer.PlayerId == pc.PlayerId) { @@ -33,10 +29,7 @@ namespace EHR.Modules public static void RPCPlayCustomSoundAll(string sound) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.PlayCustomSound, SendOption.Reliable); writer.Write(sound); @@ -51,26 +44,18 @@ namespace EHR.Modules public static void Play(string sound) { - if (!Constants.ShouldPlaySfx() || !Main.EnableCustomSoundEffect.Value) - { - return; - } + if (!Constants.ShouldPlaySfx() || !Main.EnableCustomSoundEffect.Value) return; string path = SOUNDS_PATH + sound + ".wav"; - if (!Directory.Exists(SOUNDS_PATH)) - { - Directory.CreateDirectory(SOUNDS_PATH); - } + if (!Directory.Exists(SOUNDS_PATH)) Directory.CreateDirectory(SOUNDS_PATH); DirectoryInfo folder = new(SOUNDS_PATH); - if ((folder.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden) - { - folder.Attributes = FileAttributes.Hidden; - } + if ((folder.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden) folder.Attributes = FileAttributes.Hidden; if (!File.Exists(path)) { Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EHR.Resources.Sounds." + sound + ".wav"); + if (stream == null) { Logger.Warn($"声音文件缺失:{sound}", "CustomSounds"); diff --git a/Modules/CustomTeamManager.cs b/Modules/CustomTeamManager.cs index 45f5c63fc..c39e01b56 100644 --- a/Modules/CustomTeamManager.cs +++ b/Modules/CustomTeamManager.cs @@ -18,10 +18,7 @@ namespace EHR.Modules { try { - if (!File.Exists("./EHR_DATA/CTA_Data.txt")) - { - return; - } + if (!File.Exists("./EHR_DATA/CTA_Data.txt")) return; CustomTeams = File.ReadAllLines("./EHR_DATA/CTA_Data.txt").Select(x => new CustomTeam(x)).ToHashSet(); RefreshCustomOptions(); @@ -46,21 +43,18 @@ namespace EHR.Modules static CustomTeamOptionGroup CreateSetting(CustomTeam team, int id) { - BooleanOptionItem enabled = new BooleanOptionItem(id++, "CTA.FLAG" + team.TeamName, true, tab); - BooleanOptionItem knowRoles = new BooleanOptionItem(id++, "CTA.KnowRoles", true, tab); - BooleanOptionItem winWithOriginalTeam = new BooleanOptionItem(id++, "CTA.WinWithOriginalTeam", false, tab); - BooleanOptionItem killEachOther = new BooleanOptionItem(id++, "CTA.KillEachOther", false, tab); - BooleanOptionItem guessEachOther = new BooleanOptionItem(id++, "CTA.GuessEachOther", false, tab); - BooleanOptionItem arrows = new BooleanOptionItem(id, "CTA.Arrows", true, tab); + var enabled = new BooleanOptionItem(id++, "CTA.FLAG" + team.TeamName, true, tab); + var knowRoles = new BooleanOptionItem(id++, "CTA.KnowRoles", true, tab); + var winWithOriginalTeam = new BooleanOptionItem(id++, "CTA.WinWithOriginalTeam", false, tab); + var killEachOther = new BooleanOptionItem(id++, "CTA.KillEachOther", false, tab); + var guessEachOther = new BooleanOptionItem(id++, "CTA.GuessEachOther", false, tab); + var arrows = new BooleanOptionItem(id, "CTA.Arrows", true, tab); CustomTeamOptionGroup group = new(team, enabled, knowRoles, winWithOriginalTeam, killEachOther, guessEachOther, arrows); group.AllOptions.Skip(1).Do(x => x.SetParent(enabled)); group.AllOptions.ForEach(x => x.SetColor(new Color32(215, 227, 84, byte.MaxValue))); group.AllOptions.ForEach(x => x.SetGameMode(CustomGameMode.Standard)); - if (ColorUtility.TryParseHtmlString(team.RoleRevealScreenBackgroundColor, out Color color)) - { - enabled.SetColor(color); - } + if (ColorUtility.TryParseHtmlString(team.RoleRevealScreenBackgroundColor, out Color color)) enabled.SetColor(color); enabled.RegisterUpdateValueEvent((_, _) => UpdateEnabledTeams()); return group; @@ -75,10 +69,7 @@ namespace EHR.Modules public static void InitializeCustomTeamPlayers() { UpdateEnabledTeams(); - if (EnabledCustomTeams.Count == 0) - { - return; - } + if (EnabledCustomTeams.Count == 0) return; CustomTeamPlayerIds = Main.PlayerStates .IntersectBy(Main.AllAlivePlayerControls.Select(x => x.PlayerId), x => x.Key) @@ -88,19 +79,13 @@ namespace EHR.Modules foreach ((CustomTeam team, HashSet players) in CustomTeamPlayerIds) { - if (!IsSettingEnabledForTeam(team, CTAOption.Arrows)) - { - continue; - } + if (!IsSettingEnabledForTeam(team, CTAOption.Arrows)) continue; foreach (byte player in players) { foreach (byte target in players) { - if (player == target) - { - continue; - } + if (player == target) continue; TargetArrow.Add(player, target); } @@ -110,20 +95,14 @@ namespace EHR.Modules public static string GetSuffix(PlayerControl seer) { - if (seer == null || EnabledCustomTeams.Count == 0 || Main.HasJustStarted || !IsSettingEnabledForPlayerTeam(seer.PlayerId, CTAOption.Arrows)) - { - return string.Empty; - } + if (seer == null || EnabledCustomTeams.Count == 0 || Main.HasJustStarted || !IsSettingEnabledForPlayerTeam(seer.PlayerId, CTAOption.Arrows)) return string.Empty; return CustomTeamPlayerIds[GetCustomTeam(seer.PlayerId)].Aggregate(string.Empty, (s, id) => s + Utils.ColorString(Main.PlayerColors.GetValueOrDefault(id, Color.white), TargetArrow.GetArrows(seer, id))); } public static bool CheckCustomTeamGameEnd() { - if (EnabledCustomTeams.Count == 0 || CustomTeamPlayerIds.Count == 0) - { - return false; - } + if (EnabledCustomTeams.Count == 0 || CustomTeamPlayerIds.Count == 0) return false; try { @@ -137,6 +116,7 @@ namespace EHR.Modules aliveTeamPlayers.Do(x => x.Value.RemoveWhere(p => !Utils.GetPlayerById(p).IsAlive())); CustomTeam team = aliveTeamPlayers.Keys.First(); + if (aliveTeamPlayers.Count == 1 && Main.AllAlivePlayerControls.All(x => { CustomTeam customTeam = GetCustomTeam(x.PlayerId); @@ -159,28 +139,18 @@ namespace EHR.Modules public static CustomTeam GetCustomTeam(byte id) { - if (!Main.PlayerStates.TryGetValue(id, out PlayerState state)) - { - return null; - } + if (!Main.PlayerStates.TryGetValue(id, out PlayerState state)) return null; foreach (CustomTeam team in EnabledCustomTeams) - { if (team.TeamMembers.Contains(state.MainRole)) - { return team; - } - } return null; } public static bool AreInSameCustomTeam(byte id1, byte id2) { - if (EnabledCustomTeams.Count == 0) - { - return false; - } + if (EnabledCustomTeams.Count == 0) return false; CustomTeam team1 = GetCustomTeam(id1); CustomTeam team2 = GetCustomTeam(id2); @@ -235,10 +205,7 @@ namespace EHR.Modules public override bool Equals(object obj) { - if (obj is not CustomTeam team) - { - return false; - } + if (obj is not CustomTeam team) return false; return TeamName == team.TeamName; } diff --git a/Modules/CustomWinnerHolder.cs b/Modules/CustomWinnerHolder.cs index 9fd04eae3..08deccd8b 100644 --- a/Modules/CustomWinnerHolder.cs +++ b/Modules/CustomWinnerHolder.cs @@ -45,13 +45,9 @@ namespace EHR public static void SetWinnerOrAdditonalWinner(CustomWinner winner) { if (WinnerTeam == CustomWinner.Default) - { WinnerTeam = winner; - } else - { AdditionalWinnerTeams.Add((AdditionalWinners)winner); - } Logger.Info($"WinnerTeam: {WinnerTeam}, AdditionalWinnerTeams: {string.Join(", ", AdditionalWinnerTeams)}", "CustomWinnerHolder.SetWinnerOrAdditonalWinner"); } @@ -62,10 +58,7 @@ namespace EHR /// public static void ShiftWinnerAndSetWinner(CustomWinner winner) { - if (WinnerTeam != CustomWinner.Default) - { - AdditionalWinnerTeams.Add((AdditionalWinners)WinnerTeam); - } + if (WinnerTeam != CustomWinner.Default) AdditionalWinnerTeams.Add((AdditionalWinners)WinnerTeam); WinnerTeam = winner; Logger.Info($"WinnerTeam: {WinnerTeam}, AdditionalWinnerTeams: {string.Join(", ", AdditionalWinnerTeams)}", "CustomWinnerHolder.ShiftWinnerAndSetWinner"); @@ -86,22 +79,13 @@ namespace EHR writer.WritePacked((int)WinnerTeam); writer.WritePacked(AdditionalWinnerTeams.Count); - foreach (AdditionalWinners wt in AdditionalWinnerTeams) - { - writer.WritePacked((int)wt); - } + foreach (AdditionalWinners wt in AdditionalWinnerTeams) writer.WritePacked((int)wt); writer.WritePacked(WinnerRoles.Count); - foreach (CustomRoles wr in WinnerRoles) - { - writer.WritePacked((int)wr); - } + foreach (CustomRoles wr in WinnerRoles) writer.WritePacked((int)wr); writer.WritePacked(WinnerIds.Count); - foreach (byte id in WinnerIds) - { - writer.Write(id); - } + foreach (byte id in WinnerIds) writer.Write(id); return writer; } @@ -112,24 +96,15 @@ namespace EHR AdditionalWinnerTeams = []; int AdditionalWinnerTeamsCount = reader.ReadPackedInt32(); - for (int i = 0; i < AdditionalWinnerTeamsCount; i++) - { - AdditionalWinnerTeams.Add((AdditionalWinners)reader.ReadPackedInt32()); - } + for (var i = 0; i < AdditionalWinnerTeamsCount; i++) AdditionalWinnerTeams.Add((AdditionalWinners)reader.ReadPackedInt32()); WinnerRoles = []; int WinnerRolesCount = reader.ReadPackedInt32(); - for (int i = 0; i < WinnerRolesCount; i++) - { - WinnerRoles.Add((CustomRoles)reader.ReadPackedInt32()); - } + for (var i = 0; i < WinnerRolesCount; i++) WinnerRoles.Add((CustomRoles)reader.ReadPackedInt32()); WinnerIds = []; int WinnerIdsCount = reader.ReadPackedInt32(); - for (int i = 0; i < WinnerIdsCount; i++) - { - WinnerIds.Add(reader.ReadByte()); - } + for (var i = 0; i < WinnerIdsCount; i++) WinnerIds.Add(reader.ReadByte()); } } } \ No newline at end of file diff --git a/Modules/Debugger.cs b/Modules/Debugger.cs index 4a241625c..4a8a60887 100644 --- a/Modules/Debugger.cs +++ b/Modules/Debugger.cs @@ -14,20 +14,20 @@ namespace EHR { public static void Send(string text) { - if (Main.WebhookUrl.Value == "none") - { - return; - } + if (Main.WebhookUrl.Value == "none") return; HttpClient httpClient = new(); + Dictionary strs = new() { { "content", text }, { "username", "EHR-Debugger" }, { "avatar_url", "https://npm.elemecdn.com/hexo-static@1.0.1/img/avatar.webp" } }; + TaskAwaiter awaiter = httpClient.PostAsync( Main.WebhookUrl.Value, new FormUrlEncodedContent(strs)).GetAwaiter(); + awaiter.GetResult(); } } @@ -54,30 +54,21 @@ namespace EHR public static void Enable(string tag, bool toGame = false) { DisableList.Remove(tag); + if (toGame && !SendToGameList.Contains(tag)) - { SendToGameList.Add(tag); - } else - { SendToGameList.Remove(tag); - } } public static void Disable(string tag) { - if (!DisableList.Contains(tag)) - { - DisableList.Add(tag); - } + if (!DisableList.Contains(tag)) DisableList.Add(tag); } public static void SendInGame(string text /*, bool isAlways = false*/) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; if (DestroyableSingleton._instance) { @@ -88,22 +79,17 @@ namespace EHR private static void SendToFile(string text, LogLevel level = LogLevel.Info, string tag = "", bool escapeCRLF = true, int lineNumber = 0, string fileName = "", bool multiLine = false) { - if (!IsEnable || DisableList.Contains(tag) || (level == LogLevel.Debug && !DebugModeManager.AmDebugger)) - { - return; - } + if (!IsEnable || DisableList.Contains(tag) || (level == LogLevel.Debug && !DebugModeManager.AmDebugger)) return; ManualLogSource logger = Main.Logger; - if (SendToGameList.Contains(tag) || IsAlsoInGame) - { - SendInGame($"[{tag}]{text}"); - } + if (SendToGameList.Contains(tag) || IsAlsoInGame) SendInGame($"[{tag}]{text}"); string log_text; + if (level is LogLevel.Error or LogLevel.Fatal && !multiLine && !NowDetailedErrorLog.Contains(tag)) { - string t = DateTime.Now.ToString("HH:mm:ss"); + var t = DateTime.Now.ToString("HH:mm:ss"); StackFrame stack = new(2); string className = stack.GetMethod()?.ReflectedType?.Name; string memberName = stack.GetMethod()?.Name; @@ -113,12 +99,9 @@ namespace EHR } else { - if (escapeCRLF) - { - text = text.Replace("\r", "\\r").Replace("\n", "\\n"); - } + if (escapeCRLF) text = text.Replace("\r", "\\r").Replace("\n", "\\n"); - string t = DateTime.Now.ToString("HH:mm:ss"); + var t = DateTime.Now.ToString("HH:mm:ss"); log_text = $"[{t}][{tag}]{text}"; } diff --git a/Modules/DevManager.cs b/Modules/DevManager.cs index c9b765b0f..5be7531e2 100644 --- a/Modules/DevManager.cs +++ b/Modules/DevManager.cs @@ -34,105 +34,105 @@ namespace EHR // Dev new("actorour#0029", "#ffc0cb", "TOHE/TONX Developer", true, true), // KARPED1EM new("pinklaze#1776", null, "null", true, true), // NCSIMON - new("keepchirpy#6354", "#1FF3C6", "TOHE Developer", true, false), // TommyXL //Tommy-XL + new("keepchirpy#6354", "#1FF3C6", "TOHE Developer", true), // TommyXL //Tommy-XL new("motelchief#4112", "#eb57af", "Twilight Raven", true, true), // Drakos //Drakos new("eagergaol#1562", "#5534eb", "Drakos Alt", true, true), // Drakos //Drakos Steam Alt - new("timedapper#9496", null, null, false, false), //阿龍 + new("timedapper#9496", null, null), //阿龍 new("sofaagile#3120", "null", "null", false, true), //天寸 - new("keyscreech#2151", "null", null, false, false), //Endrmen40409 + new("keyscreech#2151", "null", null), //Endrmen40409 // Up - new("primether#5348", "null", "YouTuber/Streamer", true, false), // AnonWorks - new("truantwarm#9165", "null", "null", true, false), // 萧暮不姓萧 - new("drilldinky#1386", "null", "null", true, false), // 爱玩AU的河豚 - new("farardour#6818", "null", "null", true, false), // -提米SaMa- - new("vealused#8192", "null", "null", true, false), // lag丶xy - new("storyeager#0815", "null", "null", true, false), // 航娜丽莎 - new("versegame#3885", "null", "null", true, false), // 柴唔cw - new("closegrub#6217", "null", "null", true, false), // 警长不会玩 - new("frownnatty#7935", "null", "null", true, false), // 鬼灵official - new("veryscarf#5368", "null", "null", true, false), // 小武同学102 - new("sparklybee#0275", "null", "null", true, false), // --红包SaMa-- - new("endingyon#3175", "null", "null", true, false), // 游侠开摆 - new("firmine#0232", "null", "null", true, false), // YH永恒_ - new("storkfey#3570", "null", "null", true, false), // Calypso - new("fellowsand#1003", "null", "null", true, false), // C-Faust - new("jetsafe#8512", "null", "null", true, false), // Hoream是好人 - new("spoonkey#0792", "null", "null", true, false), // 没好康的 - new("beakedmire#6099", "null", "null", true, false), // 茄-au - new("doggedsize#7892", "null", "null", true, false), // TronAndRey + new("primether#5348", "null", "YouTuber/Streamer", true), // AnonWorks + new("truantwarm#9165", "null", "null", true), // 萧暮不姓萧 + new("drilldinky#1386", "null", "null", true), // 爱玩AU的河豚 + new("farardour#6818", "null", "null", true), // -提米SaMa- + new("vealused#8192", "null", "null", true), // lag丶xy + new("storyeager#0815", "null", "null", true), // 航娜丽莎 + new("versegame#3885", "null", "null", true), // 柴唔cw + new("closegrub#6217", "null", "null", true), // 警长不会玩 + new("frownnatty#7935", "null", "null", true), // 鬼灵official + new("veryscarf#5368", "null", "null", true), // 小武同学102 + new("sparklybee#0275", "null", "null", true), // --红包SaMa-- + new("endingyon#3175", "null", "null", true), // 游侠开摆 + new("firmine#0232", "null", "null", true), // YH永恒_ + new("storkfey#3570", "null", "null", true), // Calypso + new("fellowsand#1003", "null", "null", true), // C-Faust + new("jetsafe#8512", "null", "null", true), // Hoream是好人 + new("spoonkey#0792", "null", "null", true), // 没好康的 + new("beakedmire#6099", "null", "null", true), // 茄-au + new("doggedsize#7892", "null", "null", true), // TronAndRey new("openlanded#9533", "#9e2424", "God Of Death Love Apples", true, true), // ryuk - new("unlikecity#4086", "#eD2F91", "Ward", true, false), // Ward - new("iconicdrop#2727", "null", "null", true, false), // jackler + new("unlikecity#4086", "#eD2F91", "Ward", true), // Ward + new("iconicdrop#2727", "null", "null", true), // jackler new("goneria#8334", "#FFFF00", "The Dev on Phone", true, true), // [Developer] The 200IQ guy // Me on phone new("neatnet#5851", "#FFFF00", "[Developer] The 200IQ guy", true, true), // [Developer] The 200IQ guy new("contenthue#0404", "#FFFF00", "[Developer] The 200IQ guy", true, true), // [Developer] The 200IQ guy - new("theseform#5686", "null", "PTBR-Translator/Role Idea Creator", true, false), // Tomix - new("heavyclod#2286", "#FFFF00", "小叨.exe已停止运行", true, false), // 小叨院长 - new("storeroan#0331", "#FF0066", "Night_瓜", true, false), // Night_瓜 - new("teamelder#5856", "#1379bf", "屑Slok(没信誉的鸽子)", true, false), // Slok7565 + new("theseform#5686", "null", "PTBR-Translator/Role Idea Creator", true), // Tomix + new("heavyclod#2286", "#FFFF00", "小叨.exe已停止运行", true), // 小叨院长 + new("storeroan#0331", "#FF0066", "Night_瓜", true), // Night_瓜 + new("teamelder#5856", "#1379bf", "屑Slok(没信誉的鸽子)", true), // Slok7565 new("radarright#2509", "null", "null", false, true), // EHR players - new("ravenknurl#4562", "#008000", "Moderador do FH", false, false), // RicardoFumante - new("crustzonal#9589", "#00FFFF", "Translator PT-BR", true, false), // artyleague01 - new("tinedpun#6584", "#0000ff", "Translator PT-BR", true, false), // Dechis - new("swiftlord#8072", "null", "null", true, false), // But What About - new("ovalinstep#2984", "null", "null", true, false), // Seleneous - new("seleneous#6930", "null", "null", true, false), // Seleneous - new("innerruler#4140", "null", "null", true, false), // thewhiskas27 - new("urbanecalf#4975", "#420773", "Streamer", true, false), // Gugutsik - new("crustzonal#9589", "null", "null", true, false), // aviiiv0102 - new("tubedilute#9062", "null", "null", true, false), // Xcl4udioX - new("ponyholey#5532", "#0000FF", "desenvolvedor", true, false), // DrawingsZz - new("akinlaptop#2206", "null", "null", true, false), // MR Carr - new("fursilty#4676", "#0000ff", "arthurzin", true, false), // arthurzin + new("ravenknurl#4562", "#008000", "Moderador do FH"), // RicardoFumante + new("crustzonal#9589", "#00FFFF", "Translator PT-BR", true), // artyleague01 + new("tinedpun#6584", "#0000ff", "Translator PT-BR", true), // Dechis + new("swiftlord#8072", "null", "null", true), // But What About + new("ovalinstep#2984", "null", "null", true), // Seleneous + new("seleneous#6930", "null", "null", true), // Seleneous + new("innerruler#4140", "null", "null", true), // thewhiskas27 + new("urbanecalf#4975", "#420773", "Streamer", true), // Gugutsik + new("crustzonal#9589", "null", "null", true), // aviiiv0102 + new("tubedilute#9062", "null", "null", true), // Xcl4udioX + new("ponyholey#5532", "#0000FF", "desenvolvedor", true), // DrawingsZz + new("akinlaptop#2206", "null", "null", true), // MR Carr + new("fursilty#4676", "#0000ff", "arthurzin", true), // arthurzin new("stonefuzzy#8673", "#ff0062", "Ru Translator", true, true), // HyperAtill - new("frizzytram#2508", "#1C87FF", "RafaelBIT50", false, false), // RafaelBIT50 - new("ruefulscar#0287", "null", "null", true, false), // Zendena - new("foggyzing#6238", "null", "null", true, false), // LdZinnn - new("onsideblur#3929", "#fc3a51", "YouTuber", true, false), // Manelzin - new("modestspan#7071", "null", "null", true, false), // Shark - new("divotbusy#0624", "null", "null", true, false), // PreCeptorBR - new("pinsrustic#5496", "#fc3a51", "YouTuber", true, false), // FHgameplay - new("opaquedot#5610", "null", "null", true, false), // Deh_66 - new("furpolitic#3380", "#a020f0", "EuOncologico o impostor", true, false), // EuOncologico - new("pithfierce#5073", "null", "null", true, false), // OrigeTv - new("cannylink#0564", "null", "null", true, false), // SpicyPoops - new("ghostapt#7243", "#a48d6b", "AUME", true, false), // MasterKy - new("planegame#5847", "#44fff7", "Kopp56", true, false), // Kopp56 PRO - new("clovesorry#6973", "#191970", "Master", true, false), // MAT - new("ivorywish#3580", "#ff0000", "YouTuber", true, false), // Erik Carr - new("cleardress#6310", "#ffffff", "<#00BFFF>一<#48D1CC>个<#7CFC00>热狗<#32CD32>uwu", true, false), // ABoringCat - new("rainypearl#9545", "#A020F0", "YouTuber", true, false), // bielModzs - new("kiltedbill#4145", "null", "null", true, false), // tsaki84 - new("onlyfax#3941", "#ff0000", "YouTuber", true, false), // The Nick AG - new("somewallet#5521", "#ffff00", "Artist", true, false), // YoshiBertil - new("pagersane#4064", "null", "null", true, false), // Bluejava3 - new("pocketdoor#9080", "null", "null", true, false), // Imnot - new("motorstack#2287", "#E34234", "Foxfire", true, false), // Esrazraft - new("motorlace#4741", "#DFB722", "\u2756 Assistant Tester \u2756", true, false), // PEPPERcula - new("keyrunning#8720", "#00ffff", "Miku", true, false), // EverMortal_1455 - new("yellowjoy#3138", "#FFE87C", "Sunshine", true, false), // Becksy + new("frizzytram#2508", "#1C87FF", "RafaelBIT50"), // RafaelBIT50 + new("ruefulscar#0287", "null", "null", true), // Zendena + new("foggyzing#6238", "null", "null", true), // LdZinnn + new("onsideblur#3929", "#fc3a51", "YouTuber", true), // Manelzin + new("modestspan#7071", "null", "null", true), // Shark + new("divotbusy#0624", "null", "null", true), // PreCeptorBR + new("pinsrustic#5496", "#fc3a51", "YouTuber", true), // FHgameplay + new("opaquedot#5610", "null", "null", true), // Deh_66 + new("furpolitic#3380", "#a020f0", "EuOncologico o impostor", true), // EuOncologico + new("pithfierce#5073", "null", "null", true), // OrigeTv + new("cannylink#0564", "null", "null", true), // SpicyPoops + new("ghostapt#7243", "#a48d6b", "AUME", true), // MasterKy + new("planegame#5847", "#44fff7", "Kopp56", true), // Kopp56 PRO + new("clovesorry#6973", "#191970", "Master", true), // MAT + new("ivorywish#3580", "#ff0000", "YouTuber", true), // Erik Carr + new("cleardress#6310", "#ffffff", "<#00BFFF>一<#48D1CC>个<#7CFC00>热狗<#32CD32>uwu", true), // ABoringCat + new("rainypearl#9545", "#A020F0", "YouTuber", true), // bielModzs + new("kiltedbill#4145", "null", "null", true), // tsaki84 + new("onlyfax#3941", "#ff0000", "YouTuber", true), // The Nick AG + new("somewallet#5521", "#ffff00", "Artist", true), // YoshiBertil + new("pagersane#4064", "null", "null", true), // Bluejava3 + new("pocketdoor#9080", "null", "null", true), // Imnot + new("motorstack#2287", "#E34234", "Foxfire", true), // Esrazraft + new("motorlace#4741", "#DFB722", "\u2756 Assistant Tester \u2756", true), // PEPPERcula + new("keyrunning#8720", "#00ffff", "Miku", true), // EverMortal_1455 + new("yellowjoy#3138", "#FFE87C", "Sunshine", true), // Becksy // Sponsor new("recentduct#6068", "#FF00FF", "高冷男模法师", false, true), - new("canneddrum#2370", "#fffcbe", "我是喜唉awa", false, false), - new("dovefitted#5329", "#1379bf", "不要首刀我", false, false), - new("luckylogo#7352", "#f30000", "林@林", false, false), - new("axefitful#8788", "#8e8171", "寄才是真理", false, false), - new("raftzonal#8893", "#8e8171", "寄才是真理", false, false), - new("twainrobin#8089", "#0000FF", "啊哈修maker", false, false), - new("mallcasual#6075", "#f89ccb", "波奇酱", false, false), - new("beamelfin#9478", "#6495ED", "Amaster-1111", false, false), - new("lordcosy#8966", "#FFD6EC", "HostEHR", false, false), // K - new("honestsofa#2870", "#D381D9", "Discord: SolarFlare#0700", true, false), // SolarFlare //SolarFlare - new("caseeast#7194", "#1c2451", "disc.gg/maul", false, false), // laikrai + new("canneddrum#2370", "#fffcbe", "我是喜唉awa"), + new("dovefitted#5329", "#1379bf", "不要首刀我"), + new("luckylogo#7352", "#f30000", "林@林"), + new("axefitful#8788", "#8e8171", "寄才是真理"), + new("raftzonal#8893", "#8e8171", "寄才是真理"), + new("twainrobin#8089", "#0000FF", "啊哈修maker"), + new("mallcasual#6075", "#f89ccb", "波奇酱"), + new("beamelfin#9478", "#6495ED", "Amaster-1111"), + new("lordcosy#8966", "#FFD6EC", "HostEHR"), // K + new("honestsofa#2870", "#D381D9", "Discord: SolarFlare#0700", true), // SolarFlare //SolarFlare + new("caseeast#7194", "#1c2451", "disc.gg/maul"), // laikrai // Other - new("peakcrown#8292", "null", "null", true, false) // Hakaka + new("peakcrown#8292", "null", "null", true) // Hakaka ]; } diff --git a/Modules/DisableDevice.cs b/Modules/DisableDevice.cs index c7b057445..4424de3fc 100644 --- a/Modules/DisableDevice.cs +++ b/Modules/DisableDevice.cs @@ -50,33 +50,26 @@ namespace EHR public static void FixedUpdate() { frame = frame == 3 ? 0 : ++frame; - if (frame != 0) - { - return; - } + if (frame != 0) return; bool rogueForce = Rogue.On && Main.PlayerStates.Values.Any(x => x.Role is Rogue { DisableDevices: true }); - if (!DoDisable && !rogueForce) - { - return; - } + if (!DoDisable && !rogueForce) return; foreach (PlayerControl pc in Main.AllPlayerControls) { try { - if (pc.IsModClient()) - { - continue; - } + if (pc.IsModClient()) continue; - bool doComms = false; + var doComms = false; Vector2 PlayerPos = pc.Pos(); + bool ignore = (Options.DisableDevicesIgnoreImpostors.GetBool() && pc.Is(CustomRoleTypes.Impostor)) || (Options.DisableDevicesIgnoreNeutrals.GetBool() && pc.Is(CustomRoleTypes.Neutral)) || (Options.DisableDevicesIgnoreCrewmates.GetBool() && pc.Is(CustomRoleTypes.Crewmate)) || (Options.DisableDevicesIgnoreAfterAnyoneDied.GetBool() && GameStates.AlreadyDied); + ignore &= !rogueForce; if (pc.IsAlive() && !Utils.IsActive(SystemTypes.Comms)) @@ -84,27 +77,15 @@ namespace EHR switch (Main.NormalOptions.MapId) { case 0: - if (Options.DisableSkeldAdmin.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["SkeldAdmin"]) <= UsableDistance; - } + if (Options.DisableSkeldAdmin.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["SkeldAdmin"]) <= UsableDistance; - if (Options.DisableSkeldCamera.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["SkeldCamera"]) <= UsableDistance; - } + if (Options.DisableSkeldCamera.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["SkeldCamera"]) <= UsableDistance; break; case 1: - if (Options.DisableMiraHQAdmin.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["MiraHQAdmin"]) <= UsableDistance; - } + if (Options.DisableMiraHQAdmin.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["MiraHQAdmin"]) <= UsableDistance; - if (Options.DisableMiraHQDoorLog.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["MiraHQDoorLog"]) <= UsableDistance; - } + if (Options.DisableMiraHQDoorLog.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["MiraHQDoorLog"]) <= UsableDistance; break; case 2: @@ -114,73 +95,41 @@ namespace EHR doComms |= Vector2.Distance(PlayerPos, DevicePos["PolusRightAdmin"]) <= UsableDistance; } - if (Options.DisablePolusCamera.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["PolusCamera"]) <= UsableDistance; - } + if (Options.DisablePolusCamera.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["PolusCamera"]) <= UsableDistance; - if (Options.DisablePolusVital.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["PolusVital"]) <= UsableDistance; - } + if (Options.DisablePolusVital.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["PolusVital"]) <= UsableDistance; break; case 3: - if (Options.DisableSkeldAdmin.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["DleksAdmin"]) <= UsableDistance; - } + if (Options.DisableSkeldAdmin.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["DleksAdmin"]) <= UsableDistance; - if (Options.DisableSkeldCamera.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["DleksCamera"]) <= UsableDistance; - } + if (Options.DisableSkeldCamera.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["DleksCamera"]) <= UsableDistance; break; case 4: - if (Options.DisableAirshipCockpitAdmin.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["AirshipCockpitAdmin"]) <= UsableDistance; - } + if (Options.DisableAirshipCockpitAdmin.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["AirshipCockpitAdmin"]) <= UsableDistance; - if (Options.DisableAirshipRecordsAdmin.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["AirshipRecordsAdmin"]) <= UsableDistance; - } + if (Options.DisableAirshipRecordsAdmin.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["AirshipRecordsAdmin"]) <= UsableDistance; - if (Options.DisableAirshipCamera.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["AirshipCamera"]) <= UsableDistance; - } + if (Options.DisableAirshipCamera.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["AirshipCamera"]) <= UsableDistance; - if (Options.DisableAirshipVital.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["AirshipVital"]) <= UsableDistance; - } + if (Options.DisableAirshipVital.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["AirshipVital"]) <= UsableDistance; break; case 5: - if (Options.DisableFungleCamera.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["FungleCamera"]) <= UsableDistance; - } + if (Options.DisableFungleCamera.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["FungleCamera"]) <= UsableDistance; - if (Options.DisableFungleVital.GetBool() || rogueForce) - { - doComms |= Vector2.Distance(PlayerPos, DevicePos["FungleVital"]) <= UsableDistance; - } + if (Options.DisableFungleVital.GetBool() || rogueForce) doComms |= Vector2.Distance(PlayerPos, DevicePos["FungleVital"]) <= UsableDistance; break; } } doComms &= !ignore; + if (doComms && !pc.inVent) { - if (!DesyncComms.Contains(pc.PlayerId)) - { - DesyncComms.Add(pc.PlayerId); - } + if (!DesyncComms.Contains(pc.PlayerId)) DesyncComms.Add(pc.PlayerId); pc.RpcDesyncRepairSystem(SystemTypes.Comms, 128); } @@ -190,9 +139,7 @@ namespace EHR pc.RpcDesyncRepairSystem(SystemTypes.Comms, 16); if (Main.NormalOptions.MapId is 1 or 5) // Mira HQ or The Fungle - { pc.RpcDesyncRepairSystem(SystemTypes.Comms, 17); - } } } catch (Exception ex) @@ -209,10 +156,7 @@ namespace EHR public static void Postfix() { bool rogueForce = Rogue.On && Main.PlayerStates.Values.Any(x => x.Role is Rogue { DisableDevices: true }); - if (!Options.DisableDevices.GetBool() && !rogueForce) - { - return; - } + if (!Options.DisableDevices.GetBool() && !rogueForce) return; UpdateDisableDevices(); } @@ -221,62 +165,40 @@ namespace EHR { PlayerControl player = PlayerControl.LocalPlayer; bool rogueForce = Rogue.On && Main.PlayerStates.Values.Any(x => x.Role is Rogue { DisableDevices: true }); + bool ignore = player.Is(CustomRoles.GM) || !player.IsAlive() || (Options.DisableDevicesIgnoreImpostors.GetBool() && player.Is(CustomRoleTypes.Impostor)) || (Options.DisableDevicesIgnoreNeutrals.GetBool() && player.Is(CustomRoleTypes.Neutral)) || (Options.DisableDevicesIgnoreCrewmates.GetBool() && player.Is(CustomRoleTypes.Crewmate)) || (Options.DisableDevicesIgnoreAfterAnyoneDied.GetBool() && GameStates.AlreadyDied); + ignore &= !rogueForce; Il2CppArrayBase admins = Object.FindObjectsOfType(true); Il2CppArrayBase consoles = Object.FindObjectsOfType(true); - if (admins == null || consoles == null) - { - return; - } + if (admins == null || consoles == null) return; switch (Main.NormalOptions.MapId) { case 3: case 0: - if (Options.DisableSkeldAdmin.GetBool() || rogueForce) - { - admins[0].gameObject.GetComponent().enabled = ignore; - } + if (Options.DisableSkeldAdmin.GetBool() || rogueForce) admins[0].gameObject.GetComponent().enabled = ignore; - if (Options.DisableSkeldCamera.GetBool() || rogueForce) - { - consoles.DoIf(x => x.name == "SurvConsole", x => x.gameObject.GetComponent().enabled = ignore); - } + if (Options.DisableSkeldCamera.GetBool() || rogueForce) consoles.DoIf(x => x.name == "SurvConsole", x => x.gameObject.GetComponent().enabled = ignore); break; case 1: - if (Options.DisableMiraHQAdmin.GetBool() || rogueForce) - { - admins[0].gameObject.GetComponent().enabled = ignore; - } + if (Options.DisableMiraHQAdmin.GetBool() || rogueForce) admins[0].gameObject.GetComponent().enabled = ignore; - if (Options.DisableMiraHQDoorLog.GetBool() || rogueForce) - { - consoles.DoIf(x => x.name == "SurvLogConsole", x => x.gameObject.GetComponent().enabled = ignore); - } + if (Options.DisableMiraHQDoorLog.GetBool() || rogueForce) consoles.DoIf(x => x.name == "SurvLogConsole", x => x.gameObject.GetComponent().enabled = ignore); break; case 2: - if (Options.DisablePolusAdmin.GetBool() || rogueForce) - { - admins.Do(x => x.gameObject.GetComponent().enabled = ignore); - } + if (Options.DisablePolusAdmin.GetBool() || rogueForce) admins.Do(x => x.gameObject.GetComponent().enabled = ignore); - if (Options.DisablePolusCamera.GetBool() || rogueForce) - { - consoles.DoIf(x => x.name == "Surv_Panel", x => x.gameObject.GetComponent().enabled = ignore); - } + if (Options.DisablePolusCamera.GetBool() || rogueForce) consoles.DoIf(x => x.name == "Surv_Panel", x => x.gameObject.GetComponent().enabled = ignore); - if (Options.DisablePolusVital.GetBool() || rogueForce) - { - consoles.DoIf(x => x.name == "panel_vitals", x => x.gameObject.GetComponent().enabled = ignore); - } + if (Options.DisablePolusVital.GetBool() || rogueForce) consoles.DoIf(x => x.name == "panel_vitals", x => x.gameObject.GetComponent().enabled = ignore); break; case 4: @@ -284,31 +206,18 @@ namespace EHR { if ((Options.DisableAirshipCockpitAdmin.GetBool() && x.name == "panel_cockpit_map") || (Options.DisableAirshipRecordsAdmin.GetBool() && x.name == "records_admin_map") || rogueForce) - { x.gameObject.GetComponent().enabled = ignore; - } }); - if (Options.DisableAirshipCamera.GetBool() || rogueForce) - { - consoles.DoIf(x => x.name == "task_cams", x => x.gameObject.GetComponent().enabled = ignore); - } - if (Options.DisableAirshipVital.GetBool() || rogueForce) - { - consoles.DoIf(x => x.name == "panel_vitals", x => x.gameObject.GetComponent().enabled = ignore); - } + if (Options.DisableAirshipCamera.GetBool() || rogueForce) consoles.DoIf(x => x.name == "task_cams", x => x.gameObject.GetComponent().enabled = ignore); + + if (Options.DisableAirshipVital.GetBool() || rogueForce) consoles.DoIf(x => x.name == "panel_vitals", x => x.gameObject.GetComponent().enabled = ignore); break; case 5: - if (Options.DisableFungleCamera.GetBool() || rogueForce) - { - consoles.DoIf(x => x.name == "BinocularsSecurityConsole", x => x.gameObject.GetComponent().enabled = ignore); - } + if (Options.DisableFungleCamera.GetBool() || rogueForce) consoles.DoIf(x => x.name == "BinocularsSecurityConsole", x => x.gameObject.GetComponent().enabled = ignore); - if (Options.DisableFungleCamera.GetBool() || rogueForce) - { - consoles.DoIf(x => x.name == "VitalsConsole", x => x.gameObject.GetComponent().enabled = ignore); - } + if (Options.DisableFungleCamera.GetBool() || rogueForce) consoles.DoIf(x => x.name == "VitalsConsole", x => x.gameObject.GetComponent().enabled = ignore); break; } diff --git a/Modules/DoorsReset.cs b/Modules/DoorsReset.cs index e2d4df191..184652ac9 100644 --- a/Modules/DoorsReset.cs +++ b/Modules/DoorsReset.cs @@ -30,10 +30,7 @@ namespace EHR.Modules /// Reset door status according to settings public static void ResetDoors() { - if (!IsEnabled || DoorsSystem == null) - { - return; - } + if (!IsEnabled || DoorsSystem == null) return; Logger.Info("Reset Completed", "DoorsReset"); @@ -59,10 +56,7 @@ namespace EHR.Modules { foreach (OpenableDoor door in ShipStatus.Instance.AllDoors) { - if (door == null) - { - continue; - } + if (door == null) continue; SetDoorOpenState(door, true); } @@ -75,10 +69,7 @@ namespace EHR.Modules { foreach (OpenableDoor door in ShipStatus.Instance.AllDoors) { - if (door == null) - { - continue; - } + if (door == null) continue; SetDoorOpenState(door, false); } @@ -103,10 +94,7 @@ namespace EHR.Modules /// true for open, false for close private static void SetDoorOpenState(OpenableDoor door, bool isOpen) { - if (IsValidDoor(door)) - { - door.SetDoorway(isOpen); - } + if (IsValidDoor(door)) door.SetDoorway(isOpen); } /// Determine if the door is subject to reset diff --git a/Modules/DoubleTrigger.cs b/Modules/DoubleTrigger.cs index d11713e64..cee63a57d 100644 --- a/Modules/DoubleTrigger.cs +++ b/Modules/DoubleTrigger.cs @@ -43,10 +43,7 @@ namespace EHR Logger.Info($"{killer.name} - Do Double Action", "DoubleTrigger"); FirstTriggerTimer.Remove(killer.PlayerId); FirstTriggerTarget.Remove(killer.PlayerId); - if (doAction) - { - FirstTriggerAction.Remove(killer.PlayerId); - } + if (doAction) FirstTriggerAction.Remove(killer.PlayerId); return true; } @@ -55,10 +52,7 @@ namespace EHR CheckMurderPatch.TimeSinceLastKill.Remove(killer.PlayerId); FirstTriggerTimer.Add(killer.PlayerId, 1f); FirstTriggerTarget.Add(killer.PlayerId, target.PlayerId); - if (doAction) - { - FirstTriggerAction.Add(killer.PlayerId, firstAction); - } + if (doAction) FirstTriggerAction.Add(killer.PlayerId, firstAction); return false; } @@ -74,19 +68,14 @@ namespace EHR } byte playerId = player.PlayerId; - if (!FirstTriggerTimer.ContainsKey(playerId)) - { - return; - } + if (!FirstTriggerTimer.ContainsKey(playerId)) return; FirstTriggerTimer[playerId] -= Time.fixedDeltaTime; + if (FirstTriggerTimer[playerId] <= 0) { Logger.Info($"{player.name} - Do Single Action", "DoubleTrigger"); - if (FirstTriggerAction.ContainsKey(playerId)) - { - FirstTriggerAction[playerId](); - } + if (FirstTriggerAction.ContainsKey(playerId)) FirstTriggerAction[playerId](); FirstTriggerTimer.Remove(playerId); FirstTriggerTarget.Remove(playerId); diff --git a/Modules/EAC.cs b/Modules/EAC.cs index d4797983d..0bcf8a470 100644 --- a/Modules/EAC.cs +++ b/Modules/EAC.cs @@ -16,38 +16,31 @@ namespace EHR public static void WarnHost(int denum = 1) { DeNum += denum; + if (ErrorText.Instance) { ErrorText.Instance.CheatDetected = DeNum > 3; ErrorText.Instance.SBDetected = DeNum > 10; + if (ErrorText.Instance.CheatDetected) - { ErrorText.Instance.AddError(ErrorText.Instance.SBDetected ? ErrorCode.SBDetected : ErrorCode.CheatDetected); - } else - { ErrorText.Instance.Clear(); - } } } public static bool ReceiveRpc(PlayerControl pc, byte callId, MessageReader reader) { - if (!AmongUsClient.Instance.AmHost) - { - return false; - } + if (!AmongUsClient.Instance.AmHost) return false; // if (RoleBasisChanger.IsChangeInProgress) return false; - if (pc == null || reader == null) - { - return false; - } + if (pc == null || reader == null) return false; try { MessageReader sr = MessageReader.Get(reader); - RpcCalls rpc = (RpcCalls)callId; + var rpc = (RpcCalls)callId; + switch (rpc) { case RpcCalls.CheckName: @@ -63,6 +56,7 @@ namespace EHR break; case RpcCalls.SendChat when !pc.IsHost(): string text = sr.ReadString(); + if (text.Contains('░') || text.Contains('▄') || text.Contains('█') || @@ -127,6 +121,7 @@ namespace EHR break; case RpcCalls.MurderPlayer: sr.ReadNetObject(); + if (GameStates.IsLobby) { Report(pc, "Directly Murder Player In Lobby"); @@ -203,9 +198,7 @@ namespace EHR return true; } } - catch - { - } + catch { } break; case unchecked((byte)42069): // 85 AUM @@ -221,9 +214,7 @@ namespace EHR return true; } } - catch - { - } + catch { } break; case unchecked((byte)420): // 164 Sicko @@ -249,6 +240,7 @@ namespace EHR break; case 5 when !pc.IsHost(): sr.ReadString(); + if (GameStates.IsInGame) { WarnHost(); @@ -305,12 +297,9 @@ namespace EHR public static bool PlayerPhysicsRpcCheck(PlayerPhysics __instance, byte callId, MessageReader reader) // Credit: NikoCat233 { - if (!AmongUsClient.Instance.AmHost) - { - return false; - } + if (!AmongUsClient.Instance.AmHost) return false; - RpcCalls rpcType = (RpcCalls)callId; + var rpcType = (RpcCalls)callId; MessageReader subReader = MessageReader.Get(reader); PlayerControl player = __instance.myPlayer; @@ -335,6 +324,7 @@ namespace EHR case RpcCalls.EnterVent: case RpcCalls.ExitVent: int ventid = subReader.ReadPackedInt32(); + if (!HasVent(ventid)) { if (AmongUsClient.Instance.AmHost) @@ -348,6 +338,7 @@ namespace EHR { // Not sure whether host will send null vent to a player huh Logger.Warn($"【{player.GetClientId()}:{player.GetRealName()}】 attempted to enter an unexisting vent. {ventid}", "EAC_physics"); + if (rpcType is RpcCalls.ExitVent) { player.Visible = true; @@ -372,6 +363,7 @@ namespace EHR case RpcCalls.ClimbLadder: int ladderId = subReader.ReadPackedInt32(); + if (!HasLadder(ladderId)) { if (AmongUsClient.Instance.AmHost) @@ -418,13 +410,10 @@ namespace EHR internal static void Report(PlayerControl pc, string reason) { - string msg = $"{pc.GetClientId()}|{pc.FriendCode}|{pc.Data.PlayerName}|{pc.GetClient().GetHashedPuid()}|{reason}"; + var msg = $"{pc.GetClientId()}|{pc.FriendCode}|{pc.Data.PlayerName}|{pc.GetClient().GetHashedPuid()}|{reason}"; //Cloud.SendData(msg); Logger.Fatal($"EAC report: {msg}", "EAC Cloud"); - if (Options.CheatResponses.GetInt() != 5) - { - Logger.SendInGame(string.Format(GetString("Message.NoticeByEAC"), $"{pc.Data?.PlayerName} | {pc.GetClient().GetHashedPuid()}", reason)); - } + if (Options.CheatResponses.GetInt() != 5) Logger.SendInGame(string.Format(GetString("Message.NoticeByEAC"), $"{pc.Data?.PlayerName} | {pc.GetClient().GetHashedPuid()}", reason)); } public static bool ReceiveInvalidRpc(PlayerControl pc, byte callId) @@ -473,10 +462,7 @@ namespace EHR break; case 4: string hashedPuid = pc.GetClient().GetHashedPuid(); - if (!BanManager.TempBanWhiteList.Contains(hashedPuid)) - { - BanManager.TempBanWhiteList.Add(hashedPuid); - } + if (!BanManager.TempBanWhiteList.Contains(hashedPuid)) BanManager.TempBanWhiteList.Add(hashedPuid); AmongUsClient.Instance.KickPlayer(pc.GetClientId(), true); string msg2 = string.Format(GetString("Message.TempBannedByEAC"), pc?.Data?.PlayerName, text); @@ -488,10 +474,7 @@ namespace EHR internal static bool CheckInvalidSabotage(SystemTypes systemType, PlayerControl player, byte amount) { - if (player.IsHost()) - { - return false; - } + if (player.IsHost()) return false; if ((GameStates.IsMeeting && MeetingHud.Instance.state != MeetingHud.VoteStates.Animating) || ExileController.Instance) { @@ -503,28 +486,20 @@ namespace EHR } byte Mapid = Main.NormalOptions.MapId; + switch (systemType) { case SystemTypes.LifeSupp: - if (Mapid != 0 && Mapid != 1 && Mapid != 3) - { - goto Cheat; - } + if (Mapid != 0 && Mapid != 1 && Mapid != 3) goto Cheat; - if (amount != 64 && amount != 65) - { - goto Cheat; - } + if (amount != 64 && amount != 65) goto Cheat; break; case SystemTypes.Comms: switch (amount) { case 0: - if (Mapid is 1 or 5) - { - goto Cheat; - } + if (Mapid is 1 or 5) goto Cheat; break; case 64: @@ -533,10 +508,7 @@ namespace EHR case 33: case 16: case 17: - if (Mapid is not (1 or 5)) - { - goto Cheat; - } + if (Mapid is not (1 or 5)) goto Cheat; break; default: @@ -545,51 +517,27 @@ namespace EHR break; case SystemTypes.Electrical: - if (Mapid == 5) - { - goto Cheat; - } + if (Mapid == 5) goto Cheat; - if (amount >= 5) - { - goto Cheat; - } + if (amount >= 5) goto Cheat; break; case SystemTypes.Laboratory: - if (Mapid != 2) - { - goto Cheat; - } + if (Mapid != 2) goto Cheat; - if (amount is not (64 or 65 or 32 or 33)) - { - goto Cheat; - } + if (amount is not (64 or 65 or 32 or 33)) goto Cheat; break; case SystemTypes.Reactor: - if (Mapid is 2 or 4) - { - goto Cheat; - } + if (Mapid is 2 or 4) goto Cheat; - if (amount is not (64 or 65 or 32 or 33)) - { - goto Cheat; - } + if (amount is not (64 or 65 or 32 or 33)) goto Cheat; break; case SystemTypes.HeliSabotage: - if (Mapid != 4) - { - goto Cheat; - } + if (Mapid != 4) goto Cheat; - if (amount is not (64 or 65 or 16 or 17 or 32 or 33)) - { - goto Cheat; - } + if (amount is not (64 or 65 or 16 or 17 or 32 or 33)) goto Cheat; break; case SystemTypes.MushroomMixupSabotage: @@ -599,6 +547,7 @@ namespace EHR return false; Cheat: + { WarnHost(); Report(player, "Bad Sabotage C : Hack send RPC"); @@ -629,13 +578,14 @@ namespace EHR { public static bool Prefix(InnerNetClient __instance, MessageReader reader, int msgNum) { - GameDataTag tag = (GameDataTag)reader.Tag; + var tag = (GameDataTag)reader.Tag; switch (tag) { case GameDataTag.DataFlag: { uint netId = reader.ReadPackedUInt32(); + if (__instance.allObjectsFast.TryGetValue(netId, out InnerNetObject obj)) { if (obj.AmOwner) @@ -708,10 +658,7 @@ namespace EHR Logger.Warn($"Client {client.PlayerName} ({client.Id}) tried to send SceneChangeFlag to Tutorial.", "GameDataHandlerPatch"); EAC.WarnHost(100); - if (GameStates.IsOnlineGame && AmongUsClient.Instance.AmHost) - { - Utils.ErrorEnd("SceneChange Tutorial Hack"); - } + if (GameStates.IsOnlineGame && AmongUsClient.Instance.AmHost) Utils.ErrorEnd("SceneChange Tutorial Hack"); return false; } @@ -765,18 +712,12 @@ namespace EHR public static void Prefix() { - if (LobbyBehaviour.Instance != null) - { - IsStartingAsHost = true; - } + if (LobbyBehaviour.Instance != null) IsStartingAsHost = true; } public static void Postfix() { - if (ShipStatus.Instance != null) - { - IsStartingAsHost = false; - } + if (ShipStatus.Instance != null) IsStartingAsHost = false; } } @@ -789,10 +730,7 @@ namespace EHR public static void Postfix(PlayerControl __instance) { - if (!GameStates.IsInTask || ExileController.Instance || !Options.EnableMovementChecking.GetBool() || Main.HasJustStarted || MeetingStates.FirstMeeting || Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod) >= 1.9f || AmongUsClient.Instance.Ping >= 300 || Options.CurrentGameMode == CustomGameMode.NaturalDisasters || Utils.GetRegionName() is not ("EU" or "NA" or "AS") || __instance == null || __instance.PlayerId == 255 || !__instance.IsAlive() || __instance.inVent) - { - return; - } + if (!GameStates.IsInTask || ExileController.Instance || !Options.EnableMovementChecking.GetBool() || Main.HasJustStarted || MeetingStates.FirstMeeting || Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod) >= 1.9f || AmongUsClient.Instance.Ping >= 300 || Options.CurrentGameMode == CustomGameMode.NaturalDisasters || Utils.GetRegionName() is not ("EU" or "NA" or "AS") || __instance == null || __instance.PlayerId == 255 || !__instance.IsAlive() || __instance.inVent) return; Vector2 pos = __instance.Pos(); long now = Utils.TimeStamp; @@ -803,19 +741,13 @@ namespace EHR return; } - if (LastCheck.TryGetValue(__instance.PlayerId, out long lastCheck) && lastCheck == now) - { - return; - } + if (LastCheck.TryGetValue(__instance.PlayerId, out long lastCheck) && lastCheck == now) return; SetCurrentData(); if (Vector2.Distance(lastPosition, pos) > 10f && PhysicsHelpers.AnythingBetween(__instance.Collider, lastPosition, pos, Constants.ShipOnlyMask, false)) { - if (ExemptedPlayers.Remove(__instance.PlayerId)) - { - return; - } + if (ExemptedPlayers.Remove(__instance.PlayerId)) return; EAC.WarnHost(); EAC.Report(__instance, "This player is moving too fast, possibly using a speed hack."); diff --git a/Modules/ErrorText.cs b/Modules/ErrorText.cs index 4a04a0113..04e38a825 100644 --- a/Modules/ErrorText.cs +++ b/Modules/ErrorText.cs @@ -27,39 +27,28 @@ namespace EHR { AllErrors.ForEach(err => err.IncreaseTimer()); ErrorData[] ToRemove = AllErrors.Where(err => err.ErrorLevel <= 1 && 30f < err.Timer).ToArray(); + if (ToRemove.Length > 0) { AllErrors.RemoveAll(err => ToRemove.Contains(err)); UpdateText(); - if (HnSFlag) - { - Destroy(gameObject); - } + if (HnSFlag) Destroy(gameObject); } } public void LateUpdate() { - if (!Text.enabled) - { - return; - } + if (!Text.enabled) return; - if (!Camera) - { - Camera = !HudManager.InstanceExists ? _camera : _camera1; - } + if (!Camera) Camera = !HudManager.InstanceExists ? _camera : _camera1; - if (Camera) - { - transform.position = AspectPosition.ComputeWorldPosition(Camera, AspectPosition.EdgeAlignments.Top, TextOffset); - } + if (Camera) transform.position = AspectPosition.ComputeWorldPosition(Camera, AspectPosition.EdgeAlignments.Top, TextOffset); } public static void Create(TextMeshPro baseText) { TextMeshPro Text = Instantiate(baseText); - ErrorText instance = Text.gameObject.AddComponent(); + var instance = Text.gameObject.AddComponent(); instance.Text = Text; instance.name = "ErrorText"; @@ -78,16 +67,10 @@ namespace EHR public void AddError(ErrorCode code) { - ErrorData error = new ErrorData(code); - if (0 < error.ErrorLevel && code != ErrorCode.LoadingHint) - { - Logger.Error($"Error: {error}: {error.Message}", "ErrorText"); - } + var error = new ErrorData(code); + if (0 < error.ErrorLevel && code != ErrorCode.LoadingHint) Logger.Error($"Error: {error}: {error.Message}", "ErrorText"); - if (AllErrors.All(e => e.Code != code)) - { - AllErrors.Add(error); - } + if (AllErrors.All(e => e.Code != code)) AllErrors.Add(error); UpdateText(); } @@ -96,52 +79,34 @@ namespace EHR { try { - string text = string.Empty; - int maxLevel = 0; - bool hint = false; + var text = string.Empty; + var maxLevel = 0; + var hint = false; + foreach (ErrorData err in AllErrors) { - if (err.Code == ErrorCode.LoadingHint) - { - hint = true; - } + if (err.Code == ErrorCode.LoadingHint) hint = true; text += hint ? LoadingScreen.Hint : $"{err}: {err.Message}\n"; - if (maxLevel < err.ErrorLevel) - { - maxLevel = err.ErrorLevel; - } + if (maxLevel < err.ErrorLevel) maxLevel = err.ErrorLevel; } if (maxLevel == 0) - { Text.enabled = false; - } else { - if (!HnSFlag && !hint) - { - text += $"{GetString($"ErrorLevel{maxLevel}")}"; - } + if (!HnSFlag && !hint) text += $"{GetString($"ErrorLevel{maxLevel}")}"; - if (CheatDetected) - { - text = SBDetected ? GetString("EAC.CheatDetected.HighLevel") : GetString("EAC.CheatDetected.LowLevel"); - } + if (CheatDetected) text = SBDetected ? GetString("EAC.CheatDetected.HighLevel") : GetString("EAC.CheatDetected.LowLevel"); Text.enabled = true; } - if (GameStates.IsInGame && maxLevel != 3 && !CheatDetected) - { - text += $"\n{GetString("TerminateCommand")}: Shift+L+Enter"; - } + if (GameStates.IsInGame && maxLevel != 3 && !CheatDetected) text += $"\n{GetString("TerminateCommand")}: Shift+L+Enter"; Text.text = text; } - catch (NullReferenceException) - { - } + catch (NullReferenceException) { } catch (Exception e) { Logger.Error(e.ToString(), "ErrorText.UpdateText"); @@ -192,9 +157,7 @@ namespace EHR private void Awake() { if (Instance) - { Destroy(gameObject); - } else { Instance = this; @@ -206,26 +169,18 @@ namespace EHR private void FixedUpdate() { - if (Frame++ < 40) - { - return; - } + if (Frame++ < 40) return; Frame = 0; - if (_camera != null && _camera1 != null) - { - return; - } + if (_camera != null && _camera1 != null) return; try { _camera1 = HudManager.Instance.PlayerCam.GetComponent(); _camera = Camera.main; } - catch - { - } + catch { } } #endregion diff --git a/Modules/ExtendedPlayerControl.cs b/Modules/ExtendedPlayerControl.cs index 5075fc461..6e6f79be1 100644 --- a/Modules/ExtendedPlayerControl.cs +++ b/Modules/ExtendedPlayerControl.cs @@ -32,15 +32,10 @@ namespace EHR public static void RpcSetCustomRole(this PlayerControl player, CustomRoles role, bool replaceAllAddons = false) { if (role < CustomRoles.NotAssigned) - { Main.PlayerStates[player.PlayerId].SetMainRole(role); - } else { - if (!Cleanser.CleansedCanGetAddon.GetBool() && player.Is(CustomRoles.Cleansed)) - { - return; - } + if (!Cleanser.CleansedCanGetAddon.GetBool() && player.Is(CustomRoles.Cleansed)) return; Main.PlayerStates[player.PlayerId].SetSubRole(role, replaceAllAddons); } @@ -73,10 +68,7 @@ namespace EHR public static bool CanUseVent(this PlayerControl player, int ventId) { - if (player.Is(CustomRoles.Trainee) && MeetingStates.FirstMeeting) - { - return false; - } + if (player.Is(CustomRoles.Trainee) && MeetingStates.FirstMeeting) return false; return GameStates.IsInTask && ((player.inVent && player.GetClosestVent()?.Id == ventId) || ((player.CanUseImpostorVentButton() || player.GetRoleTypes() == RoleTypes.Engineer) && Main.PlayerStates.Values.All(x => x.Role.CanUseVent(player, ventId)))); } @@ -112,10 +104,7 @@ namespace EHR public static void SetChatVisible(this PlayerControl player) // Credit: NikoCat233 | Unused for now { - if (!GameStates.IsInGame || !AmongUsClient.Instance.AmHost || GameStates.IsMeeting) - { - return; - } + if (!GameStates.IsInGame || !AmongUsClient.Instance.AmHost || GameStates.IsMeeting) return; if (player.AmOwner) { @@ -193,10 +182,7 @@ namespace EHR public static int GetClientId(this PlayerControl player) { - if (player == null) - { - return -1; - } + if (player == null) return -1; ClientData client = player.GetClient(); return client?.Id ?? -1; @@ -225,10 +211,7 @@ namespace EHR public static List GetCustomSubRoles(this PlayerControl player) { - if (GameStates.IsLobby) - { - return []; - } + if (GameStates.IsLobby) return []; if (player == null) { @@ -251,15 +234,9 @@ namespace EHR return CountTypes.None; } - if (!Main.PlayerStates.TryGetValue(player.PlayerId, out PlayerState state)) - { - return CountTypes.None; - } + if (!Main.PlayerStates.TryGetValue(player.PlayerId, out PlayerState state)) return CountTypes.None; - if (!player.IsConverted() && state.SubRoles.Contains(CustomRoles.Bloodlust)) - { - return CountTypes.Bloodlust; - } + if (!player.IsConverted() && state.SubRoles.Contains(CustomRoles.Bloodlust)) return CountTypes.Bloodlust; return state.countTypes; } @@ -286,10 +263,7 @@ namespace EHR } } - if (player.Data != null) - { - Logger.Info($"Set: {player.Data.PlayerName} => {name} for Everyone", "RpcSetNameEx"); - } + if (player.Data != null) Logger.Info($"Set: {player.Data.PlayerName} => {name} for Everyone", "RpcSetNameEx"); player.RpcSetName(name); } @@ -301,34 +275,19 @@ namespace EHR public static void RpcSetNamePrivate(this PlayerControl player, string name, PlayerControl seer = null, bool force = false) { - if (player == null || name == null || !AmongUsClient.Instance.AmHost) - { - return; - } + if (player == null || name == null || !AmongUsClient.Instance.AmHost) return; - if (seer == null) - { - seer = player; - } + if (seer == null) seer = player; - if (!force && Main.LastNotifyNames[(player.PlayerId, seer.PlayerId)] == name) - { - return; - } + if (!force && Main.LastNotifyNames[(player.PlayerId, seer.PlayerId)] == name) return; Main.LastNotifyNames[(player.PlayerId, seer.PlayerId)] = name; Logger.Info($"Set: {player.Data?.PlayerName} => {name} for {seer.GetNameWithRole().RemoveHtmlTags()}", "RpcSetNamePrivate"); - if (seer == null || player == null) - { - return; - } + if (seer == null || player == null) return; int clientId = seer.GetClientId(); - if (clientId == -1) - { - return; - } + if (clientId == -1) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(player.NetId, (byte)RpcCalls.SetName, SendOption.Reliable, clientId); writer.Write(seer.Data.NetId); @@ -340,10 +299,7 @@ namespace EHR public static void RpcSetPetDesync(this PlayerControl player, string petId, PlayerControl seer) { int clientId = seer.GetClientId(); - if (clientId == -1) - { - return; - } + if (clientId == -1) return; if (AmongUsClient.Instance.ClientId == clientId) { @@ -360,10 +316,7 @@ namespace EHR public static void RpcSetRoleDesync(this PlayerControl player, RoleTypes role, int clientId) { - if (player == null) - { - return; - } + if (player == null) return; if (AmongUsClient.Instance.ClientId == clientId) { @@ -385,10 +338,7 @@ namespace EHR // https://github.com/Ultradragon005/TownofHost-Enhanced/blob/ea5f1e8ea87e6c19466231c305d6d36d511d5b2d/Modules/ExtendedPlayerControl.cs public static void RpcRevive(this PlayerControl player) { - if (player == null) - { - return; - } + if (player == null) return; if (!player.Data.IsDead) { @@ -406,10 +356,7 @@ namespace EHR player.RpcResetAbilityCooldown(); player.SyncGeneralOptions(); - if (Camouflage.IsCamouflage) - { - Camouflage.RpcSetSkin(player); - } + if (Camouflage.IsCamouflage) Camouflage.RpcSetSkin(player); NotifyRoles(SpecifySeer: player, NoCache: true); NotifyRoles(SpecifyTarget: player, NoCache: true); @@ -418,10 +365,7 @@ namespace EHR // https://github.com/Ultradragon005/TownofHost-Enhanced/blob/ea5f1e8ea87e6c19466231c305d6d36d511d5b2d/Modules/ExtendedPlayerControl.cs public static void RpcChangeRoleBasis(this PlayerControl player, CustomRoles newCustomRole, bool loggerRoleMap = false) { - if (!AmongUsClient.Instance.AmHost || !GameStates.IsInGame || player == null || !player.IsAlive()) - { - return; - } + if (!AmongUsClient.Instance.AmHost || !GameStates.IsInGame || player == null || !player.IsAlive()) return; byte playerId = player.PlayerId; int playerClientId = player.GetClientId(); @@ -458,53 +402,37 @@ namespace EHR foreach (PlayerControl seer in Main.AllPlayerControls) { int seerClientId = seer.GetClientId(); - if (seerClientId == -1) - { - continue; - } + if (seerClientId == -1) continue; bool seerIsHost = seer.IsHost(); bool self = player.PlayerId == seer.PlayerId; if (!self && seer.HasDesyncRole() && !seerIsHost) - { remeberRoleType = newRoleVN is CustomRoles.Noisemaker ? RoleTypes.Noisemaker : RoleTypes.Scientist; - } else - { remeberRoleType = newRoleType; - } // Set role type for seer StartGameHostPatch.RpcSetRoleReplacer.RoleMap[(seer.PlayerId, playerId)] = (remeberRoleType, newCustomRole); player.RpcSetRoleDesync(remeberRoleType, seerClientId); - if (self) - { - continue; - } + if (self) continue; (RoleTypes seerRoleType, CustomRoles seerCustomRole) = seer.GetRoleMap(); + if (seer.IsAlive()) { if (seerCustomRole.IsDesyncRole()) - { remeberRoleType = seerIsHost ? RoleTypes.Crewmate : RoleTypes.Scientist; - } else - { remeberRoleType = seerRoleType; - } } else { bool playerIsKiller = playerRole.IsImpostor(); remeberRoleType = RoleTypes.CrewmateGhost; - if (!playerIsKiller && seer.Is(Team.Impostor)) - { - remeberRoleType = RoleTypes.ImpostorGhost; - } + if (!playerIsKiller && seer.Is(Team.Impostor)) remeberRoleType = RoleTypes.ImpostorGhost; StartGameHostPatch.RpcSetRoleReplacer.RoleMap[(playerId, seer.PlayerId)] = (seerCustomRole.IsDesyncRole() ? seerIsHost ? RoleTypes.Crewmate : RoleTypes.Scientist : seerRoleType, seerCustomRole); seer.RpcSetRoleDesync(remeberRoleType, playerClientId); @@ -524,10 +452,7 @@ namespace EHR foreach (PlayerControl seer in Main.AllPlayerControls) { int seerClientId = seer.GetClientId(); - if (seerClientId == -1) - { - continue; - } + if (seerClientId == -1) continue; bool self = player.PlayerId == seer.PlayerId; @@ -536,29 +461,20 @@ namespace EHR remeberRoleType = player.IsHost() ? RoleTypes.Crewmate : RoleTypes.Impostor; // For Desync Shapeshifter - if (newRoleDY is RoleTypes.Shapeshifter) - { - remeberRoleType = RoleTypes.Shapeshifter; - } + if (newRoleDY is RoleTypes.Shapeshifter) remeberRoleType = RoleTypes.Shapeshifter; } else - { remeberRoleType = newRoleVN is CustomRoles.Noisemaker ? RoleTypes.Noisemaker : RoleTypes.Scientist; - } StartGameHostPatch.RpcSetRoleReplacer.RoleMap[(seer.PlayerId, playerId)] = (remeberRoleType, newCustomRole); player.RpcSetRoleDesync(remeberRoleType, seerClientId); - if (self) - { - continue; - } + if (self) continue; CustomRoles seerCustomRole = seer.GetRoleMap().CustomRole; + if (seer.IsAlive()) - { remeberRoleType = newRoleVN is CustomRoles.Noisemaker ? RoleTypes.Noisemaker : RoleTypes.Scientist; - } else { remeberRoleType = RoleTypes.CrewmateGhost; @@ -580,22 +496,16 @@ namespace EHR default: { bool playerIsDesync = player.HasDesyncRole(); + foreach (PlayerControl seer in Main.AllPlayerControls) { int seerClientId = seer.GetClientId(); - if (seerClientId == -1) - { - continue; - } + if (seerClientId == -1) continue; if ((playerIsDesync || seer.HasDesyncRole()) && seer.PlayerId != playerId) - { remeberRoleType = Utils.GetRoleMap(seer.PlayerId, playerId).RoleType; - } else - { remeberRoleType = newRoleType; - } StartGameHostPatch.RpcSetRoleReplacer.RoleMap[(seer.PlayerId, playerId)] = (remeberRoleType, newCustomRole); player.RpcSetRoleDesync(remeberRoleType, seerClientId); @@ -610,6 +520,7 @@ namespace EHR foreach (PlayerControl seer in Main.AllPlayerControls) { NetworkedPlayerInfo seerData = seer.Data; + foreach (PlayerControl target in Main.AllPlayerControls) { NetworkedPlayerInfo targetData = target.Data; @@ -627,10 +538,7 @@ namespace EHR // https://github.com/Ultradragon005/TownofHost-Enhanced/blob/ea5f1e8ea87e6c19466231c305d6d36d511d5b2d/Modules/Utils.cs public static void SyncGeneralOptions(this PlayerControl player) { - if (!AmongUsClient.Instance.AmHost || !GameStates.IsInGame) - { - return; - } + if (!AmongUsClient.Instance.AmHost || !GameStates.IsInGame) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncGeneralOptions, SendOption.Reliable); writer.Write(player.PlayerId); @@ -646,6 +554,7 @@ namespace EHR public static void RpcExileDesync(this PlayerControl player, PlayerControl seer) { int clientId = seer.GetClientId(); + if (AmongUsClient.Instance.ClientId == clientId) { player.Exiled(); @@ -659,12 +568,10 @@ namespace EHR // Next 8: https://github.com/0xDrMoe/TownofHost-Enhanced/blob/12487ce1aa7e4f5087f2300be452b5af7c04d1ff/Modules/ExtendedPlayerControl.cs#L239 public static void RpcEnterVentDesync(this PlayerPhysics physics, int ventId, PlayerControl seer) { - if (physics == null) - { - return; - } + if (physics == null) return; int clientId = seer.GetClientId(); + if (AmongUsClient.Instance.ClientId == clientId) { physics.StopAllCoroutines(); @@ -679,12 +586,10 @@ namespace EHR public static void RpcExitVentDesync(this PlayerPhysics physics, int ventId, PlayerControl seer) { - if (physics == null) - { - return; - } + if (physics == null) return; int clientId = seer.GetClientId(); + if (AmongUsClient.Instance.ClientId == clientId) { physics.StopAllCoroutines(); @@ -699,12 +604,10 @@ namespace EHR public static void RpcBootFromVentDesync(this PlayerPhysics physics, int ventId, PlayerControl seer) { - if (physics == null) - { - return; - } + if (physics == null) return; int clientId = seer.GetClientId(); + if (AmongUsClient.Instance.ClientId == clientId) { physics.BootFromVent(ventId); @@ -782,10 +685,7 @@ namespace EHR public static void KillFlash(this PlayerControl player) { - if (GameStates.IsLobby) - { - return; - } + if (GameStates.IsLobby) return; //Kill flash (blackout + reactor flash) processing @@ -795,35 +695,29 @@ namespace EHR MapNames.Airship => SystemTypes.HeliSabotage, _ => SystemTypes.Reactor }; + bool ReactorCheck = IsActive(systemtypes); //Checking whether the reactor sabotage is active float Duration = Options.KillFlashDuration.GetFloat(); - if (ReactorCheck) - { - Duration += 0.2f; // Extend blackout during reactor - } + if (ReactorCheck) Duration += 0.2f; // Extend blackout during reactor // Execution Main.PlayerStates[player.PlayerId].IsBlackOut = true; // Blackout + if (player.AmOwner) { FlashColor(new(1f, 0f, 0f, 0.3f)); - if (Constants.ShouldPlaySfx()) - { - RPC.PlaySound(player.PlayerId, Sounds.KillSound); - } + if (Constants.ShouldPlaySfx()) RPC.PlaySound(player.PlayerId, Sounds.KillSound); } else if (player.IsModClient()) { MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.KillFlash, SendOption.Reliable, player.GetClientId()); AmongUsClient.Instance.FinishRpcImmediately(writer); } - else if (!ReactorCheck) - { - player.ReactorFlash(); // Reactor flash - } + else if (!ReactorCheck) player.ReactorFlash(); // Reactor flash player.MarkDirtySettings(); + LateTask.New(() => { Main.PlayerStates[player.PlayerId].IsBlackOut = false; // Cancel blackout @@ -843,22 +737,13 @@ namespace EHR return; } - if (target == null) - { - target = killer; - } + if (target == null) target = killer; // Check Observer - if (!forObserver && !MeetingStates.FirstMeeting) - { - Main.AllPlayerControls.Where(x => x.Is(CustomRoles.Observer) && killer.PlayerId != x.PlayerId).Do(x => x.RpcGuardAndKill(target, true)); - } + if (!forObserver && !MeetingStates.FirstMeeting) Main.AllPlayerControls.Where(x => x.Is(CustomRoles.Observer) && killer.PlayerId != x.PlayerId).Do(x => x.RpcGuardAndKill(target, true)); // Host - if (killer.AmOwner) - { - killer.MurderPlayer(target, MurderResultFlags.FailedProtected); - } + if (killer.AmOwner) killer.MurderPlayer(target, MurderResultFlags.FailedProtected); // Other Clients if (!killer.IsHost()) @@ -869,10 +754,7 @@ namespace EHR AmongUsClient.Instance.FinishRpcImmediately(writer); } - if (!fromSetKCD) - { - killer.AddKillTimerToDict(true); - } + if (!fromSetKCD) killer.AddKillTimerToDict(true); } public static void RpcSpecificVanish(this PlayerControl player, PlayerControl seer) @@ -881,10 +763,7 @@ namespace EHR * Unluckily the vanishing animation cannot be disabled * For vanila client seer side, the player must be with Phantom Role behavior, or the rpc will do nothing */ - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; MessageWriter msg = AmongUsClient.Instance.StartRpcImmediately(player.NetId, (byte)RpcCalls.StartVanish, SendOption.None, seer.GetClientId()); AmongUsClient.Instance.FinishRpcImmediately(msg); @@ -895,10 +774,7 @@ namespace EHR /* * For vanila client seer side, the player must be with Phantom Role behavior, or the rpc will do nothing */ - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; MessageWriter msg = AmongUsClient.Instance.StartRpcImmediately(player.NetId, (byte)RpcCalls.StartAppear, SendOption.None, seer.GetClientId()); msg.Write(shouldAnimate); @@ -928,10 +804,7 @@ namespace EHR public static void RemoveAbilityCD(this PlayerControl pc) { - if (Main.AbilityCD.Remove(pc.PlayerId)) - { - SendRPC(CustomRPC.SyncAbilityCD, 3, pc.PlayerId); - } + if (Main.AbilityCD.Remove(pc.PlayerId)) SendRPC(CustomRPC.SyncAbilityCD, 3, pc.PlayerId); } public static float GetAbilityUseLimit(this PlayerControl pc) @@ -947,10 +820,7 @@ namespace EHR public static void RpcRemoveAbilityUse(this PlayerControl pc, bool log = true) { float current = pc.GetAbilityUseLimit(); - if (float.IsNaN(current) || current <= 0f) - { - return; - } + if (float.IsNaN(current) || current <= 0f) return; pc.SetAbilityUseLimit(current - 1, log: log); } @@ -958,10 +828,7 @@ namespace EHR public static void RpcIncreaseAbilityUseLimitBy(this PlayerControl pc, float get, bool log = true) { float current = pc.GetAbilityUseLimit(); - if (float.IsNaN(current)) - { - return; - } + if (float.IsNaN(current)) return; pc.SetAbilityUseLimit(current + get, log: log); } @@ -975,10 +842,7 @@ namespace EHR { limit = (float)Math.Round(limit, 1); - if (float.IsNaN(limit) || limit is < 0f or > 100f || (Main.AbilityUseLimit.TryGetValue(playerId, out float beforeLimit) && Math.Abs(beforeLimit - limit) < 0.01f)) - { - return; - } + if (float.IsNaN(limit) || limit is < 0f or > 100f || (Main.AbilityUseLimit.TryGetValue(playerId, out float beforeLimit) && Math.Abs(beforeLimit - limit) < 0.01f)) return; Main.AbilityUseLimit[playerId] = limit; @@ -992,20 +856,15 @@ namespace EHR PlayerControl pc = GetPlayerById(playerId); NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - if (log) - { - Logger.Info($" {pc.GetNameWithRole()} => {Math.Round(limit, 1)}", "SetAbilityUseLimit"); - } + if (log) Logger.Info($" {pc.GetNameWithRole()} => {Math.Round(limit, 1)}", "SetAbilityUseLimit"); } public static void Suicide(this PlayerControl pc, PlayerState.DeathReason deathReason = PlayerState.DeathReason.Suicide, PlayerControl realKiller = null) { - if (!pc.IsAlive() || pc.Data.IsDead || !GameStates.IsInTask || ExileController.Instance) - { - return; - } + if (!pc.IsAlive() || pc.Data.IsDead || !GameStates.IsInTask || ExileController.Instance) return; PlayerState state = Main.PlayerStates[pc.PlayerId]; + if (realKiller != null && state.Role is SchrodingersCat cat) { cat.OnCheckMurderAsTarget(realKiller, pc); @@ -1016,69 +875,45 @@ namespace EHR state.SetDead(); Medic.IsDead(pc); + if (realKiller != null) { pc.SetRealKiller(realKiller); - if (realKiller.Is(CustomRoles.Damocles)) - { - Damocles.OnMurder(realKiller.PlayerId); - } + if (realKiller.Is(CustomRoles.Damocles)) Damocles.OnMurder(realKiller.PlayerId); IncreaseAbilityUseLimitOnKill(realKiller); } pc.Kill(pc); - if (Options.CurrentGameMode == CustomGameMode.NaturalDisasters) - { - NaturalDisasters.RecordDeath(pc, deathReason); - } + if (Options.CurrentGameMode == CustomGameMode.NaturalDisasters) NaturalDisasters.RecordDeath(pc, deathReason); } public static void SetKillCooldown(this PlayerControl player, float time = -1f, PlayerControl target = null, bool forceAnime = false) { - if (player == null) - { - return; - } + if (player == null) return; Logger.Info($"{player.GetNameWithRole()}'s KCD set to {(Math.Abs(time - -1f) < 0.5f ? Main.AllPlayerKillCooldown[player.PlayerId] : time)}s", "SetKCD"); + if (player.GetCustomRole().UsesPetInsteadOfKill()) { if (Math.Abs(time - -1f) < 0.5f) - { player.AddKCDAsAbilityCD(); - } else - { player.AddAbilityCD((int)Math.Round(time)); - } - if (player.GetCustomRole() is not CustomRoles.Necromancer and not CustomRoles.Deathknight and not CustomRoles.Refugee and not CustomRoles.Sidekick) - { - return; - } + if (player.GetCustomRole() is not CustomRoles.Necromancer and not CustomRoles.Deathknight and not CustomRoles.Refugee and not CustomRoles.Sidekick) return; } - if (!player.CanUseKillButton()) - { - return; - } + if (!player.CanUseKillButton()) return; player.AddKillTimerToDict(CD: time); - if (target == null) - { - target = player; - } + if (target == null) target = player; if (time >= 0f) - { Main.AllPlayerKillCooldown[player.PlayerId] = time * 2; - } else - { Main.AllPlayerKillCooldown[player.PlayerId] *= 2; - } if (player.Is(CustomRoles.Glitch) && Main.PlayerStates[player.PlayerId].Role is Glitch gc) { @@ -1093,10 +928,9 @@ namespace EHR else { time = Main.AllPlayerKillCooldown[player.PlayerId] / 2; + if (player.AmOwner) - { PlayerControl.LocalPlayer.SetKillTimer(time); - } else { MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetKillTimer, SendOption.Reliable, player.GetClientId()); @@ -1107,23 +941,15 @@ namespace EHR Main.AllPlayerControls.Where(x => x.Is(CustomRoles.Observer) && target.PlayerId != x.PlayerId).Do(x => x.RpcGuardAndKill(target, true, true)); } - if (player.GetCustomRole() is not CustomRoles.Inhibitor and not CustomRoles.Saboteur) - { - player.ResetKillCooldown(); - } + if (player.GetCustomRole() is not CustomRoles.Inhibitor and not CustomRoles.Saboteur) player.ResetKillCooldown(); } public static void RpcSpecificMurderPlayer(this PlayerControl killer, PlayerControl target = null) { - if (target == null) - { - target = killer; - } + if (target == null) target = killer; if (killer.AmOwner) - { killer.MurderPlayer(target, ResultFlags); - } else { MessageWriter messageWriter = AmongUsClient.Instance.StartRpcImmediately(killer.NetId, (byte)RpcCalls.MurderPlayer, SendOption.Reliable, killer.GetClientId()); @@ -1135,12 +961,10 @@ namespace EHR public static void RpcResetAbilityCooldown(this PlayerControl target) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; Logger.Info($"Reset Ability Cooldown for {target.name} (ID: {target.PlayerId})", "RpcResetAbilityCooldown"); + if (target.Is(CustomRoles.Glitch) && Main.PlayerStates[target.PlayerId].Role is Glitch gc) { gc.LastHack = TimeStamp; @@ -1207,18 +1031,13 @@ namespace EHR public static string GetSubRoleNames(this PlayerControl player, bool forUser = false) { List SubRoles = Main.PlayerStates[player.PlayerId].SubRoles; - if (SubRoles.Count == 0) - { - return string.Empty; - } + if (SubRoles.Count == 0) return string.Empty; StringBuilder sb = new(); + foreach (CustomRoles role in SubRoles) { - if (role == CustomRoles.NotAssigned) - { - continue; - } + if (role == CustomRoles.NotAssigned) continue; sb.Append($"{ColorString(Color.white, "\n")}{GetRoleName(role, forUser)}"); } @@ -1228,10 +1047,7 @@ namespace EHR public static string GetAllRoleName(this PlayerControl player, bool forUser = true) { - if (!player) - { - return null; - } + if (!player) return null; string text = GetRoleName(player.GetCustomRole(), forUser); text += player.GetSubRoleNames(forUser); @@ -1255,10 +1071,7 @@ namespace EHR public static void ResetPlayerCam(this PlayerControl pc, float delay = 0f) { - if (pc == null || !AmongUsClient.Instance.AmHost || pc.AmOwner) - { - return; - } + if (pc == null || !AmongUsClient.Instance.AmHost || pc.AmOwner) return; SystemTypes systemtypes = (MapNames)Main.NormalOptions.MapId switch { @@ -1274,19 +1087,15 @@ namespace EHR LateTask.New(() => { pc.RpcDesyncRepairSystem(systemtypes, 16); + if (Main.NormalOptions.MapId == 4) // Airship only - { pc.RpcDesyncRepairSystem(systemtypes, 17); - } }, 0.4f + delay, "Fix Desync Reactor"); } public static void ReactorFlash(this PlayerControl pc, float delay = 0f) { - if (pc == null) - { - return; - } + if (pc == null) return; Logger.Info($"Reactor Flash for {pc.GetNameWithRole()}", "ReactorFlash"); @@ -1306,9 +1115,7 @@ namespace EHR pc.RpcDesyncRepairSystem(systemtypes, 16); if (Main.NormalOptions.MapId == 4) // on Airship - { pc.RpcDesyncRepairSystem(systemtypes, 17); - } }, FlashDuration + delay, "Fix Desync Reactor"); } @@ -1368,18 +1175,13 @@ namespace EHR return; } - if (target == null || seer == null) - { - return; - } + if (target == null || seer == null) return; int seerClientId = seer.GetClientId(); - if (seerClientId == -1) - { - return; - } + if (seerClientId == -1) return; byte cnt = ++target.scannerCount; + if (AmongUsClient.Instance.ClientId == seerClientId) { target.SetScanner(IsActive, cnt); @@ -1396,35 +1198,20 @@ namespace EHR public static bool HasKillButton(this PlayerControl pc) { CustomRoles role = pc.GetCustomRole(); - if (pc.Data.Role.Role == RoleTypes.GuardianAngel) - { - return false; - } + if (pc.Data.Role.Role == RoleTypes.GuardianAngel) return false; - if (role.GetVNRole(true) is CustomRoles.Impostor or CustomRoles.Shapeshifter or CustomRoles.Phantom) - { - return true; - } + if (role.GetVNRole(true) is CustomRoles.Impostor or CustomRoles.Shapeshifter or CustomRoles.Phantom) return true; - if (pc.GetRoleTypes() is RoleTypes.Impostor or RoleTypes.Shapeshifter or RoleTypes.Phantom) - { - return true; - } + if (pc.GetRoleTypes() is RoleTypes.Impostor or RoleTypes.Shapeshifter or RoleTypes.Phantom) return true; - if (pc.Is(CustomRoles.Bloodlust)) - { - return true; - } + if (pc.Is(CustomRoles.Bloodlust)) return true; return pc.Is(CustomRoleTypes.Impostor) || pc.IsNeutralKiller() || role.IsTasklessCrewmate(); } public static bool CanUseKillButton(this PlayerControl pc) { - if (!pc.IsAlive()) - { - return false; - } + if (!pc.IsAlive()) return false; switch (Options.CurrentGameMode) { @@ -1435,30 +1222,15 @@ namespace EHR return true; } - if (Mastermind.ManipulatedPlayers.ContainsKey(pc.PlayerId)) - { - return true; - } + if (Mastermind.ManipulatedPlayers.ContainsKey(pc.PlayerId)) return true; - if (Penguin.IsVictim(pc)) - { - return false; - } + if (Penguin.IsVictim(pc)) return false; - if (Pelican.IsEaten(pc.PlayerId)) - { - return false; - } + if (Pelican.IsEaten(pc.PlayerId)) return false; - if (pc.Data.Role.Role == RoleTypes.GuardianAngel) - { - return false; - } + if (pc.Data.Role.Role == RoleTypes.GuardianAngel) return false; - if (pc.Is(CustomRoles.Bloodlust)) - { - return true; - } + if (pc.Is(CustomRoles.Bloodlust)) return true; return pc.GetCustomRole() switch { @@ -1492,15 +1264,9 @@ namespace EHR public static bool CanUseImpostorVentButton(this PlayerControl pc) { - if (!pc.IsAlive() || pc.Data.Role.Role == RoleTypes.GuardianAngel || Penguin.IsVictim(pc)) - { - return false; - } + if (!pc.IsAlive() || pc.Data.Role.Role == RoleTypes.GuardianAngel || Penguin.IsVictim(pc)) return false; - if (pc.GetRoleTypes() == RoleTypes.Engineer) - { - return false; - } + if (pc.GetRoleTypes() == RoleTypes.Engineer) return false; return Options.CurrentGameMode switch { @@ -1523,10 +1289,7 @@ namespace EHR public static bool CanUseSabotage(this PlayerControl pc) { - if (!pc.IsAlive() || pc.Data.Role.Role == RoleTypes.GuardianAngel) - { - return false; - } + if (!pc.IsAlive() || pc.Data.Role.Role == RoleTypes.GuardianAngel) return false; if (pc.Is(CustomRoles.Trainee) && MeetingStates.FirstMeeting) { @@ -1545,39 +1308,26 @@ namespace EHR public static void AddKillTimerToDict(this PlayerControl pc, bool half = false, float CD = -1f) { float resultKCD; + if (Math.Abs(CD - -1f) < 0.5f) { resultKCD = Main.AllPlayerKillCooldown.GetValueOrDefault(pc.PlayerId, 0f); - if (half) - { - resultKCD /= 2f; - } + if (half) resultKCD /= 2f; } else - { resultKCD = CD; - } - if (pc.GetCustomRole().UsesPetInsteadOfKill() && resultKCD > 0f) - { - pc.AddAbilityCD((int)Math.Round(resultKCD)); - } + if (pc.GetCustomRole().UsesPetInsteadOfKill() && resultKCD > 0f) pc.AddAbilityCD((int)Math.Round(resultKCD)); - if (Main.KillTimers.TryGetValue(pc.PlayerId, out float timer) && timer > resultKCD) - { - return; - } + if (Main.KillTimers.TryGetValue(pc.PlayerId, out float timer) && timer > resultKCD) return; Main.KillTimers[pc.PlayerId] = resultKCD; } public static bool IsDousedPlayer(this PlayerControl arsonist, PlayerControl target) { - if (arsonist == null || target == null || Arsonist.IsDoused == null) - { - return false; - } + if (arsonist == null || target == null || Arsonist.IsDoused == null) return false; Arsonist.IsDoused.TryGetValue((arsonist.PlayerId, target.PlayerId), out bool isDoused); return isDoused; @@ -1585,10 +1335,7 @@ namespace EHR public static bool IsDrawPlayer(this PlayerControl arsonist, PlayerControl target) { - if (arsonist == null || target == null || Revolutionist.IsDraw == null) - { - return false; - } + if (arsonist == null || target == null || Revolutionist.IsDraw == null) return false; Revolutionist.IsDraw.TryGetValue((arsonist.PlayerId, target.PlayerId), out bool isDraw); return isDraw; @@ -1596,10 +1343,7 @@ namespace EHR public static bool IsRevealedPlayer(this PlayerControl player, PlayerControl target) { - if (player == null || target == null || Farseer.IsRevealed == null) - { - return false; - } + if (player == null || target == null || Farseer.IsRevealed == null) return false; Farseer.IsRevealed.TryGetValue((player.PlayerId, target.PlayerId), out bool isDoused); return isDoused; @@ -1662,27 +1406,18 @@ namespace EHR CustomRoles.Killer => FFAManager.FFAKcd.GetFloat(), _ => Main.AllPlayerKillCooldown[player.PlayerId] }; - if (player.PlayerId == LastImpostor.CurrentId) - { - LastImpostor.SetKillCooldown(); - } + + if (player.PlayerId == LastImpostor.CurrentId) LastImpostor.SetKillCooldown(); if (player.Is(CustomRoles.Mare)) { if (IsActive(SystemTypes.Electrical)) - { Main.AllPlayerKillCooldown[player.PlayerId] = Options.MareKillCD.GetFloat(); - } else - { Main.AllPlayerKillCooldown[player.PlayerId] = Options.MareKillCDNormally.GetFloat(); - } } - if (player.Is(CustomRoles.Bloodlust)) - { - Main.AllPlayerKillCooldown[player.PlayerId] = Bloodlust.KCD.GetFloat(); - } + if (player.Is(CustomRoles.Bloodlust)) Main.AllPlayerKillCooldown[player.PlayerId] = Bloodlust.KCD.GetFloat(); if (Main.KilledDiseased.TryGetValue(player.PlayerId, out int value)) { @@ -1693,10 +1428,7 @@ namespace EHR if (Main.KilledAntidote.TryGetValue(player.PlayerId, out int value1)) { float kcd = Main.AllPlayerKillCooldown[player.PlayerId] - (value1 * Options.AntidoteCDOpt.GetFloat()); - if (kcd < 0) - { - kcd = 0; - } + if (kcd < 0) kcd = 0; Main.AllPlayerKillCooldown[player.PlayerId] = kcd; Logger.Info($"KCD of player set to {Main.AllPlayerKillCooldown[player.PlayerId]}", "Antidote"); @@ -1710,6 +1442,7 @@ namespace EHR Main.AllPlayerSpeed[killer.PlayerId] = Main.MinSpeed; ReportDeadBodyPatch.CanReport[killer.PlayerId] = false; killer.MarkDirtySettings(); + LateTask.New(() => { Main.AllPlayerSpeed[killer.PlayerId] = tmpSpeed; @@ -1721,10 +1454,7 @@ namespace EHR public static bool IsDouseDone(this PlayerControl player) { - if (!player.Is(CustomRoles.Arsonist)) - { - return false; - } + if (!player.Is(CustomRoles.Arsonist)) return false; (int, int) count = GetDousedPlayerCount(player.PlayerId); return count.Item1 >= count.Item2; @@ -1732,10 +1462,7 @@ namespace EHR public static bool IsDrawDone(this PlayerControl player) // Determine whether the conditions to win are met { - if (!player.Is(CustomRoles.Revolutionist)) - { - return false; - } + if (!player.Is(CustomRoles.Revolutionist)) return false; (int, int) count = GetDrawPlayerCount(player.PlayerId, out _); return count.Item1 >= count.Item2; @@ -1775,51 +1502,28 @@ namespace EHR public static void Kill(this PlayerControl killer, PlayerControl target) { - if (Options.CurrentGameMode == CustomGameMode.SoloKombat) - { - return; - } + if (Options.CurrentGameMode == CustomGameMode.SoloKombat) return; - if (target == null) - { - target = killer; - } + if (target == null) target = killer; CheckAndSpawnAdditionalRefugee(target.Data); - if (target.GetTeam() is Team.Impostor or Team.Neutral) - { - Stressed.OnNonCrewmateDead(); - } + if (target.GetTeam() is Team.Impostor or Team.Neutral) Stressed.OnNonCrewmateDead(); if (killer.Is(CustomRoles.Damocles)) - { Damocles.OnMurder(killer.PlayerId); - } else if (killer.Is(Team.Impostor)) - { Damocles.OnOtherImpostorMurder(); - } - else if (target.Is(Team.Impostor)) - { - Damocles.OnImpostorDeath(); - } + else if (target.Is(Team.Impostor)) Damocles.OnImpostorDeath(); if (killer.Is(CustomRoles.Bloodlust)) - { FixedUpdatePatch.AddExtraAbilityUsesOnFinishedTasks(killer); - } else - { IncreaseAbilityUseLimitOnKill(killer); - } target.SetRealKiller(killer, true); - if (target.Is(CustomRoles.Jackal)) - { - Jackal.Instances.Do(x => x.PromoteSidekick()); - } + if (target.Is(CustomRoles.Jackal)) Jackal.Instances.Do(x => x.PromoteSidekick()); Main.DiedThisRound.Add(target.PlayerId); @@ -1844,10 +1548,7 @@ namespace EHR public static void NoCheckStartMeeting(this PlayerControl reporter, NetworkedPlayerInfo target, bool force = false) { - if (Options.DisableMeeting.GetBool() && !force) - { - return; - } + if (Options.DisableMeeting.GetBool() && !force) return; ReportDeadBodyPatch.AfterReportTasks(reporter, target, true); MeetingRoomManager.Instance.AssignSelf(reporter, target); @@ -1858,6 +1559,7 @@ namespace EHR public static void CheckAndSetUnshiftState(this PlayerControl pc, bool notify = true, bool force = false) { CustomRoles role = pc.GetCustomRole(); + if (force || role.AlwaysUsesUnshift() || (role.SimpleAbilityTrigger() && Options.UseUnshiftTrigger.GetBool() && (!pc.IsNeutralKiller() || Options.UseUnshiftTriggerForNKs.GetBool()))) { Logger.Info($"Set Unshift State For {pc.GetNameWithRole()}", "CheckAndSetUnshiftState"); @@ -1868,13 +1570,11 @@ namespace EHR pc.RpcShapeshift(target, false); Main.ProcessShapeshifts = process; Main.CheckShapeshift[pc.PlayerId] = false; + LateTask.New(() => { RpcChangeSkin(pc, outfit); - if (notify) - { - NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc, NoCache: true); - } + if (notify) NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc, NoCache: true); }, 0.1f, log: false); } } @@ -1894,13 +1594,10 @@ namespace EHR Il2CppSystem.Collections.Generic.List rangePlayersIL = RoleBehaviour.GetTempPlayerList(); List rangePlayers = []; player.Data.Role.GetPlayersInAbilityRangeSorted(rangePlayersIL, ignoreColliders); + foreach (PlayerControl pc in rangePlayersIL) - { if (predicate(pc)) - { rangePlayers.Add(pc); - } - } return rangePlayers; } @@ -1948,14 +1645,12 @@ namespace EHR public static string GetRoleInfo(this PlayerControl player, bool InfoLong = false) { CustomRoles role = player.GetCustomRole(); - if (role is CustomRoles.Crewmate or CustomRoles.Impostor) - { - InfoLong = false; - } + if (role is CustomRoles.Crewmate or CustomRoles.Impostor) InfoLong = false; - string text = role.ToString(); + var text = role.ToString(); + + var Prefix = string.Empty; - string Prefix = string.Empty; if (!InfoLong) { Prefix = role switch @@ -1978,10 +1673,7 @@ namespace EHR } PlayerState State = Main.PlayerStates[target.PlayerId]; - if (State.RealKiller.TimeStamp != DateTime.MinValue && NotOverRide) - { - return; // Do not overwrite if value already exists - } + if (State.RealKiller.TimeStamp != DateTime.MinValue && NotOverRide) return; // Do not overwrite if value already exists byte killerId = killer == null ? byte.MaxValue : killer.PlayerId; RPC.SetRealKiller(target.PlayerId, killerId); @@ -1995,10 +1687,7 @@ namespace EHR public static PlainShipRoom GetPlainShipRoom(this PlayerControl pc) { - if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId)) - { - return default; - } + if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId)) return default; Il2CppReferenceArray Rooms = ShipStatus.Instance.AllRooms; return Rooms.Where(room => room.roomArea).FirstOrDefault(room => pc.Collider.IsTouching(room.roomArea)); @@ -2066,32 +1755,17 @@ namespace EHR public static Team GetTeam(this PlayerControl target) { - if (Framer.FramedPlayers.Contains(target.PlayerId)) - { - return Team.Impostor; - } + if (Framer.FramedPlayers.Contains(target.PlayerId)) return Team.Impostor; List subRoles = target.GetCustomSubRoles(); - if (subRoles.Contains(CustomRoles.Bloodlust) || target.IsConverted()) - { - return Team.Neutral; - } + if (subRoles.Contains(CustomRoles.Bloodlust) || target.IsConverted()) return Team.Neutral; - if (subRoles.Contains(CustomRoles.Madmate)) - { - return Team.Impostor; - } + if (subRoles.Contains(CustomRoles.Madmate)) return Team.Impostor; CustomRoles role = target.GetCustomRole(); - if (role.IsImpostorTeamV2()) - { - return Team.Impostor; - } + if (role.IsImpostorTeamV2()) return Team.Impostor; - if (role.IsNeutralTeamV2()) - { - return Team.Neutral; - } + if (role.IsNeutralTeamV2()) return Team.Neutral; return role.IsCrewmateTeamV2() ? Team.Crewmate : Team.None; } @@ -2103,10 +1777,7 @@ namespace EHR public static bool IsAlive(this PlayerControl target) { - if (target == null || target.Is(CustomRoles.GM)) - { - return false; - } + if (target == null || target.Is(CustomRoles.GM)) return false; return GameStates.IsLobby || !Main.PlayerStates.TryGetValue(target.PlayerId, out PlayerState ps) || !ps.IsDead; } diff --git a/Modules/Extensions/CollectionExtensions.cs b/Modules/Extensions/CollectionExtensions.cs index 5f8a9e0c2..4617b6edc 100644 --- a/Modules/Extensions/CollectionExtensions.cs +++ b/Modules/Extensions/CollectionExtensions.cs @@ -24,12 +24,8 @@ namespace EHR public static TKey GetKeyByValue(this Dictionary dictionary, TValue value) { foreach (KeyValuePair pair in dictionary) - { if (pair.Value.Equals(value)) - { return pair.Key; - } - } return default; } @@ -43,10 +39,7 @@ namespace EHR /// public static void SetAllValues(this Dictionary dictionary, TValue value) { - foreach (TKey key in dictionary.Keys.ToArray()) - { - dictionary[key] = value; - } + foreach (TKey key in dictionary.Keys.ToArray()) dictionary[key] = value; } /// @@ -58,10 +51,7 @@ namespace EHR /// public static void AdjustAllValues(this Dictionary dictionary, Func adjust) { - foreach (TKey key in dictionary.Keys.ToArray()) - { - dictionary[key] = adjust(dictionary[key]); - } + foreach (TKey key in dictionary.Keys.ToArray()) dictionary[key] = adjust(dictionary[key]); } /// @@ -75,10 +65,7 @@ namespace EHR /// public static T RandomElement(this IList collection) { - if (collection.Count == 0) - { - return default; - } + if (collection.Count == 0) return default; return collection[IRandom.Instance.Next(collection.Count)]; } @@ -94,10 +81,7 @@ namespace EHR /// public static T RandomElement(this IEnumerable collection) { - if (collection is IList list) - { - return list.RandomElement(); - } + if (collection is IList list) return list.RandomElement(); return collection.ToList().RandomElement(); } @@ -127,18 +111,12 @@ namespace EHR { if (collection is List list) { - for (int i = 0; i < list.Count; i++) - { - action(list[i]); - } + for (var i = 0; i < list.Count; i++) action(list[i]); return; } - foreach (T element in collection) - { - action(element); - } + foreach (T element in collection) action(element); } /// @@ -155,25 +133,18 @@ namespace EHR { if (collection is List list) { - for (int i = 0; i < list.Count; i++) + for (var i = 0; i < list.Count; i++) { T element = list[i]; - if (predicate(element)) - { - action(element); - } + if (predicate(element)) action(element); } return; } foreach (T element in collection) - { if (predicate(element)) - { action(element); - } - } return; } @@ -193,18 +164,15 @@ namespace EHR /// public static (List TrueList, List FalseList) Split(this IEnumerable collection, Func predicate) { - List list1 = new List(); - List list2 = new List(); + var list1 = new List(); + var list2 = new List(); + foreach (T element in collection) { if (predicate(element)) - { list1.Add(element); - } else - { list2.Add(element); - } } return (list1, list2); @@ -228,12 +196,8 @@ namespace EHR public static Dictionary AddRange(this Dictionary dictionary, Dictionary other, bool overrideExistingKeys = true) { foreach ((TKey key, TValue value) in other) - { if (overrideExistingKeys || !dictionary.ContainsKey(key)) - { dictionary[key] = value; - } - } return dictionary; } @@ -265,9 +229,10 @@ namespace EHR { if (collection is List list) { - for (int i = 0; i < list.Count; i++) + for (var i = 0; i < list.Count; i++) { T item = list[i]; + if (predicate(item)) { element = item; @@ -353,7 +318,8 @@ namespace EHR { List list = collection.ToList(); int n = list.Count; - IRandom r = IRandom.Instance; + var r = IRandom.Instance; + while (n > 1) { n--; @@ -373,7 +339,8 @@ namespace EHR public static List Shuffle(this List collection) { int n = collection.Count; - IRandom r = IRandom.Instance; + var r = IRandom.Instance; + while (n > 1) { n--; @@ -393,7 +360,8 @@ namespace EHR public static T[] Shuffle(this T[] collection) { int n = collection.Length; - IRandom r = IRandom.Instance; + var r = IRandom.Instance; + while (n > 1) { n--; @@ -419,20 +387,15 @@ namespace EHR { List list = collection.ToList(); int length = list.Count; - if (parts <= 0 || length == 0) - { - yield break; - } + if (parts <= 0 || length == 0) yield break; - if (parts > length) - { - parts = length; - } + if (parts > length) parts = length; int size = length / parts; int remainder = length % parts; - int index = 0; - for (int i = 0; i < parts; i++) + var index = 0; + + for (var i = 0; i < parts; i++) { int partSize = size + (i < remainder ? 1 : 0); yield return list.Skip(index).Take(partSize); @@ -450,20 +413,15 @@ namespace EHR public static IEnumerable> Partition(this IList collection, int parts) { int length = collection.Count; - if (parts <= 0 || length == 0) - { - yield break; - } + if (parts <= 0 || length == 0) yield break; - if (parts > length) - { - parts = length; - } + if (parts > length) parts = length; int size = length / parts; int remainder = length % parts; - int index = 0; - for (int i = 0; i < parts; i++) + var index = 0; + + for (var i = 0; i < parts; i++) { int partSize = size + (i < remainder ? 1 : 0); yield return collection.Skip(index).Take(partSize); @@ -478,10 +436,7 @@ namespace EHR { public static void Times(int count, Action action) { - for (int i = 0; i < count; i++) - { - action(i); - } + for (var i = 0; i < count; i++) action(i); } } } \ No newline at end of file diff --git a/Modules/Extensions/IGameManagerEx.cs b/Modules/Extensions/IGameManagerEx.cs index ae9606b61..a24773cf9 100644 --- a/Modules/Extensions/IGameManagerEx.cs +++ b/Modules/Extensions/IGameManagerEx.cs @@ -11,10 +11,7 @@ namespace EHR.Modules.Extensions public static void Set(this BoolOptionNames name, bool value, NormalGameOptionsV08 opt) { - if (name != BoolOptionNames.GhostsDoTasks) - { - opt.SetBool(name, value); - } + if (name != BoolOptionNames.GhostsDoTasks) opt.SetBool(name, value); } public static void Set(this BoolOptionNames name, bool value, HideNSeekGameOptionsV08 opt) diff --git a/Modules/Extensions/ObjectHelper.cs b/Modules/Extensions/ObjectHelper.cs index 899a81f31..0656b0f7b 100644 --- a/Modules/Extensions/ObjectHelper.cs +++ b/Modules/Extensions/ObjectHelper.cs @@ -7,10 +7,7 @@ namespace EHR { public static void DestroyTranslator(this GameObject obj) { - if (obj == null) - { - return; - } + if (obj == null) return; obj.ForEachChild((Action)DestroyTranslator); // False error TextTranslatorTMP[] translator = obj.GetComponentsInChildren(true); diff --git a/Modules/GameOptionsSender/GameOptionsSender.cs b/Modules/GameOptionsSender/GameOptionsSender.cs index 381a564ca..9ae8a09ff 100644 --- a/Modules/GameOptionsSender/GameOptionsSender.cs +++ b/Modules/GameOptionsSender/GameOptionsSender.cs @@ -23,14 +23,11 @@ namespace EHR.Modules writer.Write(opt.Version); writer.StartMessage(0); writer.Write((byte)opt.GameMode); - if (opt.TryCast(out NormalGameOptionsV08 normalOpt)) - { + + if (opt.TryCast(out NormalGameOptionsV08 normalOpt)) NormalGameOptionsV08.Serialize(writer, normalOpt); - } - else if (opt.TryCast(out HideNSeekGameOptionsV08 hnsOpt)) - { + else if (opt.TryCast(out HideNSeekGameOptionsV08 hnsOpt)) HideNSeekGameOptionsV08.Serialize(writer, hnsOpt); - } else { writer.Recycle(); @@ -40,7 +37,7 @@ namespace EHR.Modules writer.EndMessage(); // Array & Send - Il2CppStructArray byteArray = new Il2CppStructArray(writer.Length - 1); + var byteArray = new Il2CppStructArray(writer.Length - 1); // MessageWriter.ToByteArray Buffer.BlockCopy(writer.Buffer.Cast(), 1, byteArray.Cast(), 0, writer.Length - 1); @@ -53,10 +50,7 @@ namespace EHR.Modules for (byte i = 0; i < GameManager.Instance.LogicComponents.Count; i++) { Il2CppSystem.Object logicComponent = GameManager.Instance.LogicComponents[(Index)i]; - if (logicComponent.TryCast(out _)) - { - SendOptionsArray(optionArray, i, -1); - } + if (logicComponent.TryCast(out _)) SendOptionsArray(optionArray, i, -1); } } @@ -67,24 +61,27 @@ namespace EHR.Modules MessageWriter writer = MessageWriter.Get(SendOption.Reliable); writer.StartMessage(targetClientId == -1 ? Tags.GameData : Tags.GameDataTo); + { writer.Write(AmongUsClient.Instance.GameId); - if (targetClientId != -1) - { - writer.WritePacked(targetClientId); - } + if (targetClientId != -1) writer.WritePacked(targetClientId); writer.StartMessage(1); + { writer.WritePacked(GameManager.Instance.NetId); writer.StartMessage(LogicOptionsIndex); + { writer.WriteBytesAndSize(optionArray); } + writer.EndMessage(); } + writer.EndMessage(); } + writer.EndMessage(); AmongUsClient.Instance.SendOrDisconnect(writer); @@ -110,6 +107,7 @@ namespace EHR.Modules public static IEnumerator SendAllGameOptionsAsync() { AllSenders.RemoveAll(s => s == null || !s.AmValid()); + foreach (GameOptionsSender sender in AllSenders.ToArray()) { if (sender.IsDirty) @@ -125,14 +123,12 @@ namespace EHR.Modules public static void SendAllGameOptions() { AllSenders.RemoveAll(s => s == null || !s.AmValid()); + // ReSharper disable once ForCanBeConvertedToForeach - for (int index = 0; index < AllSenders.Count; index++) + for (var index = 0; index < AllSenders.Count; index++) { GameOptionsSender sender = AllSenders[index]; - if (sender.IsDirty) - { - sender.SendGameOptions(); - } + if (sender.IsDirty) sender.SendGameOptions(); sender.IsDirty = false; } diff --git a/Modules/GameOptionsSender/NormalGameOptionsSender.cs b/Modules/GameOptionsSender/NormalGameOptionsSender.cs index 88e507807..371592e0a 100644 --- a/Modules/GameOptionsSender/NormalGameOptionsSender.cs +++ b/Modules/GameOptionsSender/NormalGameOptionsSender.cs @@ -17,12 +17,8 @@ namespace EHR.Modules if (GameManager.Instance != null && GameManager.Instance.LogicComponents != null && (_logicOptions == null || !GameManager.Instance.LogicComponents.Contains(_logicOptions))) { foreach (GameLogicComponent glc in GameManager.Instance.LogicComponents) - { - if (glc.TryCast(out LogicOptions lo)) - { + if (glc.TryCast(out LogicOptions lo)) _logicOptions = lo; - } - } } return _logicOptions is { IsDirty: true }; diff --git a/Modules/GameOptionsSender/PlayerGameOptionsSender.cs b/Modules/GameOptionsSender/PlayerGameOptionsSender.cs index aa5cd1456..0d4459d34 100644 --- a/Modules/GameOptionsSender/PlayerGameOptionsSender.cs +++ b/Modules/GameOptionsSender/PlayerGameOptionsSender.cs @@ -28,9 +28,10 @@ namespace EHR.Modules public static void SetDirty(byte playerId) { - for (int index = 0; index < AllSenders.Count; index++) + for (var index = 0; index < AllSenders.Count; index++) { GameOptionsSender allSender = AllSenders[index]; + if (allSender is PlayerGameOptionsSender sender && sender.player.PlayerId == playerId) { sender.SetDirty(); @@ -41,52 +42,40 @@ namespace EHR.Modules public static void SetDirtyToAll() { - for (int index = 0; index < AllSenders.Count; index++) + for (var index = 0; index < AllSenders.Count; index++) { GameOptionsSender allSender = AllSenders[index]; - if (allSender is PlayerGameOptionsSender sender) - { - sender.SetDirty(); - } + if (allSender is PlayerGameOptionsSender sender) sender.SetDirty(); } } // For lights call/fix public static void SetDirtyToAllV2() { - for (int index = 0; index < AllSenders.Count; index++) + for (var index = 0; index < AllSenders.Count; index++) { GameOptionsSender allSender = AllSenders[index]; - if (allSender is PlayerGameOptionsSender { IsDirty: false } sender && sender.player.IsAlive() && (sender.player.GetCustomRole().NeedUpdateOnLights() || sender.player.Is(CustomRoles.Torch) || sender.player.Is(CustomRoles.Mare) || sender.player.Is(CustomRoles.Sleep) || Beacon.IsAffectedPlayer(sender.player.PlayerId))) - { - sender.SetDirty(); - } + if (allSender is PlayerGameOptionsSender { IsDirty: false } sender && sender.player.IsAlive() && (sender.player.GetCustomRole().NeedUpdateOnLights() || sender.player.Is(CustomRoles.Torch) || sender.player.Is(CustomRoles.Mare) || sender.player.Is(CustomRoles.Sleep) || Beacon.IsAffectedPlayer(sender.player.PlayerId))) sender.SetDirty(); } } // For Grenadier blidning/restoring public static void SetDirtyToAllV3() { - for (int index = 0; index < AllSenders.Count; index++) + for (var index = 0; index < AllSenders.Count; index++) { GameOptionsSender allSender = AllSenders[index]; - if (allSender is PlayerGameOptionsSender { IsDirty: false } sender && sender.player.IsAlive() && ((Grenadier.GrenadierBlinding.Count > 0 && (sender.player.IsImpostor() || (sender.player.GetCustomRole().IsNeutral() && Options.GrenadierCanAffectNeutral.GetBool()))) || (Grenadier.MadGrenadierBlinding.Count > 0 && !sender.player.GetCustomRole().IsImpostorTeam() && !sender.player.Is(CustomRoles.Madmate)))) - { - sender.SetDirty(); - } + if (allSender is PlayerGameOptionsSender { IsDirty: false } sender && sender.player.IsAlive() && ((Grenadier.GrenadierBlinding.Count > 0 && (sender.player.IsImpostor() || (sender.player.GetCustomRole().IsNeutral() && Options.GrenadierCanAffectNeutral.GetBool()))) || (Grenadier.MadGrenadierBlinding.Count > 0 && !sender.player.GetCustomRole().IsImpostorTeam() && !sender.player.Is(CustomRoles.Madmate)))) sender.SetDirty(); } } // For players with kill buttons public static void SetDirtyToAllV4() { - for (int index = 0; index < AllSenders.Count; index++) + for (var index = 0; index < AllSenders.Count; index++) { GameOptionsSender allSender = AllSenders[index]; - if (allSender is PlayerGameOptionsSender { IsDirty: false } sender && sender.player.IsAlive() && sender.player.CanUseKillButton()) - { - sender.SetDirty(); - } + if (allSender is PlayerGameOptionsSender { IsDirty: false } sender && sender.player.IsAlive() && sender.player.CanUseKillButton()) sender.SetDirty(); } } @@ -100,23 +89,18 @@ namespace EHR.Modules if (player.AmOwner) { IGameOptions opt = BuildGameOptions(); + if (GameManager.Instance?.LogicComponents != null) { foreach (GameLogicComponent com in GameManager.Instance.LogicComponents) - { - if (com.TryCast(out LogicOptions lo)) - { + if (com.TryCast(out LogicOptions lo)) lo.SetGameOptions(opt); - } - } } GameOptionsManager.Instance.CurrentGameOptions = opt; } else - { base.SendGameOptions(); - } } protected override void SendOptionsArray(Il2CppStructArray optionArray) @@ -126,10 +110,7 @@ namespace EHR.Modules for (byte i = 0; i < GameManager.Instance.LogicComponents.Count; i++) { Il2CppSystem.Object logicComponent = GameManager.Instance.LogicComponents[(Index)i]; - if (logicComponent.TryCast(out _)) - { - SendOptionsArray(optionArray, i, player.GetClientId()); - } + if (logicComponent.TryCast(out _)) SendOptionsArray(optionArray, i, player.GetClientId()); } } catch (Exception ex) @@ -142,10 +123,8 @@ namespace EHR.Modules { PlayerGameOptionsSender sender = AllSenders.OfType() .FirstOrDefault(sender => sender.player.PlayerId == player.PlayerId); - if (sender == null) - { - return; - } + + if (sender == null) return; sender.player = null; AllSenders.Remove(sender); @@ -174,9 +153,7 @@ namespace EHR.Modules opt.SetFloat(FloatOptionNames.ImpostorLightMod, FFAManager.FFALowerVision.GetFloat()); } else - { SetMaxVision(); - } break; case CustomGameMode.CaptureTheFlag: @@ -245,25 +222,15 @@ namespace EHR.Modules // When impostor alert is off, and the player is a desync crewmate, set impostor alert as true if (role.IsDesyncRole() && role.IsCrewmate() && !CrewmateVanillaRoles.NoiseMakerImpostorAlert.GetBool()) - { AURoleOptions.NoisemakerImpostorAlert = true; - } else - { AURoleOptions.NoisemakerImpostorAlert = CrewmateVanillaRoles.NoiseMakerImpostorAlert.GetBool(); - } - if (Shifter.WasShifter.Contains(player.PlayerId) && role.IsImpostor()) - { - opt.SetVision(true); - } + if (Shifter.WasShifter.Contains(player.PlayerId) && role.IsImpostor()) opt.SetVision(true); Main.PlayerStates[player.PlayerId].Role.ApplyGameOptions(opt, player.PlayerId); - if (player.Is(CustomRoles.Bloodlust) && Bloodlust.HasImpVision.GetBool()) - { - opt.SetVision(true); - } + if (player.Is(CustomRoles.Bloodlust) && Bloodlust.HasImpVision.GetBool()) opt.SetVision(true); if (Main.AllPlayerControls.Any(x => x.Is(CustomRoles.Bewilder) && !x.IsAlive() && x.GetRealKiller()?.PlayerId == player.PlayerId && !x.Is(CustomRoles.Hangman))) { @@ -286,14 +253,11 @@ namespace EHR.Modules { case CustomRoles.Alchemist when ((Alchemist)Main.PlayerStates[player.PlayerId].Role).VisionPotionActive: opt.SetVisionV2(); + if (Utils.IsActive(SystemTypes.Electrical)) - { opt.SetFloat(FloatOptionNames.CrewLightMod, Alchemist.VisionOnLightsOut.GetFloat() * 5); - } else - { opt.SetFloat(FloatOptionNames.CrewLightMod, Alchemist.Vision.GetFloat()); - } break; case CustomRoles.Mayor when Mayor.MayorSeesVoteColorsWhenDoneTasks.GetBool() && player.GetTaskState().IsTaskFinished: @@ -313,10 +277,7 @@ namespace EHR.Modules opt.SetFloat(FloatOptionNames.ImpostorLightMod, Sprayer.LoweredVision.GetFloat()); } - if (Minion.BlindPlayers.Contains(player.PlayerId)) - { - SetBlind(); - } + if (Minion.BlindPlayers.Contains(player.PlayerId)) SetBlind(); if (Sentinel.IsPatrolling(player.PlayerId)) { @@ -337,15 +298,11 @@ namespace EHR.Modules Spiritcaller.ReduceVision(opt, player); if (Randomizer.HasSuperVision(player)) - { SetMaxVision(); - } - else if (Randomizer.IsBlind(player)) - { - SetBlind(); - } + else if (Randomizer.IsBlind(player)) SetBlind(); List array = Main.PlayerStates[player.PlayerId].SubRoles; + foreach (CustomRoles subRole in array) { if (subRole.IsGhostRole() && subRole != CustomRoles.EvilSpirit) @@ -427,20 +384,11 @@ namespace EHR.Modules } } - if (Magician.BlindPpl.ContainsKey(player.PlayerId)) - { - SetBlind(); - } + if (Magician.BlindPpl.ContainsKey(player.PlayerId)) SetBlind(); - if (player.IsCrewmate() && Main.PlayerStates.Values.Any(s => s.Role is Adventurer { IsEnable: true } av && av.ActiveWeapons.Contains(Adventurer.Weapon.Lantern))) - { - SetMaxVision(); - } + if (player.IsCrewmate() && Main.PlayerStates.Values.Any(s => s.Role is Adventurer { IsEnable: true } av && av.ActiveWeapons.Contains(Adventurer.Weapon.Lantern))) SetMaxVision(); - if (Chemist.Instances.Any(x => x.IsBlinding && player.PlayerId != x.ChemistPC.PlayerId)) - { - SetBlind(); - } + if (Chemist.Instances.Any(x => x.IsBlinding && player.PlayerId != x.ChemistPC.PlayerId)) SetBlind(); if (Changeling.ChangedRole.TryGetValue(player.PlayerId, out bool changed) && changed && player.GetRoleTypes() != RoleTypes.Shapeshifter) { @@ -448,35 +396,20 @@ namespace EHR.Modules AURoleOptions.ShapeshifterDuration = 1f; } - if (Options.UsePhantomBasis.GetBool() && role.SimpleAbilityTrigger()) - { - AURoleOptions.PhantomDuration = 1f; - } + if (Options.UsePhantomBasis.GetBool() && role.SimpleAbilityTrigger()) AURoleOptions.PhantomDuration = 1f; - if ((Options.UseUnshiftTrigger.GetBool() || role.AlwaysUsesUnshift()) && role.SimpleAbilityTrigger()) - { - AURoleOptions.ShapeshifterDuration = 0f; - } + if ((Options.UseUnshiftTrigger.GetBool() || role.AlwaysUsesUnshift()) && role.SimpleAbilityTrigger()) AURoleOptions.ShapeshifterDuration = 0f; // =================================================================================================================== AURoleOptions.EngineerCooldown = Mathf.Max(0.01f, AURoleOptions.EngineerCooldown); - if (Main.AllPlayerKillCooldown.TryGetValue(player.PlayerId, out float killCooldown)) - { - AURoleOptions.KillCooldown = Mathf.Max(0.01f, killCooldown); - } + if (Main.AllPlayerKillCooldown.TryGetValue(player.PlayerId, out float killCooldown)) AURoleOptions.KillCooldown = Mathf.Max(0.01f, killCooldown); - if (Main.AllPlayerSpeed.TryGetValue(player.PlayerId, out float speed)) - { - AURoleOptions.PlayerSpeedMod = Mathf.Clamp(speed, Main.MinSpeed, 3f); - } + if (Main.AllPlayerSpeed.TryGetValue(player.PlayerId, out float speed)) AURoleOptions.PlayerSpeedMod = Mathf.Clamp(speed, Main.MinSpeed, 3f); state.TaskState.HasTasks = Utils.HasTasks(player.Data, false); - if (Options.GhostCanSeeOtherVotes.GetBool() && player.Data.IsDead) - { - opt.SetBool(BoolOptionNames.AnonymousVotes, false); - } + if (Options.GhostCanSeeOtherVotes.GetBool() && player.Data.IsDead) opt.SetBool(BoolOptionNames.AnonymousVotes, false); if (Options.AdditionalEmergencyCooldown.GetBool() && Options.AdditionalEmergencyCooldownThreshold.GetInt() <= Utils.AllAlivePlayersCount) @@ -486,10 +419,7 @@ namespace EHR.Modules Options.AdditionalEmergencyCooldownTime.GetInt()); } - if (Options.SyncButtonMode.GetBool() && Options.SyncedButtonCount.GetValue() <= Options.UsedButtonCount) - { - opt.SetInt(Int32OptionNames.EmergencyCooldown, 3600); - } + if (Options.SyncButtonMode.GetBool() && Options.SyncedButtonCount.GetValue() <= Options.UsedButtonCount) opt.SetInt(Int32OptionNames.EmergencyCooldown, 3600); MeetingTimeManager.ApplyGameOptions(opt); diff --git a/Modules/GameState.cs b/Modules/GameState.cs index e9bfff6e8..6a6820135 100644 --- a/Modules/GameState.cs +++ b/Modules/GameState.cs @@ -107,24 +107,15 @@ namespace EHR }; } - if (CustomTeamManager.GetCustomTeam(PlayerId) != null && !CustomTeamManager.IsSettingEnabledForPlayerTeam(PlayerId, CTAOption.WinWithOriginalTeam)) - { - countTypes = CountTypes.CustomTeam; - } + if (CustomTeamManager.GetCustomTeam(PlayerId) != null && !CustomTeamManager.IsSettingEnabledForPlayerTeam(PlayerId, CTAOption.WinWithOriginalTeam)) countTypes = CountTypes.CustomTeam; SubRoles.ForEach(SetAddonCountTypes); - if (!Player.HasKillButton() && role == CustomRoles.Refugee) - { - Player.RpcChangeRoleBasis(CustomRoles.Refugee); - } + if (!Player.HasKillButton() && role == CustomRoles.Refugee) Player.RpcChangeRoleBasis(CustomRoles.Refugee); Role = role.GetRoleClass(); - if (!role.RoleExist(true)) - { - Role.Init(); - } + if (!role.RoleExist(true)) Role.Init(); MainRole = role; @@ -132,10 +123,7 @@ namespace EHR Logger.Info($"ID {PlayerId} ({Player?.GetRealName()}) => {role}, CountTypes => {countTypes}", "SetMainRole"); - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; if (!Main.HasJustStarted) { @@ -143,34 +131,23 @@ namespace EHR Player.SyncSettings(); Utils.NotifyRoles(SpecifySeer: Player); Utils.NotifyRoles(SpecifyTarget: Player); + if (PlayerId == PlayerControl.LocalPlayer.PlayerId && GameStates.IsInTask) { HudManager.Instance.SetHudActive(true); RemoveDisableDevicesPatch.UpdateDisableDevices(); } - if (Lyncher.On) - { - Lyncher.Instances.ForEach(x => x.OnRoleChange(PlayerId)); - } + if (Lyncher.On) Lyncher.Instances.ForEach(x => x.OnRoleChange(PlayerId)); - if (!role.Is(Team.Impostor)) - { - SubRoles.ToArray().DoIf(x => x.IsImpOnlyAddon(), RemoveSubRole); - } + if (!role.Is(Team.Impostor)) SubRoles.ToArray().DoIf(x => x.IsImpOnlyAddon(), RemoveSubRole); - if (role is CustomRoles.Sidekick or CustomRoles.Necromancer or CustomRoles.Deathknight or CustomRoles.Refugee) - { - SubRoles.ToArray().DoIf(StartGameHostPatch.BasisChangingAddons.ContainsKey, RemoveSubRole); - } + if (role is CustomRoles.Sidekick or CustomRoles.Necromancer or CustomRoles.Deathknight or CustomRoles.Refugee) SubRoles.ToArray().DoIf(StartGameHostPatch.BasisChangingAddons.ContainsKey, RemoveSubRole); - if (role == CustomRoles.Sidekick && Jackal.Instances.FindFirst(x => x.SidekickId == byte.MaxValue || x.SidekickId.GetPlayer() == null, out Jackal jackal)) - { - jackal.SidekickId = PlayerId; - } + if (role == CustomRoles.Sidekick && Jackal.Instances.FindFirst(x => x.SidekickId == byte.MaxValue || x.SidekickId.GetPlayer() == null, out Jackal jackal)) jackal.SidekickId = PlayerId; LateTask.New(() => Player.CheckAndSetUnshiftState(), 1f, log: false); - + if (Options.CurrentGameMode == CustomGameMode.Standard && !GameStates.IsMeeting && !AntiBlackout.SkipTasks) Player.Notify(string.Format(Translator.GetString("RoleChangedNotify"), role.ToColoredString()), 10f); } @@ -180,10 +157,7 @@ namespace EHR public void SetSubRole(CustomRoles role, bool AllReplace = false) { - if (role == CustomRoles.Cleansed) - { - AllReplace = true; - } + if (role == CustomRoles.Cleansed) AllReplace = true; if (AllReplace) { @@ -191,10 +165,7 @@ namespace EHR Utils.SendRPC(CustomRPC.RemoveSubRole, PlayerId, 2); } - if (!SubRoles.Contains(role)) - { - SubRoles.Add(role); - } + if (!SubRoles.Contains(role)) SubRoles.Add(role); SetAddonCountTypes(role); @@ -212,6 +183,7 @@ namespace EHR case CustomRoles.Madmate: TaskState.HasTasks = false; TaskState.AllTasksCount = 0; + countTypes = Options.MadmateCountMode.GetInt() switch { 0 => CountTypes.OutOfGame, @@ -219,6 +191,7 @@ namespace EHR 2 => CountTypes.Crew, _ => throw new NotImplementedException() }; + SubRoles.Remove(CustomRoles.Charmed); SubRoles.Remove(CustomRoles.Recruit); SubRoles.Remove(CustomRoles.Contagious); @@ -232,6 +205,7 @@ namespace EHR case CustomRoles.Charmed: TaskState.HasTasks = false; TaskState.AllTasksCount = 0; + countTypes = Succubus.CharmedCountMode.GetInt() switch { 0 => CountTypes.OutOfGame, @@ -239,6 +213,7 @@ namespace EHR 2 => countTypes, _ => throw new NotImplementedException() }; + SubRoles.Remove(CustomRoles.Madmate); SubRoles.Remove(CustomRoles.Recruit); SubRoles.Remove(CustomRoles.Contagious); @@ -252,6 +227,7 @@ namespace EHR case CustomRoles.Undead: TaskState.HasTasks = false; TaskState.AllTasksCount = 0; + countTypes = Necromancer.UndeadCountMode.GetInt() switch { 0 => CountTypes.OutOfGame, @@ -259,6 +235,7 @@ namespace EHR 2 => countTypes, _ => throw new NotImplementedException() }; + SubRoles.Remove(CustomRoles.Madmate); SubRoles.Remove(CustomRoles.Recruit); SubRoles.Remove(CustomRoles.Contagious); @@ -275,6 +252,7 @@ namespace EHR case CustomRoles.Recruit: TaskState.HasTasks = false; TaskState.AllTasksCount = 0; + countTypes = Jackal.SidekickCountMode.GetInt() switch { 0 => CountTypes.Jackal, @@ -282,6 +260,7 @@ namespace EHR 2 => countTypes, _ => throw new NotImplementedException() }; + SubRoles.Remove(CustomRoles.Madmate); SubRoles.Remove(CustomRoles.Charmed); SubRoles.Remove(CustomRoles.Contagious); @@ -295,6 +274,7 @@ namespace EHR case CustomRoles.Contagious: TaskState.HasTasks = false; TaskState.AllTasksCount = 0; + countTypes = Virus.ContagiousCountMode.GetInt() switch { 0 => CountTypes.OutOfGame, @@ -302,6 +282,7 @@ namespace EHR 2 => countTypes, _ => throw new NotImplementedException() }; + SubRoles.Remove(CustomRoles.Madmate); SubRoles.Remove(CustomRoles.Recruit); SubRoles.Remove(CustomRoles.Charmed); @@ -331,6 +312,7 @@ namespace EHR public void SetDead() { IsDead = true; + if (AmongUsClient.Instance.AmHost) { RPC.SendDeathReason(PlayerId, deathReason); @@ -371,10 +353,7 @@ namespace EHR public void Init(PlayerControl player) { Logger.Info($"{player.GetNameWithRole().RemoveHtmlTags()}: InitTask", "TaskState.Init"); - if (player == null || player.Data?.Tasks == null) - { - return; - } + if (player == null || player.Data?.Tasks == null) return; if (!Utils.HasTasks(player.Data, false)) { @@ -393,15 +372,9 @@ namespace EHR GameData.Instance.RecomputeTaskCounts(); Logger.Info($"TotalTaskCounts = {GameData.Instance.CompletedTasks}/{GameData.Instance.TotalTasks}", "TaskState.Update"); - if (AllTasksCount == -1) - { - Init(player); - } + if (AllTasksCount == -1) Init(player); - if (!HasTasks) - { - return; - } + if (!HasTasks) return; if (AmongUsClient.Instance.AmHost) { @@ -409,10 +382,7 @@ namespace EHR if (alive && Options.CurrentGameMode == CustomGameMode.Speedrun) { - if (CompletedTasksCount + 1 >= AllTasksCount) - { - SpeedrunManager.OnTaskFinish(player); - } + if (CompletedTasksCount + 1 >= AllTasksCount) SpeedrunManager.OnTaskFinish(player); SpeedrunManager.ResetTimer(player); } @@ -423,37 +393,23 @@ namespace EHR switch (player.GetCustomRole()) { case CustomRoles.SabotageMaster: - if (Main.PlayerStates[player.PlayerId].Role is not SabotageMaster sm) - { - break; - } + if (Main.PlayerStates[player.PlayerId].Role is not SabotageMaster sm) break; sm.UsedSkillCount -= SabotageMaster.SmAbilityUseGainWithEachTaskCompleted.GetFloat(); sm.SendRPC(); break; case CustomRoles.NiceHacker: if (!player.IsModClient() && NiceHacker.UseLimit.ContainsKey(player.PlayerId)) - { NiceHacker.UseLimit[player.PlayerId] += NiceHacker.NiceHackerAbilityUseGainWithEachTaskCompleted.GetFloat(); - } - else if (NiceHacker.UseLimitSeconds.ContainsKey(player.PlayerId)) - { - NiceHacker.UseLimitSeconds[player.PlayerId] += NiceHacker.NiceHackerAbilityUseGainWithEachTaskCompleted.GetInt() * NiceHacker.ModdedClientAbilityUseSecondsMultiplier.GetInt(); - } + else if (NiceHacker.UseLimitSeconds.ContainsKey(player.PlayerId)) NiceHacker.UseLimitSeconds[player.PlayerId] += NiceHacker.NiceHackerAbilityUseGainWithEachTaskCompleted.GetInt() * NiceHacker.ModdedClientAbilityUseSecondsMultiplier.GetInt(); - if (NiceHacker.UseLimitSeconds.ContainsKey(player.PlayerId)) - { - NiceHacker.SendRPC(player.PlayerId, NiceHacker.UseLimitSeconds[player.PlayerId]); - } + if (NiceHacker.UseLimitSeconds.ContainsKey(player.PlayerId)) NiceHacker.SendRPC(player.PlayerId, NiceHacker.UseLimitSeconds[player.PlayerId]); break; } float add = Utils.GetSettingNameAndValueForRole(player.GetCustomRole(), "AbilityUseGainWithEachTaskCompleted"); - if (Math.Abs(add - float.MaxValue) > 0.5f && add > 0) - { - player.RpcIncreaseAbilityUseLimitBy(add); - } + if (Math.Abs(add - float.MaxValue) > 0.5f && add > 0) player.RpcIncreaseAbilityUseLimitBy(add); } try @@ -467,38 +423,21 @@ namespace EHR List addons = Main.PlayerStates[player.PlayerId].SubRoles; - if (addons.Contains(CustomRoles.Deadlined)) - { - Deadlined.SetDone(player); - } + if (addons.Contains(CustomRoles.Deadlined)) Deadlined.SetDone(player); - if (addons.Contains(CustomRoles.Stressed)) - { - Stressed.OnTaskComplete(player); - } + if (addons.Contains(CustomRoles.Stressed)) Stressed.OnTaskComplete(player); - if (addons.Contains(CustomRoles.Unlucky) && alive && IRandom.Instance.Next(0, 100) < Options.UnluckyTaskSuicideChance.GetInt()) - { - player.Suicide(); - } + if (addons.Contains(CustomRoles.Unlucky) && alive && IRandom.Instance.Next(0, 100) < Options.UnluckyTaskSuicideChance.GetInt()) player.Suicide(); if (GhostRolesManager.AssignedGhostRoles.TryGetValue(player.PlayerId, out (CustomRoles Role, IGhostRole Instance) ghostRole)) { - if (ghostRole is { Role: CustomRoles.Specter, Instance: Specter specter } && CompletedTasksCount + 1 >= AllTasksCount) - { - specter.OnFinishedTasks(player); - } + if (ghostRole is { Role: CustomRoles.Specter, Instance: Specter specter } && CompletedTasksCount + 1 >= AllTasksCount) specter.OnFinishedTasks(player); if (ghostRole is { Role: CustomRoles.Haunter, Instance: Haunter haunter }) { if (CompletedTasksCount + 1 >= AllTasksCount) - { haunter.OnFinishedTasks(player); - } - else if (CompletedTasksCount + 1 >= Haunter.TasksBeforeBeingKnown.GetInt()) - { - haunter.OnOneTaskLeft(player); - } + else if (CompletedTasksCount + 1 >= Haunter.TasksBeforeBeingKnown.GetInt()) haunter.OnOneTaskLeft(player); } } @@ -506,18 +445,11 @@ namespace EHR // Update the player's task count for Task Managers foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { if (pc.Is(CustomRoles.TaskManager) && pc.PlayerId != player.PlayerId) - { Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: player); - } - } } - if (CompletedTasksCount >= AllTasksCount) - { - return; - } + if (CompletedTasksCount >= AllTasksCount) return; CompletedTasksCount++; @@ -532,21 +464,13 @@ namespace EHR public readonly string tag = tagStr; public readonly Version version = ver; - public PlayerVersion(string ver, string tagStr, string forkId) : this(Version.Parse(ver), tagStr, forkId) - { - } + public PlayerVersion(string ver, string tagStr, string forkId) : this(Version.Parse(ver), tagStr, forkId) { } public override bool Equals(object obj) { - if (obj is null) - { - return false; - } + if (obj is null) return false; - if (ReferenceEquals(this, obj)) - { - return true; - } + if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((PlayerVersion)obj); } @@ -584,10 +508,7 @@ namespace EHR { get { - if (!IsOnlineGame) - { - return false; - } + if (!IsOnlineGame) return false; const string domain = "among.us"; diff --git a/Modules/GhostRolesManager.cs b/Modules/GhostRolesManager.cs index 9b1b42d69..aeaf51438 100644 --- a/Modules/GhostRolesManager.cs +++ b/Modules/GhostRolesManager.cs @@ -26,10 +26,7 @@ namespace EHR.Modules public static void AssignGhostRole(PlayerControl pc) { - if (GhostRoles.Count == 0) - { - return; - } + if (GhostRoles.Count == 0) return; CustomRoles suitableRole = GetSuitableGhostRole(pc); Logger.Warn($"Assigning Ghost Role: {pc.GetNameWithRole()} => {suitableRole}", "GhostRolesManager"); @@ -41,26 +38,17 @@ namespace EHR.Modules Main.ResetCamPlayerList.Add(pc.PlayerId); AssignedGhostRoles[pc.PlayerId] = (suitableRole, instance); - if (suitableRole == CustomRoles.Haunter) - { - GhostRoles.Remove(suitableRole); - } + if (suitableRole == CustomRoles.Haunter) GhostRoles.Remove(suitableRole); NotifyAboutGhostRole(pc, true); } public static void SpecificAssignGhostRole(byte id, CustomRoles role, bool set) { - if (AssignedGhostRoles.Any(x => x.Key == id || x.Value.Role == role)) - { - return; - } + if (AssignedGhostRoles.Any(x => x.Key == id || x.Value.Role == role)) return; PlayerControl pc = Utils.GetPlayerById(id); - if (set) - { - pc.RpcSetRole(RoleTypes.GuardianAngel); - } + if (set) pc.RpcSetRole(RoleTypes.GuardianAngel); IGhostRole instance = CreateGhostRoleInstance(role); instance.OnAssign(pc); @@ -70,20 +58,14 @@ namespace EHR.Modules public static void NotifyAboutGhostRole(PlayerControl pc, bool first = false) { - if (!AssignedGhostRoles.TryGetValue(pc.PlayerId, out (CustomRoles Role, IGhostRole Instance) ghostRole)) - { - return; - } + if (!AssignedGhostRoles.TryGetValue(pc.PlayerId, out (CustomRoles Role, IGhostRole Instance) ghostRole)) return; - if (!first && pc.IsModClient()) - { - return; - } + if (!first && pc.IsModClient()) return; CustomRoles role = ghostRole.Role; (string Split, string Message) info = GetMessage(Translator.GetString($"{role}InfoLong").Split("\n")[1..].Join(delimiter: "\n")); - string text = $"{Translator.GetString("GotGhostRoleNotify")}\n{info.Message}"; - string notifyText = $"{Translator.GetString("GotGhostRoleNotify")}\n{info.Split}"; + var text = $"{Translator.GetString("GotGhostRoleNotify")}\n{info.Message}"; + var notifyText = $"{Translator.GetString("GotGhostRoleNotify")}\n{info.Split}"; Utils.SendMessage(title: text, sendTo: pc.PlayerId, text: "\n"); pc.Notify(notifyText, 5 + (5 * text.Count(x => x == '\n'))); return; @@ -91,13 +73,11 @@ namespace EHR.Modules (string Split, string Message) GetMessage(string baseMessage) { string message = baseMessage; - for (int i = 50; i < message.Length; i += 50) + + for (var i = 50; i < message.Length; i += 50) { int index = message.LastIndexOf(' ', i); - if (index != -1) - { - message = message.Insert(index + 1, "\n"); - } + if (index != -1) message = message.Insert(index + 1, "\n"); } return (ApplyFormat(message), ApplyFormat(baseMessage)); @@ -113,20 +93,11 @@ namespace EHR.Modules { try { - if (Options.CurrentGameMode != CustomGameMode.Standard) - { - return false; - } + if (Options.CurrentGameMode != CustomGameMode.Standard) return false; - if (AssignedGhostRoles.Count >= GhostRoles.Count) - { - return false; - } + if (AssignedGhostRoles.Count >= GhostRoles.Count) return false; - if (pc.IsAlive() || pc.GetCountTypes() is CountTypes.None or CountTypes.OutOfGame || pc.Is(CustomRoles.EvilSpirit)) - { - return false; - } + if (pc.IsAlive() || pc.GetCountTypes() is CountTypes.None or CountTypes.OutOfGame || pc.Is(CustomRoles.EvilSpirit)) return false; switch (pc.GetCustomRole()) { @@ -135,6 +106,7 @@ namespace EHR.Modules } CustomRoles suitableRole = GetSuitableGhostRole(pc); + return suitableRole switch { CustomRoles.Specter when IsPartnerPickedRole() => false, @@ -168,24 +140,18 @@ namespace EHR.Modules try { Type ghostRoleClass = Assembly.GetExecutingAssembly().GetTypes().First(x => typeof(IGhostRole).IsAssignableFrom(x) && !x.IsInterface && x.Name == $"{ghostRole}"); - IGhostRole ghostRoleInstance = (IGhostRole)Activator.CreateInstance(ghostRoleClass); + var ghostRoleInstance = (IGhostRole)Activator.CreateInstance(ghostRoleClass); return ghostRoleInstance; } catch (InvalidOperationException) { - if (!check) - { - Logger.Error($"Ghost role {ghostRole} not found", "CreateGhostRoleInstance"); - } + if (!check) Logger.Error($"Ghost role {ghostRole} not found", "CreateGhostRoleInstance"); return null; } catch (Exception e) { - if (!check) - { - Utils.ThrowException(e); - } + if (!check) Utils.ThrowException(e); return null; } @@ -193,10 +159,7 @@ namespace EHR.Modules public static void RemoveGhostRole(byte id) { - if (!AssignedGhostRoles.TryGetValue(id, out (CustomRoles Role, IGhostRole Instance) ghostRole)) - { - return; - } + if (!AssignedGhostRoles.TryGetValue(id, out (CustomRoles Role, IGhostRole Instance) ghostRole)) return; Main.PlayerStates[id].RemoveSubRole(ghostRole.Role); AssignedGhostRoles.Remove(id); diff --git a/Modules/GuessManager.cs b/Modules/GuessManager.cs index 715347238..4a909d82a 100644 --- a/Modules/GuessManager.cs +++ b/Modules/GuessManager.cs @@ -33,9 +33,10 @@ namespace EHR public static string GetFormatString() { string text = GetString("PlayerIdList"); + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - string id = pc.PlayerId.ToString(); + var id = pc.PlayerId.ToString(); string name = pc.GetRealName(); text += $"\n{id} → {name}"; } @@ -46,14 +47,12 @@ namespace EHR private static bool CheckCommand(ref string msg, string command, bool exact = true) { string[] comList = command.Split('|'); + foreach (string str in comList) { if (exact) { - if (msg == "/" + str) - { - return true; - } + if (msg == "/" + str) return true; } else { @@ -103,31 +102,19 @@ namespace EHR { string originMsg = msg; - if (!AmongUsClient.Instance.AmHost) - { - return false; - } + if (!AmongUsClient.Instance.AmHost) return false; - if (!GameStates.IsMeeting || pc == null) - { - return false; - } + if (!GameStates.IsMeeting || pc == null) return false; - if (!pc.Is(CustomRoles.NiceGuesser) && !pc.Is(CustomRoles.EvilGuesser) && !pc.Is(CustomRoles.Doomsayer) && !pc.Is(CustomRoles.Judge) && !pc.Is(CustomRoles.NiceSwapper) && !pc.Is(CustomRoles.Councillor) && !pc.Is(CustomRoles.Guesser) && !Options.GuesserMode.GetBool()) - { - return false; - } + if (!pc.Is(CustomRoles.NiceGuesser) && !pc.Is(CustomRoles.EvilGuesser) && !pc.Is(CustomRoles.Doomsayer) && !pc.Is(CustomRoles.Judge) && !pc.Is(CustomRoles.NiceSwapper) && !pc.Is(CustomRoles.Councillor) && !pc.Is(CustomRoles.Guesser) && !Options.GuesserMode.GetBool()) return false; int operate; // 1: ID, 2: Guess msg = msg.ToLower().TrimStart().TrimEnd(); + if (CheckCommand(ref msg, "id|guesslist|gl编号|玩家编号|玩家id|id列表|玩家列表|列表|所有id|全部id")) - { operate = 1; - } else if (CheckCommand(ref msg, "shoot|guess|bet|st|bt|猜|赌", false)) - { operate = 2; - } else { Logger.Msg("Not a guessing command", "Msg Guesser"); @@ -147,21 +134,14 @@ namespace EHR if (!pc.IsAlive()) { if (!isUI) - { Utils.SendMessage(GetString("GuessDead"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessDead")); - } return true; } - if (pc.Is(CustomRoles.Lyncher) && Lyncher.GuessMode.GetValue() == 2) - { - goto SkipCheck; - } + if (pc.Is(CustomRoles.Lyncher) && Lyncher.GuessMode.GetValue() == 2) goto SkipCheck; if ((!pc.Is(CustomRoles.NiceGuesser) && pc.IsCrewmate() && !Options.CrewmatesCanGuess.GetBool() && !pc.Is(CustomRoles.Guesser) && !pc.Is(CustomRoles.Judge) && !pc.Is(CustomRoles.NiceSwapper)) || (!pc.Is(CustomRoles.EvilGuesser) && pc.IsImpostor() && !Options.ImpostorsCanGuess.GetBool() && !pc.Is(CustomRoles.Guesser) && !pc.Is(CustomRoles.Councillor)) || @@ -169,19 +149,12 @@ namespace EHR (pc.GetCustomRole().IsNonNK() && !Options.PassiveNeutralsCanGuess.GetBool() && !pc.Is(CustomRoles.Guesser) && !pc.Is(CustomRoles.Doomsayer)) || (pc.Is(CustomRoles.Lyncher) && Lyncher.GuessMode.GetValue() == 0)) { - if (pc.IsConverted() && Options.BetrayalAddonsCanGuess.GetBool()) - { - goto SkipCheck; - } + if (pc.IsConverted() && Options.BetrayalAddonsCanGuess.GetBool()) goto SkipCheck; if (!isUI) - { Utils.SendMessage(GetString("GuessNotAllowed"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessNotAllowed")); - } return true; } @@ -192,45 +165,33 @@ namespace EHR (pc.Is(CustomRoles.EvilGuesser) && Options.EGTryHideMsg.GetBool()) || (pc.Is(CustomRoles.Doomsayer) && Doomsayer.DoomsayerTryHideMsg.GetBool()) || (pc.Is(CustomRoles.Guesser) && Guesser.GTryHideMsg.GetBool()) || (Options.GuesserMode.GetBool() && Options.HideGuesserCommands.GetBool())) - { ChatManager.SendPreviousMessagesToAll(); - } - else if (pc.AmOwner && !isUI) - { - Utils.SendMessage(originMsg, 255, pc.GetRealName()); - } + else if (pc.AmOwner && !isUI) Utils.SendMessage(originMsg, 255, pc.GetRealName()); if (!MsgToPlayerAndRole(msg, out byte targetId, out CustomRoles role, out string error)) { if (!isUI) - { Utils.SendMessage(error, pc.PlayerId); - } else - { pc.ShowPopUp(error); - } return true; } PlayerControl target = Utils.GetPlayerById(targetId); + if (target != null) { Main.GuesserGuessed.TryAdd(pc.PlayerId, 0); - bool guesserSuicide = false; + var guesserSuicide = false; if (CopyCat.Instances.Any(x => x.CopyCatPC.PlayerId == pc.PlayerId)) { if (!isUI) - { Utils.SendMessage(GetString("GuessDisabled"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessDisabled")); - } return true; } @@ -238,13 +199,9 @@ namespace EHR if (CustomTeamManager.AreInSameCustomTeam(pc.PlayerId, targetId) && !CustomTeamManager.IsSettingEnabledForPlayerTeam(targetId, CTAOption.GuessEachOther)) { if (!isUI) - { Utils.SendMessage(GetString("GuessSameCTAPlayer"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessSameCTAPlayer")); - } return true; } @@ -254,18 +211,15 @@ namespace EHR if (hasGuessSetting && guessSetting.GetValue() == 1) { if (!isUI) - { Utils.SendMessage(GetString("GuessDisabledAddonOverride"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessDisabledAddonOverride")); - } return true; } OptionItem convertedGuessSetting = null; + if (role == CustomRoles.Egoist || role.IsConverted()) { convertedGuessSetting = role switch @@ -277,16 +231,13 @@ namespace EHR CustomRoles.Egoist => Options.EgoistCanBeGuessed, _ => null }; + if (convertedGuessSetting?.GetValue() == 1) { if (!isUI) - { Utils.SendMessage(GetString("GuessDisabledAddonOverride"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessDisabledAddonOverride")); - } return true; } @@ -297,13 +248,9 @@ namespace EHR if (role == CustomRoles.Lovers && Lovers.GuessAbility.GetValue() == 0) { if (!isUI) - { Utils.SendMessage(GetString("GuessLovers"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessLovers")); - } return true; } @@ -312,103 +259,67 @@ namespace EHR { case CustomRoles.NiceGuesser when Main.GuesserGuessed[pc.PlayerId] >= Options.GGCanGuessTime.GetInt(): if (!isUI) - { Utils.SendMessage(GetString("GGGuessMax"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GGGuessMax")); - } return true; case CustomRoles.EvilGuesser when Main.GuesserGuessed[pc.PlayerId] >= Options.EGCanGuessTime.GetInt(): if (!isUI) - { Utils.SendMessage(GetString("EGGuessMax"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("EGGuessMax")); - } return true; case CustomRoles.Phantasm when !Options.PhantomCanGuess.GetBool(): if (!isUI) - { Utils.SendMessage(GetString("GuessDisabled"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessDisabled")); - } return true; case CustomRoles.Terrorist when !Options.TerroristCanGuess.GetBool(): if (!isUI) - { Utils.SendMessage(GetString("GuessDisabled"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessDisabled")); - } return true; case CustomRoles.Workaholic when !Workaholic.WorkaholicCanGuess.GetBool(): if (!isUI) - { Utils.SendMessage(GetString("GuessDisabled"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessDisabled")); - } return true; case CustomRoles.God when !God.GodCanGuess.GetBool(): if (!isUI) - { Utils.SendMessage(GetString("GuessDisabled"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessDisabled")); - } return true; case CustomRoles.Monarch when role == CustomRoles.Knighted: if (!isUI) - { Utils.SendMessage(GetString("GuessKnighted"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessKnighted")); - } return true; case CustomRoles.Executioner when Executioner.Target[pc.PlayerId] == target.PlayerId && Executioner.KnowTargetRole.GetBool() && !Executioner.CanGuessTarget.GetBool(): if (!isUI) - { Utils.SendMessage(GetString("GuessDisabled"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessDisabled")); - } return true; case CustomRoles.Doomsayer: if (Doomsayer.CantGuess) { if (!isUI) - { Utils.SendMessage(GetString("DoomsayerCantGuess"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("DoomsayerCantGuess")); - } return true; } @@ -416,13 +327,9 @@ namespace EHR if (role.IsImpostor() && !Doomsayer.DCanGuessImpostors.GetBool() && !forceAllowGuess) { if (!isUI) - { Utils.SendMessage(GetString("GuessNotAllowed"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessNotAllowed")); - } return true; } @@ -430,13 +337,9 @@ namespace EHR if (target.IsCrewmate() && !Doomsayer.DCanGuessCrewmates.GetBool() && !forceAllowGuess) { if (!isUI) - { Utils.SendMessage(GetString("GuessNotAllowed"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessNotAllowed")); - } return true; } @@ -444,13 +347,9 @@ namespace EHR if (role.IsNeutral() && !Doomsayer.DCanGuessNeutrals.GetBool()) { if (!isUI) - { Utils.SendMessage(GetString("GuessNotAllowed"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessNotAllowed")); - } return true; } @@ -458,13 +357,9 @@ namespace EHR if (role.IsAdditionRole() && !Doomsayer.DCanGuessAdt.GetBool() && !forceAllowGuess) { if (!isUI) - { Utils.SendMessage(GetString("GuessAdtRole"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessAdtRole")); - } return true; } @@ -475,13 +370,9 @@ namespace EHR if (Medic.ProtectList.Contains(target.PlayerId) && !Medic.GuesserIgnoreShield.GetBool()) { if (!isUI) - { Utils.SendMessage(GetString("GuessShielded"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessShielded")); - } return true; } @@ -490,185 +381,118 @@ namespace EHR { case CustomRoles.Crewmate or CustomRoles.CrewmateEHR when CrewmateVanillaRoles.VanillaCrewmateCannotBeGuessed.GetBool(): if (!isUI) - { Utils.SendMessage(GetString("GuessVanillaCrewmate"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessVanillaCrewmate")); - } return true; case CustomRoles.Workaholic when Workaholic.WorkaholicVisibleToEveryone.GetBool(): if (!isUI) - { Utils.SendMessage(GetString("GuessWorkaholic"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessWorkaholic")); - } return true; case CustomRoles.Doctor when Options.DoctorVisibleToEveryone.GetBool() && !target.HasEvilAddon(): if (!isUI) - { Utils.SendMessage(GetString("GuessDoctor"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessDoctor")); - } return true; case CustomRoles.Marshall when target.Is(CustomRoles.Marshall) && !Marshall.CanBeGuessedOnTaskCompletion.GetBool() && target.GetTaskState().IsTaskFinished: if (!isUI) - { Utils.SendMessage(GetString("GuessMarshallTask"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessMarshall")); - } return true; case CustomRoles.Monarch when pc.Is(CustomRoles.Knighted): if (!isUI) - { Utils.SendMessage(GetString("GuessMonarch"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessMonarch")); - } return true; case CustomRoles.Mayor when target.Is(CustomRoles.Mayor) && Mayor.MayorRevealWhenDoneTasks.GetBool() && target.GetTaskState().IsTaskFinished: if (!isUI) - { Utils.SendMessage(GetString("GuessMayor"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessMayor")); - } return true; case CustomRoles.Bait when Options.BaitNotification.GetBool(): if (!isUI) - { Utils.SendMessage(GetString("GuessNotifiedBait"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessNotifiedBait")); - } return true; case CustomRoles.Pestilence: if (!isUI) - { Utils.SendMessage(GetString("GuessPestilence"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessPestilence")); - } - if (DoubleShot.CheckGuess(pc, isUI)) - { - return true; - } + if (DoubleShot.CheckGuess(pc, isUI)) return true; guesserSuicide = true; break; case CustomRoles.Phantasm: if (!isUI) - { Utils.SendMessage(GetString("GuessPhantom"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessPhantom")); - } return true; case CustomRoles.Snitch when target.GetTaskState().RemainingTasksCount <= Snitch.RemainingTasksToBeFound: if (!isUI) - { Utils.SendMessage(GetString("EGGuessSnitchTaskDone"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("EGGuessSnitchTaskDone")); - } return true; case CustomRoles.Merchant when Merchant.IsBribedKiller(pc, target): if (!isUI) - { Utils.SendMessage(GetString("BribedByMerchant2"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("BribedByMerchant2")); - } return true; case CustomRoles.SuperStar: if (!isUI) - { Utils.SendMessage(GetString("GuessSuperStar"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessSuperStar")); - } return true; case CustomRoles.Backstabber when target.Is(CustomRoles.Backstabber) && Backstabber.RevealAfterKilling.GetBool() && target.GetAbilityUseLimit() == 0f: if (!isUI) - { Utils.SendMessage(GetString("GuessBackstabber"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessBackstabber")); - } return true; case CustomRoles.President when Main.PlayerStates[target.PlayerId].Role is President { IsRevealed: true }: if (!isUI) - { Utils.SendMessage(GetString("GuessPresident"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessPresident")); - } return true; case CustomRoles.Eraser when Eraser.ErasedPlayers.Contains(target.PlayerId) && pc.Is(CustomRoles.Eraser): case CustomRoles.NiceEraser when NiceEraser.ErasedPlayers.Contains(target.PlayerId) && pc.Is(CustomRoles.NiceEraser): if (!isUI) - { Utils.SendMessage(GetString("GuessErased"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessErased")); - } return true; case CustomRoles.Tank when !Tank.CanBeGuessed.GetBool(): if (!isUI) - { Utils.SendMessage(GetString("GuessTank"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessTank")); - } return true; case CustomRoles.DonutDelivery when DonutDelivery.IsUnguessable(pc, target): @@ -679,13 +503,9 @@ namespace EHR case CustomRoles.Glow: case CustomRoles.LastImpostor: if (!isUI) - { Utils.SendMessage(GetString("GuessObviousAddon"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessObviousAddon")); - } return true; case CustomRoles.GM: @@ -696,39 +516,26 @@ namespace EHR if (target.Is(CustomRoles.Onbound)) { if (!isUI) - { Utils.SendMessage(GetString("GuessOnbound"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessOnbound")); - } if (Onbound.GuesserSuicides.GetBool()) { - if (DoubleShot.CheckGuess(pc, isUI)) - { - return true; - } + if (DoubleShot.CheckGuess(pc, isUI)) return true; guesserSuicide = true; } else - { return true; - } } if (target.Is(CustomRoles.Lovers) && Lovers.GuessAbility.GetValue() == 0) { if (!isUI) - { Utils.SendMessage(GetString("GuessLovers"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessLovers")); - } return true; } @@ -736,13 +543,9 @@ namespace EHR if (Jailor.PlayerIdList.Any(x => Main.PlayerStates[x].Role is Jailor { IsEnable: true } jl && jl.JailorTarget == target.PlayerId)) { if (!isUI) - { Utils.SendMessage(GetString("CantGuessJailed"), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Jailor), GetString("JailorTitle"))); - } else - { pc.ShowPopUp(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Jailor), GetString("JailorTitle")) + "\n" + GetString("CantGuessJailed")); - } return true; } @@ -750,13 +553,9 @@ namespace EHR if (Jailor.PlayerIdList.Any(x => Main.PlayerStates[x].Role is Jailor { IsEnable: true } jl && jl.JailorTarget == pc.PlayerId && role != CustomRoles.Jailor)) { if (!isUI) - { Utils.SendMessage(GetString("JailedCanOnlyGuessJailor"), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Jailor), GetString("JailorTitle"))); - } else - { pc.ShowPopUp(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Jailor), GetString("JailorTitle")) + "\n" + GetString("JailedCanOnlyGuessJailor")); - } return true; } @@ -764,13 +563,9 @@ namespace EHR if (Markseeker.PlayerIdList.Any(x => Main.PlayerStates[x].Role is Markseeker { TargetRevealed: true } ms && ms.MarkedId == target.PlayerId)) { if (!isUI) - { Utils.SendMessage(GetString("GuessMarkseekerTarget"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessMarkseekerTarget")); - } return true; } @@ -783,25 +578,17 @@ namespace EHR // Assassin Can't Guess Addons case CustomRoles.EvilGuesser when role.IsAdditionRole() && !Options.EGCanGuessAdt.GetBool(): if (!isUI) - { Utils.SendMessage(GetString("GuessAdtRole"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessAdtRole")); - } return true; // Nice Guesser Can't Guess Addons case CustomRoles.NiceGuesser when role.IsAdditionRole() && !Options.GGCanGuessAdt.GetBool(): if (!isUI) - { Utils.SendMessage(GetString("GuessAdtRole"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessAdtRole")); - } return true; // Guesser (add-on) Can't Guess Addons @@ -809,13 +596,9 @@ namespace EHR if (role.IsAdditionRole() && pc.Is(CustomRoles.Guesser) && !Guesser.GCanGuessAdt.GetBool()) { if (!isUI) - { Utils.SendMessage(GetString("GuessAdtRole"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessAdtRole")); - } return true; } @@ -832,13 +615,9 @@ namespace EHR if (Options.ImpostorsCanGuess.GetBool() && pc.Is(CustomRoleTypes.Impostor) && !(pc.GetCustomRole() == CustomRoles.EvilGuesser || pc.Is(CustomRoles.Guesser))) { if (!isUI) - { Utils.SendMessage(GetString("GuessAdtRole"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessAdtRole")); - } return true; } @@ -847,13 +626,9 @@ namespace EHR if (Options.CrewmatesCanGuess.GetBool() && pc.Is(CustomRoleTypes.Crewmate) && !(pc.GetCustomRole() == CustomRoles.NiceGuesser || pc.Is(CustomRoles.Guesser))) { if (!isUI) - { Utils.SendMessage(GetString("GuessAdtRole"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessAdtRole")); - } return true; } @@ -862,13 +637,9 @@ namespace EHR if ((Options.NeutralKillersCanGuess.GetBool() || Options.PassiveNeutralsCanGuess.GetBool()) && pc.Is(CustomRoleTypes.Neutral) && !(pc.GetCustomRole() is CustomRoles.Ritualist or CustomRoles.Doomsayer || pc.Is(CustomRoles.Guesser))) { if (!isUI) - { Utils.SendMessage(GetString("GuessAdtRole"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("GuessAdtRole")); - } return true; } @@ -879,53 +650,35 @@ namespace EHR if (pc.PlayerId == target.PlayerId) { if (!isUI) - { Utils.SendMessage(GetString("LaughToWhoGuessSelf"), pc.PlayerId, Utils.ColorString(Color.cyan, GetString("MessageFromKPD"))); - } else - { pc.ShowPopUp(Utils.ColorString(Color.cyan, GetString("MessageFromKPD")) + "\n" + GetString("LaughToWhoGuessSelf")); - } - if (DoubleShot.CheckGuess(pc, isUI)) - { - return true; - } + if (DoubleShot.CheckGuess(pc, isUI)) return true; guesserSuicide = true; } else if (pc.Is(CustomRoles.NiceGuesser) && target.IsCrewmate() && !Options.GGCanGuessCrew.GetBool() && !pc.Is(CustomRoles.Madmate)) { if (!isUI) - { Utils.SendMessage(GetString("GuessCrewRole"), pc.PlayerId, Utils.ColorString(Color.cyan, GetString("MessageFromGurge44"))); - } else - { pc.ShowPopUp(Utils.ColorString(Color.cyan, GetString("MessageFromGurge44")) + "\n" + GetString("GuessCrewRole")); - } return true; } else if (pc.Is(CustomRoles.EvilGuesser) && target.IsImpostor() && !Options.EGCanGuessImp.GetBool()) { if (!isUI) - { Utils.SendMessage(GetString("GuessImpRole"), pc.PlayerId, Utils.ColorString(Color.cyan, GetString("MessageFromGurge44"))); - } else - { pc.ShowPopUp(Utils.ColorString(Color.cyan, GetString("MessageFromGurge44")) + "\n" + GetString("GuessImpRole")); - } return true; } else if (!target.Is(role)) { - if (DoubleShot.CheckGuess(pc, isUI)) - { - return true; - } + if (DoubleShot.CheckGuess(pc, isUI)) return true; guesserSuicide = true; Logger.Msg($"{guesserSuicide}", "guesserSuicide3"); @@ -934,13 +687,9 @@ namespace EHR if (guesserSuicide && Options.GuesserDoesntDieOnMisguess.GetBool()) { if (!isUI) - { Utils.SendMessage(GetString("MisguessButNoSuicide"), pc.PlayerId, Utils.ColorString(Color.yellow, GetString("MessageFromGurge44"))); - } else - { pc.ShowPopUp(Utils.ColorString(Color.yellow, GetString("MessageFromGurge44")) + "\n" + GetString("MisguessButNoSuicide")); - } return true; } @@ -963,39 +712,26 @@ namespace EHR if (Doomsayer.GuessesCountPerMeeting >= Doomsayer.MaxNumberOfGuessesPerMeeting.GetInt() && pc.PlayerId != dp.PlayerId) { if (!isUI) - { Utils.SendMessage(GetString("DoomsayerCantGuess"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("DoomsayerCantGuess")); - } return true; } Doomsayer.GuessesCountPerMeeting++; - if (Doomsayer.GuessesCountPerMeeting >= Doomsayer.MaxNumberOfGuessesPerMeeting.GetInt()) - { - Doomsayer.CantGuess = true; - } + if (Doomsayer.GuessesCountPerMeeting >= Doomsayer.MaxNumberOfGuessesPerMeeting.GetInt()) Doomsayer.CantGuess = true; if (!Doomsayer.KillCorrectlyGuessedPlayers.GetBool() && pc.PlayerId != dp.PlayerId) { if (!isUI) - { Utils.SendMessage(GetString("DoomsayerCorrectlyGuessRole"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("DoomsayerCorrectlyGuessRole")); - } if (Doomsayer.GuessedRoles.Contains(role)) - { LateTask.New(() => { Utils.SendMessage(GetString("DoomsayerGuessSameRoleAgainMsg"), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Doomsayer), GetString("DoomsayerGuessCountTitle"))); }, 0.7f, "Doomsayer Guess Same Role Again Msg"); - } else { Doomsayer.GuessingToWin[pc.PlayerId]++; @@ -1013,28 +749,18 @@ namespace EHR if (Doomsayer.DoesNotSuicideWhenMisguessing.GetBool() && pc.PlayerId == dp.PlayerId) { if (!isUI) - { Utils.SendMessage(GetString("DoomsayerNotCorrectlyGuessRole"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("DoomsayerNotCorrectlyGuessRole")); - } - if (Doomsayer.MisguessRolePrevGuessRoleUntilNextMeeting.GetBool()) - { - Doomsayer.CantGuess = true; - } + if (Doomsayer.MisguessRolePrevGuessRoleUntilNextMeeting.GetBool()) Doomsayer.CantGuess = true; return true; } } string Name = dp.GetRealName(); - if (!Options.DisableKillAnimationOnGuess.GetBool()) - { - CustomSoundsManager.RPCPlayCustomSoundAll("Gunfire"); - } + if (!Options.DisableKillAnimationOnGuess.GetBool()) CustomSoundsManager.RPCPlayCustomSoundAll("Gunfire"); LateTask.New(() => { @@ -1042,20 +768,14 @@ namespace EHR dp.SetRealKiller(pc); dp.RpcGuesserMurderPlayer(); - if (dp.Is(CustomRoles.Medic)) - { - Medic.IsDead(dp); - } + if (dp.Is(CustomRoles.Medic)) Medic.IsDead(dp); if (pc.Is(CustomRoles.Doomsayer) && pc.PlayerId != dp.PlayerId) { Doomsayer.GuessingToWin[pc.PlayerId]++; Doomsayer.SendRPC(pc); - if (!Doomsayer.GuessedRoles.Contains(role)) - { - Doomsayer.GuessedRoles.Add(role); - } + if (!Doomsayer.GuessedRoles.Contains(role)) Doomsayer.GuessedRoles.Add(role); Doomsayer.CheckCountGuess(pc); } @@ -1068,20 +788,11 @@ namespace EHR LateTask.New(() => { Utils.SendMessage(string.Format(GetString("GuessKill"), Name), 255, Utils.ColorString(Utils.GetRoleColor(CustomRoles.NiceGuesser), GetString("GuessKillTitle"))); }, 0.6f, "Guess Msg"); - if (pc.Is(CustomRoles.Doomsayer) && pc.PlayerId != dp.PlayerId) - { - LateTask.New(() => Utils.SendMessage(string.Format(GetString("DoomsayerGuessCountMsg"), Doomsayer.GuessingToWin[pc.PlayerId]), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Doomsayer), GetString("DoomsayerGuessCountTitle"))), 0.7f, "Doomsayer Guess Msg 2"); - } + if (pc.Is(CustomRoles.Doomsayer) && pc.PlayerId != dp.PlayerId) LateTask.New(() => Utils.SendMessage(string.Format(GetString("DoomsayerGuessCountMsg"), Doomsayer.GuessingToWin[pc.PlayerId]), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Doomsayer), GetString("DoomsayerGuessCountTitle"))), 0.7f, "Doomsayer Guess Msg 2"); - if (pc.Is(CustomRoles.TicketsStealer) && pc.PlayerId != dp.PlayerId) - { - LateTask.New(() => Utils.SendMessage(string.Format(GetString("TicketsStealerGetTicket"), (int)(Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == pc.PlayerId) * Options.TicketsPerKill.GetFloat()))), 0.7f, log: false); - } + if (pc.Is(CustomRoles.TicketsStealer) && pc.PlayerId != dp.PlayerId) LateTask.New(() => Utils.SendMessage(string.Format(GetString("TicketsStealerGetTicket"), (int)(Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == pc.PlayerId) * Options.TicketsPerKill.GetFloat()))), 0.7f, log: false); - if (pc.Is(CustomRoles.Pickpocket) && pc.PlayerId != dp.PlayerId) - { - LateTask.New(() => Utils.SendMessage(string.Format(GetString("PickpocketGetVote"), (int)(Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == pc.PlayerId) * Pickpocket.VotesPerKill.GetFloat()))), 0.7f, log: false); - } + if (pc.Is(CustomRoles.Pickpocket) && pc.PlayerId != dp.PlayerId) LateTask.New(() => Utils.SendMessage(string.Format(GetString("PickpocketGetVote"), (int)(Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == pc.PlayerId) * Pickpocket.VotesPerKill.GetFloat()))), 0.7f, log: false); }, 0.2f, "Guesser Kill"); } @@ -1102,20 +813,17 @@ namespace EHR pc.Data.IsDead = true; pc.RpcExileV2(); Main.PlayerStates[pc.PlayerId].SetDead(); - MeetingHud meetingHud = MeetingHud.Instance; + var meetingHud = MeetingHud.Instance; HudManager hudManager = DestroyableSingleton.Instance; SoundManager.Instance.PlaySound(pc.KillSfx, false, 0.8f); - if (!Options.DisableKillAnimationOnGuess.GetBool()) - { - hudManager.KillOverlay.ShowKillAnimation(pc.Data, pc.Data); - } + if (!Options.DisableKillAnimationOnGuess.GetBool()) hudManager.KillOverlay.ShowKillAnimation(pc.Data, pc.Data); if (amOwner) { hudManager.ShadowQuad.gameObject.SetActive(false); pc.cosmetics.nameText.GetComponent().material.SetInt(Mask, 0); pc.RpcSetScanner(false); - ImportantTextTask importantTextTask = new GameObject("_Player").AddComponent(); + var importantTextTask = new GameObject("_Player").AddComponent(); importantTextTask.transform.SetParent(AmongUsClient.Instance.transform, false); meetingHud.SetForegroundForDead(); } @@ -1123,29 +831,22 @@ namespace EHR PlayerVoteArea voteArea = MeetingHud.Instance.playerStates.First( x => x.TargetPlayerId == pc.PlayerId ); - if (voteArea.DidVote) - { - voteArea.UnsetVote(); - } + + if (voteArea.DidVote) voteArea.UnsetVote(); voteArea.AmDead = true; voteArea.Overlay.gameObject.SetActive(true); voteArea.Overlay.color = Color.white; voteArea.XMark.gameObject.SetActive(true); voteArea.XMark.transform.localScale = Vector3.one; + foreach (PlayerVoteArea playerVoteArea in meetingHud.playerStates) { - if (playerVoteArea.VotedFor != pc.PlayerId) - { - continue; - } + if (playerVoteArea.VotedFor != pc.PlayerId) continue; playerVoteArea.UnsetVote(); PlayerControl voteAreaPlayer = Utils.GetPlayerById(playerVoteArea.TargetPlayerId); - if (!voteAreaPlayer.AmOwner) - { - continue; - } + if (!voteAreaPlayer.AmOwner) continue; meetingHud.ClearVote(); } @@ -1163,20 +864,17 @@ namespace EHR public static void RpcClientGuess(PlayerControl pc) { bool amOwner = pc.AmOwner; - MeetingHud meetingHud = MeetingHud.Instance; + var meetingHud = MeetingHud.Instance; HudManager hudManager = DestroyableSingleton.Instance; SoundManager.Instance.PlaySound(pc.KillSfx, false, 0.8f); - if (!Options.DisableKillAnimationOnGuess.GetBool()) - { - hudManager.KillOverlay.ShowKillAnimation(pc.Data, pc.Data); - } + if (!Options.DisableKillAnimationOnGuess.GetBool()) hudManager.KillOverlay.ShowKillAnimation(pc.Data, pc.Data); if (amOwner) { hudManager.ShadowQuad.gameObject.SetActive(false); pc.cosmetics.nameText.GetComponent().material.SetInt(Mask, 0); pc.RpcSetScanner(false); - ImportantTextTask importantTextTask = new GameObject("_Player").AddComponent(); + var importantTextTask = new GameObject("_Player").AddComponent(); importantTextTask.transform.SetParent(AmongUsClient.Instance.transform, false); meetingHud.SetForegroundForDead(); } @@ -1184,29 +882,22 @@ namespace EHR PlayerVoteArea voteArea = MeetingHud.Instance.playerStates.First( x => x.TargetPlayerId == pc.PlayerId ); - if (voteArea.DidVote) - { - voteArea.UnsetVote(); - } + + if (voteArea.DidVote) voteArea.UnsetVote(); voteArea.AmDead = true; voteArea.Overlay.gameObject.SetActive(true); voteArea.Overlay.color = Color.white; voteArea.XMark.gameObject.SetActive(true); voteArea.XMark.transform.localScale = Vector3.one; + foreach (PlayerVoteArea playerVoteArea in meetingHud.playerStates) { - if (playerVoteArea.VotedFor != pc.PlayerId) - { - continue; - } + if (playerVoteArea.VotedFor != pc.PlayerId) continue; playerVoteArea.UnsetVote(); PlayerControl voteAreaPlayer = Utils.GetPlayerById(playerVoteArea.TargetPlayerId); - if (!voteAreaPlayer.AmOwner) - { - continue; - } + if (!voteAreaPlayer.AmOwner) continue; meetingHud.ClearVote(); } @@ -1214,23 +905,15 @@ namespace EHR public static bool MsgToPlayerAndRole(string msg, out byte id, out CustomRoles role, out string error) { - if (msg.StartsWith("/")) - { - msg = msg.Replace("/", string.Empty); - } + if (msg.StartsWith("/")) msg = msg.Replace("/", string.Empty); Regex r = new("\\d+"); MatchCollection mc = r.Matches(msg); - string result = string.Empty; - for (int i = 0; i < mc.Count; i++) - { - result += mc[i]; // The matching result is a complete number, and no splicing is required here. - } + var result = string.Empty; + for (var i = 0; i < mc.Count; i++) result += mc[i]; // The matching result is a complete number, and no splicing is required here. if (byte.TryParse(result, out byte num)) - { id = num; - } else { // It is not the player number, it determines whether it is the color or not. @@ -1244,6 +927,7 @@ namespace EHR // Determine whether the selected player is reasonable PlayerControl target = Utils.GetPlayerById(id); + if (target == null || target.Data.IsDead) { error = GetString("GuessNull"); @@ -1266,18 +950,15 @@ namespace EHR foreach (PlayerVoteArea pva in __instance.playerStates) { PlayerControl pc = Utils.GetPlayerById(pva.TargetPlayerId); - if (pc == null || !pc.IsAlive()) - { - continue; - } + if (pc == null || !pc.IsAlive()) continue; GameObject template = pva.Buttons.transform.Find("CancelButton").gameObject; GameObject targetBox = Object.Instantiate(template, pva.transform); targetBox.name = "ShootButton"; targetBox.transform.localPosition = new(-0.95f, 0.03f, -1.31f); - SpriteRenderer renderer = targetBox.GetComponent(); + var renderer = targetBox.GetComponent(); renderer.sprite = CustomButton.Get("TargetIcon"); - PassiveButton button = targetBox.GetComponent(); + var button = targetBox.GetComponent(); button.OnClick.RemoveAllListeners(); PlayerVoteArea pva1 = pva; button.OnClick.AddListener((Action)(() => GuesserOnClick(pva1.TargetPlayerId, __instance))); @@ -1287,22 +968,18 @@ namespace EHR private static void GuesserSelectRole(CustomRoleTypes Role, bool SetPage = true) { CurrentTeamType = Role; - if (SetPage) - { - Page = 1; - } + if (SetPage) Page = 1; foreach (KeyValuePair> RoleButton in RoleButtons) { - int index = 0; + var index = 0; + foreach (Transform RoleBtn in RoleButton.Value) { - if (RoleBtn == null) - { - continue; - } + if (RoleBtn == null) continue; index++; + if (index <= (Page - 1) * 40) { RoleBtn.gameObject.SetActive(false); @@ -1321,10 +998,7 @@ namespace EHR foreach (KeyValuePair RoleButton in RoleSelectButtons) { - if (RoleButton.Value == null) - { - continue; - } + if (RoleButton.Value == null) continue; RoleButton.Value.color = new(0, 0, 0, RoleButton.Key == Role ? 1 : 0.25f); } @@ -1333,10 +1007,7 @@ namespace EHR private static void GuesserOnClick(byte playerId, MeetingHud __instance) { PlayerControl pc = Utils.GetPlayerById(playerId); - if (pc == null || !pc.IsAlive() || GuesserUI != null || !GameStates.IsVoting) - { - return; - } + if (pc == null || !pc.IsAlive() || GuesserUI != null || !GameStates.IsVoting) return; try { @@ -1355,10 +1026,7 @@ namespace EHR Transform maskTemplate = __instance.playerStates[0].transform.FindChild("MaskArea"); Transform smallButtonTemplate = __instance.playerStates[0].Buttons.transform.Find("CancelButton"); TextTemplate.enabled = true; - if (TextTemplate.transform.FindChild("RoleTextMeeting") != null) - { - Object.Destroy(TextTemplate.transform.FindChild("RoleTextMeeting").gameObject); - } + if (TextTemplate.transform.FindChild("RoleTextMeeting") != null) Object.Destroy(TextTemplate.transform.FindChild("RoleTextMeeting").gameObject); Transform exitButtonParent = new GameObject().transform; exitButtonParent.SetParent(container); @@ -1372,91 +1040,58 @@ namespace EHR exitButtonParent.transform.localScale = new(0.22f, 0.9f, 1f); exitButtonParent.transform.SetAsFirstSibling(); exitButton.GetComponent().OnClick.RemoveAllListeners(); + exitButton.GetComponent().OnClick.AddListener((Action)(() => { __instance.playerStates.ToList().ForEach(x => x.gameObject.SetActive(true)); Object.Destroy(container.gameObject); })); + exitButton.GetComponent(); List buttons = []; Transform selectedButton = null; - int tabCount = 0; - for (int index = 0; index < 4; index++) + var tabCount = 0; + + for (var index = 0; index < 4; index++) { if (PlayerControl.LocalPlayer.Is(CustomRoles.EvilGuesser)) { - if (!Options.EGCanGuessImp.GetBool() && index == 1) - { - continue; - } + if (!Options.EGCanGuessImp.GetBool() && index == 1) continue; - if (!Options.EGCanGuessAdt.GetBool() && index == 3) - { - continue; - } + if (!Options.EGCanGuessAdt.GetBool() && index == 3) continue; } else if (PlayerControl.LocalPlayer.Is(CustomRoles.NiceGuesser)) { - if (!Options.GGCanGuessCrew.GetBool() && index == 0) - { - continue; - } + if (!Options.GGCanGuessCrew.GetBool() && index == 0) continue; - if (!Options.GGCanGuessAdt.GetBool() && index == 3) - { - continue; - } + if (!Options.GGCanGuessAdt.GetBool() && index == 3) continue; } else if (PlayerControl.LocalPlayer.Is(CustomRoles.Doomsayer)) { - if (!Doomsayer.DCanGuessCrewmates.GetBool() && index == 0) - { - continue; - } + if (!Doomsayer.DCanGuessCrewmates.GetBool() && index == 0) continue; - if (!Doomsayer.DCanGuessImpostors.GetBool() && index == 1) - { - continue; - } + if (!Doomsayer.DCanGuessImpostors.GetBool() && index == 1) continue; - if (!Doomsayer.DCanGuessNeutrals.GetBool() && index == 2) - { - continue; - } + if (!Doomsayer.DCanGuessNeutrals.GetBool() && index == 2) continue; - if (!Doomsayer.DCanGuessAdt.GetBool() && index == 3) - { - continue; - } + if (!Doomsayer.DCanGuessAdt.GetBool() && index == 3) continue; } else if (PlayerControl.LocalPlayer.Is(CustomRoles.Guesser)) { // if (!Options.GCanGuessCrew.GetBool() && PlayerControl.LocalPlayer.Is(CustomRoleTypes.Crewmate) && index == 0) continue; // if (!Options.GCanGuessImp.GetBool() && PlayerControl.LocalPlayer.Is(CustomRoleTypes.Impostor) && index == 1) continue; - if (!Guesser.GCanGuessAdt.GetBool() && index == 3) - { - continue; - } + if (!Guesser.GCanGuessAdt.GetBool() && index == 3) continue; } else if (Options.GuesserMode.GetBool()) { - if (!Options.CrewCanGuessCrew.GetBool() && PlayerControl.LocalPlayer.Is(CustomRoleTypes.Crewmate) && index == 0) - { - continue; - } + if (!Options.CrewCanGuessCrew.GetBool() && PlayerControl.LocalPlayer.Is(CustomRoleTypes.Crewmate) && index == 0) continue; - if (!Options.ImpCanGuessImp.GetBool() && PlayerControl.LocalPlayer.Is(CustomRoleTypes.Impostor) && index == 1) - { - continue; - } + if (!Options.ImpCanGuessImp.GetBool() && PlayerControl.LocalPlayer.Is(CustomRoleTypes.Impostor) && index == 1) continue; // if (index == 2) continue; - if (!Options.CanGuessAddons.GetBool() && index == 3) - { - continue; - } + if (!Options.CanGuessAddons.GetBool() && index == 3) continue; } Transform TeambuttonParent = new GameObject().transform; @@ -1469,6 +1104,7 @@ namespace EHR RoleSelectButtons.Add((CustomRoleTypes)index, Teambutton.GetComponent()); TeambuttonParent.localPosition = new(-2.75f + (tabCount++ * 1.73f), 2.225f, -200); TeambuttonParent.localScale = new(0.53f, 0.53f, 1f); + Teamlabel.color = (CustomRoleTypes)index switch { CustomRoleTypes.Crewmate => new(140, 255, 255, byte.MaxValue), @@ -1477,6 +1113,7 @@ namespace EHR CustomRoleTypes.Addon => new Color32(255, 154, 206, byte.MaxValue), _ => throw new NotImplementedException() }; + Logger.Info(Teamlabel.color.ToString(), ((CustomRoleTypes)index).ToString()); Teamlabel.text = GetString("Type" + (CustomRoleTypes)index); Teamlabel.alignment = TextAlignmentOptions.Center; @@ -1484,10 +1121,7 @@ namespace EHR Teamlabel.transform.localScale *= 1.6f; Teamlabel.autoSizeTextContainer = true; - if (PlayerControl.LocalPlayer.IsAlive()) - { - CreateTeamButton(Teambutton, (CustomRoleTypes)index); - } + if (PlayerControl.LocalPlayer.IsAlive()) CreateTeamButton(Teambutton, (CustomRoleTypes)index); continue; @@ -1505,15 +1139,13 @@ namespace EHR { PageButtons[0].color = new(1, 1, 1, 1f); PageButtons[1].color = new(1, 1, 1, 1f); + if ((RoleButtons[CurrentTeamType].Count / MaxOneScreenRole) + (RoleButtons[CurrentTeamType].Count % MaxOneScreenRole != 0 ? 1 : 0) < Page) { Page -= 1; PageButtons[1].color = new(1, 1, 1, 0.1f); } - else if ((RoleButtons[CurrentTeamType].Count / MaxOneScreenRole) + (RoleButtons[CurrentTeamType].Count % MaxOneScreenRole != 0 ? 1 : 0) < Page + 1) - { - PageButtons[1].color = new(1, 1, 1, 0.1f); - } + else if ((RoleButtons[CurrentTeamType].Count / MaxOneScreenRole) + (RoleButtons[CurrentTeamType].Count % MaxOneScreenRole != 0 ? 1 : 0) < Page + 1) PageButtons[1].color = new(1, 1, 1, 0.1f); if (Page <= 1) { @@ -1544,10 +1176,7 @@ namespace EHR Pagelabel.transform.localPosition = new(0, 0, Pagelabel.transform.localPosition.z); Pagelabel.transform.localScale *= 1.6f; Pagelabel.autoSizeTextContainer = true; - if (!IsNext && Page <= 1) - { - Pagebutton.GetComponent().color = new(1, 1, 1, 0.1f); - } + if (!IsNext && Page <= 1) Pagebutton.GetComponent().color = new(1, 1, 1, 0.1f); Pagebutton.GetComponent().OnClick.AddListener((Action)ClickEvent); @@ -1557,18 +1186,11 @@ namespace EHR void ClickEvent() { if (IsNext) - { Page += 1; - } else - { Page -= 1; - } - if (Page < 1) - { - Page = 1; - } + if (Page < 1) Page = 1; ReloadPage(); } @@ -1581,6 +1203,7 @@ namespace EHR } CustomRoles[] sortedRoles = Enum.GetValues().OrderBy(x => GetString($"{x}")).ToArray(); + foreach (CustomRoles role in sortedRoles) { if (role is CustomRoles.GM @@ -1601,29 +1224,18 @@ namespace EHR or CustomRoles.Konan or CustomRoles.GuardianAngelEHR ) - { continue; - } - if (!role.IsEnable() && !role.RoleExist(true) && !role.IsConverted()) - { - continue; - } + if (!role.IsEnable() && !role.RoleExist(true) && !role.IsConverted()) continue; - if (Options.CurrentGameMode != CustomGameMode.Standard || HnSManager.AllHnSRoles.Contains(role)) - { - continue; - } + if (Options.CurrentGameMode != CustomGameMode.Standard || HnSManager.AllHnSRoles.Contains(role)) continue; CreateRole(role); } void CreateRole(CustomRoles role) { - if (40 <= i[(int)role.GetCustomRoleTypes()]) - { - i[(int)role.GetCustomRoleTypes()] = 0; - } + if (40 <= i[(int)role.GetCustomRoleTypes()]) i[(int)role.GetCustomRoleTypes()] = 0; Transform buttonParent = new GameObject().transform; buttonParent.SetParent(container); @@ -1632,10 +1244,7 @@ namespace EHR Object.Instantiate(maskTemplate, buttonParent); TextMeshPro label = Object.Instantiate(TextTemplate, button); button.GetComponent().sprite = CustomButton.Get("GuessPlate"); - if (!RoleButtons.ContainsKey(role.GetCustomRoleTypes())) - { - RoleButtons.Add(role.GetCustomRoleTypes(), []); - } + if (!RoleButtons.ContainsKey(role.GetCustomRoleTypes())) RoleButtons.Add(role.GetCustomRoleTypes(), []); RoleButtons[role.GetCustomRoleTypes()].Add(button); buttons.Add(button); @@ -1652,6 +1261,7 @@ namespace EHR _ = i[(int)role.GetCustomRoleTypes()]; button.GetComponent().OnClick.RemoveAllListeners(); + if (PlayerControl.LocalPlayer.IsAlive()) { button.GetComponent().OnClick.AddListener((Action)(() => @@ -1663,21 +1273,14 @@ namespace EHR } else { - if (!(__instance.state == MeetingHud.VoteStates.Voted || __instance.state == MeetingHud.VoteStates.NotVoted) || !PlayerControl.LocalPlayer.IsAlive()) - { - return; - } + if (!(__instance.state == MeetingHud.VoteStates.Voted || __instance.state == MeetingHud.VoteStates.NotVoted) || !PlayerControl.LocalPlayer.IsAlive()) return; Logger.Msg($"Click: {pc.GetNameWithRole().RemoveHtmlTags()} => {role}", "Guesser UI"); if (AmongUsClient.Instance.AmHost) - { GuesserMsg(PlayerControl.LocalPlayer, $"/bt {playerId} {GetString(role.ToString())}", true); - } else - { SendRPC(playerId, role); - } // Reset the GUI __instance.playerStates.ToList().ForEach(x => x.gameObject.SetActive(true)); @@ -1720,7 +1323,7 @@ namespace EHR int PlayerId = reader.ReadInt32(); Logger.Msg($"{PlayerId}", "GuessManager - Player Id"); - CustomRoles role = (CustomRoles)reader.ReadInt32(); + var role = (CustomRoles)reader.ReadInt32(); Logger.Msg($"{role}", "GuessManager - Role Int32"); Logger.Msg($"{GetString(role.ToString())}", "GuessManager - Role String"); @@ -1775,10 +1378,7 @@ namespace EHR public static void Postfix(MeetingHud __instance) { PlayerControl lp = PlayerControl.LocalPlayer; - if (!lp.IsAlive()) - { - return; - } + if (!lp.IsAlive()) return; bool canGuess = lp.Is(CustomRoles.Guesser) || lp.GetCustomRole() switch { @@ -1797,10 +1397,7 @@ namespace EHR _ => false }; - if (canGuess) - { - CreateGuesserButton(__instance); - } + if (canGuess) CreateGuesserButton(__instance); } } diff --git a/Modules/HashAuth.cs b/Modules/HashAuth.cs index de9b9e5f0..39ccffe9b 100644 --- a/Modules/HashAuth.cs +++ b/Modules/HashAuth.cs @@ -24,10 +24,7 @@ namespace EHR algorithm ??= SHA256.Create(); // 1. Apply salt - if (salt != null) - { - source += salt; - } + if (salt != null) source += salt; // 2. Convert source to a byte array byte[] sourceBytes = Encoding.UTF8.GetBytes(source); @@ -36,11 +33,8 @@ namespace EHR byte[] hashBytes = algorithm.ComputeHash(sourceBytes); // 4. Convert hashBytes to a string - StringBuilder sb = new StringBuilder(); - foreach (byte b in hashBytes) - { - sb.Append(b.ToString("x2")); // Convert each byte to 2-digit hexadecimal notation - } + var sb = new StringBuilder(); + foreach (byte b in hashBytes) sb.Append(b.ToString("x2")); // Convert each byte to 2-digit hexadecimal notation return sb.ToString(); } @@ -50,7 +44,7 @@ namespace EHR public static HashAuth CreateByUnhashedValue(string value, string salt = null) { // 1. Calculate hash value - SHA256 algorithm = SHA256.Create(); + var algorithm = SHA256.Create(); string hashValue = CalculateHash(value, salt, algorithm); // 2. Log output of hash value diff --git a/Modules/LateTask.cs b/Modules/LateTask.cs index 58d3ff4e6..a5f5c6a69 100644 --- a/Modules/LateTask.cs +++ b/Modules/LateTask.cs @@ -21,15 +21,13 @@ namespace EHR this.log = log; this.callerData = callerData; Tasks.Add(this); - if (log && name is not "" and not "No Name Task") - { - Logger.Info("\"" + name + "\" is created", "LateTask"); - } + if (log && name is not "" and not "No Name Task") Logger.Info("\"" + name + "\" is created", "LateTask"); } private bool Run(float deltaTime) { timer -= deltaTime; + if (timer <= 0) { action(); @@ -59,10 +57,7 @@ namespace EHR { if (task.Run(deltaTime)) { - if (task.name is not "" and not "No Name Task" && task.log) - { - Logger.Info($"\"{task.name}\" is finished", "LateTask"); - } + if (task.name is not "" and not "No Name Task" && task.log) Logger.Info($"\"{task.name}\" is finished", "LateTask"); Tasks.Remove(task); } diff --git a/Modules/LoadingScreen.cs b/Modules/LoadingScreen.cs index cb6da3541..49da05dae 100644 --- a/Modules/LoadingScreen.cs +++ b/Modules/LoadingScreen.cs @@ -19,10 +19,7 @@ namespace EHR.Modules { try { - if (!LoadingAnimation.IsNullOrDestroyed()) - { - Object.Destroy(LoadingAnimation); - } + if (!LoadingAnimation.IsNullOrDestroyed()) Object.Destroy(LoadingAnimation); LoadingAnimation = Object.Instantiate(ModManager.Instance.ModStamp); LoadingAnimation.sprite = Utils.LoadSprite("EHR.Resources.Loading.png", 300f); @@ -43,21 +40,14 @@ namespace EHR.Modules private static void NewHint() { int index; - if (ToldHints.Count == HintCount) - { - ToldHints.Clear(); - } + if (ToldHints.Count == HintCount) ToldHints.Clear(); do - { index = IRandom.Instance.Next(HintCount); - } while (!ToldHints.Add(index)); + while (!ToldHints.Add(index)); bool joke = IRandom.Instance.Next(20) == 0; - if (joke) - { - index = IRandom.Instance.Next(40, 40 + JokeHintCount); - } + if (joke) index = IRandom.Instance.Next(40, 40 + JokeHintCount); string text = Translator.GetString($"LoadingHint.{index}"); text = text.Insert(0, joke ? "" : ""); @@ -70,16 +60,10 @@ namespace EHR.Modules { try { - if (HintHideTimer <= 15f) - { - HintHideTimer += Time.deltaTime; - } + if (HintHideTimer <= 15f) HintHideTimer += Time.deltaTime; PlayerControl lp = PlayerControl.LocalPlayer; - if (lp == null) - { - return; - } + if (lp == null) return; PlayerAnimations anims = lp.MyPhysics.Animations; @@ -103,10 +87,7 @@ namespace EHR.Modules float y = basePos.y - 4.5f; float z = basePos.z; - if (LoadingAnimation.transform.position != new Vector3(x, y, z)) - { - LoadingAnimation.transform.position = new(x, y, z); - } + if (LoadingAnimation.transform.position != new Vector3(x, y, z)) LoadingAnimation.transform.position = new(x, y, z); LoadingAnimation.transform.Rotate(Vector3.forward, 200f * Time.deltaTime); } @@ -117,10 +98,7 @@ namespace EHR.Modules ErrorText.RemoveHint(); return; case true when !ErrorText.HasHint: - if (HintHideTimer > 15f) - { - NewHint(); - } + if (HintHideTimer > 15f) NewHint(); HintHideTimer = 0f; ErrorText.Instance.AddError(ErrorCode.LoadingHint); diff --git a/Modules/LocateArrow.cs b/Modules/LocateArrow.cs index 212a6bf53..1ddd521fb 100644 --- a/Modules/LocateArrow.cs +++ b/Modules/LocateArrow.cs @@ -52,6 +52,7 @@ namespace EHR public static void Add(byte seer, Vector3 locate) { ArrowInfo arrowInfo = new(seer, locate); + if (!LocateArrows.Any(a => a.Key.Equals(arrowInfo))) { LocateArrows[arrowInfo] = "・"; @@ -69,10 +70,7 @@ namespace EHR { ArrowInfo arrowInfo = new(seer, locate); List removeList = new(LocateArrows.Keys.Where(k => k.Equals(arrowInfo))); - foreach (ArrowInfo a in removeList.ToArray()) - { - LocateArrows.Remove(a); - } + foreach (ArrowInfo a in removeList.ToArray()) LocateArrows.Remove(a); Utils.SendRPC(CustomRPC.Arrow, false, 2, seer, locate); Logger.Info($"Removed locate arrow: {seer} ({seer.GetPlayer()?.GetRealName()}) => {locate}", "LocateArrow"); @@ -85,10 +83,7 @@ namespace EHR public static void RemoveAllTarget(byte seer) { List removeList = new(LocateArrows.Keys.Where(k => k.From == seer)); - foreach (ArrowInfo arrowInfo in removeList.ToArray()) - { - LocateArrows.Remove(arrowInfo); - } + foreach (ArrowInfo arrowInfo in removeList.ToArray()) LocateArrows.Remove(arrowInfo); Utils.SendRPC(CustomRPC.Arrow, false, 3, seer); Logger.Info($"Removed all locate arrows for: {seer} ({seer.GetPlayer()?.GetRealName()})", "LocateArrow"); @@ -111,23 +106,19 @@ namespace EHR /// public static void OnFixedUpdate(PlayerControl seer) { - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; bool seerIsDead = !seer.IsAlive(); List arrowList = new(LocateArrows.Keys.Where(a => a.From == seer.PlayerId)); - if (arrowList.Count == 0) - { - return; - } + if (arrowList.Count == 0) return; + + var update = false; - bool update = false; foreach (ArrowInfo arrowInfo in arrowList.ToArray()) { Vector3 loc = arrowInfo.To; + if (seerIsDead) { LocateArrows.Remove(arrowInfo); @@ -138,6 +129,7 @@ namespace EHR // Take the direction vector of the target Vector3 dir = loc - seer.transform.position; int index; + if (dir.magnitude < 2) { // Display a dot when close @@ -154,6 +146,7 @@ namespace EHR } string arrow = Arrows[index]; + if (LocateArrows[arrowInfo] != arrow) { LocateArrows[arrowInfo] = arrow; @@ -161,10 +154,7 @@ namespace EHR } } - if (update) - { - Utils.NotifyRoles(SpecifySeer: seer, ForceLoop: false, SpecifyTarget: seer); - } + if (update) Utils.NotifyRoles(SpecifySeer: seer, ForceLoop: false, SpecifyTarget: seer); } private class ArrowInfo(byte from, Vector3 to) diff --git a/Modules/MeetingTimeManager.cs b/Modules/MeetingTimeManager.cs index 60560d9aa..6ae636f71 100644 --- a/Modules/MeetingTimeManager.cs +++ b/Modules/MeetingTimeManager.cs @@ -46,10 +46,10 @@ namespace EHR.Modules } ResetMeetingTime(); - int BonusMeetingTime = 0; - int MeetingTimeMinTimeThief = 0; - int MeetingTimeMinTimeManager = 0; - int MeetingTimeMax = 300; + var BonusMeetingTime = 0; + var MeetingTimeMinTimeThief = 0; + var MeetingTimeMinTimeManager = 0; + var MeetingTimeMax = 300; if (TimeThief.PlayerIdList.Count > 0) { @@ -66,28 +66,18 @@ namespace EHR.Modules int TotalMeetingTime = DiscussionTime + VotingTime; - if (TimeManager.PlayerIdList.Count > 0) - { - BonusMeetingTime = Math.Clamp(TotalMeetingTime + BonusMeetingTime, MeetingTimeMinTimeManager, MeetingTimeMax) - TotalMeetingTime; - } + if (TimeManager.PlayerIdList.Count > 0) BonusMeetingTime = Math.Clamp(TotalMeetingTime + BonusMeetingTime, MeetingTimeMinTimeManager, MeetingTimeMax) - TotalMeetingTime; - if (TimeThief.PlayerIdList.Count > 0) - { - BonusMeetingTime = Math.Clamp(TotalMeetingTime + BonusMeetingTime, MeetingTimeMinTimeThief, MeetingTimeMax) - TotalMeetingTime; - } + if (TimeThief.PlayerIdList.Count > 0) BonusMeetingTime = Math.Clamp(TotalMeetingTime + BonusMeetingTime, MeetingTimeMinTimeThief, MeetingTimeMax) - TotalMeetingTime; - if (TimeManager.PlayerIdList.Count == 0 && TimeThief.PlayerIdList.Count == 0) - { - BonusMeetingTime = Math.Clamp(TotalMeetingTime + BonusMeetingTime, MeetingTimeMinTimeThief, MeetingTimeMax) - TotalMeetingTime; - } + if (TimeManager.PlayerIdList.Count == 0 && TimeThief.PlayerIdList.Count == 0) BonusMeetingTime = Math.Clamp(TotalMeetingTime + BonusMeetingTime, MeetingTimeMinTimeThief, MeetingTimeMax) - TotalMeetingTime; if (BonusMeetingTime >= 0) - { VotingTime += BonusMeetingTime; - } else { DiscussionTime += BonusMeetingTime; + if (DiscussionTime < 0) { VotingTime += DiscussionTime; diff --git a/Modules/ModUpdater.cs b/Modules/ModUpdater.cs index a865e1f96..f22a0722f 100644 --- a/Modules/ModUpdater.cs +++ b/Modules/ModUpdater.cs @@ -37,6 +37,7 @@ namespace EHR InfoPopup = Object.Instantiate(TwitchManager.Instance.TwitchPopup); InfoPopup.name = "InfoPopup"; InfoPopup.TextAreaTMP.GetComponent().sizeDelta = new(2.5f, 2f); + if (!IsChecked) { bool done = CheckReleaseFromGithub(Main.BetaBuildUrl.Value != "").GetAwaiter().GetResult(); @@ -54,6 +55,7 @@ namespace EHR HttpClient req = new(); HttpResponseMessage res = req.GetAsync(url).Result; Stream stream = res.Content.ReadAsStreamAsync().Result; + try { using StreamReader reader = new(stream); @@ -71,13 +73,16 @@ namespace EHR { Logger.Warn("Checking GitHub Release", "CheckRelease"); const string url = URLGithub + "/releases/latest"; + try { string result; + using (HttpClient client = new()) { client.DefaultRequestHeaders.Add("User-Agent", "EHR Updater"); using HttpResponseMessage response = await client.GetAsync(new Uri(url), HttpCompletionOption.ResponseContentRead); + if (!response.IsSuccessStatusCode) { Logger.Error($"Response Status Code: {response.StatusCode}", "CheckRelease"); @@ -88,6 +93,7 @@ namespace EHR } JObject data = JObject.Parse(result); + if (beta) { LatestTitle = data["name"].ToString(); @@ -98,8 +104,9 @@ namespace EHR { LatestVersion = new(data["tag_name"]?.ToString().TrimStart('v') ?? string.Empty); LatestTitle = $"Ver. {LatestVersion}"; - JArray assets = data["assets"].Cast(); - for (int i = 0; i < assets.Count; i++) + var assets = data["assets"].Cast(); + + for (var i = 0; i < assets.Count; i++) { if (assets[i]["name"].ToString() == $"EHR.v{LatestVersion}.zip") { @@ -168,9 +175,11 @@ namespace EHR { string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); const string searchPattern = "EHR.dll*"; + if (path != null) { string[] files = Directory.GetFiles(path, searchPattern); + try { foreach (string filePath in files) @@ -196,33 +205,21 @@ namespace EHR const string savePath = "BepInEx/plugins/EHR.dll.temp"; // Delete the temporary file if it exists - if (File.Exists(savePath)) - { - File.Delete(savePath); - } + if (File.Exists(savePath)) File.Delete(savePath); HttpResponseMessage response; - using (HttpClient client = new()) - { - response = await client.GetAsync(url); - } + using (HttpClient client = new()) response = await client.GetAsync(url); - if (response is not { IsSuccessStatusCode: true }) - { - throw new($"File retrieval failed with status code: {response.StatusCode}"); - } + if (response is not { IsSuccessStatusCode: true }) throw new($"File retrieval failed with status code: {response.StatusCode}"); await using (Stream stream = await response.Content.ReadAsStreamAsync()) - await using (FileStream fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true)) + await using (var fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true)) { - byte[] buffer = new byte[1024]; + var buffer = new byte[1024]; int length; - while ((length = await stream.ReadAsync(buffer)) != 0) - { - await fileStream.WriteAsync(buffer.AsMemory(0, length)); - } + while ((length = await stream.ReadAsync(buffer)) != 0) await fileStream.WriteAsync(buffer.AsMemory(0, length)); } string fileName = Assembly.GetExecutingAssembly().Location; @@ -247,25 +244,16 @@ namespace EHR const string savePath = "BepInEx/plugins/EHR.dll.temp"; // Delete the temporary file if it exists - if (File.Exists(savePath)) - { - File.Delete(savePath); - } + if (File.Exists(savePath)) File.Delete(savePath); HttpResponseMessage response; - using (HttpClient client = new()) - { - response = await client.GetAsync(url); - } + using (HttpClient client = new()) response = await client.GetAsync(url); - if (response is not { IsSuccessStatusCode: true }) - { - throw new($"File retrieval failed with status code: {response.StatusCode}"); - } + if (response is not { IsSuccessStatusCode: true }) throw new($"File retrieval failed with status code: {response.StatusCode}"); await using (Stream stream = await response.Content.ReadAsStreamAsync()) - using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read)) + using (var archive = new ZipArchive(stream, ZipArchiveMode.Read)) { // Specify the relative path within the ZIP archive where "EHR.dll" is located const string entryPath = "BepInEx/plugins/EHR.dll"; @@ -273,7 +261,7 @@ namespace EHR // Extract "EHR.dll" to the temporary file await using Stream entryStream = entry.Open(); - await using FileStream fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true); + await using var fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true); await entryStream.CopyToAsync(fileStream); } @@ -294,27 +282,22 @@ namespace EHR public static void ShowPopup(string message, StringNames buttonText, bool showButton = false, bool buttonIsExit = true) { - if (InfoPopup == null) - { - return; - } + if (InfoPopup == null) return; InfoPopup.Show(message); Transform button = InfoPopup.transform.FindChild("ExitGame"); + if (button != null) { button.gameObject.SetActive(showButton); button.GetChild(0).GetComponent().TargetText = buttonText; button.GetChild(0).GetComponent().ResetText(); button.GetComponent().OnClick = new(); + if (buttonIsExit) - { button.GetComponent().OnClick.AddListener((Action)Application.Quit); - } else - { button.GetComponent().OnClick.AddListener((Action)(() => InfoPopup.Close())); - } } } } diff --git a/Modules/NameColorManager.cs b/Modules/NameColorManager.cs index d3bf3259c..dcf1b6cb0 100644 --- a/Modules/NameColorManager.cs +++ b/Modules/NameColorManager.cs @@ -13,26 +13,17 @@ namespace EHR { public static string ApplyNameColorData(this string name, PlayerControl seer, PlayerControl target, bool isMeeting) { - if (!AmongUsClient.Instance.IsGameStarted) - { - return name; - } + if (!AmongUsClient.Instance.IsGameStarted) return name; if (!TryGetData(seer, target, out string colorCode)) - { if (KnowTargetRoleColor(seer, target, isMeeting, out string color)) - { colorCode = color == "" ? target.GetRoleColorCode() : color; - } - } string openTag = "", closeTag = ""; + if (colorCode != "") { - if (!colorCode.StartsWith('#')) - { - colorCode = "#" + colorCode; - } + if (!colorCode.StartsWith('#')) colorCode = "#" + colorCode; openTag = $"<{colorCode}>"; closeTag = ""; @@ -57,18 +48,13 @@ namespace EHR return true; case CustomGameMode.HotPotato: (byte HolderID, byte LastHolderID) = HotPotatoManager.GetState(); + if (target.PlayerId == HolderID) - { color = "#000000"; - } else if (target.PlayerId == LastHolderID) - { color = "#00ffff"; - } else - { color = "#ffffff"; - } return true; case CustomGameMode.HideAndSeek: @@ -84,81 +70,39 @@ namespace EHR RoleBase targetRoleClass = Main.PlayerStates[target.PlayerId].Role; // Global (low priority) - if (Stained.VioletNameList.Contains(target.PlayerId)) - { - color = "#ff00ff"; - } + if (Stained.VioletNameList.Contains(target.PlayerId)) color = "#ff00ff"; // Impostors and Madmates - if (seer.Is(CustomRoleTypes.Impostor) && target.Is(CustomRoleTypes.Impostor)) - { - color = target.Is(CustomRoles.Egoist) && Options.ImpEgoistVisibalToAllies.GetBool() && seer != target ? Main.RoleColors[CustomRoles.Egoist] : Main.ImpostorColor; - } + if (seer.Is(CustomRoleTypes.Impostor) && target.Is(CustomRoleTypes.Impostor)) color = target.Is(CustomRoles.Egoist) && Options.ImpEgoistVisibalToAllies.GetBool() && seer != target ? Main.RoleColors[CustomRoles.Egoist] : Main.ImpostorColor; - if (seer.Is(CustomRoles.Madmate) && target.Is(CustomRoleTypes.Impostor) && Options.MadmateKnowWhosImp.GetBool()) - { - color = Main.ImpostorColor; - } + if (seer.Is(CustomRoles.Madmate) && target.Is(CustomRoleTypes.Impostor) && Options.MadmateKnowWhosImp.GetBool()) color = Main.ImpostorColor; - if (seer.Is(CustomRoleTypes.Impostor) && target.Is(CustomRoles.Madmate) && Options.ImpKnowWhosMadmate.GetBool()) - { - color = Main.RoleColors[CustomRoles.Madmate]; - } + if (seer.Is(CustomRoleTypes.Impostor) && target.Is(CustomRoles.Madmate) && Options.ImpKnowWhosMadmate.GetBool()) color = Main.RoleColors[CustomRoles.Madmate]; - if (seer.Is(CustomRoles.Madmate) && target.Is(CustomRoles.Madmate) && Options.MadmateKnowWhosMadmate.GetBool()) - { - color = Main.RoleColors[CustomRoles.Madmate]; - } + if (seer.Is(CustomRoles.Madmate) && target.Is(CustomRoles.Madmate) && Options.MadmateKnowWhosMadmate.GetBool()) color = Main.RoleColors[CustomRoles.Madmate]; - if (Blackmailer.On && seerRoleClass is Blackmailer { IsEnable: true } bm && bm.BlackmailedPlayerIds.Contains(target.PlayerId)) - { - color = Main.RoleColors[CustomRoles.BloodKnight]; - } + if (Blackmailer.On && seerRoleClass is Blackmailer { IsEnable: true } bm && bm.BlackmailedPlayerIds.Contains(target.PlayerId)) color = Main.RoleColors[CustomRoles.BloodKnight]; if (Commander.On && seer.Is(Team.Impostor)) { - if (Commander.PlayerList.Any(x => x.MarkedPlayer == target.PlayerId)) - { - color = Main.RoleColors[CustomRoles.Sprayer]; - } + if (Commander.PlayerList.Any(x => x.MarkedPlayer == target.PlayerId)) color = Main.RoleColors[CustomRoles.Sprayer]; - if (Commander.PlayerList.Any(x => x.DontKillMarks.Contains(target.PlayerId))) - { - color = "#0daeff"; - } + if (Commander.PlayerList.Any(x => x.DontKillMarks.Contains(target.PlayerId))) color = "#0daeff"; } // Custom Teams - if (CustomTeamManager.AreInSameCustomTeam(seer.PlayerId, target.PlayerId) && CustomTeamManager.IsSettingEnabledForPlayerTeam(seer.PlayerId, CTAOption.KnowRoles)) - { - color = Main.RoleColors[target.GetCustomRole()]; - } + if (CustomTeamManager.AreInSameCustomTeam(seer.PlayerId, target.PlayerId) && CustomTeamManager.IsSettingEnabledForPlayerTeam(seer.PlayerId, CTAOption.KnowRoles)) color = Main.RoleColors[target.GetCustomRole()]; // Add-ons - if (target.Is(CustomRoles.Glow) && Utils.IsActive(SystemTypes.Electrical)) - { - color = Main.RoleColors[CustomRoles.Glow]; - } + if (target.Is(CustomRoles.Glow) && Utils.IsActive(SystemTypes.Electrical)) color = Main.RoleColors[CustomRoles.Glow]; - if (target.Is(CustomRoles.Mare) && Utils.IsActive(SystemTypes.Electrical) && !isMeeting) - { - color = Main.RoleColors[CustomRoles.Mare]; - } + if (target.Is(CustomRoles.Mare) && Utils.IsActive(SystemTypes.Electrical) && !isMeeting) color = Main.RoleColors[CustomRoles.Mare]; - if (seer.Is(CustomRoles.Contagious) && target.Is(CustomRoles.Contagious) && Virus.TargetKnowOtherTarget.GetBool()) - { - color = Main.RoleColors[CustomRoles.Virus]; - } + if (seer.Is(CustomRoles.Contagious) && target.Is(CustomRoles.Contagious) && Virus.TargetKnowOtherTarget.GetBool()) color = Main.RoleColors[CustomRoles.Virus]; - if (seer.Is(CustomRoles.Charmed) && target.Is(CustomRoles.Charmed) && Succubus.TargetKnowOtherTarget.GetBool()) - { - color = Main.RoleColors[CustomRoles.Charmed]; - } + if (seer.Is(CustomRoles.Charmed) && target.Is(CustomRoles.Charmed) && Succubus.TargetKnowOtherTarget.GetBool()) color = Main.RoleColors[CustomRoles.Charmed]; - if (seer.Is(CustomRoles.Undead) && target.Is(CustomRoles.Undead)) - { - color = Main.RoleColors[CustomRoles.Undead]; - } + if (seer.Is(CustomRoles.Undead) && target.Is(CustomRoles.Undead)) color = Main.RoleColors[CustomRoles.Undead]; // Ghost roles if (GhostRolesManager.AssignedGhostRoles.TryGetValue(target.PlayerId, out (CustomRoles Role, IGhostRole Instance) ghostRole)) @@ -175,19 +119,13 @@ namespace EHR } } - if (isMeeting && Haunter.AllHauntedPlayers.Contains(target.PlayerId)) - { - color = Main.ImpostorColor; - } + if (isMeeting && Haunter.AllHauntedPlayers.Contains(target.PlayerId)) color = Main.ImpostorColor; CustomRoles seerRole = seer.GetCustomRole(); CustomRoles targetRole = target.GetCustomRole(); // If 2 players have the same role and that role is a NK role, they can see each other's name color - if (seerRole.IsNK() && seerRole == targetRole) - { - color = Main.RoleColors[seerRole]; - } + if (seerRole.IsNK() && seerRole == targetRole) color = Main.RoleColors[seerRole]; // Specific seer-target role combinations (excluding NK roles) color = (seerRole, targetRole) switch @@ -272,53 +210,26 @@ namespace EHR _ => color }; - if (target.GetCustomRole() is CustomRoles.Parasite or CustomRoles.Crewpostor or CustomRoles.Convict or CustomRoles.Refugee) - { - color = Main.ImpostorColor; - } + if (target.GetCustomRole() is CustomRoles.Parasite or CustomRoles.Crewpostor or CustomRoles.Convict or CustomRoles.Refugee) color = Main.ImpostorColor; - if (target.Is(CustomRoles.Madmate)) - { - color = Main.ImpostorColor; - } + if (target.Is(CustomRoles.Madmate)) color = Main.ImpostorColor; - if (target.Is(CustomRoles.Rascal)) - { - color = Main.ImpostorColor; - } + if (target.Is(CustomRoles.Rascal)) color = Main.ImpostorColor; - if (target.Is(CustomRoles.Charmed)) - { - color = Main.NeutralColor; - } + if (target.Is(CustomRoles.Charmed)) color = Main.NeutralColor; - if (target.Is(CustomRoles.Contagious)) - { - color = Main.NeutralColor; - } + if (target.Is(CustomRoles.Contagious)) color = Main.NeutralColor; - if (target.Is(CustomRoles.Egoist)) - { - color = Main.NeutralColor; - } + if (target.Is(CustomRoles.Egoist)) color = Main.NeutralColor; - if (target.Is(CustomRoles.Recruit)) - { - color = Main.NeutralColor; - } + if (target.Is(CustomRoles.Recruit)) color = Main.NeutralColor; } // Global (important) - if (Bubble.EncasedPlayers.TryGetValue(target.PlayerId, out long ts) && (ts + Bubble.NotifyDelay.GetInt() < Utils.TimeStamp || seer.Is(CustomRoles.Bubble))) - { - color = Main.RoleColors[CustomRoles.Bubble]; - } + if (Bubble.EncasedPlayers.TryGetValue(target.PlayerId, out long ts) && (ts + Bubble.NotifyDelay.GetInt() < Utils.TimeStamp || seer.Is(CustomRoles.Bubble))) color = Main.RoleColors[CustomRoles.Bubble]; // If the color was determined, return true, else, check if the seer can see the target's role color without knowing the color - if (color != "") - { - return true; - } + if (color != "") return true; return seer == target || (Main.GodMode.Value && seer.AmOwner) @@ -349,10 +260,7 @@ namespace EHR { colorCode = ""; PlayerState state = Main.PlayerStates[seer.PlayerId]; - if (!state.TargetColorData.TryGetValue(target.PlayerId, out string value)) - { - return false; - } + if (!state.TargetColorData.TryGetValue(target.PlayerId, out string value)) return false; colorCode = value; return true; @@ -363,19 +271,13 @@ namespace EHR if (colorCode == "") { PlayerControl target = Utils.GetPlayerById(targetId); - if (target == null) - { - return; - } + if (target == null) return; colorCode = target.GetRoleColorCode(); } PlayerState state = Main.PlayerStates[seerId]; - if (state.TargetColorData.TryGetValue(targetId, out string value) && colorCode == value) - { - return; - } + if (state.TargetColorData.TryGetValue(targetId, out string value) && colorCode == value) return; state.TargetColorData.Add(targetId, colorCode); @@ -385,10 +287,7 @@ namespace EHR private static void Remove(byte seerId, byte targetId) { PlayerState state = Main.PlayerStates[seerId]; - if (!state.TargetColorData.ContainsKey(targetId)) - { - return; - } + if (!state.TargetColorData.ContainsKey(targetId)) return; state.TargetColorData.Remove(targetId); @@ -404,10 +303,7 @@ namespace EHR private static void SendRPC(byte seerId, byte targetId = byte.MaxValue, string colorCode = "") { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetNameColorData, SendOption.Reliable); writer.Write(seerId); @@ -423,17 +319,11 @@ namespace EHR string colorCode = reader.ReadString(); if (targetId == byte.MaxValue) - { RemoveAll(seerId); - } else if (colorCode == "") - { Remove(seerId, targetId); - } else - { Add(seerId, targetId, colorCode); - } } } } \ No newline at end of file diff --git a/Modules/NameNotifyManager.cs b/Modules/NameNotifyManager.cs index abcce46d7..6e19eba0b 100644 --- a/Modules/NameNotifyManager.cs +++ b/Modules/NameNotifyManager.cs @@ -17,42 +17,24 @@ namespace EHR public static void Notify(this PlayerControl pc, string text, float time = 6f, bool overrideAll = false, bool log = true) { - if (!AmongUsClient.Instance.AmHost || pc == null) - { - return; - } + if (!AmongUsClient.Instance.AmHost || pc == null) return; - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; - if (!text.Contains("")) - { - text = Utils.ColorString(Color.white, text); - } + if (!text.Contains("")) text = Utils.ColorString(Color.white, text); - if (!text.Contains("{text}"; - } + if (!text.Contains("{text}"; long expireTS = Utils.TimeStamp + (long)time; + if (overrideAll || !Notifies.TryGetValue(pc.PlayerId, out Dictionary notifies)) - { Notifies[pc.PlayerId] = new() { { text, expireTS } }; - } else - { notifies[text] = expireTS; - } SendRPC(pc.PlayerId, text, expireTS, overrideAll); Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - if (log) - { - Logger.Info($"New name notify for {pc.GetNameWithRole().RemoveHtmlTags()}: {text} ({time}s)", "Name Notify"); - } + if (log) Logger.Info($"New name notify for {pc.GetNameWithRole().RemoveHtmlTags()}: {text} ({time}s)", "Name Notify"); } public static void OnFixedUpdate(PlayerControl player) @@ -63,7 +45,7 @@ namespace EHR return; } - bool removed = false; + var removed = false; if (Notifies.TryGetValue(player.PlayerId, out Dictionary notifies)) { @@ -77,19 +59,13 @@ namespace EHR } } - if (removed) - { - Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); - } + if (removed) Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); } public static bool GetNameNotify(PlayerControl player, out string name) { name = string.Empty; - if (!Notifies.TryGetValue(player.PlayerId, out Dictionary notifies)) - { - return false; - } + if (!Notifies.TryGetValue(player.PlayerId, out Dictionary notifies)) return false; name = string.Join('\n', notifies.OrderBy(x => x.Value).Select(x => x.Key)); return true; @@ -97,10 +73,7 @@ namespace EHR private static void SendRPC(byte playerId, string text, long expireTS, bool overrideAll) // Only sent when adding a new notification { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncNameNotify, SendOption.Reliable); writer.Write(playerId); @@ -112,23 +85,17 @@ namespace EHR public static void ReceiveRPC(MessageReader reader) { - if (AmongUsClient.Instance.AmHost) - { - return; - } + if (AmongUsClient.Instance.AmHost) return; byte playerId = reader.ReadByte(); string text = reader.ReadString(); long expireTS = long.Parse(reader.ReadString()); bool overrideAll = reader.ReadBoolean(); + if (overrideAll || !Notifies.TryGetValue(playerId, out Dictionary notifies)) - { Notifies[playerId] = new() { { text, expireTS } }; - } else - { notifies[text] = expireTS; - } Logger.Info($"New name notify for {Main.AllPlayerNames[playerId]}: {text} ({expireTS - Utils.TimeStamp}s)", "Name Notify"); } diff --git a/Modules/OptionBackup/OptionBackupData.cs b/Modules/OptionBackup/OptionBackupData.cs index c2b46df12..089d4711f 100644 --- a/Modules/OptionBackup/OptionBackupData.cs +++ b/Modules/OptionBackup/OptionBackupData.cs @@ -14,36 +14,20 @@ namespace EHR AllValues = new(32); foreach (ByteOptionNames name in Enum.GetValues()) - { if (option.TryGetByte(name, out byte value)) - { AllValues.Add(new ByteOptionBackupValue(name, value)); - } - } foreach (BoolOptionNames name in Enum.GetValues()) - { if (option.TryGetBool(name, out bool value) && name != BoolOptionNames.GhostsDoTasks) - { AllValues.Add(new BoolOptionBackupValue(name, value)); - } - } foreach (FloatOptionNames name in Enum.GetValues()) - { if (option.TryGetFloat(name, out float value)) - { AllValues.Add(new FloatOptionBackupValue(name, value)); - } - } foreach (Int32OptionNames name in Enum.GetValues()) - { if (option.TryGetInt(name, out int value)) - { AllValues.Add(new IntOptionBackupValue(name, value)); - } - } // [Vanilla bug] Get the number of people in the room separately, since GetInt cannot get the number of people in the room AllValues.Add(new IntOptionBackupValue(Int32OptionNames.MaxPlayers, option.MaxPlayers)); @@ -51,10 +35,7 @@ namespace EHR AllValues.Add(new UIntOptionBackupValue(UInt32OptionNames.Keywords, (uint)option.Keywords)); RoleTypes[] array = [RoleTypes.Scientist, RoleTypes.Engineer, RoleTypes.GuardianAngel, RoleTypes.Shapeshifter, RoleTypes.Noisemaker, RoleTypes.Phantom, RoleTypes.Tracker]; - foreach (RoleTypes role in array) - { - AllValues.Add(new RoleRateBackupValue(role, option.RoleOptions.GetNumPerGame(role), option.RoleOptions.GetChancePerGame(role))); - } + foreach (RoleTypes role in array) AllValues.Add(new RoleRateBackupValue(role, option.RoleOptions.GetNumPerGame(role), option.RoleOptions.GetChancePerGame(role))); } public IGameOptions Restore(IGameOptions option) diff --git a/Modules/OptionBackup/OptionBackupValue.cs b/Modules/OptionBackup/OptionBackupValue.cs index 909d04367..c9d221583 100644 --- a/Modules/OptionBackup/OptionBackupValue.cs +++ b/Modules/OptionBackup/OptionBackupValue.cs @@ -27,10 +27,7 @@ namespace EHR { public override void Restore(IGameOptions option) { - if (OptionName != BoolOptionNames.GhostsDoTasks) - { - option.SetBool(OptionName, Value); - } + if (OptionName != BoolOptionNames.GhostsDoTasks) option.SetBool(OptionName, Value); } } diff --git a/Modules/OptionHolder.cs b/Modules/OptionHolder.cs index 0dd16a8e6..6c30626c4 100644 --- a/Modules/OptionHolder.cs +++ b/Modules/OptionHolder.cs @@ -902,10 +902,7 @@ namespace EHR { roleCounts[role] = count; - if (CustomRoleCounts.TryGetValue(role, out OptionItem option)) - { - option.SetValue(count - 1); - } + if (CustomRoleCounts.TryGetValue(role, out OptionItem option)) option.SetValue(count - 1); } public static int GetRoleSpawnMode(CustomRoles role) @@ -929,16 +926,14 @@ namespace EHR LoadingPercentage = 0; MainLoadingText = "Building system settings"; - if (IsLoaded) - { - yield break; - } + if (IsLoaded) yield break; OptionSaver.Initialize(); yield return null; int defaultPresetNumber = OptionSaver.GetDefaultPresetNumber(); + _ = new PresetOptionItem(defaultPresetNumber, TabGroup.SystemSettings) .SetColor(new Color32(255, 235, 4, byte.MaxValue)) .SetHidden(true); @@ -958,18 +953,23 @@ namespace EHR ImpKnowAlliesRole = new BooleanOptionItem(150, "ImpKnowAlliesRole", true, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.Standard) .SetHeader(true); + ImpKnowWhosMadmate = new BooleanOptionItem(151, "ImpKnowWhosMadmate", false, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.Standard); + ImpCanKillMadmate = new BooleanOptionItem(152, "ImpCanKillMadmate", true, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.Standard); MadmateKnowWhosMadmate = new BooleanOptionItem(153, "MadmateKnowWhosMadmate", false, TabGroup.ImpostorRoles) .SetHeader(true) .SetGameMode(CustomGameMode.Standard); + MadmateKnowWhosImp = new BooleanOptionItem(154, "MadmateKnowWhosImp", true, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.Standard); + MadmateCanKillImp = new BooleanOptionItem(155, "MadmateCanKillImp", true, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.Standard); + MadmateHasImpostorVision = new BooleanOptionItem(156, "MadmateHasImpostorVision", true, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.Standard); @@ -981,6 +981,7 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetHeader(true) .SetValueFormat(OptionFormat.Seconds); + DeadImpCantSabotage = new BooleanOptionItem(201, "DeadImpCantSabotage", false, TabGroup.ImpostorRoles) .SetGameMode(CustomGameMode.Standard); @@ -988,6 +989,7 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetHeader(true) .SetValueFormat(OptionFormat.Players); + NonNeutralKillingRolesMaxPlayer = new IntegerOptionItem(203, "NonNeutralKillingRolesMaxPlayer", new(0, 15, 1), 0, TabGroup.NeutralRoles) .SetGameMode(CustomGameMode.Standard) .SetValueFormat(OptionFormat.Players); @@ -996,6 +998,7 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetHeader(true) .SetValueFormat(OptionFormat.Players); + NeutralKillingRolesMaxPlayer = new IntegerOptionItem(205, "NeutralKillingRolesMaxPlayer", new(0, 15, 1), 0, TabGroup.NeutralRoles) .SetGameMode(CustomGameMode.Standard) .SetValueFormat(OptionFormat.Players); @@ -1003,15 +1006,18 @@ namespace EHR NeutralRoleWinTogether = new BooleanOptionItem(208, "NeutralRoleWinTogether", false, TabGroup.NeutralRoles) .SetGameMode(CustomGameMode.Standard) .SetHeader(true); + NeutralWinTogether = new BooleanOptionItem(209, "NeutralWinTogether", false, TabGroup.NeutralRoles) .SetParent(NeutralRoleWinTogether) .SetGameMode(CustomGameMode.Standard); + NeutralsKnowEachOther = new BooleanOptionItem(212, "NeutralsKnowEachOther", false, TabGroup.NeutralRoles) .SetGameMode(CustomGameMode.Standard); NameDisplayAddons = new BooleanOptionItem(210, "NameDisplayAddons", true, TabGroup.Addons) .SetGameMode(CustomGameMode.Standard) .SetHeader(true); + NoLimitAddonsNumMax = new IntegerOptionItem(211, "NoLimitAddonsNumMax", new(1, 90, 1), 1, TabGroup.Addons) .SetGameMode(CustomGameMode.Standard); @@ -1019,15 +1025,19 @@ namespace EHR .SetHeader(true) .SetGameMode(CustomGameMode.Standard) .AddReplacement(("{role}", CustomRoles.Charmed.ToColoredString())); + RecruitCanBeGuessed = new StringOptionItem(214, "ConvertedAddonCanBeGuessed", AddonGuessOptions, 2, TabGroup.Addons) .SetGameMode(CustomGameMode.Standard) .AddReplacement(("{role}", CustomRoles.Recruit.ToColoredString())); + ContagiousCanBeGuessed = new StringOptionItem(215, "ConvertedAddonCanBeGuessed", AddonGuessOptions, 2, TabGroup.Addons) .SetGameMode(CustomGameMode.Standard) .AddReplacement(("{role}", CustomRoles.Contagious.ToColoredString())); + UndeadCanBeGuessed = new StringOptionItem(216, "ConvertedAddonCanBeGuessed", AddonGuessOptions, 2, TabGroup.Addons) .SetGameMode(CustomGameMode.Standard) .AddReplacement(("{role}", CustomRoles.Undead.ToColoredString())); + EgoistCanBeGuessed = new StringOptionItem(217, "ConvertedAddonCanBeGuessed", AddonGuessOptions, 2, TabGroup.Addons) .SetGameMode(CustomGameMode.Standard) .AddReplacement(("{role}", CustomRoles.Egoist.ToColoredString())); @@ -1044,12 +1054,13 @@ namespace EHR #region Roles/AddOns_Settings - int titleId = 100100; + var titleId = 100100; LoadingPercentage = 5; MainLoadingText = "Building Add-on Settings"; Type IAddonType = typeof(IAddon); + Dictionary addonTypes = Assembly .GetExecutingAssembly() .GetTypes() @@ -1063,12 +1074,13 @@ namespace EHR foreach (KeyValuePair addonType in addonTypes) { MainLoadingText = $"Building Add-on Settings ({addonType.Key})"; - int index = 0; + var index = 0; new TextOptionItem(titleId, $"ROT.AddonType.{addonType.Key}", TabGroup.Addons) .SetGameMode(CustomGameMode.Standard) .SetColor(addonType.Key.GetAddonTypeColor()) .SetHeader(true); + titleId += 10; foreach (IAddon addon in addonType.Value) @@ -1087,6 +1099,7 @@ namespace EHR MainLoadingText = "Building Role Settings"; Type IVanillaType = typeof(IVanillaSettingHolder); + Assembly .GetExecutingAssembly() .GetTypes() @@ -1099,6 +1112,7 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetColor(Color.white) .SetHeader(true); + titleId += 10; RoleLoadingText = x.GetType().Name; @@ -1108,6 +1122,7 @@ namespace EHR }); Type IType = typeof(IGhostRole); + Assembly .GetExecutingAssembly() .GetTypes() @@ -1126,7 +1141,7 @@ namespace EHR { MainLoadingText = $"Building Role Settings: {roleClasses.Key} Roles"; int allRoles = roleClasses.Value.Length; - int index = 0; + var index = 0; TabGroup tab = roleClasses.Key.GetTabFromOptionType(); @@ -1134,6 +1149,7 @@ namespace EHR .SetHeader(true) .SetGameMode(CustomGameMode.Standard) .SetColor(roleClasses.Key.GetRoleOptionTypeColor()); + titleId += 10; foreach (RoleBase roleClass in roleClasses.Value) @@ -1141,6 +1157,7 @@ namespace EHR index++; RoleLoadingText = $"{index}/{allRoles} ({roleClass.GetType().Name})"; Log(); + try { roleClass.SetupCustomOption(); @@ -1159,6 +1176,7 @@ namespace EHR .SetHeader(true) .SetGameMode(CustomGameMode.Standard) .SetColor(Palette.ImpostorRed); + titleId += 10; } @@ -1186,6 +1204,7 @@ namespace EHR KickLowLevelPlayer = new IntegerOptionItem(19300, "KickLowLevelPlayer", new(0, 100, 1), 0, TabGroup.SystemSettings) .SetValueFormat(OptionFormat.Level) .SetHeader(true); + KickAndroidPlayer = new BooleanOptionItem(19301, "KickAndroidPlayer", false, TabGroup.SystemSettings); KickPlayerFriendCodeNotExist = new BooleanOptionItem(19302, "KickPlayerFriendCodeNotExist", false, TabGroup.SystemSettings, true); ApplyDenyNameList = new BooleanOptionItem(19303, "ApplyDenyNameList", true, TabGroup.SystemSettings, true); @@ -1196,15 +1215,20 @@ namespace EHR LoadingPercentage = 61; AutoKickStart = new BooleanOptionItem(19310, "AutoKickStart", false, TabGroup.SystemSettings); + AutoKickStartTimes = new IntegerOptionItem(19311, "AutoKickStartTimes", new(0, 90, 1), 1, TabGroup.SystemSettings) .SetParent(AutoKickStart) .SetValueFormat(OptionFormat.Times); + AutoKickStartAsBan = new BooleanOptionItem(19312, "AutoKickStartAsBan", false, TabGroup.SystemSettings) .SetParent(AutoKickStart); + AutoKickStopWords = new BooleanOptionItem(19313, "AutoKickStopWords", false, TabGroup.SystemSettings); + AutoKickStopWordsTimes = new IntegerOptionItem(19314, "AutoKickStopWordsTimes", new(0, 90, 1), 3, TabGroup.SystemSettings) .SetParent(AutoKickStopWords) .SetValueFormat(OptionFormat.Times); + AutoKickStopWordsAsBan = new BooleanOptionItem(19315, "AutoKickStopWordsAsBan", false, TabGroup.SystemSettings) .SetParent(AutoKickStopWords); @@ -1214,9 +1238,12 @@ namespace EHR MinWaitAutoStart = new FloatOptionItem(44420, "MinWaitAutoStart", new(0f, 10f, 0.5f), 1.5f, TabGroup.SystemSettings); MaxWaitAutoStart = new FloatOptionItem(44421, "MaxWaitAutoStart", new(0f, 10f, 0.5f), 1.5f, TabGroup.SystemSettings); PlayerAutoStart = new IntegerOptionItem(44422, "PlayerAutoStart", new(1, 15, 1), 14, TabGroup.SystemSettings); + AutoStartTimer = new IntegerOptionItem(44423, "AutoStartTimer", new(10, 600, 1), 20, TabGroup.SystemSettings) .SetValueFormat(OptionFormat.Seconds); + AutoPlayAgain = new BooleanOptionItem(44424, "AutoPlayAgain", false, TabGroup.SystemSettings); + AutoPlayAgainCountdown = new IntegerOptionItem(44425, "AutoPlayAgainCountdown", new(1, 90, 1), 10, TabGroup.SystemSettings) .SetParent(AutoPlayAgain); @@ -1258,12 +1285,14 @@ namespace EHR AutoDisplayKillLog = new BooleanOptionItem(19321, "AutoDisplayKillLog", true, TabGroup.SystemSettings) .SetHeader(true); + AutoDisplayLastRoles = new BooleanOptionItem(19322, "AutoDisplayLastRoles", true, TabGroup.SystemSettings); AutoDisplayLastAddOns = new BooleanOptionItem(19328, "AutoDisplayLastAddOns", true, TabGroup.SystemSettings); AutoDisplayLastResult = new BooleanOptionItem(19323, "AutoDisplayLastResult", true, TabGroup.SystemSettings); SuffixMode = new StringOptionItem(19324, "SuffixMode", SuffixModes, 0, TabGroup.SystemSettings, true) .SetHeader(true); + HideGameSettings = new BooleanOptionItem(19400, "HideGameSettings", false, TabGroup.SystemSettings); DIYGameSettings = new BooleanOptionItem(19401, "DIYGameSettings", false, TabGroup.SystemSettings); PlayerCanSetColor = new BooleanOptionItem(19402, "PlayerCanSetColor", false, TabGroup.SystemSettings); @@ -1272,16 +1301,23 @@ namespace EHR FormatNameMode = new StringOptionItem(19403, "FormatNameMode", FormatNameModes, 0, TabGroup.SystemSettings); DisableEmojiName = new BooleanOptionItem(19404, "DisableEmojiName", true, TabGroup.SystemSettings); ChangeNameToRoleInfo = new BooleanOptionItem(19405, "ChangeNameToRoleInfo", true, TabGroup.SystemSettings); + ShowLongInfo = new BooleanOptionItem(19420, "ShowLongInfo", true, TabGroup.SystemSettings) .SetParent(ChangeNameToRoleInfo); + SendRoleDescriptionFirstMeeting = new BooleanOptionItem(19406, "SendRoleDescriptionFirstMeeting", true, TabGroup.SystemSettings); + NoGameEnd = new BooleanOptionItem(19407, "NoGameEnd", false, TabGroup.SystemSettings) .SetColor(Color.red); + AllowConsole = new BooleanOptionItem(19408, "AllowConsole", false, TabGroup.SystemSettings) .SetColor(Color.red); + ShowAntiBlackoutWarning = new BooleanOptionItem(19421, "ShowAntiBlackoutWarning", true, TabGroup.SystemSettings); + RoleAssigningAlgorithm = new StringOptionItem(19409, "RoleAssigningAlgorithm", RoleAssigningAlgorithms, 4, TabGroup.SystemSettings, true) .RegisterUpdateValueEvent((_, args) => IRandom.SetInstanceById(args.CurrentValue)); + KPDCamouflageMode = new StringOptionItem(19500, "KPDCamouflageMode", CamouflageMode, 0, TabGroup.SystemSettings) .SetHeader(true) .SetColor(new Color32(255, 192, 203, byte.MaxValue)); @@ -1329,9 +1365,11 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetHeader(true) .SetColor(new Color32(255, 238, 232, byte.MaxValue)); + ShowImpRemainOnEject = new BooleanOptionItem(19810, "ShowImpRemainOnEject", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(255, 238, 232, byte.MaxValue)); + ShowNKRemainOnEject = new BooleanOptionItem(19811, "ShowNKRemainOnEject", true, TabGroup.GameSettings) .SetParent(ShowImpRemainOnEject) .SetGameMode(CustomGameMode.Standard) @@ -1342,10 +1380,12 @@ namespace EHR ShowTeamNextToRoleNameOnEject = new BooleanOptionItem(19812, "ShowTeamNextToRoleNameOnEject", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(255, 238, 232, byte.MaxValue)); + ConfirmEgoistOnEject = new BooleanOptionItem(19813, "ConfirmEgoistOnEject", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(255, 238, 232, byte.MaxValue)) .SetHeader(true); + ConfirmLoversOnEject = new BooleanOptionItem(19815, "ConfirmLoversOnEject", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(255, 238, 232, byte.MaxValue)); @@ -1368,18 +1408,23 @@ namespace EHR SkeldChance = new IntegerOptionItem(19910, "SkeldChance", new(0, 100, 5), 0, TabGroup.GameSettings) .SetParent(RandomMapsMode) .SetValueFormat(OptionFormat.Percent); + MiraChance = new IntegerOptionItem(19911, "MiraChance", new(0, 100, 5), 0, TabGroup.GameSettings) .SetParent(RandomMapsMode) .SetValueFormat(OptionFormat.Percent); + PolusChance = new IntegerOptionItem(19912, "PolusChance", new(0, 100, 5), 0, TabGroup.GameSettings) .SetParent(RandomMapsMode) .SetValueFormat(OptionFormat.Percent); + DleksChance = new IntegerOptionItem(19914, "DleksChance", new(0, 100, 5), 0, TabGroup.GameSettings) .SetParent(RandomMapsMode) .SetValueFormat(OptionFormat.Percent); + AirshipChance = new IntegerOptionItem(19913, "AirshipChance", new(0, 100, 5), 0, TabGroup.GameSettings) .SetParent(RandomMapsMode) .SetValueFormat(OptionFormat.Percent); + FungleChance = new IntegerOptionItem(19922, "FungleChance", new(0, 100, 5), 0, TabGroup.GameSettings) .SetParent(RandomMapsMode) .SetValueFormat(OptionFormat.Percent); @@ -1390,6 +1435,7 @@ namespace EHR // Random Spawn RandomSpawn = new BooleanOptionItem(22000, "RandomSpawn", false, TabGroup.GameSettings) .SetColor(new Color32(19, 188, 233, byte.MaxValue)); + AirshipAdditionalSpawn = new BooleanOptionItem(22010, "AirshipAdditionalSpawn", false, TabGroup.GameSettings) .SetParent(RandomSpawn); @@ -1397,6 +1443,7 @@ namespace EHR AirshipVariableElectrical = new BooleanOptionItem(22100, "AirshipVariableElectrical", false, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(19, 188, 233, byte.MaxValue)); + // Disable Airship Moving Platform DisableAirshipMovingPlatform = new BooleanOptionItem(22110, "DisableAirshipMovingPlatform", false, TabGroup.GameSettings) .SetColor(new Color32(19, 188, 233, byte.MaxValue)); @@ -1408,10 +1455,12 @@ namespace EHR // Disable Zipline On Fungle DisableZiplineOnFungle = new BooleanOptionItem(22305, "DisableZiplineOnFungle", false, TabGroup.GameSettings) .SetColor(new Color32(19, 188, 233, byte.MaxValue)); + // Disable Zipline From Top DisableZiplineFromTop = new BooleanOptionItem(22308, "DisableZiplineFromTop", false, TabGroup.GameSettings) .SetParent(DisableZiplineOnFungle) .SetColor(new Color32(19, 188, 233, byte.MaxValue)); + // Disable Zipline From Under DisableZiplineFromUnder = new BooleanOptionItem(22310, "DisableZiplineFromUnder", false, TabGroup.GameSettings) .SetParent(DisableZiplineOnFungle) @@ -1420,15 +1469,18 @@ namespace EHR DisableZiplineForCrew = new BooleanOptionItem(22316, "DisableZiplineForCrew", false, TabGroup.GameSettings) .SetParent(DisableZiplineOnFungle) .SetColor(new Color32(19, 188, 233, byte.MaxValue)); + DisableZiplineForImps = new BooleanOptionItem(22318, "DisableZiplineForImps", false, TabGroup.GameSettings) .SetParent(DisableZiplineOnFungle) .SetColor(new Color32(19, 188, 233, byte.MaxValue)); + DisableZiplineForNeutrals = new BooleanOptionItem(22320, "DisableZiplineForNeutrals", false, TabGroup.GameSettings) .SetParent(DisableZiplineOnFungle) .SetColor(new Color32(19, 188, 233, byte.MaxValue)); ZiplineTravelTimeFromBottom = new FloatOptionItem(22312, "ZiplineTravelTimeFromBottom", new(0.5f, 10f, 0.5f), 4f, TabGroup.GameSettings) .SetColor(new Color32(19, 188, 233, byte.MaxValue)); + ZiplineTravelTimeFromTop = new FloatOptionItem(22314, "ZiplineTravelTimeFromTop", new(0.5f, 10f, 0.5f), 2f, TabGroup.GameSettings) .SetColor(new Color32(19, 188, 233, byte.MaxValue)); @@ -1436,6 +1488,7 @@ namespace EHR ResetDoorsEveryTurns = new BooleanOptionItem(22120, "ResetDoorsEveryTurns", false, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(19, 188, 233, byte.MaxValue)); + // Reset Doors Mode DoorsResetMode = new StringOptionItem(22122, "DoorsResetMode", Enum.GetNames(), 2, TabGroup.GameSettings) .SetColor(new Color32(19, 188, 233, byte.MaxValue)) @@ -1445,11 +1498,13 @@ namespace EHR // Change decontamination time on MiraHQ/Polus ChangeDecontaminationTime = new BooleanOptionItem(60503, "ChangeDecontaminationTime", false, TabGroup.GameSettings) .SetColor(new Color32(19, 188, 233, byte.MaxValue)); + // Decontamination time on MiraHQ DecontaminationTimeOnMiraHQ = new FloatOptionItem(60504, "DecontaminationTimeOnMiraHQ", new(0.5f, 10f, 0.25f), 3f, TabGroup.GameSettings) .SetParent(ChangeDecontaminationTime) .SetValueFormat(OptionFormat.Multiplier) .SetColor(new Color32(19, 188, 233, byte.MaxValue)); + // Decontamination time on Polus DecontaminationTimeOnPolus = new FloatOptionItem(60505, "DecontaminationTimeOnPolus", new(0.5f, 10f, 0.25f), 3f, TabGroup.GameSettings) .SetParent(ChangeDecontaminationTime) @@ -1472,10 +1527,12 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetHeader(true) .SetColor(new Color32(243, 96, 96, byte.MaxValue)); + CommsCamouflageDisableOnFungle = new BooleanOptionItem(22202, "CommsCamouflageDisableOnFungle", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetParent(CommsCamouflage) .SetColor(new Color32(243, 96, 96, byte.MaxValue)); + DisableReportWhenCC = new BooleanOptionItem(22300, "DisableReportWhenCC", false, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(243, 96, 96, byte.MaxValue)); @@ -1487,6 +1544,7 @@ namespace EHR SabotageCooldownControl = new BooleanOptionItem(22400, "SabotageCooldownControl", false, TabGroup.GameSettings) .SetColor(new Color32(243, 96, 96, byte.MaxValue)) .SetGameMode(CustomGameMode.Standard); + SabotageCooldown = new FloatOptionItem(22405, "SabotageCooldown", new(1f, 60f, 1f), 30f, TabGroup.GameSettings) .SetParent(SabotageCooldownControl) .SetValueFormat(OptionFormat.Seconds) @@ -1502,34 +1560,41 @@ namespace EHR .SetParent(SabotageTimeControl) .SetValueFormat(OptionFormat.Seconds) .SetGameMode(CustomGameMode.Standard); + SkeldO2TimeLimit = new FloatOptionItem(22419, "SkeldO2TimeLimit", new(5f, 90f, 1f), 30f, TabGroup.GameSettings) .SetParent(SabotageTimeControl) .SetValueFormat(OptionFormat.Seconds) .SetGameMode(CustomGameMode.Standard); + // Mira HQ MiraReactorTimeLimit = new FloatOptionItem(22422, "MiraReactorTimeLimit", new(5f, 90f, 1f), 45f, TabGroup.GameSettings) .SetParent(SabotageTimeControl) .SetValueFormat(OptionFormat.Seconds) .SetGameMode(CustomGameMode.Standard); + MiraO2TimeLimit = new FloatOptionItem(22423, "MiraO2TimeLimit", new(5f, 90f, 1f), 45f, TabGroup.GameSettings) .SetParent(SabotageTimeControl) .SetValueFormat(OptionFormat.Seconds) .SetGameMode(CustomGameMode.Standard); + // Polus PolusReactorTimeLimit = new FloatOptionItem(22424, "PolusReactorTimeLimit", new(5f, 90f, 1f), 60f, TabGroup.GameSettings) .SetParent(SabotageTimeControl) .SetValueFormat(OptionFormat.Seconds) .SetGameMode(CustomGameMode.Standard); + // The Airship AirshipReactorTimeLimit = new FloatOptionItem(22425, "AirshipReactorTimeLimit", new(5f, 90f, 1f), 90f, TabGroup.GameSettings) .SetParent(SabotageTimeControl) .SetValueFormat(OptionFormat.Seconds) .SetGameMode(CustomGameMode.Standard); + // The Fungle FungleReactorTimeLimit = new FloatOptionItem(22426, "FungleReactorTimeLimit", new(5f, 90f, 1f), 60f, TabGroup.GameSettings) .SetParent(SabotageTimeControl) .SetValueFormat(OptionFormat.Seconds) .SetGameMode(CustomGameMode.Standard); + FungleMushroomMixupDuration = new FloatOptionItem(22427, "FungleMushroomMixupDuration", new(5f, 90f, 1f), 10f, TabGroup.GameSettings) .SetParent(SabotageTimeControl) .SetValueFormat(OptionFormat.Seconds) @@ -1540,15 +1605,19 @@ namespace EHR LightsOutSpecialSettings = new BooleanOptionItem(22500, "LightsOutSpecialSettings", false, TabGroup.GameSettings) .SetColor(new Color32(243, 96, 96, byte.MaxValue)) .SetGameMode(CustomGameMode.Standard); + BlockDisturbancesToSwitches = new BooleanOptionItem(60551, "BlockDisturbancesToSwitches", false, TabGroup.GameSettings) .SetParent(LightsOutSpecialSettings) .SetGameMode(CustomGameMode.Standard); + DisableAirshipViewingDeckLightsPanel = new BooleanOptionItem(22510, "DisableAirshipViewingDeckLightsPanel", false, TabGroup.GameSettings) .SetParent(LightsOutSpecialSettings) .SetGameMode(CustomGameMode.Standard); + DisableAirshipGapRoomLightsPanel = new BooleanOptionItem(22511, "DisableAirshipGapRoomLightsPanel", false, TabGroup.GameSettings) .SetParent(LightsOutSpecialSettings) .SetGameMode(CustomGameMode.Standard); + DisableAirshipCargoLightsPanel = new BooleanOptionItem(22512, "DisableAirshipCargoLightsPanel", false, TabGroup.GameSettings) .SetParent(LightsOutSpecialSettings) .SetGameMode(CustomGameMode.Standard); @@ -1568,25 +1637,32 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetHeader(true) .SetColor(new Color32(255, 153, 153, byte.MaxValue)); + DisableKillAnimationOnGuess = new BooleanOptionItem(22602, "DisableKillAnimationOnGuess", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(255, 153, 153, byte.MaxValue)); + DisableShapeshiftAnimations = new BooleanOptionItem(22604, "DisableShapeshiftAnimations", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(255, 153, 153, byte.MaxValue)); + DisableAllShapeshiftAnimations = new BooleanOptionItem(22605, "DisableAllShapeshiftAnimations", false, TabGroup.GameSettings) .SetParent(DisableShapeshiftAnimations) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(255, 153, 153, byte.MaxValue)); + DisableVanillaRoles = new BooleanOptionItem(22600, "DisableVanillaRoles", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(255, 153, 153, byte.MaxValue)); + DisableTaskWin = new BooleanOptionItem(22650, "DisableTaskWin", false, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(255, 153, 153, byte.MaxValue)); + DisableTaskWinIfAllCrewsAreDead = new BooleanOptionItem(22651, "DisableTaskWinIfAllCrewsAreDead", false, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(255, 153, 153, byte.MaxValue)); + DisableTaskWinIfAllCrewsAreConverted = new BooleanOptionItem(22652, "DisableTaskWinIfAllCrewsAreConverted", false, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(255, 153, 153, byte.MaxValue)); @@ -1597,8 +1673,10 @@ namespace EHR DisableMeeting = new BooleanOptionItem(22700, "DisableMeeting", false, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(255, 153, 153, byte.MaxValue)); + DisableSabotage = new BooleanOptionItem(22800, "DisableSabotage", false, TabGroup.GameSettings) .SetColor(new Color32(255, 153, 153, byte.MaxValue)); + DisableCloseDoor = new BooleanOptionItem(22810, "DisableCloseDoor", false, TabGroup.GameSettings) .SetParent(DisableSabotage) .SetColor(new Color32(255, 153, 153, byte.MaxValue)); @@ -1607,10 +1685,13 @@ namespace EHR DisableDevices = new BooleanOptionItem(22900, "DisableDevices", false, TabGroup.GameSettings) .SetColor(new Color32(255, 153, 153, byte.MaxValue)); + DisableSkeldDevices = new BooleanOptionItem(22905, "DisableSkeldDevices", false, TabGroup.GameSettings) .SetParent(DisableDevices); + DisableSkeldAdmin = new BooleanOptionItem(22906, "DisableSkeldAdmin", false, TabGroup.GameSettings) .SetParent(DisableSkeldDevices); + DisableSkeldCamera = new BooleanOptionItem(22907, "DisableSkeldCamera", false, TabGroup.GameSettings) .SetParent(DisableSkeldDevices); @@ -1618,20 +1699,28 @@ namespace EHR DisableMiraHQDevices = new BooleanOptionItem(22908, "DisableMiraHQDevices", false, TabGroup.GameSettings) .SetParent(DisableDevices); + DisableMiraHQAdmin = new BooleanOptionItem(22909, "DisableMiraHQAdmin", false, TabGroup.GameSettings) .SetParent(DisableMiraHQDevices); + DisableMiraHQDoorLog = new BooleanOptionItem(22910, "DisableMiraHQDoorLog", false, TabGroup.GameSettings) .SetParent(DisableMiraHQDevices); + DisablePolusDevices = new BooleanOptionItem(22911, "DisablePolusDevices", false, TabGroup.GameSettings) .SetParent(DisableDevices); + DisablePolusAdmin = new BooleanOptionItem(22912, "DisablePolusAdmin", false, TabGroup.GameSettings) .SetParent(DisablePolusDevices); + DisablePolusCamera = new BooleanOptionItem(22913, "DisablePolusCamera", false, TabGroup.GameSettings) .SetParent(DisablePolusDevices); + DisablePolusVital = new BooleanOptionItem(22914, "DisablePolusVital", false, TabGroup.GameSettings) .SetParent(DisablePolusDevices); + DisableAirshipDevices = new BooleanOptionItem(22915, "DisableAirshipDevices", false, TabGroup.GameSettings) .SetParent(DisableDevices); + DisableAirshipCockpitAdmin = new BooleanOptionItem(22916, "DisableAirshipCockpitAdmin", false, TabGroup.GameSettings) .SetParent(DisableAirshipDevices); @@ -1639,27 +1728,37 @@ namespace EHR DisableAirshipRecordsAdmin = new BooleanOptionItem(22917, "DisableAirshipRecordsAdmin", false, TabGroup.GameSettings) .SetParent(DisableAirshipDevices); + DisableAirshipCamera = new BooleanOptionItem(22918, "DisableAirshipCamera", false, TabGroup.GameSettings) .SetParent(DisableAirshipDevices); + DisableAirshipVital = new BooleanOptionItem(22919, "DisableAirshipVital", false, TabGroup.GameSettings) .SetParent(DisableAirshipDevices); + DisableFungleDevices = new BooleanOptionItem(22925, "DisableFungleDevices", false, TabGroup.GameSettings) .SetParent(DisableDevices) .SetGameMode(CustomGameMode.Standard); + DisableFungleCamera = new BooleanOptionItem(22926, "DisableFungleCamera", false, TabGroup.GameSettings) .SetParent(DisableFungleDevices) .SetGameMode(CustomGameMode.Standard); + DisableFungleVital = new BooleanOptionItem(22927, "DisableFungleVital", false, TabGroup.GameSettings) .SetParent(DisableFungleDevices) .SetGameMode(CustomGameMode.Standard); + DisableDevicesIgnoreConditions = new BooleanOptionItem(22920, "IgnoreConditions", false, TabGroup.GameSettings) .SetParent(DisableDevices); + DisableDevicesIgnoreImpostors = new BooleanOptionItem(22921, "IgnoreImpostors", false, TabGroup.GameSettings) .SetParent(DisableDevicesIgnoreConditions); + DisableDevicesIgnoreNeutrals = new BooleanOptionItem(22922, "IgnoreNeutrals", false, TabGroup.GameSettings) .SetParent(DisableDevicesIgnoreConditions); + DisableDevicesIgnoreCrewmates = new BooleanOptionItem(22923, "IgnoreCrewmates", false, TabGroup.GameSettings) .SetParent(DisableDevicesIgnoreConditions); + DisableDevicesIgnoreAfterAnyoneDied = new BooleanOptionItem(22924, "IgnoreAfterAnyoneDied", false, TabGroup.GameSettings) .SetParent(DisableDevicesIgnoreConditions) .SetGameMode(CustomGameMode.Standard); @@ -1670,6 +1769,7 @@ namespace EHR UsePets = new BooleanOptionItem(23850, "UsePets", false, TabGroup.TaskSettings) .SetHeader(true) .SetColor(new Color32(60, 0, 255, byte.MaxValue)); + PetToAssignToEveryone = new StringOptionItem(23854, "PetToAssign", PetToAssign, 24, TabGroup.TaskSettings) .SetParent(UsePets) .SetColor(new Color32(60, 0, 255, byte.MaxValue)); @@ -1678,6 +1778,7 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetHeader(true) .SetColor(new Color32(255, 44, 44, byte.MaxValue)); + UseUnshiftTriggerForNKs = new BooleanOptionItem(23872, "UseUnshiftTriggerForNKs", false, TabGroup.TaskSettings) .SetParent(UseUnshiftTrigger) .SetGameMode(CustomGameMode.Standard) @@ -1687,6 +1788,7 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetHeader(true) .SetColor(new Color32(255, 255, 44, byte.MaxValue)); + UsePhantomBasisForNKs = new BooleanOptionItem(23864, "UsePhantomBasisForNKs", false, TabGroup.TaskSettings) .SetGameMode(CustomGameMode.Standard) .SetParent(UsePhantomBasis) @@ -1701,9 +1803,11 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetHeader(true) .SetColor(Color.green); + OverrideScientistBasedRoles = new BooleanOptionItem(23855, "OverrideScientistBasedRoles", false, TabGroup.TaskSettings) .SetGameMode(CustomGameMode.Standard) .SetParent(EveryoneCanVent); + WhackAMole = new BooleanOptionItem(23856, "WhackAMole", false, TabGroup.TaskSettings) .SetGameMode(CustomGameMode.Standard) .SetParent(EveryoneCanVent); @@ -1712,10 +1816,12 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetColor(Color.magenta) .SetHeader(true); + SpawnAdditionalRefugeeWhenNKAlive = new BooleanOptionItem(23858, "SpawnAdditionalRefugeeWhenNKAlive", false, TabGroup.TaskSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(Color.magenta) .SetParent(SpawnAdditionalRefugeeOnImpsDead); + SpawnAdditionalRefugeeMinAlivePlayers = new IntegerOptionItem(23859, "SpawnAdditionalRefugeeMinAlivePlayers", new(1, 14, 1), 7, TabGroup.TaskSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(Color.magenta) @@ -1732,12 +1838,15 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetHeader(true) .SetColor(new Color32(239, 89, 175, byte.MaxValue)); + DisableCleanVent = new BooleanOptionItem(23001, "DisableCleanVent", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableCalibrateDistributor = new BooleanOptionItem(23002, "DisableCalibrateDistributor", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableChartCourse = new BooleanOptionItem(23003, "DisableChartCourse", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); @@ -1747,15 +1856,19 @@ namespace EHR DisableStabilizeSteering = new BooleanOptionItem(23004, "DisableStabilizeSteering", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableCleanO2Filter = new BooleanOptionItem(23005, "DisableCleanO2Filter", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableUnlockManifolds = new BooleanOptionItem(23006, "DisableUnlockManifolds", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisablePrimeShields = new BooleanOptionItem(23007, "DisablePrimeShields", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableMeasureWeather = new BooleanOptionItem(23008, "DisableMeasureWeather", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); @@ -1765,15 +1878,19 @@ namespace EHR DisableBuyBeverage = new BooleanOptionItem(23009, "DisableBuyBeverage", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableAssembleArtifact = new BooleanOptionItem(23010, "DisableAssembleArtifact", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableSortSamples = new BooleanOptionItem(23011, "DisableSortSamples", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableProcessData = new BooleanOptionItem(23012, "DisableProcessData", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableRunDiagnostics = new BooleanOptionItem(23013, "DisableRunDiagnostics", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); @@ -1783,12 +1900,15 @@ namespace EHR DisableRepairDrill = new BooleanOptionItem(23014, "DisableRepairDrill", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableAlignTelescope = new BooleanOptionItem(23015, "DisableAlignTelescope", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableRecordTemperature = new BooleanOptionItem(23016, "DisableRecordTemperature", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableFillCanisters = new BooleanOptionItem(23017, "DisableFillCanisters", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); @@ -1798,15 +1918,19 @@ namespace EHR DisableMonitorTree = new BooleanOptionItem(23018, "DisableMonitorTree", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableStoreArtifacts = new BooleanOptionItem(23019, "DisableStoreArtifacts", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisablePutAwayPistols = new BooleanOptionItem(23020, "DisablePutAwayPistols", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisablePutAwayRifles = new BooleanOptionItem(23021, "DisablePutAwayRifles", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableMakeBurger = new BooleanOptionItem(23022, "DisableMakeBurger", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); @@ -1816,30 +1940,39 @@ namespace EHR DisableCleanToilet = new BooleanOptionItem(23023, "DisableCleanToilet", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableDecontaminate = new BooleanOptionItem(23024, "DisableDecontaminate", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableSortRecords = new BooleanOptionItem(23025, "DisableSortRecords", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableFixShower = new BooleanOptionItem(23026, "DisableFixShower", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisablePickUpTowels = new BooleanOptionItem(23027, "DisablePickUpTowels", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisablePolishRuby = new BooleanOptionItem(23028, "DisablePolishRuby", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableDressMannequin = new BooleanOptionItem(23029, "DisableDressMannequin", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableRoastMarshmallow = new BooleanOptionItem(23030, "DisableRoastMarshmallow", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableCollectSamples = new BooleanOptionItem(23031, "DisableCollectSamples", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); + DisableReplaceParts = new BooleanOptionItem(23032, "DisableReplaceParts", false, TabGroup.TaskSettings) .SetParent(DisableShortTasks) .SetGameMode(CustomGameMode.Standard); @@ -1851,39 +1984,51 @@ namespace EHR DisableCommonTasks = new BooleanOptionItem(23100, "DisableCommonTasks", false, TabGroup.TaskSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(239, 89, 175, byte.MaxValue)); + DisableSwipeCard = new BooleanOptionItem(23101, "DisableSwipeCardTask", false, TabGroup.TaskSettings) .SetParent(DisableCommonTasks) .SetGameMode(CustomGameMode.Standard); + DisableFixWiring = new BooleanOptionItem(23102, "DisableFixWiring", false, TabGroup.TaskSettings) .SetParent(DisableCommonTasks) .SetGameMode(CustomGameMode.Standard); + DisableEnterIdCode = new BooleanOptionItem(23103, "DisableEnterIdCode", false, TabGroup.TaskSettings) .SetParent(DisableCommonTasks) .SetGameMode(CustomGameMode.Standard); + DisableInsertKeys = new BooleanOptionItem(23104, "DisableInsertKeys", false, TabGroup.TaskSettings) .SetParent(DisableCommonTasks) .SetGameMode(CustomGameMode.Standard); + DisableScanBoardingPass = new BooleanOptionItem(23105, "DisableScanBoardingPass", false, TabGroup.TaskSettings) .SetParent(DisableCommonTasks) .SetGameMode(CustomGameMode.Standard); + DisableCollectVegetables = new BooleanOptionItem(23106, "DisableCollectVegetables", false, TabGroup.TaskSettings) .SetParent(DisableCommonTasks) .SetGameMode(CustomGameMode.Standard); + DisableMineOres = new BooleanOptionItem(23107, "DisableMineOres", false, TabGroup.TaskSettings) .SetParent(DisableCommonTasks) .SetGameMode(CustomGameMode.Standard); + DisableExtractFuel = new BooleanOptionItem(23108, "DisableExtractFuel", false, TabGroup.TaskSettings) .SetParent(DisableCommonTasks) .SetGameMode(CustomGameMode.Standard); + DisableCatchFish = new BooleanOptionItem(23109, "DisableCatchFish", false, TabGroup.TaskSettings) .SetParent(DisableCommonTasks) .SetGameMode(CustomGameMode.Standard); + DisablePolishGem = new BooleanOptionItem(23110, "DisablePolishGem", false, TabGroup.TaskSettings) .SetParent(DisableCommonTasks) .SetGameMode(CustomGameMode.Standard); + DisableHelpCritter = new BooleanOptionItem(23111, "DisableHelpCritter", false, TabGroup.TaskSettings) .SetParent(DisableCommonTasks) .SetGameMode(CustomGameMode.Standard); + DisableHoistSupplies = new BooleanOptionItem(23112, "DisableHoistSupplies", false, TabGroup.TaskSettings) .SetParent(DisableCommonTasks) .SetGameMode(CustomGameMode.Standard); @@ -1894,15 +2039,19 @@ namespace EHR DisableLongTasks = new BooleanOptionItem(23150, "DisableLongTasks", false, TabGroup.TaskSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(239, 89, 175, byte.MaxValue)); + DisableSubmitScan = new BooleanOptionItem(23151, "DisableSubmitScanTask", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableUnlockSafe = new BooleanOptionItem(23152, "DisableUnlockSafeTask", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableStartReactor = new BooleanOptionItem(23153, "DisableStartReactorTask", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableResetBreaker = new BooleanOptionItem(23154, "DisableResetBreakerTask", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); @@ -1912,18 +2061,23 @@ namespace EHR DisableAlignEngineOutput = new BooleanOptionItem(23155, "DisableAlignEngineOutput", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableInspectSample = new BooleanOptionItem(23156, "DisableInspectSample", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableEmptyChute = new BooleanOptionItem(23157, "DisableEmptyChute", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableClearAsteroids = new BooleanOptionItem(23158, "DisableClearAsteroids", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableWaterPlants = new BooleanOptionItem(23159, "DisableWaterPlants", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableOpenWaterways = new BooleanOptionItem(23160, "DisableOpenWaterways", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); @@ -1933,21 +2087,27 @@ namespace EHR DisableReplaceWaterJug = new BooleanOptionItem(23161, "DisableReplaceWaterJug", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableRebootWifi = new BooleanOptionItem(23162, "DisableRebootWifi", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableDevelopPhotos = new BooleanOptionItem(23163, "DisableDevelopPhotos", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableRewindTapes = new BooleanOptionItem(23164, "DisableRewindTapes", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableStartFans = new BooleanOptionItem(23165, "DisableStartFans", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableFixAntenna = new BooleanOptionItem(23166, "DisableFixAntenna", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableBuildSandcastle = new BooleanOptionItem(23167, "DisableBuildSandcastle", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); @@ -1957,21 +2117,27 @@ namespace EHR DisableCrankGenerator = new BooleanOptionItem(23168, "DisableCrankGenerator", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableMonitorMushroom = new BooleanOptionItem(23169, "DisableMonitorMushroom", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisablePlayVideoGame = new BooleanOptionItem(23170, "DisablePlayVideoGame", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableFindSignal = new BooleanOptionItem(23171, "DisableFindSignal", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableThrowFisbee = new BooleanOptionItem(23172, "DisableThrowFisbee", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableLiftWeights = new BooleanOptionItem(23173, "DisableLiftWeights", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); + DisableCollectShells = new BooleanOptionItem(23174, "DisableCollectShells", false, TabGroup.TaskSettings) .SetParent(DisableLongTasks) .SetGameMode(CustomGameMode.Standard); @@ -1983,18 +2149,23 @@ namespace EHR DisableOtherTasks = new BooleanOptionItem(23200, "DisableOtherTasks", false, TabGroup.TaskSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(239, 89, 175, byte.MaxValue)); + DisableUploadData = new BooleanOptionItem(23205, "DisableUploadDataTask", false, TabGroup.TaskSettings) .SetParent(DisableOtherTasks) .SetGameMode(CustomGameMode.Standard); + DisableEmptyGarbage = new BooleanOptionItem(23206, "DisableEmptyGarbage", false, TabGroup.TaskSettings) .SetParent(DisableOtherTasks) .SetGameMode(CustomGameMode.Standard); + DisableFuelEngines = new BooleanOptionItem(23207, "DisableFuelEngines", false, TabGroup.TaskSettings) .SetParent(DisableOtherTasks) .SetGameMode(CustomGameMode.Standard); + DisableDivertPower = new BooleanOptionItem(23208, "DisableDivertPower", false, TabGroup.TaskSettings) .SetParent(DisableOtherTasks) .SetGameMode(CustomGameMode.Standard); + DisableActivateWeatherNodes = new BooleanOptionItem(23209, "DisableActivateWeatherNodes", false, TabGroup.TaskSettings) .SetParent(DisableOtherTasks) .SetGameMode(CustomGameMode.Standard); @@ -2008,12 +2179,15 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetColor(Color.yellow) .SetHeader(true); + GuesserMode = new BooleanOptionItem(19700, "GuesserMode", false, TabGroup.TaskSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(Color.yellow) .SetHeader(true); + CrewmatesCanGuess = new BooleanOptionItem(19710, "CrewmatesCanGuess", false, TabGroup.TaskSettings) .SetParent(GuesserMode); + ImpostorsCanGuess = new BooleanOptionItem(19711, "ImpostorsCanGuess", false, TabGroup.TaskSettings) .SetParent(GuesserMode); @@ -2021,16 +2195,22 @@ namespace EHR NeutralKillersCanGuess = new BooleanOptionItem(19712, "NeutralKillersCanGuess", false, TabGroup.TaskSettings) .SetParent(GuesserMode); + PassiveNeutralsCanGuess = new BooleanOptionItem(19713, "PassiveNeutralsCanGuess", false, TabGroup.TaskSettings) .SetParent(GuesserMode); + BetrayalAddonsCanGuess = new BooleanOptionItem(19719, "BetrayalAddonsCanGuess", false, TabGroup.TaskSettings) .SetParent(GuesserMode); + CanGuessAddons = new BooleanOptionItem(19714, "CanGuessAddons", true, TabGroup.TaskSettings) .SetParent(GuesserMode); + CrewCanGuessCrew = new BooleanOptionItem(19715, "CrewCanGuessCrew", true, TabGroup.TaskSettings) .SetParent(GuesserMode); + ImpCanGuessImp = new BooleanOptionItem(19716, "ImpCanGuessImp", true, TabGroup.TaskSettings) .SetParent(GuesserMode); + HideGuesserCommands = new BooleanOptionItem(19717, "GuesserTryHideMsg", true, TabGroup.TaskSettings) .SetParent(GuesserMode) .SetColor(Color.green); @@ -2050,6 +2230,7 @@ namespace EHR .SetColor(new Color32(147, 241, 240, byte.MaxValue)) .SetHeader(true) .SetGameMode(CustomGameMode.Standard); + SyncedButtonCount = new IntegerOptionItem(23310, "SyncedButtonCount", new(0, 100, 1), 10, TabGroup.GameSettings) .SetParent(SyncButtonMode) .SetValueFormat(OptionFormat.Times) @@ -2060,6 +2241,7 @@ namespace EHR AllAliveMeeting = new BooleanOptionItem(23400, "AllAliveMeeting", false, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(147, 241, 240, byte.MaxValue)); + AllAliveMeetingTime = new FloatOptionItem(23410, "AllAliveMeetingTime", new(1f, 300f, 1f), 10f, TabGroup.GameSettings) .SetParent(AllAliveMeeting) .SetValueFormat(OptionFormat.Seconds); @@ -2067,13 +2249,15 @@ namespace EHR EnableKillerLeftCommand = new BooleanOptionItem(44428, "EnableKillerLeftCommand", true, TabGroup.GameSettings) .SetColor(new Color32(147, 241, 240, byte.MaxValue)); - int i = 0; + var i = 0; + foreach (GameStateInfo s in Enum.GetValues()) { GameStateSettings[s] = new BooleanOptionItem(44429 + i, $"GameStateCommand.Show{s}", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetParent(EnableKillerLeftCommand) .SetColor(new Color32(147, 241, 240, byte.MaxValue)); + i++; } @@ -2095,10 +2279,12 @@ namespace EHR AdditionalEmergencyCooldown = new BooleanOptionItem(23500, "AdditionalEmergencyCooldown", false, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(147, 241, 240, byte.MaxValue)); + AdditionalEmergencyCooldownThreshold = new IntegerOptionItem(23510, "AdditionalEmergencyCooldownThreshold", new(1, 15, 1), 1, TabGroup.GameSettings) .SetParent(AdditionalEmergencyCooldown) .SetGameMode(CustomGameMode.Standard) .SetValueFormat(OptionFormat.Players); + AdditionalEmergencyCooldownTime = new FloatOptionItem(23511, "AdditionalEmergencyCooldownTime", new(1f, 60f, 1f), 1f, TabGroup.GameSettings) .SetParent(AdditionalEmergencyCooldown) .SetGameMode(CustomGameMode.Standard) @@ -2109,21 +2295,27 @@ namespace EHR VoteMode = new BooleanOptionItem(23600, "VoteMode", false, TabGroup.GameSettings) .SetColor(new Color32(147, 241, 240, byte.MaxValue)) .SetGameMode(CustomGameMode.Standard); + WhenSkipVote = new StringOptionItem(23610, "WhenSkipVote", VoteModes[..3], 0, TabGroup.GameSettings) .SetParent(VoteMode) .SetGameMode(CustomGameMode.Standard); + WhenSkipVoteIgnoreFirstMeeting = new BooleanOptionItem(23611, "WhenSkipVoteIgnoreFirstMeeting", false, TabGroup.GameSettings) .SetParent(WhenSkipVote) .SetGameMode(CustomGameMode.Standard); + WhenSkipVoteIgnoreNoDeadBody = new BooleanOptionItem(23612, "WhenSkipVoteIgnoreNoDeadBody", false, TabGroup.GameSettings) .SetParent(WhenSkipVote) .SetGameMode(CustomGameMode.Standard); + WhenSkipVoteIgnoreEmergency = new BooleanOptionItem(23613, "WhenSkipVoteIgnoreEmergency", false, TabGroup.GameSettings) .SetParent(WhenSkipVote) .SetGameMode(CustomGameMode.Standard); + WhenNonVote = new StringOptionItem(23700, "WhenNonVote", VoteModes, 0, TabGroup.GameSettings) .SetParent(VoteMode) .SetGameMode(CustomGameMode.Standard); + WhenTie = new StringOptionItem(23750, "WhenTie", TieModes, 0, TabGroup.GameSettings) .SetParent(VoteMode) .SetGameMode(CustomGameMode.Standard); @@ -2139,6 +2331,7 @@ namespace EHR LadderDeath = new BooleanOptionItem(23800, "LadderDeath", false, TabGroup.GameSettings) .SetHeader(true) .SetColor(new Color32(193, 255, 209, byte.MaxValue)); + LadderDeathChance = new StringOptionItem(23810, "LadderDeathChance", Rates[1..], 0, TabGroup.GameSettings) .SetParent(LadderDeath); @@ -2181,9 +2374,11 @@ namespace EHR .SetGameMode(CustomGameMode.Standard) .SetHeader(true) .SetColor(new Color32(217, 218, 255, byte.MaxValue)); + GhostCanSeeOtherVotes = new BooleanOptionItem(24400, "GhostCanSeeOtherVotes", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(217, 218, 255, byte.MaxValue)); + GhostCanSeeDeathReason = new BooleanOptionItem(24500, "GhostCanSeeDeathReason", true, TabGroup.GameSettings) .SetGameMode(CustomGameMode.Standard) .SetColor(new Color32(217, 218, 255, byte.MaxValue)); @@ -2216,7 +2411,7 @@ namespace EHR public static void SetupRoleOptions(int id, TabGroup tab, CustomRoles role, CustomGameMode customGameMode = CustomGameMode.Standard, bool zeroOne = false) { - StringOptionItem spawnOption = new StringOptionItem(id, role.ToString(), zeroOne ? RatesZeroOne : Rates, 0, tab).SetColor(Utils.GetRoleColor(role)) + var spawnOption = new StringOptionItem(id, role.ToString(), zeroOne ? RatesZeroOne : Rates, 0, tab).SetColor(Utils.GetRoleColor(role)) .SetHeader(true) .SetGameMode(customGameMode) as StringOptionItem; @@ -2232,7 +2427,7 @@ namespace EHR public static void SetupAdtRoleOptions(int id, CustomRoles role, CustomGameMode customGameMode = CustomGameMode.Standard, bool canSetNum = false, TabGroup tab = TabGroup.Addons, bool canSetChance = true, bool teamSpawnOptions = false, bool allowZeroCount = false) { - StringOptionItem spawnOption = new StringOptionItem(id, role.ToString(), RatesZeroOne, 0, tab).SetColor(Utils.GetRoleColor(role)) + var spawnOption = new StringOptionItem(id, role.ToString(), RatesZeroOne, 0, tab).SetColor(Utils.GetRoleColor(role)) .SetHeader(true) .SetGameMode(customGameMode) as StringOptionItem; @@ -2242,7 +2437,7 @@ namespace EHR .SetHidden(!canSetNum) .SetGameMode(customGameMode); - IntegerOptionItem spawnRateOption = new IntegerOptionItem(id + 2, "AdditionRolesSpawnRate", new(0, 100, 5), canSetChance ? 65 : 100, tab) + var spawnRateOption = new IntegerOptionItem(id + 2, "AdditionRolesSpawnRate", new(0, 100, 5), canSetChance ? 65 : 100, tab) .SetParent(spawnOption) .SetValueFormat(OptionFormat.Percent) .SetHidden(!canSetChance) @@ -2281,7 +2476,7 @@ namespace EHR public static void SetupSingleRoleOptions(int id, TabGroup tab, CustomRoles role, int count = 1, CustomGameMode customGameMode = CustomGameMode.Standard, bool zeroOne = false, bool hideMaxSetting = true) { - StringOptionItem spawnOption = new StringOptionItem(id, role.ToString(), zeroOne ? RatesZeroOne : Rates, 0, tab).SetColor(Utils.GetRoleColor(role)) + var spawnOption = new StringOptionItem(id, role.ToString(), zeroOne ? RatesZeroOne : Rates, 0, tab).SetColor(Utils.GetRoleColor(role)) .SetHeader(true) .SetGameMode(customGameMode) as StringOptionItem; @@ -2327,31 +2522,35 @@ namespace EHR private OverrideTasksData(int idStart, TabGroup tab, CustomRoles role) { Dictionary replacementDic = new() { { "%role%", role.ToColoredString() } }; + DoOverride = new BooleanOptionItem(idStart++, "doOverride", false, tab) .SetParent(CustomRoleSpawnChances[role]) .SetValueFormat(OptionFormat.None); + DoOverride.ReplacementDictionary = replacementDic; + AssignCommonTasks = new BooleanOptionItem(idStart++, "assignCommonTasks", true, tab) .SetParent(DoOverride) .SetValueFormat(OptionFormat.None); + AssignCommonTasks.ReplacementDictionary = replacementDic; + NumLongTasks = new IntegerOptionItem(idStart++, "roleLongTasksNum", new(0, 90, 1), 3, tab) .SetParent(DoOverride) .SetValueFormat(OptionFormat.Pieces); + NumLongTasks.ReplacementDictionary = replacementDic; + NumShortTasks = new IntegerOptionItem(idStart, "roleShortTasksNum", new(0, 90, 1), 3, tab) .SetParent(DoOverride) .SetValueFormat(OptionFormat.Pieces); + NumShortTasks.ReplacementDictionary = replacementDic; if (!AllData.ContainsKey(role)) - { AllData.Add(role, this); - } else - { Logger.Warn("OverrideTasksData created for duplicate CustomRoles", "OverrideTasksData"); - } } public static OverrideTasksData Create(int idStart, TabGroup tab, CustomRoles role) diff --git a/Modules/OptionItem/OptionItem.cs b/Modules/OptionItem/OptionItem.cs index d1002a797..f931eb37a 100644 --- a/Modules/OptionItem/OptionItem.cs +++ b/Modules/OptionItem/OptionItem.cs @@ -39,25 +39,15 @@ namespace EHR CurrentPreset = SingleValue; } else if (IsSingleValue) - { SingleValue = DefaultValue; - } else - { - for (int i = 0; i < NumPresets; i++) - { + for (var i = 0; i < NumPresets; i++) AllValues[i] = DefaultValue; - } - } if (FastOpts.TryAdd(id, this)) - { Options.Add(this); - } else - { Logger.Error($"Duplicate ID: {id} ({name})", "OptionItem"); - } } public int Id { get; } @@ -79,13 +69,9 @@ namespace EHR set { if (value == null) - { _replacementDictionary?.Clear(); - } else - { _replacementDictionary = value; - } } } @@ -187,10 +173,7 @@ namespace EHR // Getter public virtual string GetName(bool disableColor = false, bool console = false) { - if (Name.Contains("CTA.FLAG")) - { - return Utils.ColorString(NameColor, Translator.GetString("CTA.TeamEnabled.Prefix") + Name[8..] + Translator.GetString("CTA.TeamEnabled.Suffix")); - } + if (Name.Contains("CTA.FLAG")) return Utils.ColorString(NameColor, Translator.GetString("CTA.TeamEnabled.Prefix") + Name[8..] + Translator.GetString("CTA.TeamEnabled.Suffix")); return disableColor ? Translator.GetString(Name, ReplacementDictionary, console) : Utils.ColorString(NameColor, Translator.GetString(Name, ReplacementDictionary)); } @@ -235,12 +218,9 @@ namespace EHR { int LastParent = Id; - for (int i = 0; i < 5; i++) + for (var i = 0; i < 5; i++) { - if (AllOptions.First(x => x.Id == LastParent).Parent == null) - { - break; - } + if (AllOptions.First(x => x.Id == LastParent).Parent == null) break; LastParent = AllOptions.First(x => x.Id == LastParent).Parent.Id; } @@ -250,10 +230,7 @@ namespace EHR protected string ApplyFormat(string value) { - if (ValueFormat == OptionFormat.None) - { - return value; - } + if (ValueFormat == OptionFormat.None) return value; return string.Format(Translator.GetString("Format." + ValueFormat), value); } @@ -271,26 +248,17 @@ namespace EHR public void SetValue(int afterValue, bool doSave, bool doSync = true) { int beforeValue = CurrentValue; + if (IsSingleValue) - { SingleValue = afterValue; - } else - { AllValues[CurrentPreset] = afterValue; - } CallUpdateValueEvent(beforeValue, afterValue); Refresh(); - if (doSync) - { - SyncAllOptions(); - } + if (doSync) SyncAllOptions(); - if (doSave) - { - OptionSaver.Save(); - } + if (doSave) OptionSaver.Save(); } public virtual void SetValue(int afterValue, bool doSync = true) @@ -301,16 +269,10 @@ namespace EHR public void SetAllValues(int[] values) { if (values.Length == AllValues.Length) - { AllValues = values; - } else - { - for (int i = 0; i < values.Length; i++) - { + for (var i = 0; i < values.Length; i++) AllValues[i] = values[i]; - } - } } public static OptionItem operator ++(OptionItem item) @@ -327,10 +289,7 @@ namespace EHR { CurrentPreset = Math.Clamp(newPreset, 0, NumPresets - 1); - foreach (OptionItem op in AllOptions) - { - op.Refresh(); - } + foreach (OptionItem op in AllOptions) op.Refresh(); SyncAllOptions(); } @@ -342,9 +301,7 @@ namespace EHR || AmongUsClient.Instance.AmHost == false || PlayerControl.LocalPlayer == null ) - { return; - } RPC.SyncCustomSettingsRPC(targetId); } @@ -353,10 +310,7 @@ namespace EHR // EventArgs private void CallUpdateValueEvent(int beforeValue, int currentValue) { - if (UpdateValueEvent == null) - { - return; - } + if (UpdateValueEvent == null) return; try { diff --git a/Modules/OptionItem/ValueRule.cs b/Modules/OptionItem/ValueRule.cs index e30da6240..4b75bdc43 100644 --- a/Modules/OptionItem/ValueRule.cs +++ b/Modules/OptionItem/ValueRule.cs @@ -5,9 +5,7 @@ namespace EHR public abstract class ValueRule(T minValue, T maxValue, T step) { public ValueRule((T, T, T) tuple) - : this(tuple.Item1, tuple.Item2, tuple.Item3) - { - } + : this(tuple.Item1, tuple.Item2, tuple.Item3) { } public T MinValue { get; protected set; } = minValue; public T MaxValue { get; protected set; } = maxValue; @@ -21,14 +19,10 @@ namespace EHR public class IntegerValueRule : ValueRule { public IntegerValueRule(int minValue, int maxValue, int step) - : base(minValue, maxValue, step) - { - } + : base(minValue, maxValue, step) { } public IntegerValueRule((int, int, int) tuple) - : base(tuple) - { - } + : base(tuple) { } public static implicit operator IntegerValueRule((int, int, int) tuple) { @@ -39,10 +33,7 @@ namespace EHR { int MaxIndex = (MaxValue - MinValue) / Step; value %= MaxIndex + 1; - if (value < 0) - { - value = MaxIndex; - } + if (value < 0) value = MaxIndex; return value; } @@ -61,14 +52,10 @@ namespace EHR public class FloatValueRule : ValueRule { public FloatValueRule(float minValue, float maxValue, float step) - : base(minValue, maxValue, step) - { - } + : base(minValue, maxValue, step) { } public FloatValueRule((float, float, float) tuple) - : base(tuple) - { - } + : base(tuple) { } public static implicit operator FloatValueRule((float, float, float) tuple) { @@ -77,12 +64,9 @@ namespace EHR public override int RepeatIndex(int value) { - int MaxIndex = (int)((MaxValue - MinValue) / Step); + var MaxIndex = (int)((MaxValue - MinValue) / Step); value %= MaxIndex + 1; - if (value < 0) - { - value = MaxIndex; - } + if (value < 0) value = MaxIndex; return value; } diff --git a/Modules/OptionSaver.cs b/Modules/OptionSaver.cs index 50a0bf343..24227509f 100644 --- a/Modules/OptionSaver.cs +++ b/Modules/OptionSaver.cs @@ -20,10 +20,7 @@ namespace EHR.Modules if (DefaultPresetFileInfo.Exists) { string presetNmber = File.ReadAllText(DefaultPresetFileInfo.FullName); - if (int.TryParse(presetNmber, out int number) && number is >= 0 and <= OptionItem.NumPresets - 1) - { - return number; - } + if (int.TryParse(presetNmber, out int number) && number is >= 0 and <= OptionItem.NumPresets - 1) return number; } return 0; @@ -37,37 +34,27 @@ namespace EHR.Modules SaveDataDirectoryInfo.Attributes |= FileAttributes.Hidden; } - if (!OptionSaverFileInfo.Exists) - { - OptionSaverFileInfo.Create().Dispose(); - } + if (!OptionSaverFileInfo.Exists) OptionSaverFileInfo.Create().Dispose(); - if (!DefaultPresetFileInfo.Exists) - { - DefaultPresetFileInfo.Create().Dispose(); - } + if (!DefaultPresetFileInfo.Exists) DefaultPresetFileInfo.Create().Dispose(); } private static SerializableOptionsData GenerateOptionsData() { Dictionary singleOptions = []; Dictionary presetOptions = []; + foreach (OptionItem option in OptionItem.AllOptions) { if (option.IsSingleValue) { - if (!singleOptions.TryAdd(option.Id, option.SingleValue)) - { - EHR.Logger.Warn($"Duplicate SingleOption ID: {option.Id}", "Options Load"); - } - } - else if (!presetOptions.TryAdd(option.Id, option.AllValues)) - { - EHR.Logger.Warn($"Duplicate preset option ID: {option.Id}", "Options Load"); + if (!singleOptions.TryAdd(option.Id, option.SingleValue)) EHR.Logger.Warn($"Duplicate SingleOption ID: {option.Id}", "Options Load"); } + else if (!presetOptions.TryAdd(option.Id, option.AllValues)) EHR.Logger.Warn($"Duplicate preset option ID: {option.Id}", "Options Load"); } DefaultPresetNumber = singleOptions[0]; + return new() { Version = Version, @@ -87,29 +74,19 @@ namespace EHR.Modules Dictionary singleOptions = serializableOptionsData.SingleOptions; Dictionary presetOptions = serializableOptionsData.PresetOptions; + foreach ((int id, int value) in singleOptions) - { if (OptionItem.FastOptions.TryGetValue(id, out OptionItem optionItem)) - { optionItem.SetValue(value, doSave: false); - } - } foreach ((int id, int[] values) in presetOptions) - { if (OptionItem.FastOptions.TryGetValue(id, out OptionItem optionItem)) - { optionItem.SetAllValues(values); - } - } } public static void Save() { - if (AmongUsClient.Instance != null && !AmongUsClient.Instance.AmHost) - { - return; - } + if (AmongUsClient.Instance != null && !AmongUsClient.Instance.AmHost) return; string jsonString = JsonSerializer.Serialize(GenerateOptionsData(), new JsonSerializerOptions { WriteIndented = true }); File.WriteAllText(OptionSaverFileInfo.FullName, jsonString); diff --git a/Modules/OptionShower.cs b/Modules/OptionShower.cs index f1cb736d2..98c8b9c6a 100644 --- a/Modules/OptionShower.cs +++ b/Modules/OptionShower.cs @@ -14,9 +14,7 @@ namespace EHR private static long LastUpdate; - static OptionShower() - { - } + static OptionShower() { } public static string GetTextNoFresh() { @@ -32,23 +30,24 @@ namespace EHR public static string GetText() { StringBuilder sb = new(); + Pages = [ GameOptionsManager.Instance.CurrentGameOptions.ToHudString(GameData.Instance ? GameData.Instance.PlayerCount : 10).Split('\n').SkipLast(8).Join(delimiter: "\n") + "\n\n" ]; sb.Append($"{Options.GameMode.GetName()}: {Options.GameMode.GetString()}\n\n"); + if (Options.HideGameSettings.GetBool() && !AmongUsClient.Instance.AmHost) - { sb.Append($"{GetString("Message.HideGameSettings")}"); - } else { if (Options.CurrentGameMode == CustomGameMode.Standard) { sb.Append($"{Utils.GetRoleName(CustomRoles.GM)}: {(Main.GM.Value ? GetString("RoleRate") : GetString("RoleOff"))}\n\n"); sb.Append(GetString("ActiveRolesList")).Append('\n'); - int count = 4; + var count = 4; + foreach (KeyValuePair kvp in Options.CustomRoleSpawnChances) { if (kvp.Value.GameMode is CustomGameMode.Standard or CustomGameMode.All && kvp.Value.GetBool()) @@ -71,14 +70,12 @@ namespace EHR Pages.Add(""); sb.Append($"{Utils.GetRoleName(CustomRoles.GM)}: {(Main.GM.Value ? GetString("RoleRate") : GetString("RoleOff"))}\n\n"); + if (Options.CurrentGameMode != CustomGameMode.HideAndSeek) { foreach (KeyValuePair kvp in Options.CustomRoleSpawnChances) { - if (!kvp.Key.IsEnable() || kvp.Value.IsHiddenOn(Options.CurrentGameMode)) - { - continue; - } + if (!kvp.Key.IsEnable() || kvp.Value.IsHiddenOn(Options.CurrentGameMode)) continue; sb.Append('\n'); sb.Append($"{Utils.ColorString(Utils.GetRoleColor(kvp.Key), Utils.GetRoleName(kvp.Key))}: {kvp.Value.GetString()} ×{kvp.Key.GetCount()}\n"); @@ -90,37 +87,25 @@ namespace EHR { if (opt.Id is >= 90000 and (< 600000 or > 700000) && !opt.IsHiddenOn(Options.CurrentGameMode) && opt.Parent == null && !opt.IsText) { - if (opt.IsHeader) - { - sb.Append('\n'); - } + if (opt.IsHeader) sb.Append('\n'); sb.Append($"{opt.GetName()}: {opt.GetString()}\n"); - if (opt.GetBool()) - { - ShowChildren(opt, ref sb, Color.white, 1); - } + if (opt.GetBool()) ShowChildren(opt, ref sb, Color.white, 1); } } } string[] tmp = sb.ToString().Split("\n\n"); + foreach (string str in tmp) { if (Pages[^1].Count(c => c == '\n') + 1 + str.Count(c => c == '\n') + 1 > 44) - { Pages.Add(str + "\n\n"); - } else - { Pages[^1] += str + "\n\n"; - } } - if (CurrentPage >= Pages.Count) - { - CurrentPage = Pages.Count - 1; - } + if (CurrentPage >= Pages.Count) CurrentPage = Pages.Count - 1; return $"{Pages[CurrentPage]}{GetString("PressTabToNextPage")}({CurrentPage + 1}/{Pages.Count})"; } @@ -128,28 +113,19 @@ namespace EHR public static void Next() { CurrentPage++; - if (CurrentPage >= Pages.Count) - { - CurrentPage = 0; - } + if (CurrentPage >= Pages.Count) CurrentPage = 0; } private static void ShowChildren(OptionItem option, ref StringBuilder sb, Color color, int deep = 0) { foreach (var opt in option.Children.Select((v, i) => new { Value = v, Index = i + 1 })) { - if (opt.Value.Name == "Maximum") - { - continue; - } + if (opt.Value.Name == "Maximum") continue; sb.Append(string.Concat(Enumerable.Repeat(Utils.ColorString(color, "┃"), deep - 1))); sb.Append(Utils.ColorString(color, opt.Index == option.Children.Count ? "┗ " : "┣ ")); sb.Append($"{opt.Value.GetName()}: {opt.Value.GetString()}\n"); - if (opt.Value.GetBool()) - { - ShowChildren(opt.Value, ref sb, color, deep + 1); - } + if (opt.Value.GetBool()) ShowChildren(opt.Value, ref sb, color, deep + 1); } } } diff --git a/Modules/RPC.cs b/Modules/RPC.cs index 01b6241b4..47131112c 100644 --- a/Modules/RPC.cs +++ b/Modules/RPC.cs @@ -167,20 +167,15 @@ namespace EHR.Modules public static bool Prefix(PlayerControl __instance, [HarmonyArgument(0)] byte callId, [HarmonyArgument(1)] MessageReader reader) { - RpcCalls rpcType = (RpcCalls)callId; + var rpcType = (RpcCalls)callId; MessageReader subReader = MessageReader.Get(reader); - if (EAC.ReceiveRpc(__instance, callId, reader)) - { - return false; - } + if (EAC.ReceiveRpc(__instance, callId, reader)) return false; Logger.Info($"From ID: {__instance?.Data?.PlayerId} ({(__instance?.Data?.PlayerId == 0 ? "Host" : __instance?.Data?.PlayerName)}) : {callId} ({RPC.GetRpcName(callId)})", "ReceiveRPC"); + if (callId == 11 && __instance != null) { - if (!ReportDeadBodyRPCs.ContainsKey(__instance.PlayerId)) - { - ReportDeadBodyRPCs.TryAdd(__instance.PlayerId, 0); - } + if (!ReportDeadBodyRPCs.ContainsKey(__instance.PlayerId)) ReportDeadBodyRPCs.TryAdd(__instance.PlayerId, 0); ReportDeadBodyRPCs[__instance.PlayerId]++; Logger.Info($"ReportDeadBody RPC count: {ReportDeadBodyRPCs[__instance.PlayerId]}, from {__instance.Data?.PlayerName}", "EAC"); @@ -191,15 +186,12 @@ namespace EHR.Modules case RpcCalls.SetName: subReader.ReadUInt32(); string name = subReader.ReadString(); - if (subReader.BytesRemaining > 0 && subReader.ReadBoolean()) - { - return false; - } + if (subReader.BytesRemaining > 0 && subReader.ReadBoolean()) return false; Logger.Info($"RPC Set Name For Player: {__instance.GetNameWithRole().RemoveHtmlTags()} => {name}", "SetName"); break; case RpcCalls.SetRole: - RoleTypes role = (RoleTypes)subReader.ReadUInt16(); + var role = (RoleTypes)subReader.ReadUInt16(); bool canOverriddenRole = subReader.ReadBoolean(); Logger.Info($"RPC Set Role For Player: {__instance.GetRealName()} => {role} CanOverrideRole: {canOverriddenRole}", "SetRole"); break; @@ -207,10 +199,7 @@ namespace EHR.Modules string text = subReader.ReadString(); Logger.Info($"{__instance.GetNameWithRole().RemoveHtmlTags()}:{text}", "ReceiveChat"); ChatCommands.OnReceiveChat(__instance, text, out bool canceled); - if (canceled) - { - return false; - } + if (canceled) return false; break; case RpcCalls.StartMeeting: @@ -229,15 +218,9 @@ namespace EHR.Modules if (__instance != null && !__instance.IsHost() && Enum.IsDefined(typeof(CustomRPC), (int)callId) && !TrustedRpc(callId)) { Logger.Warn($"{__instance.Data?.PlayerName}:{callId}({RPC.GetRpcName(callId)}) canceled because it was sent by someone other than the host.", "CustomRPC"); - if (!AmongUsClient.Instance.AmHost) - { - return false; - } + if (!AmongUsClient.Instance.AmHost) return false; - if (!EAC.ReceiveInvalidRpc(__instance, callId)) - { - return false; - } + if (!EAC.ReceiveInvalidRpc(__instance, callId)) return false; AmongUsClient.Instance.KickPlayer(__instance.GetClientId(), false); Logger.Warn($"The RPC received from {__instance.Data?.PlayerName} is not trusted, so they were kicked.", "Kick"); @@ -245,10 +228,7 @@ namespace EHR.Modules return false; } - if (__instance != null && (!ReportDeadBodyRPCs.TryGetValue(__instance.PlayerId, out int times) || times <= 4)) - { - return true; - } + if (__instance != null && (!ReportDeadBodyRPCs.TryGetValue(__instance.PlayerId, out int times) || times <= 4)) return true; AmongUsClient.Instance.KickPlayer(__instance.GetClientId(), true); Logger.Warn($"{__instance?.Data?.PlayerName} has sent 5 or more ReportDeadBody RPCs in the last 1 second, they were banned for hacking.", "EAC"); @@ -258,11 +238,8 @@ namespace EHR.Modules public static void Postfix(PlayerControl __instance, [HarmonyArgument(0)] byte callId, [HarmonyArgument(1)] MessageReader reader) { - CustomRPC rpcType = (CustomRPC)callId; - if (AmongUsClient.Instance.AmHost && !TrustedRpc(callId)) - { - return; - } + var rpcType = (CustomRPC)callId; + if (AmongUsClient.Instance.AmHost && !TrustedRpc(callId)) return; switch (rpcType) { @@ -274,12 +251,14 @@ namespace EHR.Modules ChatUpdatePatch.DoBlockChat = true; Main.OverrideWelcomeMsg = string.Format(GetString("RpcAntiBlackOutNotifyInLobby"), __instance?.Data?.PlayerName, GetString("EndWhenPlayerBug")); LateTask.New(() => { Logger.SendInGame(string.Format(GetString("RpcAntiBlackOutEndGame"), __instance?.Data?.PlayerName) /*, true*/); }, 3f, "Anti-Black Msg SendInGame"); + LateTask.New(() => { CustomWinnerHolder.ResetAndSetWinner(CustomWinner.Error); GameManager.Instance.LogicFlow.CheckEndCriteria(); RPC.ForceEndGame(CustomWinner.Error); }, 5.5f, "Anti-Black End Game"); + LateTask.New(() => ChatUpdatePatch.DoBlockChat = false, 6f, log: false); } else if (GameStates.IsOnlineGame) @@ -300,14 +279,9 @@ namespace EHR.Modules try { - if (!Main.PlayerVersion.ContainsKey(__instance.PlayerId)) - { - RPC.RpcVersionCheck(); - } - } - catch - { + if (!Main.PlayerVersion.ContainsKey(__instance.PlayerId)) RPC.RpcVersionCheck(); } + catch { } Main.PlayerVersion[__instance.PlayerId] = new(version, tag, forkId); @@ -331,10 +305,7 @@ namespace EHR.Modules { Logger.Warn($"{__instance?.Data?.PlayerName}({__instance?.PlayerId}): error during version check", "RpcVersionCheck"); Utils.ThrowException(e); - if (GameStates.InGame || AmongUsClient.Instance.IsGameStarted) - { - break; - } + if (GameStates.InGame || AmongUsClient.Instance.IsGameStarted) break; LateTask.New(() => { @@ -352,10 +323,7 @@ namespace EHR.Modules } case CustomRPC.SyncCustomSettings: { - if (AmongUsClient.Instance.AmHost) - { - break; - } + if (AmongUsClient.Instance.AmHost) break; List listOptions = []; int startAmount = reader.ReadInt32(); @@ -364,10 +332,7 @@ namespace EHR.Modules int countAllOptions = OptionItem.AllOptions.Count; // Add Options - for (int option = startAmount; option < countAllOptions && option <= lastAmount; option++) - { - listOptions.Add(OptionItem.AllOptions[option]); - } + for (int option = startAmount; option < countAllOptions && option <= lastAmount; option++) listOptions.Add(OptionItem.AllOptions[option]); int countOptions = listOptions.Count; Logger.Msg($"StartAmount: {startAmount} - LastAmount: {lastAmount} ({startAmount}/{lastAmount}) :--: ListOptionsCount: {countOptions} - AllOptions: {countAllOptions} ({countOptions}/{countAllOptions})", "SyncCustomSettings"); @@ -379,9 +344,7 @@ namespace EHR.Modules { option.SetValue(reader.ReadPackedInt32()); } - catch - { - } + catch { } } OptionShower.GetText(); @@ -400,7 +363,7 @@ namespace EHR.Modules case CustomRPC.PlaySound: { byte playerID = reader.ReadByte(); - Sounds sound = (Sounds)reader.ReadByte(); + var sound = (Sounds)reader.ReadByte(); RPC.PlaySound(playerID, sound); break; } @@ -414,17 +377,14 @@ namespace EHR.Modules { Main.AllClientRealNames.Clear(); int num2 = reader.ReadPackedInt32(); - for (int i = 0; i < num2; i++) - { - Main.AllClientRealNames.TryAdd(reader.ReadInt32(), reader.ReadString()); - } + for (var i = 0; i < num2; i++) Main.AllClientRealNames.TryAdd(reader.ReadInt32(), reader.ReadString()); break; } case CustomRPC.SetCustomRole: { byte CustomRoleTargetId = reader.ReadByte(); - CustomRoles role = (CustomRoles)reader.ReadPackedInt32(); + var role = (CustomRoles)reader.ReadPackedInt32(); bool replaceAllAddons = reader.ReadBoolean(); RPC.SetCustomRole(CustomRoleTargetId, role, replaceAllAddons); break; @@ -443,27 +403,20 @@ namespace EHR.Modules case CustomRPC.RemoveSubRole: { byte id = reader.ReadByte(); + if (reader.ReadPackedInt32() == 2) - { Main.PlayerStates[id].SubRoles.Clear(); - } else - { Main.PlayerStates[id].RemoveSubRole((CustomRoles)reader.ReadPackedInt32()); - } break; } case CustomRPC.Arrow: { if (reader.ReadBoolean()) - { TargetArrow.ReceiveRPC(reader); - } else - { LocateArrow.ReceiveRPC(reader); - } break; } @@ -503,7 +456,7 @@ namespace EHR.Modules } case CustomRPC.FixModdedClientCNO: { - PlayerControl CNO = reader.ReadNetObject(); + var CNO = reader.ReadNetObject(); bool active = reader.ReadBoolean(); CNO.transform.FindChild("Names").FindChild("NameText_TMP").gameObject.SetActive(active); break; @@ -511,9 +464,10 @@ namespace EHR.Modules case CustomRPC.SyncGeneralOptions: { byte id = reader.ReadByte(); - CustomRoles role = (CustomRoles)reader.ReadPackedInt32(); + var role = (CustomRoles)reader.ReadPackedInt32(); bool dead = reader.ReadBoolean(); - PlayerState.DeathReason dr = (PlayerState.DeathReason)reader.ReadPackedInt32(); + var dr = (PlayerState.DeathReason)reader.ReadPackedInt32(); + if (Main.PlayerStates.TryGetValue(id, out PlayerState state)) { state.MainRole = role; @@ -529,10 +483,7 @@ namespace EHR.Modules } case CustomRPC.RequestSendMessage: { - if (!AmongUsClient.Instance.AmHost) - { - break; - } + if (!AmongUsClient.Instance.AmHost) break; string text = reader.ReadString(); byte sendTo = reader.ReadByte(); @@ -548,6 +499,7 @@ namespace EHR.Modules int customRole = reader.ReadPackedInt32(); bool playSound = reader.ReadBoolean(); OptionItem key = OptionItem.AllOptions[item]; + switch (typeId) { case 0: @@ -565,10 +517,7 @@ namespace EHR.Modules byte id = reader.ReadByte(); byte target = reader.ReadByte(); bool isFinished = reader.ReadBoolean(); - if (Main.PlayerStates[id].Role is not Postman pm) - { - break; - } + if (Main.PlayerStates[id].Role is not Postman pm) break; pm.Target = target; pm.IsFinished = isFinished; @@ -576,20 +525,14 @@ namespace EHR.Modules } case CustomRPC.SyncChangeling: { - if (Main.PlayerStates[reader.ReadByte()].Role is not Changeling changeling) - { - break; - } + if (Main.PlayerStates[reader.ReadByte()].Role is not Changeling changeling) break; changeling.CurrentRole = (CustomRoles)reader.ReadPackedInt32(); break; } case CustomRPC.SyncTiger: { - if (Main.PlayerStates[reader.ReadByte()].Role is not Tiger tiger) - { - break; - } + if (Main.PlayerStates[reader.ReadByte()].Role is not Tiger tiger) break; tiger.EnrageTimer = reader.ReadSingle(); break; @@ -597,10 +540,7 @@ namespace EHR.Modules case CustomRPC.SyncSentry: { byte id = reader.ReadByte(); - if (Main.PlayerStates[id].Role is not Crewmate.Sentry sentry) - { - break; - } + if (Main.PlayerStates[id].Role is not Crewmate.Sentry sentry) break; sentry.MonitoredRoom = Utils.GetPlayerById(id).GetPlainShipRoom(); break; @@ -716,6 +656,7 @@ namespace EHR.Modules byte id = reader.ReadByte(); (Main.PlayerStates[id].Role as Sniper)?.ReceiveRPC(reader); } + break; case CustomRPC.SyncSpy: { @@ -753,6 +694,7 @@ namespace EHR.Modules byte targetId = reader.ReadByte(); (Main.PlayerStates[hitmanId].Role as Hitman)?.ReceiveRPC(targetId); } + break; case CustomRPC.SetWeaponMasterMode: { @@ -783,11 +725,9 @@ namespace EHR.Modules { Main.LoversPlayers.Clear(); int count = reader.ReadInt32(); - for (int i = 0; i < count; i++) - { - Main.LoversPlayers.Add(Utils.GetPlayerById(reader.ReadByte())); - } + for (var i = 0; i < count; i++) Main.LoversPlayers.Add(Utils.GetPlayerById(reader.ReadByte())); } + break; case CustomRPC.SetExecutionerTarget: { @@ -814,9 +754,10 @@ namespace EHR.Modules byte id = reader.ReadByte(); int count = reader.ReadInt32(); int state = reader.ReadInt32(); - FireWorks.FireWorksState newState = (FireWorks.FireWorksState)state; + var newState = (FireWorks.FireWorksState)state; (Main.PlayerStates[id].Role as FireWorks)?.ReceiveRPC(count, newState); } + break; case CustomRPC.SyncMycologist: { @@ -832,10 +773,7 @@ namespace EHR.Modules { byte arsonistId = reader.ReadByte(); byte dousingTargetId = reader.ReadByte(); - if (PlayerControl.LocalPlayer.PlayerId == arsonistId) - { - Arsonist.CurrentDousingTarget = dousingTargetId; - } + if (PlayerControl.LocalPlayer.PlayerId == arsonistId) Arsonist.CurrentDousingTarget = dousingTargetId; break; } @@ -843,10 +781,7 @@ namespace EHR.Modules { byte arsonistId1 = reader.ReadByte(); byte doTargetId = reader.ReadByte(); - if (PlayerControl.LocalPlayer.PlayerId == arsonistId1) - { - Revolutionist.CurrentDrawTarget = doTargetId; - } + if (PlayerControl.LocalPlayer.PlayerId == arsonistId1) Revolutionist.CurrentDrawTarget = doTargetId; break; } @@ -864,6 +799,7 @@ namespace EHR.Modules { byte id = reader.ReadByte(); int operate = reader.ReadInt32(); + if (operate == 1) { byte victim = reader.ReadByte(); @@ -888,10 +824,7 @@ namespace EHR.Modules { uint clientId = reader.ReadPackedUInt32(); bool show = reader.ReadBoolean(); - if (AmongUsClient.Instance.ClientId == clientId) - { - HudManager.Instance.Chat.SetVisible(show); - } + if (AmongUsClient.Instance.ClientId == clientId) HudManager.Instance.Chat.SetVisible(show); break; } @@ -941,6 +874,7 @@ namespace EHR.Modules bool isOdd = reader.ReadBoolean(); (Main.PlayerStates[id].Role as Greedier)?.ReceiveRPC(isOdd); } + break; case CustomRPC.SetCollectorVotes: { @@ -970,6 +904,7 @@ namespace EHR.Modules long lastUpdate = long.Parse(reader.ReadString()); (Main.PlayerStates[id].Role as Chronomancer)?.ReceiveRPC(isRampaging, chargePercent, lastUpdate); } + break; case CustomRPC.SetMedicalerProtectList: { @@ -991,10 +926,7 @@ namespace EHR.Modules { Main.AllPlayerNames = []; int num = reader.ReadInt32(); - for (int i = 0; i < num; i++) - { - Main.AllPlayerNames.TryAdd(reader.ReadByte(), reader.ReadString()); - } + for (var i = 0; i < num; i++) Main.AllPlayerNames.TryAdd(reader.ReadByte(), reader.ReadString()); break; } @@ -1003,12 +935,14 @@ namespace EHR.Modules byte id = reader.ReadByte(); (Main.PlayerStates[id].Role as Mafioso)?.ReceiveRPC(reader); } + break; case CustomRPC.SyncMafiosoPistolCD: { byte id = reader.ReadByte(); (Main.PlayerStates[id].Role as Mafioso)?.ReceiveRPCSyncPistolCD(reader); } + break; case CustomRPC.SyncNameNotify: { @@ -1040,6 +974,7 @@ namespace EHR.Modules byte id = reader.ReadByte(); (Main.PlayerStates[id].Role as Swooper)?.ReceiveRPC(reader); } + break; case CustomRPC.SetAlchemistTimer: { @@ -1075,6 +1010,7 @@ namespace EHR.Modules byte targetId = reader.ReadByte(); (Main.PlayerStates[id].Role as EvilDiviner)?.ReceiveRPC(targetId); } + break; case CustomRPC.SyncHookshot: { @@ -1104,10 +1040,7 @@ namespace EHR.Modules case CustomRPC.KillFlash: { Utils.FlashColor(new(1f, 0f, 0f, 0.3f)); - if (Constants.ShouldPlaySfx()) - { - RPC.PlaySound(PlayerControl.LocalPlayer.PlayerId, Sounds.KillSound); - } + if (Constants.ShouldPlaySfx()) RPC.PlaySound(PlayerControl.LocalPlayer.PlayerId, Sounds.KillSound); break; } @@ -1123,7 +1056,7 @@ namespace EHR.Modules } case CustomRPC.SetJailorTarget: { - Jailor.ReceiveRPC(reader, true); + Jailor.ReceiveRPC(reader); break; } case CustomRPC.SetWwTimer: @@ -1131,6 +1064,7 @@ namespace EHR.Modules byte id = reader.ReadByte(); (Main.PlayerStates[id].Role as Werewolf)?.ReceiveRPC(reader); } + break; case CustomRPC.SetNiceSwapperVotes: { @@ -1156,13 +1090,10 @@ namespace EHR.Modules break; } - PlayerControl killer = reader.ReadNetObject(); - PlayerControl target = reader.ReadNetObject(); + var killer = reader.ReadNetObject(); + var target = reader.ReadNetObject(); - if (!killer.IsAlive() || !target.IsAlive() || AntiBlackout.SkipTasks || target.inMovingPlat || target.onLadder || target.inVent || MeetingHud.Instance) - { - break; - } + if (!killer.IsAlive() || !target.IsAlive() || AntiBlackout.SkipTasks || target.inMovingPlat || target.onLadder || target.inVent || MeetingHud.Instance) break; FFAManager.OnPlayerAttack(killer, target); break; @@ -1179,23 +1110,14 @@ namespace EHR.Modules if (targetId != -1) { ClientData client = Utils.GetClientById(targetId); - if (client == null || client.Character == null || !Main.PlayerVersion.ContainsKey(client.Character.PlayerId)) - { - return; - } + if (client == null || client.Character == null || !Main.PlayerVersion.ContainsKey(client.Character.PlayerId)) return; } - if (!AmongUsClient.Instance.AmHost || PlayerControl.AllPlayerControls.Count <= 1 || (AmongUsClient.Instance.AmHost == false && PlayerControl.LocalPlayer == null)) - { - return; - } + if (!AmongUsClient.Instance.AmHost || PlayerControl.AllPlayerControls.Count <= 1 || (AmongUsClient.Instance.AmHost == false && PlayerControl.LocalPlayer == null)) return; int amount = OptionItem.AllOptions.Count; int divideBy = amount / 10; - for (int i = 0; i <= 10; i++) - { - SyncOptionsBetween(i * divideBy, (i + 1) * divideBy, targetId); - } + for (var i = 0; i <= 10; i++) SyncOptionsBetween(i * divideBy, (i + 1) * divideBy, targetId); } private static void SyncOptionsBetween(int startAmount, int lastAmount, int targetId = -1) @@ -1203,16 +1125,10 @@ namespace EHR.Modules if (targetId != -1) { ClientData client = Utils.GetClientById(targetId); - if (client == null || client.Character == null || !Main.PlayerVersion.ContainsKey(client.Character.PlayerId)) - { - return; - } + if (client == null || client.Character == null || !Main.PlayerVersion.ContainsKey(client.Character.PlayerId)) return; } - if (!AmongUsClient.Instance.AmHost || PlayerControl.AllPlayerControls.Count <= 1 || (AmongUsClient.Instance.AmHost == false && PlayerControl.LocalPlayer == null)) - { - return; - } + if (!AmongUsClient.Instance.AmHost || PlayerControl.AllPlayerControls.Count <= 1 || (AmongUsClient.Instance.AmHost == false && PlayerControl.LocalPlayer == null)) return; int amountAllOptions = OptionItem.AllOptions.Count; @@ -1223,29 +1139,20 @@ namespace EHR.Modules List listOptions = []; // Add Options - for (int option = startAmount; option < amountAllOptions && option <= lastAmount; option++) - { - listOptions.Add(OptionItem.AllOptions[option]); - } + for (int option = startAmount; option < amountAllOptions && option <= lastAmount; option++) listOptions.Add(OptionItem.AllOptions[option]); int countListOptions = listOptions.Count; Logger.Msg($"StartAmount: {startAmount} - LastAmount: {lastAmount} ({startAmount}/{lastAmount}) :--: ListOptionsCount: {countListOptions} - AllOptions: {amountAllOptions} ({countListOptions}/{amountAllOptions})", "SyncCustomSettings"); // Sync Settings - foreach (OptionItem option in listOptions) - { - writer.WritePacked(option.GetValue()); - } + foreach (OptionItem option in listOptions) writer.WritePacked(option.GetValue()); AmongUsClient.Instance.FinishRpcImmediately(writer); } public static void PlaySoundRPC(byte PlayerID, Sounds sound) { - if (AmongUsClient.Instance.AmHost) - { - PlaySound(PlayerID, sound); - } + if (AmongUsClient.Instance.AmHost) PlaySound(PlayerID, sound); MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.PlaySound, SendOption.Reliable); writer.Write(PlayerID); @@ -1255,13 +1162,11 @@ namespace EHR.Modules public static void SyncAllPlayerNames() { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncAllPlayerNames, SendOption.Reliable); writer.Write(Main.AllPlayerNames.Count); + foreach (KeyValuePair name in Main.AllPlayerNames) { writer.Write(name.Key); @@ -1273,20 +1178,14 @@ namespace EHR.Modules public static void SendGameData(int clientId = -1) { - foreach (NetworkedPlayerInfo innerNetObject in GameData.Instance.AllPlayers) - { - innerNetObject.SetDirtyBit(uint.MaxValue); - } + foreach (NetworkedPlayerInfo innerNetObject in GameData.Instance.AllPlayers) innerNetObject.SetDirtyBit(uint.MaxValue); AmongUsClient.Instance.SendAllStreamedObjects(); } public static void ShowPopUp(this PlayerControl pc, string msg) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.ShowPopUp, SendOption.Reliable, pc.GetClientId()); writer.Write(msg); @@ -1295,13 +1194,11 @@ namespace EHR.Modules public static void SyncAllClientRealNames() { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncAllClientRealNames, SendOption.Reliable); writer.WritePacked(Main.AllClientRealNames.Count); + foreach (KeyValuePair name in Main.AllClientRealNames) { writer.Write(name.Key); @@ -1325,15 +1222,10 @@ namespace EHR.Modules static IEnumerator VersionCheck() { - while (PlayerControl.LocalPlayer == null) - { - yield return null; - } + while (PlayerControl.LocalPlayer == null) yield return null; if (AmongUsClient.Instance.AmHost) - { Utils.SendRPC(CustomRPC.VersionCheck, Main.PluginVersion, $"{ThisAssembly.Git.Commit}({ThisAssembly.Git.Branch})", Main.ForkId); - } else { MessageWriter writer = AmongUsClient.Instance.StartRpc(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.VersionCheck); @@ -1358,44 +1250,36 @@ namespace EHR.Modules public static void GetDeathReason(MessageReader reader) { byte playerId = reader.ReadByte(); - PlayerState.DeathReason deathReason = (PlayerState.DeathReason)reader.ReadInt32(); + var deathReason = (PlayerState.DeathReason)reader.ReadInt32(); Main.PlayerStates[playerId].deathReason = deathReason; Main.PlayerStates[playerId].IsDead = true; } public static void ForceEndGame(CustomWinner win) { - if (ShipStatus.Instance == null) - { - return; - } + if (ShipStatus.Instance == null) return; try { CustomWinnerHolder.ResetAndSetWinner(win); } - catch - { - } + catch { } if (AmongUsClient.Instance.AmHost) { ShipStatus.Instance.enabled = false; + try { GameManager.Instance.LogicFlow.CheckEndCriteria(); } - catch - { - } + catch { } try { GameManager.Instance.RpcEndGame(GameOverReason.ImpostorDisconnect, false); } - catch - { - } + catch { } } } @@ -1436,56 +1320,39 @@ namespace EHR.Modules public static void SetCustomRole(byte targetId, CustomRoles role, bool replaceAllAddons = false) { if (role < CustomRoles.NotAssigned) - { Main.PlayerStates[targetId].SetMainRole(role); - } else - { Main.PlayerStates[targetId].SetSubRole(role, replaceAllAddons); - } HudManager.Instance.SetHudActive(true); - if (PlayerControl.LocalPlayer.PlayerId == targetId) - { - RemoveDisableDevicesPatch.UpdateDisableDevices(); - } + if (PlayerControl.LocalPlayer.PlayerId == targetId) RemoveDisableDevicesPatch.UpdateDisableDevices(); } public static void SyncLoversPlayers() { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetLoversPlayers, SendOption.Reliable); writer.Write(Main.LoversPlayers.Count); - foreach (PlayerControl lp in Main.LoversPlayers) - { - writer.Write(lp.PlayerId); - } + foreach (PlayerControl lp in Main.LoversPlayers) writer.Write(lp.PlayerId); AmongUsClient.Instance.FinishRpcImmediately(writer); } public static void SendRpcLogger(uint targetNetId, byte callId, int targetClientId = -1) { - if (!DebugModeManager.AmDebugger) - { - return; - } + if (!DebugModeManager.AmDebugger) return; string rpcName = GetRpcName(callId); - string from = targetNetId.ToString(); - string target = targetClientId.ToString(); + var from = targetNetId.ToString(); + var target = targetClientId.ToString(); + try { target = targetClientId < 0 ? "All" : AmongUsClient.Instance.GetClient(targetClientId).PlayerName; from = Main.AllPlayerControls.FirstOrDefault(c => c.NetId == targetNetId)?.Data?.PlayerName; } - catch - { - } + catch { } Logger.Info($"FromNetID: {targetNetId} ({from}) / TargetClientID: {targetClientId} ({target}) / CallID: {callId} ({rpcName})", "SendRPC"); } @@ -1493,16 +1360,11 @@ namespace EHR.Modules public static string GetRpcName(byte callId) { string rpcName; - if ((rpcName = Enum.GetName(typeof(RpcCalls), callId)) != null) - { - } - else if ((rpcName = Enum.GetName(typeof(CustomRPC), callId)) != null) - { - } + + if ((rpcName = Enum.GetName(typeof(RpcCalls), callId)) != null) { } + else if ((rpcName = Enum.GetName(typeof(CustomRPC), callId)) != null) { } else - { rpcName = callId.ToString(); - } return rpcName; } @@ -1510,9 +1372,7 @@ namespace EHR.Modules public static void SetCurrentDousingTarget(byte arsonistId, byte targetId) { if (PlayerControl.LocalPlayer.PlayerId == arsonistId) - { Arsonist.CurrentDousingTarget = targetId; - } else { MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetCurrentDousingTarget, SendOption.Reliable); @@ -1525,9 +1385,7 @@ namespace EHR.Modules public static void SetCurrentDrawTarget(byte arsonistId, byte targetId) { if (PlayerControl.LocalPlayer.PlayerId == arsonistId) - { Revolutionist.CurrentDrawTarget = targetId; - } else { MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetCurrentDrawTarget, SendOption.Reliable); @@ -1540,9 +1398,7 @@ namespace EHR.Modules public static void SetCurrentRevealTarget(byte arsonistId, byte targetId) { if (PlayerControl.LocalPlayer.PlayerId == arsonistId) - { Revolutionist.CurrentDrawTarget = targetId; - } else { MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetCurrentRevealTarget, SendOption.Reliable); @@ -1573,10 +1429,7 @@ namespace EHR.Modules state.RealKiller.TimeStamp = DateTime.Now; state.RealKiller.ID = killerId; - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetRealKiller, SendOption.Reliable); writer.Write(targetId); @@ -1591,12 +1444,10 @@ namespace EHR.Modules public static bool Prefix(PlayerPhysics __instance, byte callId, MessageReader reader) { bool host = __instance.IsHost(); - if (!host && EAC.PlayerPhysicsRpcCheck(__instance, callId, reader)) - { - return false; - } + if (!host && EAC.PlayerPhysicsRpcCheck(__instance, callId, reader)) return false; PlayerControl player = __instance.myPlayer; + if (!player) { Logger.Warn("Received Physics RPC without a player", "PlayerPhysics_ReceiveRPC"); diff --git a/Modules/Random/IRandom.cs b/Modules/Random/IRandom.cs index e0e8ede9b..59c63ddd1 100644 --- a/Modules/Random/IRandom.cs +++ b/Modules/Random/IRandom.cs @@ -34,10 +34,7 @@ namespace EHR /// A sequence of random numbers. public static IEnumerable Sequence(int count, int minValue, int maxValue) { - for (int i = 0; i < count; i++) - { - yield return Instance.Next(minValue, maxValue); - } + for (var i = 0; i < count; i++) yield return Instance.Next(minValue, maxValue); } /// @@ -49,20 +46,18 @@ namespace EHR /// A sequence of unique random numbers. public static IEnumerable SequenceUnique(int count, int minValue, int maxValue) { - HashSet set = new HashSet(); - for (int i = 0; i < count; i++) + var set = new HashSet(); + + for (var i = 0; i < count; i++) { // If all possible values are used, the loop will be infinite. Break the loop if the set is full. - if (set.Count == maxValue - minValue) - { - break; - } + if (set.Count == maxValue - minValue) break; int value; + do - { value = Instance.Next(minValue, maxValue); - } while (!set.Add(value)); + while (!set.Add(value)); yield return value; } @@ -70,10 +65,7 @@ namespace EHR public static void SetInstance(IRandom instance) { - if (instance != null) - { - Instance = instance; - } + if (instance != null) Instance = instance; } public static void SetInstanceById(int id) @@ -81,15 +73,10 @@ namespace EHR if (RandomTypes.TryGetValue(id, out Type type)) { // The current instance is null or the type of the current instance does not match the specified type. - if (Instance == null || Instance.GetType() != type) - { - Instance = Activator.CreateInstance(type) as IRandom ?? Instance; - } + if (Instance == null || Instance.GetType() != type) Instance = Activator.CreateInstance(type) as IRandom ?? Instance; } else - { Logger.Warn($"無効なID: {id}", "IRandom.SetInstanceById"); - } } } } \ No newline at end of file diff --git a/Modules/Random/MersenneTwister.cs b/Modules/Random/MersenneTwister.cs index 5c0212249..6adc60ac0 100644 --- a/Modules/Random/MersenneTwister.cs +++ b/Modules/Random/MersenneTwister.cs @@ -47,9 +47,7 @@ namespace EHR private readonly UInt32[] _mt = new UInt32[N]; private Int16 _mtItems; - public MersenneTwister() : this((Int32)DateTime.UtcNow.Ticks) - { - } + public MersenneTwister() : this((Int32)DateTime.UtcNow.Ticks) { } public MersenneTwister(Int32 seed) { @@ -58,20 +56,11 @@ namespace EHR public int Next(int minValue, int maxValue) { - if (minValue < 0 || maxValue < 0) - { - throw new ArgumentOutOfRangeException("minValue and maxValue must be bigger than 0."); - } + if (minValue < 0 || maxValue < 0) throw new ArgumentOutOfRangeException("minValue and maxValue must be bigger than 0."); - if (minValue > maxValue) - { - throw new ArgumentException("maxValue must be bigger than minValue."); - } + if (minValue > maxValue) throw new ArgumentException("maxValue must be bigger than minValue."); - if (minValue == maxValue) - { - return minValue; - } + if (minValue == maxValue) return minValue; return (int)(minValue + (Next() % (maxValue - minValue))); } diff --git a/Modules/Random/NetRandomWrapper.cs b/Modules/Random/NetRandomWrapper.cs index bd25bbe43..59259600a 100644 --- a/Modules/Random/NetRandomWrapper.cs +++ b/Modules/Random/NetRandomWrapper.cs @@ -6,13 +6,9 @@ namespace EHR { public Random wrapping = instance; - public NetRandomWrapper() : this(new Random()) - { - } + public NetRandomWrapper() : this(new Random()) { } - public NetRandomWrapper(int seed) : this(new Random(seed)) - { - } + public NetRandomWrapper(int seed) : this(new Random(seed)) { } public int Next(int minValue, int maxValue) { diff --git a/Modules/Random/Xorshift.cs b/Modules/Random/Xorshift.cs index ce5e65af7..d9a5a4a52 100644 --- a/Modules/Random/Xorshift.cs +++ b/Modules/Random/Xorshift.cs @@ -9,26 +9,15 @@ namespace EHR private uint num = seed; - public Xorshift() : this((uint)DateTime.UtcNow.Ticks) - { - } + public Xorshift() : this((uint)DateTime.UtcNow.Ticks) { } public int Next(int minValue, int maxValue) { - if (minValue < 0 || maxValue < 0) - { - throw new ArgumentOutOfRangeException("minValue and maxValue must be bigger than 0."); - } + if (minValue < 0 || maxValue < 0) throw new ArgumentOutOfRangeException("minValue and maxValue must be bigger than 0."); - if (minValue > maxValue) - { - throw new ArgumentException("maxValue must be bigger than minValue."); - } + if (minValue > maxValue) throw new ArgumentException("maxValue must be bigger than minValue."); - if (minValue == maxValue) - { - return minValue; - } + if (minValue == maxValue) return minValue; return (int)(minValue + (Next() % (maxValue - minValue))); } diff --git a/Modules/RoleBlockManager.cs b/Modules/RoleBlockManager.cs index f4d0c494a..bb00e0bfc 100644 --- a/Modules/RoleBlockManager.cs +++ b/Modules/RoleBlockManager.cs @@ -15,6 +15,7 @@ namespace EHR.Modules public static void AddRoleBlock(PlayerControl pc, float duration) { long now = Utils.TimeStamp; + if (RoleBlockedPlayers.TryGetValue(pc.PlayerId, out (long StartTimeStamp, float Duration) data) && data.Duration - (now - data.StartTimeStamp) + 1 > duration) { Logger.Info($"{pc.GetNameWithRole()} got role blocked, but the duration is less than the previous one", "RoleBlockManager"); @@ -30,6 +31,7 @@ namespace EHR.Modules if (RoleBlockedPlayers.TryGetValue(pc.PlayerId, out (long StartTimeStamp, float Duration) data)) { long now = Utils.TimeStamp; + if (now - data.StartTimeStamp >= data.Duration) { RoleBlockedPlayers.Remove(pc.PlayerId); diff --git a/Modules/SimpleButton.cs b/Modules/SimpleButton.cs index d8025d53d..2fbbc33a6 100644 --- a/Modules/SimpleButton.cs +++ b/Modules/SimpleButton.cs @@ -30,10 +30,7 @@ namespace EHR string label, bool isActive = true) { - if (baseButton == null) - { - throw new InvalidOperationException("baseButtonが未設定"); - } + if (baseButton == null) throw new InvalidOperationException("baseButtonが未設定"); Button = Object.Instantiate(baseButton, parent); Label = Button.transform.Find("FontPlacer/Text_TMP").GetComponent(); @@ -76,14 +73,11 @@ namespace EHR public static void SetBase(PassiveButton passiveButton) { - if (baseButton != null || passiveButton == null) - { - return; - } + if (baseButton != null || passiveButton == null) return; // 複製 baseButton = Object.Instantiate(passiveButton); - TextMeshPro label = baseButton.transform.Find("FontPlacer/Text_TMP").GetComponent(); + var label = baseButton.transform.Find("FontPlacer/Text_TMP").GetComponent(); baseButton.gameObject.SetActive(false); // シーン切替時に破棄されないようにする Object.DontDestroyOnLoad(baseButton); @@ -95,7 +89,7 @@ namespace EHR label.enableWordWrapping = false; label.text = "EHR SIMPLE BUTTON BASE"; // 当たり判定がズレてるのを直す - BoxCollider2D buttonCollider = baseButton.GetComponent(); + var buttonCollider = baseButton.GetComponent(); buttonCollider.offset = new(0f, 0f); baseButton.OnClick = new(); } diff --git a/Modules/SpamManager.cs b/Modules/SpamManager.cs index 8d265e7da..a8cbfc3c8 100644 --- a/Modules/SpamManager.cs +++ b/Modules/SpamManager.cs @@ -26,19 +26,15 @@ namespace EHR { try { - if (!Directory.Exists(@"EHR_DATA")) - { - Directory.CreateDirectory(@"EHR_DATA"); - } + if (!Directory.Exists(@"EHR_DATA")) Directory.CreateDirectory(@"EHR_DATA"); if (File.Exists(@"./BanWords.txt")) - { File.Move(@"./BanWords.txt", BANEDWORDS_FILE_PATH); - } else { string fileName; string[] name = CultureInfo.CurrentCulture.Name.Split("-"); + if (name.Length >= 2) { fileName = name[0] switch @@ -49,9 +45,7 @@ namespace EHR }; } else - { fileName = "English"; - } Logger.Warn($"创建新的 BanWords 文件:{fileName}", "SpamManager"); File.WriteAllText(BANEDWORDS_FILE_PATH, GetResourcesTxt($"EHR.Resources.Config.BanWords.{fileName}.txt")); @@ -74,62 +68,45 @@ namespace EHR public static List ReturnAllNewLinesInFile(string filename) { - if (!File.Exists(filename)) - { - return []; - } + if (!File.Exists(filename)) return []; using StreamReader sr = new(filename, Encoding.GetEncoding("UTF-8")); string text; List sendList = []; + while ((text = sr.ReadLine()) != null) - { if (text.Length > 1 && text != "") - { sendList.Add(text.Replace("\\n", "\n").ToLower()); - } - } return sendList; } public static bool CheckSpam(PlayerControl player, string text) { - if (player.PlayerId == PlayerControl.LocalPlayer.PlayerId) - { - return false; - } + if (player.PlayerId == PlayerControl.LocalPlayer.PlayerId) return false; string name = player.GetRealName(); - bool kick = false; - string msg = string.Empty; + var kick = false; + var msg = string.Empty; if (Options.AutoKickStart.GetBool()) { if (ContainsStart(text) && GameStates.IsLobby) { - if (!Main.SayStartTimes.ContainsKey(player.GetClientId())) - { - Main.SayStartTimes.Add(player.GetClientId(), 0); - } + if (!Main.SayStartTimes.ContainsKey(player.GetClientId())) Main.SayStartTimes.Add(player.GetClientId(), 0); Main.SayStartTimes[player.GetClientId()]++; msg = string.Format(GetString("Message.WarnWhoSayStart"), name, Main.SayStartTimes[player.GetClientId()]); + if (Main.SayStartTimes[player.GetClientId()] > Options.AutoKickStartTimes.GetInt()) { msg = string.Format(GetString("Message.KickStartAfterWarn"), name, Main.SayStartTimes[player.GetClientId()]); kick = true; } - if (msg != string.Empty && msg != "") - { - Utils.SendMessage(msg); - } + if (msg != string.Empty && msg != "") Utils.SendMessage(msg); - if (kick) - { - AmongUsClient.Instance.KickPlayer(player.GetClientId(), Options.AutoKickStartAsBan.GetBool()); - } + if (kick) AmongUsClient.Instance.KickPlayer(player.GetClientId(), Options.AutoKickStartAsBan.GetBool()); return true; } @@ -137,25 +114,17 @@ namespace EHR bool banned = BanWords.Any(text.Contains); - if (!banned) - { - return false; - } + if (!banned) return false; - if (Options.AutoWarnStopWords.GetBool()) - { - msg = string.Format(GetString("Message.WarnWhoSayBanWord"), name); - } + if (Options.AutoWarnStopWords.GetBool()) msg = string.Format(GetString("Message.WarnWhoSayBanWord"), name); if (Options.AutoKickStopWords.GetBool()) { - if (!Main.SayBanwordsTimes.ContainsKey(player.GetClientId())) - { - Main.SayBanwordsTimes.Add(player.GetClientId(), 0); - } + if (!Main.SayBanwordsTimes.ContainsKey(player.GetClientId())) Main.SayBanwordsTimes.Add(player.GetClientId(), 0); Main.SayBanwordsTimes[player.GetClientId()]++; msg = string.Format(GetString("Message.WarnWhoSayBanWordTimes"), name, Main.SayBanwordsTimes[player.GetClientId()]); + if (Main.SayBanwordsTimes[player.GetClientId()] > Options.AutoKickStopWordsTimes.GetInt()) { msg = string.Format(GetString("Message.KickWhoSayBanWordAfterWarn"), name, Main.SayBanwordsTimes[player.GetClientId()]); @@ -166,22 +135,13 @@ namespace EHR if (msg != string.Empty && msg != "") { if (kick || !GameStates.IsInGame) - { Utils.SendMessage(msg); - } else - { foreach (PlayerControl pc in Main.AllPlayerControls.Where(x => x.IsAlive() == player.IsAlive()).ToArray()) - { Utils.SendMessage(msg, pc.PlayerId); - } - } } - if (kick) - { - AmongUsClient.Instance.KickPlayer(player.GetClientId(), Options.AutoKickStopWordsAsBan.GetBool()); - } + if (kick) AmongUsClient.Instance.KickPlayer(player.GetClientId(), Options.AutoKickStopWordsAsBan.GetBool()); return true; } @@ -190,635 +150,261 @@ namespace EHR { text = text.Trim().ToLower(); - int stNum = 0; - for (int i = 0; i < text.Length; i++) - { - if (text[i..].Equals("k")) - { - stNum++; - } - - if (text[i..].Equals("开")) - { - stNum++; - } - } + var stNum = 0; - if (stNum >= 3) + for (var i = 0; i < text.Length; i++) { - return true; - } + if (text[i..].Equals("k")) stNum++; - if (text == "Start") - { - return true; + if (text[i..].Equals("开")) stNum++; } - if (text == "start") - { - return true; - } + if (stNum >= 3) return true; - if (text == "/Start") - { - return true; - } + if (text == "Start") return true; - if (text == "/Start/") - { - return true; - } + if (text == "start") return true; - if (text == "Start/") - { - return true; - } + if (text == "/Start") return true; - if (text == "/start") - { - return true; - } + if (text == "/Start/") return true; - if (text == "/start/") - { - return true; - } + if (text == "Start/") return true; - if (text == "start/") - { - return true; - } + if (text == "/start") return true; - if (text == "plsstart") - { - return true; - } + if (text == "/start/") return true; - if (text == "pls start") - { - return true; - } + if (text == "start/") return true; - if (text == "please start") - { - return true; - } + if (text == "plsstart") return true; - if (text == "pleasestart") - { - return true; - } + if (text == "pls start") return true; - if (text == "Plsstart") - { - return true; - } + if (text == "please start") return true; - if (text == "Pls start") - { - return true; - } + if (text == "pleasestart") return true; - if (text == "Please start") - { - return true; - } + if (text == "Plsstart") return true; - if (text == "Pleasestart") - { - return true; - } + if (text == "Pls start") return true; - if (text == "plsStart") - { - return true; - } + if (text == "Please start") return true; - if (text == "pls Start") - { - return true; - } + if (text == "Pleasestart") return true; - if (text == "please Start") - { - return true; - } + if (text == "plsStart") return true; - if (text == "pleaseStart") - { - return true; - } + if (text == "pls Start") return true; - if (text == "PlsStart") - { - return true; - } + if (text == "please Start") return true; - if (text == "Pls Start") - { - return true; - } + if (text == "pleaseStart") return true; - if (text == "Please Start") - { - return true; - } + if (text == "PlsStart") return true; - if (text == "PleaseStart") - { - return true; - } + if (text == "Pls Start") return true; - if (text == "sTart") - { - return true; - } + if (text == "Please Start") return true; - if (text == "stArt") - { - return true; - } + if (text == "PleaseStart") return true; - if (text == "staRt") - { - return true; - } + if (text == "sTart") return true; - if (text == "starT") - { - return true; - } + if (text == "stArt") return true; - if (text == "s t a r t") - { - return true; - } + if (text == "staRt") return true; - if (text == "S t a r t") - { - return true; - } + if (text == "starT") return true; - if (text == "started") - { - return true; - } + if (text == "s t a r t") return true; - if (text == "Started") - { - return true; - } + if (text == "S t a r t") return true; - if (text == "s t a r t e d") - { - return true; - } + if (text == "started") return true; - if (text == "S t a r t e d") - { - return true; - } + if (text == "Started") return true; - if (text == "Го") - { - return true; - } + if (text == "s t a r t e d") return true; - if (text == "гО") - { - return true; - } + if (text == "S t a r t e d") return true; - if (text == "го") - { - return true; - } + if (text == "Го") return true; - if (text == "Гоу") - { - return true; - } + if (text == "гО") return true; - if (text == "гоу") - { - return true; - } + if (text == "го") return true; - if (text == "Старт") - { - return true; - } + if (text == "Гоу") return true; - if (text == "старт") - { - return true; - } + if (text == "гоу") return true; - if (text == "/Старт") - { - return true; - } + if (text == "Старт") return true; - if (text == "/Старт/") - { - return true; - } + if (text == "старт") return true; - if (text == "Старт/") - { - return true; - } + if (text == "/Старт") return true; - if (text == "/старт") - { - return true; - } + if (text == "/Старт/") return true; - if (text == "/старт/") - { - return true; - } + if (text == "Старт/") return true; - if (text == "старт/") - { - return true; - } + if (text == "/старт") return true; - if (text == "пжстарт") - { - return true; - } + if (text == "/старт/") return true; - if (text == "пж старт") - { - return true; - } + if (text == "старт/") return true; - if (text == "пжСтарт") - { - return true; - } + if (text == "пжстарт") return true; - if (text == "пж Старт") - { - return true; - } + if (text == "пж старт") return true; - if (text == "Пжстарт") - { - return true; - } + if (text == "пжСтарт") return true; - if (text == "Пж старт") - { - return true; - } + if (text == "пж Старт") return true; - if (text == "ПжСтарт") - { - return true; - } + if (text == "Пжстарт") return true; - if (text == "Пж Старт") - { - return true; - } + if (text == "Пж старт") return true; - if (text == "сТарт") - { - return true; - } + if (text == "ПжСтарт") return true; - if (text == "стАрт") - { - return true; - } + if (text == "Пж Старт") return true; - if (text == "стаРт") - { - return true; - } + if (text == "сТарт") return true; - if (text == "старТ") - { - return true; - } + if (text == "стАрт") return true; - if (text == "с т а р т") - { - return true; - } + if (text == "стаРт") return true; - if (text == "С т а р т") - { - return true; - } + if (text == "старТ") return true; - if (text == "начни") - { - return true; - } + if (text == "с т а р т") return true; - if (text == "Начни") - { - return true; - } + if (text == "С т а р т") return true; - if (text == "начинай") - { - return true; - } + if (text == "начни") return true; - if (text == "начинай уже") - { - return true; - } + if (text == "Начни") return true; - if (text == "Начинай") - { - return true; - } + if (text == "начинай") return true; - if (text == "Начинай уже") - { - return true; - } + if (text == "начинай уже") return true; - if (text == "Начинай Уже") - { - return true; - } + if (text == "Начинай") return true; - if (text == "н а ч и н а й") - { - return true; - } + if (text == "Начинай уже") return true; - if (text == "Н а ч и н а й") - { - return true; - } + if (text == "Начинай Уже") return true; - if (text == "пж го") - { - return true; - } + if (text == "н а ч и н а й") return true; - if (text == "пжго") - { - return true; - } + if (text == "Н а ч и н а й") return true; - if (text == "Пж Го") - { - return true; - } + if (text == "пж го") return true; - if (text == "Пж го") - { - return true; - } + if (text == "пжго") return true; - if (text == "пж Го") - { - return true; - } + if (text == "Пж Го") return true; - if (text == "ПжГо") - { - return true; - } + if (text == "Пж го") return true; - if (text == "Пжго") - { - return true; - } + if (text == "пж Го") return true; - if (text == "пжГо") - { - return true; - } + if (text == "ПжГо") return true; - if (text == "ГоПж") - { - return true; - } + if (text == "Пжго") return true; - if (text == "гоПж") - { - return true; - } + if (text == "пжГо") return true; - if (text == "Гопж") - { - return true; - } + if (text == "ГоПж") return true; - if (text == "开") - { - return true; - } + if (text == "гоПж") return true; - if (text == "快开") - { - return true; - } + if (text == "Гопж") return true; - if (text == "开始") - { - return true; - } + if (text == "开") return true; - if (text == "开啊") - { - return true; - } + if (text == "快开") return true; - if (text == "开阿") - { - return true; - } + if (text == "开始") return true; - if (text == "kai") - { - return true; - } + if (text == "开啊") return true; - if (text == "kaishi") - { - return true; - } + if (text == "开阿") return true; + + if (text == "kai") return true; + + if (text == "kaishi") return true; //if (text.Length >= 3) return false; - if (text.Contains("start")) - { - return true; - } + if (text.Contains("start")) return true; - if (text.Contains("Start")) - { - return true; - } + if (text.Contains("Start")) return true; - if (text.Contains("STart")) - { - return true; - } + if (text.Contains("STart")) return true; - if (text.Contains("s t a r t")) - { - return true; - } + if (text.Contains("s t a r t")) return true; - if (text.Contains("begin")) - { - return true; - } + if (text.Contains("begin")) return true; - if (text.Contains('了')) - { - return false; - } + if (text.Contains('了')) return false; - if (text.Contains('没')) - { - return false; - } + if (text.Contains('没')) return false; - if (text.Contains('吗')) - { - return false; - } + if (text.Contains('吗')) return false; - if (text.Contains('哈')) - { - return false; - } + if (text.Contains('哈')) return false; - if (text.Contains('还')) - { - return false; - } + if (text.Contains('还')) return false; - if (text.Contains('现')) - { - return false; - } + if (text.Contains('现')) return false; - if (text.Contains('不')) - { - return false; - } + if (text.Contains('不')) return false; - if (text.Contains('可')) - { - return false; - } + if (text.Contains('可')) return false; - if (text.Contains('刚')) - { - return false; - } + if (text.Contains('刚')) return false; - if (text.Contains('的')) - { - return false; - } + if (text.Contains('的')) return false; - if (text.Contains('打')) - { - return false; - } + if (text.Contains('打')) return false; - if (text.Contains('门')) - { - return false; - } + if (text.Contains('门')) return false; - if (text.Contains('关')) - { - return false; - } + if (text.Contains('关')) return false; - if (text.Contains('怎')) - { - return false; - } + if (text.Contains('怎')) return false; - if (text.Contains('要')) - { - return false; - } + if (text.Contains('要')) return false; - if (text.Contains('摆')) - { - return false; - } + if (text.Contains('摆')) return false; - if (text.Contains('啦')) - { - return false; - } + if (text.Contains('啦')) return false; - if (text.Contains('咯')) - { - return false; - } + if (text.Contains('咯')) return false; - if (text.Contains('嘞')) - { - return false; - } + if (text.Contains('嘞')) return false; - if (text.Contains('勒')) - { - return false; - } + if (text.Contains('勒')) return false; - if (text.Contains('心')) - { - return false; - } + if (text.Contains('心')) return false; - if (text.Contains('呢')) - { - return false; - } + if (text.Contains('呢')) return false; - if (text.Contains('门')) - { - return false; - } + if (text.Contains('门')) return false; - if (text.Contains('总')) - { - return false; - } + if (text.Contains('总')) return false; - if (text.Contains('哥')) - { - return false; - } + if (text.Contains('哥')) return false; - if (text.Contains('姐')) - { - return false; - } + if (text.Contains('姐')) return false; - if (text.Contains('《')) - { - return false; - } + if (text.Contains('《')) return false; - if (text.Contains('?')) - { - return false; - } + if (text.Contains('?')) return false; - if (text.Contains('?')) - { - return false; - } + if (text.Contains('?')) return false; return text.Contains('开') || text.Contains("kai"); } diff --git a/Modules/TargetArrow.cs b/Modules/TargetArrow.cs index d6db47162..7eba0945f 100644 --- a/Modules/TargetArrow.cs +++ b/Modules/TargetArrow.cs @@ -52,6 +52,7 @@ namespace EHR public static void Add(byte seer, byte target) { ArrowInfo arrowInfo = new(seer, target); + if (!TargetArrows.Any(a => a.Key.Equals(arrowInfo))) { TargetArrows[arrowInfo] = "・"; @@ -69,10 +70,7 @@ namespace EHR { ArrowInfo arrowInfo = new(seer, target); List removeList = new(TargetArrows.Keys.Where(k => k.Equals(arrowInfo))); - foreach (ArrowInfo a in removeList.ToArray()) - { - TargetArrows.Remove(a); - } + foreach (ArrowInfo a in removeList.ToArray()) TargetArrows.Remove(a); Utils.SendRPC(CustomRPC.Arrow, true, 2, seer, target); Logger.Info($"Removed target arrow: {seer} ({seer.GetPlayer()?.GetRealName()}) => {target} ({target.GetPlayer()?.GetRealName()})", "TargetArrow"); @@ -85,10 +83,7 @@ namespace EHR public static void RemoveAllTarget(byte seer) { List removeList = new(TargetArrows.Keys.Where(k => k.From == seer)); - foreach (ArrowInfo arrowInfo in removeList.ToArray()) - { - TargetArrows.Remove(arrowInfo); - } + foreach (ArrowInfo arrowInfo in removeList.ToArray()) TargetArrows.Remove(arrowInfo); Utils.SendRPC(CustomRPC.Arrow, true, 3, seer); Logger.Info($"Removed all target arrows for {seer} ({seer.GetPlayer()?.GetRealName()})", "TargetArrow"); @@ -122,24 +117,20 @@ namespace EHR /// public static void OnFixedUpdate(PlayerControl seer) { - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; bool seerIsDead = !seer.IsAlive(); List arrowList = new(TargetArrows.Keys.Where(a => a.From == seer.PlayerId)); - if (arrowList.Count == 0) - { - return; - } + if (arrowList.Count == 0) return; + + var update = false; - bool update = false; foreach (ArrowInfo arrowInfo in arrowList.ToArray()) { byte targetId = arrowInfo.To; PlayerControl target = Utils.GetPlayerById(targetId); + if (seerIsDead || (!target.IsAlive() && !seer.Is(CustomRoles.Spiritualist))) { TargetArrows.Remove(arrowInfo); @@ -150,6 +141,7 @@ namespace EHR // Take the direction vector of the target Vector3 dir = target.transform.position - seer.transform.position; int index; + if (dir.magnitude < 2) { // Display a dot when close @@ -166,6 +158,7 @@ namespace EHR } string arrow = Arrows[index]; + if (TargetArrows[arrowInfo] != arrow) { TargetArrows[arrowInfo] = arrow; @@ -173,10 +166,7 @@ namespace EHR } } - if (update) - { - Utils.NotifyRoles(SpecifySeer: seer, ForceLoop: false, SpecifyTarget: seer); - } + if (update) Utils.NotifyRoles(SpecifySeer: seer, ForceLoop: false, SpecifyTarget: seer); } private class ArrowInfo(byte from, byte to) diff --git a/Modules/TemplateManager.cs b/Modules/TemplateManager.cs index 1fb3b58db..76baf3a49 100644 --- a/Modules/TemplateManager.cs +++ b/Modules/TemplateManager.cs @@ -52,19 +52,15 @@ namespace EHR { try { - if (!Directory.Exists("EHR_DATA")) - { - Directory.CreateDirectory("EHR_DATA"); - } + if (!Directory.Exists("EHR_DATA")) Directory.CreateDirectory("EHR_DATA"); if (File.Exists("./template.txt")) - { File.Move("./template.txt", TemplateFilePath); - } else { string fileName; string[] name = CultureInfo.CurrentCulture.Name.Split("-"); + if (name.Length >= 2) { fileName = name[0] switch @@ -75,9 +71,7 @@ namespace EHR }; } else - { fileName = "English"; - } Logger.Warn($"创建新的 Template 文件:{fileName}", "TemplateManager"); File.WriteAllText(TemplateFilePath, GetResourcesTxt($"EHR.Resources.Config.template.{fileName}.txt")); @@ -98,10 +92,7 @@ namespace EHR private static string GetResourcesTxt(string path) { Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path); - if (stream == null) - { - return string.Empty; - } + if (stream == null) return string.Empty; stream.Position = 0; using StreamReader reader = new(stream, Encoding.UTF8); @@ -114,45 +105,33 @@ namespace EHR using StreamReader sr = new(TemplateFilePath, Encoding.GetEncoding("UTF-8")); List sendList = []; HashSet tags = []; + while (sr.ReadLine() is { } text) { string[] tmp = text.Split(":"); + if (tmp.Length > 1 && tmp[1] != "") { tags.Add(tmp[0]); - if (string.Equals(tmp[0], str, StringComparison.CurrentCultureIgnoreCase)) - { - sendList.Add(tmp.Skip(1).Join(delimiter: ":").Replace("\\n", "\n")); - } + if (string.Equals(tmp[0], str, StringComparison.CurrentCultureIgnoreCase)) sendList.Add(tmp.Skip(1).Join(delimiter: ":").Replace("\\n", "\n")); } } if (sendList.Count == 0 && !noErr) { if (playerId == 0xff) - { HudManager.Instance.Chat.AddChat(PlayerControl.LocalPlayer, string.Format(GetString("Message.TemplateNotFoundHost"), str, tags.Join(delimiter: ", "))); - } else - { Utils.SendMessage(string.Format(GetString("Message.TemplateNotFoundClient"), str), playerId); - } } else - { foreach (string x in sendList) - { Utils.SendMessage(ApplyReplaceDictionary(x), playerId); - } - } } private static string ApplyReplaceDictionary(string text) { - foreach (KeyValuePair> kvp in ReplaceDictionary) - { - text = Regex.Replace(text, "{{" + kvp.Key + "}}", kvp.Value.Invoke() ?? "", RegexOptions.IgnoreCase); - } + foreach (KeyValuePair> kvp in ReplaceDictionary) text = Regex.Replace(text, "{{" + kvp.Key + "}}", kvp.Value.Invoke() ?? "", RegexOptions.IgnoreCase); return text; } diff --git a/Modules/Translator.cs b/Modules/Translator.cs index 49801dc57..cf0984326 100644 --- a/Modules/Translator.cs +++ b/Modules/Translator.cs @@ -29,9 +29,9 @@ namespace EHR try { // Get the directory containing the JSON files (e.g., EHR.Resources.Lang) - string jsonDirectory = "EHR.Resources.Lang"; + var jsonDirectory = "EHR.Resources.Lang"; // Get the assembly containing the resources - Assembly assembly = Assembly.GetExecutingAssembly(); + var assembly = Assembly.GetExecutingAssembly(); string[] jsonFileNames = GetJsonFileNames(assembly, jsonDirectory); translateMaps = []; @@ -46,13 +46,15 @@ namespace EHR { // Read the JSON file content using Stream resourceStream = assembly.GetManifestResourceStream(jsonFileName); + if (resourceStream != null) { using StreamReader reader = new(resourceStream); string jsonContent = reader.ReadToEnd(); // Deserialize the JSON into a dictionary - Dictionary jsonDictionary = JsonSerializer.Deserialize>(jsonContent); + var jsonDictionary = JsonSerializer.Deserialize>(jsonContent); + if (jsonDictionary.TryGetValue("LanguageID", out string languageIdObj) && int.TryParse(languageIdObj, out int languageId)) { // Remove the "LanguageID" entry @@ -81,13 +83,11 @@ namespace EHR } // Loading custom translation files - if (!Directory.Exists(LANGUAGE_FOLDER_NAME)) - { - Directory.CreateDirectory(LANGUAGE_FOLDER_NAME); - } + if (!Directory.Exists(LANGUAGE_FOLDER_NAME)) Directory.CreateDirectory(LANGUAGE_FOLDER_NAME); // Creating a translation template CreateTemplateFile(); + foreach (SupportedLangs lang in Enum.GetValues()) { if (File.Exists(@$"./{LANGUAGE_FOLDER_NAME}/{lang}.dat")) @@ -103,13 +103,11 @@ namespace EHR foreach (KeyValuePair kvp in jsonDictionary) { string textString = kvp.Key; + if (kvp.Value is string translation) { // If the textString is not already in the translation map, add it - if (!translationMaps.ContainsKey(textString)) - { - translationMaps[textString] = []; - } + if (!translationMaps.ContainsKey(textString)) translationMaps[textString] = []; // Add or update the translation for the current id and textString translationMaps[textString][languageId] = translation.Replace("\\n", "\n").Replace("\\r", "\r"); @@ -127,45 +125,32 @@ namespace EHR public static string GetString(string s, Dictionary replacementDic = null, bool console = false) { SupportedLangs langId = TranslationController.InstanceExists ? TranslationController.Instance.currentLanguage.languageID : SupportedLangs.English; - if (console) - { - langId = SupportedLangs.English; - } + if (console) langId = SupportedLangs.English; - if (Main.ForceOwnLanguage.Value) - { - langId = GetUserTrueLang(); - } + if (Main.ForceOwnLanguage.Value) langId = GetUserTrueLang(); string str = GetString(s, langId); + if (replacementDic != null) - { foreach (KeyValuePair rd in replacementDic) - { str = str.Replace(rd.Key, rd.Value); - } - } return str; } public static string GetString(string str, SupportedLangs langId) { - string res = $""; + var res = $""; + try { if (translateMaps.TryGetValue(str, out Dictionary dic) && (!dic.TryGetValue((int)langId, out res) || res == "" || (langId is not SupportedLangs.SChinese and not SupportedLangs.TChinese && Regex.IsMatch(res, @"[\u4e00-\u9fa5]") && res == GetString(str, SupportedLangs.SChinese)))) //strに該当する&無効なlangIdかresが空 - { res = langId == SupportedLangs.English ? $"*{str}" : GetString(str, SupportedLangs.English); - } if (!translateMaps.ContainsKey(str)) //translateMapsにない場合、StringNamesにあれば取得する { StringNames[] stringNames = Enum.GetValues().Where(x => x.ToString() == str).ToArray(); - if (stringNames.Length > 0) - { - res = GetString(stringNames.FirstOrDefault()); - } + if (stringNames.Length > 0) res = GetString(stringNames.FirstOrDefault()); } } catch (Exception Ex) @@ -186,10 +171,7 @@ namespace EHR { SupportedLangs CurrentLanguage = TranslationController.Instance.currentLanguage.languageID; SupportedLangs lang = forUser ? CurrentLanguage : SupportedLangs.English; - if (Main.ForceOwnLanguageRoleName.Value) - { - lang = GetUserTrueLang(); - } + if (Main.ForceOwnLanguageRoleName.Value) lang = GetUserTrueLang(); return GetString(str, lang); } @@ -199,25 +181,13 @@ namespace EHR try { string name = CultureInfo.CurrentUICulture.Name; - if (name.StartsWith("en")) - { - return SupportedLangs.English; - } + if (name.StartsWith("en")) return SupportedLangs.English; - if (name.StartsWith("zh_CHT")) - { - return SupportedLangs.TChinese; - } + if (name.StartsWith("zh_CHT")) return SupportedLangs.TChinese; - if (name.StartsWith("zh")) - { - return SupportedLangs.SChinese; - } + if (name.StartsWith("zh")) return SupportedLangs.SChinese; - if (name.StartsWith("ru")) - { - return SupportedLangs.Russian; - } + if (name.StartsWith("ru")) return SupportedLangs.Russian; return TranslationController.Instance.currentLanguage.languageID; } @@ -229,16 +199,20 @@ namespace EHR private static void UpdateCustomTranslation(string filename /*, SupportedLangs lang*/) { - string path = @$"./{LANGUAGE_FOLDER_NAME}/{filename}"; + var path = @$"./{LANGUAGE_FOLDER_NAME}/{filename}"; + if (File.Exists(path)) { Logger.Info("Updating Custom Translations", "UpdateCustomTranslation"); + try { List textStrings = []; + using (StreamReader reader = new(path, Encoding.GetEncoding("UTF-8"))) { string line; + while ((line = reader.ReadLine()) != null) { // Split the line by ':' to get the first part @@ -254,14 +228,11 @@ namespace EHR } } - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); + foreach (string templateString in translateMaps.Keys) - { if (!textStrings.Contains(templateString)) - { sb.Append($"{templateString}:\n"); - } - } using FileStream fileStream = new(path, FileMode.Append, FileAccess.Write); using StreamWriter writer = new(fileStream); @@ -276,18 +247,22 @@ namespace EHR public static void LoadCustomTranslation(string filename, SupportedLangs lang) { - string path = @$"./{LANGUAGE_FOLDER_NAME}/{filename}"; + var path = @$"./{LANGUAGE_FOLDER_NAME}/{filename}"; + if (File.Exists(path)) { Logger.Info($"Loading Custom Translation File:{filename}", "LoadCustomTranslation"); + try { using StreamReader sr = new(path, Encoding.GetEncoding("UTF-8")); string text; string[] tmp = []; + while ((text = sr.ReadLine()) != null) { tmp = text.Split(":"); + if (tmp.Length > 1 && tmp[1] != "") { try @@ -301,27 +276,20 @@ namespace EHR } } } - catch (ObjectDisposedException) - { - } + catch (ObjectDisposedException) { } catch (Exception e) { Logger.Error(e.ToString(), "Translator.LoadCustomTranslation"); } } else - { Logger.Error($"Custom Translation File Not Found:{filename}", "LoadCustomTranslation"); - } } private static void CreateTemplateFile() { - StringBuilder sb = new StringBuilder(); - foreach (KeyValuePair> title in translateMaps) - { - sb.Append($"{title.Key}:\n"); - } + var sb = new StringBuilder(); + foreach (KeyValuePair> title in translateMaps) sb.Append($"{title.Key}:\n"); File.WriteAllText(@$"./{LANGUAGE_FOLDER_NAME}/template.dat", sb.ToString()); } @@ -329,8 +297,9 @@ namespace EHR public static void ExportCustomTranslation() { LoadLangs(); - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); SupportedLangs lang = TranslationController.Instance.currentLanguage.languageID; + foreach (KeyValuePair> title in translateMaps) { string text = title.Value.GetValueOrDefault((int)lang, ""); diff --git a/Modules/Utils.cs b/Modules/Utils.cs index cf875778d..3a7b981a3 100644 --- a/Modules/Utils.cs +++ b/Modules/Utils.cs @@ -81,12 +81,14 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ ChatUpdatePatch.DoBlockChat = true; Main.OverrideWelcomeMsg = GetString("AntiBlackOutNotifyInLobby"); LateTask.New(() => { Logger.SendInGame(GetString("AntiBlackOutLoggerSendInGame") /*, true*/); }, 3f, "Anti-Black Msg SendInGame"); + LateTask.New(() => { CustomWinnerHolder.ResetAndSetWinner(CustomWinner.Error); GameManager.Instance.LogicFlow.CheckEndCriteria(); RPC.ForceEndGame(CustomWinner.Error); }, 5.5f, "Anti-Black End Game"); + LateTask.New(() => ChatUpdatePatch.DoBlockChat = false, 6f, log: false); } else @@ -94,13 +96,13 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ MessageWriter writer = AmongUsClient.Instance.StartRpc(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.AntiBlackout); writer.Write(text); writer.EndMessage(); + if (Options.EndWhenPlayerBug.GetBool()) - { LateTask.New(() => { Logger.SendInGame(GetString("AntiBlackOutRequestHostToForceEnd") /*, true*/); }, 3f, "Anti-Black Msg SendInGame"); - } else { LateTask.New(() => { Logger.SendInGame(GetString("AntiBlackOutHostRejectForceEnd") /*, true*/); }, 3f, "Anti-Black Msg SendInGame"); + LateTask.New(() => { AmongUsClient.Instance.ExitGame(DisconnectReasons.Custom); @@ -112,7 +114,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static void CheckAndSetVentInteractions() { - bool shouldPerformVentInteractions = false; + var shouldPerformVentInteractions = false; foreach (PlayerControl pc in Main.AllPlayerControls) { @@ -123,36 +125,25 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ } } - if (shouldPerformVentInteractions) - { - SetAllVentInteractions(); - } + if (shouldPerformVentInteractions) SetAllVentInteractions(); } public static void TPAll(Vector2 location, bool log = true) { - foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { - TP(pc.NetTransform, location, log); - } + foreach (PlayerControl pc in Main.AllAlivePlayerControls) TP(pc.NetTransform, location, log); } public static bool TP(CustomNetworkTransform nt, Vector2 location, bool noCheckState = false, bool log = true) { PlayerControl pc = nt.myPlayer; + if (!noCheckState) { - if (pc.Is(CustomRoles.AntiTP)) - { - return false; - } + if (pc.Is(CustomRoles.AntiTP)) return false; if (pc.inVent || pc.inMovingPlat || pc.onLadder || !pc.IsAlive() || pc.MyPhysics.Animations.IsPlayingAnyLadderAnimation() || pc.MyPhysics.Animations.IsPlayingEnterVentAnimation()) { - if (log) - { - Logger.Warn($"Target ({pc.GetNameWithRole().RemoveHtmlTags()}) is in an un-teleportable state - Teleporting canceled", "TP"); - } + if (log) Logger.Warn($"Target ({pc.GetNameWithRole().RemoveHtmlTags()}) is in an un-teleportable state - Teleporting canceled", "TP"); return false; } @@ -164,16 +155,13 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ nt.SetDirtyBit(uint.MaxValue); } - ushort newSid = (ushort)(nt.lastSequenceId + 8); + var newSid = (ushort)(nt.lastSequenceId + 8); MessageWriter messageWriter = AmongUsClient.Instance.StartRpcImmediately(nt.NetId, (byte)RpcCalls.SnapTo, SendOption.Reliable); NetHelpers.WriteVector2(location, messageWriter); messageWriter.Write(newSid); AmongUsClient.Instance.FinishRpcImmediately(messageWriter); - if (log) - { - Logger.Info($"{pc.GetNameWithRole().RemoveHtmlTags()} => {location}", "TP"); - } + if (log) Logger.Info($"{pc.GetNameWithRole().RemoveHtmlTags()} => {location}", "TP"); CheckInvalidMovementPatch.LastPosition[pc.PlayerId] = location; CheckInvalidMovementPatch.ExemptedPlayers.Add(pc.PlayerId); @@ -208,22 +196,17 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { try { - if (GameStates.IsLobby || !ShipStatus.Instance.Systems.TryGetValue(type, out ISystemType systemType)) - { - return false; - } + if (GameStates.IsLobby || !ShipStatus.Instance.Systems.TryGetValue(type, out ISystemType systemType)) return false; int mapId = Main.NormalOptions.MapId; + switch (type) { case SystemTypes.Electrical: { - if (mapId == 5) - { - return false; // if The Fungle return false - } + if (mapId == 5) return false; // if The Fungle return false - SwitchSystem SwitchSystem = systemType.TryCast(); + var SwitchSystem = systemType.TryCast(); return SwitchSystem is { IsActive: true }; } case SystemTypes.Reactor: @@ -235,65 +218,53 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ // Only Airhip case 4: { - HeliSabotageSystem HeliSabotageSystem = systemType.TryCast(); + var HeliSabotageSystem = systemType.TryCast(); return HeliSabotageSystem != null && HeliSabotageSystem.IsActive; } default: { - ReactorSystemType ReactorSystemType = systemType.TryCast(); + var ReactorSystemType = systemType.TryCast(); return ReactorSystemType is { IsActive: true }; } } } case SystemTypes.Laboratory: { - if (mapId != 2) - { - return false; // Only Polus - } + if (mapId != 2) return false; // Only Polus - ReactorSystemType ReactorSystemType = systemType.TryCast(); + var ReactorSystemType = systemType.TryCast(); return ReactorSystemType is { IsActive: true }; } case SystemTypes.LifeSupp: { - if (mapId is 2 or 4 or 5) - { - return false; // Only Skeld & Mira HQ - } + if (mapId is 2 or 4 or 5) return false; // Only Skeld & Mira HQ - LifeSuppSystemType LifeSuppSystemType = systemType.TryCast(); + var LifeSuppSystemType = systemType.TryCast(); return LifeSuppSystemType is { IsActive: true }; } case SystemTypes.Comms: { if (mapId is 1 or 5) // Only Mira HQ & The Fungle { - HqHudSystemType HqHudSystemType = systemType.TryCast(); + var HqHudSystemType = systemType.TryCast(); return HqHudSystemType is { IsActive: true }; } - HudOverrideSystemType HudOverrideSystemType = systemType.TryCast(); + var HudOverrideSystemType = systemType.TryCast(); return HudOverrideSystemType is { IsActive: true }; } case SystemTypes.HeliSabotage: { - if (mapId != 4) - { - return false; // Only Airhip - } + if (mapId != 4) return false; // Only Airhip - HeliSabotageSystem HeliSabotageSystem = systemType.TryCast(); + var HeliSabotageSystem = systemType.TryCast(); return HeliSabotageSystem != null && HeliSabotageSystem.IsActive; } case SystemTypes.MushroomMixupSabotage: { - if (mapId != 5) - { - return false; // Only The Fungle - } + if (mapId != 5) return false; // Only The Fungle - MushroomMixupSabotageSystem MushroomMixupSabotageSystem = systemType.TryCast(); + var MushroomMixupSabotageSystem = systemType.TryCast(); return MushroomMixupSabotageSystem != null && MushroomMixupSabotageSystem.IsActive; } default: @@ -313,37 +284,25 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { opt.SetFloat(FloatOptionNames.CrewLightMod, opt.GetFloat(FloatOptionNames.ImpostorLightMod)); - if (IsActive(SystemTypes.Electrical)) - { - opt.SetFloat(FloatOptionNames.CrewLightMod, opt.GetFloat(FloatOptionNames.CrewLightMod) * 5); - } + if (IsActive(SystemTypes.Electrical)) opt.SetFloat(FloatOptionNames.CrewLightMod, opt.GetFloat(FloatOptionNames.CrewLightMod) * 5); return; } opt.SetFloat(FloatOptionNames.ImpostorLightMod, opt.GetFloat(FloatOptionNames.CrewLightMod)); - if (IsActive(SystemTypes.Electrical)) - { - opt.SetFloat(FloatOptionNames.ImpostorLightMod, opt.GetFloat(FloatOptionNames.ImpostorLightMod) / 5); - } + if (IsActive(SystemTypes.Electrical)) opt.SetFloat(FloatOptionNames.ImpostorLightMod, opt.GetFloat(FloatOptionNames.ImpostorLightMod) / 5); } public static void SetVisionV2(this IGameOptions opt) { opt.SetFloat(FloatOptionNames.ImpostorLightMod, opt.GetFloat(FloatOptionNames.CrewLightMod)); - if (IsActive(SystemTypes.Electrical)) - { - opt.SetFloat(FloatOptionNames.ImpostorLightMod, opt.GetFloat(FloatOptionNames.ImpostorLightMod) / 5); - } + if (IsActive(SystemTypes.Electrical)) opt.SetFloat(FloatOptionNames.ImpostorLightMod, opt.GetFloat(FloatOptionNames.ImpostorLightMod) / 5); } public static void TargetDies(PlayerControl killer, PlayerControl target) { - if (!target.Data.IsDead || GameStates.IsMeeting) - { - return; - } + if (!target.Data.IsDead || GameStates.IsMeeting) return; CustomRoles targetRole = target.GetCustomRole(); @@ -357,15 +316,9 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ if (targetRole == CustomRoles.CyberStar) { - if (!Options.ImpKnowCyberStarDead.GetBool() && seer.GetCustomRole().IsImpostor()) - { - continue; - } + if (!Options.ImpKnowCyberStarDead.GetBool() && seer.GetCustomRole().IsImpostor()) continue; - if (!Options.NeutralKnowCyberStarDead.GetBool() && seer.GetCustomRole().IsNeutral()) - { - continue; - } + if (!Options.NeutralKnowCyberStarDead.GetBool() && seer.GetCustomRole().IsNeutral()) continue; seer.KillFlash(); seer.Notify(ColorString(GetRoleColor(CustomRoles.CyberStar), GetString("OnCyberStarDead"))); @@ -385,15 +338,9 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static bool KillFlashCheck(PlayerControl killer, PlayerControl target, PlayerControl seer) { - if (seer.Is(CustomRoles.GM) || seer.Is(CustomRoles.Seer)) - { - return true; - } + if (seer.Is(CustomRoles.GM) || seer.Is(CustomRoles.Seer)) return true; - if (seer.Data.IsDead || killer == seer || target == seer) - { - return false; - } + if (seer.Data.IsDead || killer == seer || target == seer) return false; return seer.Is(CustomRoles.EvilTracker) && EvilTracker.KillFlashCheck(killer, target); } @@ -402,6 +349,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { opt.SetFloat(FloatOptionNames.ImpostorLightMod, Main.DefaultImpostorVision); opt.SetFloat(FloatOptionNames.CrewLightMod, Main.DefaultCrewmateVision); + if (IsBlackOut) { opt.SetFloat(FloatOptionNames.ImpostorLightMod, 0); @@ -421,16 +369,19 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { Il2CppSystem.Collections.Generic.Dictionary>> data = new(); Dictionary>> dict = path.Contains("Always") ? Main.AlwaysSpawnTogetherCombos : Main.NeverSpawnTogetherCombos; + dict.Do(kvp => { data[kvp.Key] = new(); + kvp.Value.Do(pair => { - string key = pair.Key.ToString(); + var key = pair.Key.ToString(); data[kvp.Key][key] = new(); pair.Value.Do(x => data[kvp.Key][key].Add(x.ToString())); }); }); + File.WriteAllText(path, JsonConvert.SerializeObject(data, Formatting.Indented)); } catch (Exception e) @@ -451,25 +402,21 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { try { - if (!File.Exists(path)) - { - return; - } + if (!File.Exists(path)) return; - Il2CppSystem.Collections.Generic.Dictionary>> data = JsonConvert.DeserializeObject>>>(File.ReadAllText(path)); + var data = JsonConvert.DeserializeObject>>>(File.ReadAllText(path)); Dictionary>> dict = path.Contains("Always") ? Main.AlwaysSpawnTogetherCombos : Main.NeverSpawnTogetherCombos; dict.Clear(); + foreach (Il2CppSystem.Collections.Generic.KeyValuePair>> kvp in data) { dict[kvp.Key] = []; + foreach (Il2CppSystem.Collections.Generic.KeyValuePair> pair in kvp.Value) { - CustomRoles key = Enum.Parse(pair.Key); + var key = Enum.Parse(pair.Key); dict[kvp.Key][key] = []; - foreach (string n in pair.Value) - { - dict[kvp.Key][key].Add(Enum.Parse(n)); - } + foreach (string n in pair.Value) dict[kvp.Key][key].Add(Enum.Parse(n)); } } } @@ -494,12 +441,10 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static string GetRoleMode(CustomRoles role, bool parentheses = true) { - if (Options.HideGameSettings.GetBool() && Main.AllPlayerControls.Length > 1) - { - return string.Empty; - } + if (Options.HideGameSettings.GetBool() && Main.AllPlayerControls.Length > 1) return string.Empty; string mode; + try { mode = !role.IsAdditionRole() @@ -543,13 +488,11 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ bool self = seerId == targetId || Main.PlayerStates[seerId].IsDead; - if (!self && Main.DiedThisRound.Contains(seerId)) - { - return (string.Empty, Color.white); - } + if (!self && Main.DiedThisRound.Contains(seerId)) return (string.Empty, Color.white); bool isHnsAgentOverride = Options.CurrentGameMode == CustomGameMode.HideAndSeek && targetMainRole == CustomRoles.Agent && HnSManager.PlayerRoles[seerId].Interface.Team != Team.Impostor; - bool loversShowDifferentRole = false; + var loversShowDifferentRole = false; + if (!GameStates.IsEnded && targetMainRole == CustomRoles.LovingImpostor && !self && seerMainRole != CustomRoles.LovingCrewmate && !seerSubRoles.Contains(CustomRoles.Lovers)) { targetMainRole = Lovers.LovingImpostorRoleForOtherImps.GetValue() switch @@ -558,16 +501,14 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ 1 => Lovers.LovingImpostorRole, _ => CustomRoles.LovingImpostor }; + loversShowDifferentRole = true; } string RoleText = GetRoleName(isHnsAgentOverride ? CustomRoles.Hider : targetMainRole); Color RoleColor = GetRoleColor(isHnsAgentOverride ? CustomRoles.Hider : loversShowDifferentRole ? CustomRoles.Impostor : targetMainRole); - if (LastImpostor.CurrentId == targetId) - { - RoleText = GetRoleString("Last-") + RoleText; - } + if (LastImpostor.CurrentId == targetId) RoleText = GetRoleString("Last-") + RoleText; if (Options.NameDisplayAddons.GetBool() && !pure && self) { @@ -576,20 +517,14 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ if (subRole is not CustomRoles.LastImpostor and not CustomRoles.Madmate and not CustomRoles.Charmed and not CustomRoles.Recruit and not CustomRoles.Lovers and not CustomRoles.Contagious and not CustomRoles.Bloodlust) { string str = GetString("Prefix." + subRole); - if (!subRole.IsAdditionRole()) - { - str = GetString(subRole.ToString()); - } + if (!subRole.IsAdditionRole()) str = GetString(subRole.ToString()); RoleText = ColorString(GetRoleColor(subRole), (Options.AddBracketsToAddons.GetBool() ? "<#ffffff>(" : string.Empty) + str + (Options.AddBracketsToAddons.GetBool() ? "<#ffffff>)" : string.Empty) + " ") + RoleText; } } } - if (seerMainRole == CustomRoles.LovingImpostor && self) - { - RoleColor = GetRoleColor(CustomRoles.LovingImpostor); - } + if (seerMainRole == CustomRoles.LovingImpostor && self) RoleColor = GetRoleColor(CustomRoles.LovingImpostor); if (targetSubRoles.Contains(CustomRoles.Madmate)) { @@ -626,10 +561,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static string GetKillCountText(byte playerId, bool ffa = false) { - if (Main.PlayerStates.All(x => x.Value.GetRealKiller() != playerId) && !ffa) - { - return string.Empty; - } + if (Main.PlayerStates.All(x => x.Value.GetRealKiller() != playerId) && !ffa) return string.Empty; return ' ' + ColorString(new(255, 69, 0, byte.MaxValue), string.Format(GetString("KillCount"), Main.PlayerStates.Count(x => x.Value.GetRealKiller() == playerId))); } @@ -638,14 +570,12 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { PlayerState state = Main.PlayerStates[playerId]; string deathReason = state.IsDead ? GetString("DeathReason." + state.deathReason) : GetString("Alive"); + if (realKillerColor) { byte KillerId = state.GetRealKiller(); Color color = KillerId != byte.MaxValue ? Main.PlayerColors[KillerId] : GetRoleColor(CustomRoles.Doctor); - if (state.deathReason == PlayerState.DeathReason.Disconnected) - { - color = new(255, 255, 255, 50); - } + if (state.deathReason == PlayerState.DeathReason.Disconnected) color = new(255, 255, 255, 50); deathReason = ColorString(color, deathReason); } @@ -665,12 +595,10 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static void SendRPC(CustomRPC rpc, params object[] data) { - if (!DoRPC) - { - return; - } + if (!DoRPC) return; MessageWriter w; + try { w = CreateRPC(rpc); @@ -719,10 +647,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ default: try { - if (o != null && Enum.TryParse(o.GetType(), o.ToString(), out object e) && e != null) - { - w.WritePacked((int)e); - } + if (o != null && Enum.TryParse(o.GetType(), o.ToString(), out object e) && e != null) w.WritePacked((int)e); } catch (InvalidCastException e) { @@ -741,10 +666,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static void IncreaseAbilityUseLimitOnKill(PlayerControl killer) { - if (Main.PlayerStates[killer.PlayerId].Role is Mafioso { IsEnable: true } mo) - { - mo.OnMurder(killer, null); - } + if (Main.PlayerStates[killer.PlayerId].Role is Mafioso { IsEnable: true } mo) mo.OnMurder(killer, null); float add = GetSettingNameAndValueForRole(killer.GetCustomRole(), "AbilityUseGainWithEachKill"); killer.RpcIncreaseAbilityUseLimitBy(add); @@ -762,7 +684,8 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ StringBuilder sb = new(); sb.Append($" {ex.GetType().Name}: {ex.Message}\n thrown by {ex.Source}\n at {ex.TargetSite}\n in {fileName.Split('\\')[^1]}\n at line {lineNumber}\n in method \"{callerMemberName}\"\n------ Method Stack Trace ------"); - bool skip = true; + var skip = true; + foreach (StackFrame sf in stFrames) { if (skip) @@ -804,9 +727,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ Logger.Error(sb.ToString(), firstFrame?.GetMethod()?.ToString(), multiLine: true); } - catch - { - } + catch { } } public static void SetAllVentInteractions() @@ -816,32 +737,17 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static bool HasTasks(NetworkedPlayerInfo p, bool ForRecompute = true) { - if (GameStates.IsLobby) - { - return false; - } + if (GameStates.IsLobby) return false; - if (p.Tasks == null) - { - return false; - } + if (p.Tasks == null) return false; - if (p.Role == null) - { - return false; - } + if (p.Role == null) return false; - bool hasTasks = true; + var hasTasks = true; PlayerState state = Main.PlayerStates[p.PlayerId]; - if (p.Disconnected) - { - return false; - } + if (p.Disconnected) return false; - if (p.Role.IsImpostor) - { - hasTasks = false; - } + if (p.Role.IsImpostor) hasTasks = false; switch (Options.CurrentGameMode) { @@ -857,6 +763,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ } CustomRoles role = state.MainRole; + switch (role) { case CustomRoles.GM: @@ -975,33 +882,21 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ case CustomRoles.Executioner: case CustomRoles.Lawyer: case CustomRoles.Phantasm: - if (ForRecompute) - { - hasTasks = false; - } + if (ForRecompute) hasTasks = false; break; case CustomRoles.Cherokious: case CustomRoles.Crewpostor: - if (ForRecompute && !p.IsDead) - { - hasTasks = false; - } + if (ForRecompute && !p.IsDead) hasTasks = false; - if (p.IsDead) - { - hasTasks = false; - } + if (p.IsDead) hasTasks = false; break; case CustomRoles.Wizard: hasTasks = true; break; default: - if (role.IsImpostor()) - { - hasTasks = false; - } + if (role.IsImpostor()) hasTasks = false; break; } @@ -1029,10 +924,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ } } - if (CopyCat.Instances.Any(x => x.CopyCatPC.PlayerId == p.PlayerId) && ForRecompute && (!Options.UsePets.GetBool() || CopyCat.UsePet.GetBool())) - { - hasTasks = false; - } + if (CopyCat.Instances.Any(x => x.CopyCatPC.PlayerId == p.PlayerId) && ForRecompute && (!Options.UsePets.GetBool() || CopyCat.UsePet.GetBool())) hasTasks = false; hasTasks |= role.UsesPetInsteadOfKill() && role is not (CustomRoles.Refugee or CustomRoles.Necromancer or CustomRoles.Deathknight or CustomRoles.Sidekick); @@ -1074,15 +966,9 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ return true; } - if ((Main.VisibleTasksCount && PlayerControl.LocalPlayer.Data.IsDead && Options.GhostCanSeeOtherRoles.GetBool()) || (PlayerControl.LocalPlayer.Is(CustomRoles.Mimic) && Main.VisibleTasksCount && __instance.Data.IsDead && Options.MimicCanSeeDeadRoles.GetBool())) - { - return true; - } + if ((Main.VisibleTasksCount && PlayerControl.LocalPlayer.Data.IsDead && Options.GhostCanSeeOtherRoles.GetBool()) || (PlayerControl.LocalPlayer.Is(CustomRoles.Mimic) && Main.VisibleTasksCount && __instance.Data.IsDead && Options.MimicCanSeeDeadRoles.GetBool())) return true; - if (__instance.PlayerId == PlayerControl.LocalPlayer.PlayerId) - { - return true; - } + if (__instance.PlayerId == PlayerControl.LocalPlayer.PlayerId) return true; switch (__instance.GetCustomRole()) { @@ -1132,18 +1018,13 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static string GetProgressText(PlayerControl pc) { TaskState taskState = pc.GetTaskState(); - bool Comms = false; + var Comms = false; + if (taskState.HasTasks) { - if (IsActive(SystemTypes.Comms)) - { - Comms = true; - } + if (IsActive(SystemTypes.Comms)) Comms = true; - if (Camouflager.IsActive) - { - Comms = true; - } + if (Camouflager.IsActive) Comms = true; //if (PlayerControl.LocalPlayer.myTasks.ToArray().Any(x => x.TaskType == TaskTypes.FixComms)) Comms = true; } @@ -1160,6 +1041,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ StringBuilder ProgressText = new(); PlayerControl pc = GetPlayerById(playerId); + try { ProgressText.Append(Main.PlayerStates[playerId].Role.GetProgressText(playerId, comms)); @@ -1169,20 +1051,11 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ Logger.Error($"For {pc.GetNameWithRole().RemoveHtmlTags()}, failed to get progress text: " + ex, "Utils.GetProgressText"); } - if (pc.Is(CustomRoles.Damocles)) - { - ProgressText.Append($" {Damocles.GetProgressText(playerId)}"); - } + if (pc.Is(CustomRoles.Damocles)) ProgressText.Append($" {Damocles.GetProgressText(playerId)}"); - if (pc.Is(CustomRoles.Stressed)) - { - ProgressText.Append($" {Stressed.GetProgressText(playerId)}"); - } + if (pc.Is(CustomRoles.Stressed)) ProgressText.Append($" {Stressed.GetProgressText(playerId)}"); - if (pc.Is(CustomRoles.Circumvent)) - { - ProgressText.Append($" {Circumvent.GetProgressText(playerId)}"); - } + if (pc.Is(CustomRoles.Circumvent)) ProgressText.Append($" {Circumvent.GetProgressText(playerId)}"); if (pc.Is(CustomRoles.Taskcounter)) { @@ -1190,10 +1063,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ ProgressText.Append($" <#00ffa5>{totalCompleted}<#ffffff>/{GameData.Instance.TotalTasks}"); } - if (ProgressText.Length != 0 && !ProgressText.ToString().RemoveHtmlTags().StartsWith(' ')) - { - ProgressText.Insert(0, ' '); - } + if (ProgressText.Length != 0 && !ProgressText.ToString().RemoveHtmlTags().StartsWith(' ')) ProgressText.Insert(0, ' '); return ProgressText.ToString(); } @@ -1203,24 +1073,16 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ try { float limit = playerId.GetAbilityUseLimit(); - if (float.IsNaN(limit) /* || limit is > 100 or < 0*/) - { - return string.Empty; - } + if (float.IsNaN(limit) /* || limit is > 100 or < 0*/) return string.Empty; Color TextColor; + if (limit < 1) - { TextColor = Color.red; - } else if (usingAbility) - { TextColor = Color.green; - } else - { TextColor = GetRoleColor(Main.PlayerStates[playerId].MainRole).ShadeColor(0.25f); - } return ColorString(TextColor, $" ({Math.Round(limit, 1)})"); } @@ -1234,27 +1096,19 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { try { - if (playerId == 0 && Main.GM.Value) - { - return string.Empty; - } + if (playerId == 0 && Main.GM.Value) return string.Empty; TaskState taskState = Main.PlayerStates[playerId].TaskState; - if (!taskState.HasTasks) - { - return string.Empty; - } + if (!taskState.HasTasks) return string.Empty; NetworkedPlayerInfo info = GetPlayerInfoById(playerId); Color TaskCompleteColor = HasTasks(info) ? Color.green : GetRoleColor(Main.PlayerStates[playerId].MainRole).ShadeColor(0.5f); Color NonCompleteColor = HasTasks(info) ? Color.yellow : Color.white; - if (Workhorse.IsThisRole(playerId)) - { - NonCompleteColor = Workhorse.RoleColor; - } + if (Workhorse.IsThisRole(playerId)) NonCompleteColor = Workhorse.RoleColor; Color NormalColor = taskState.IsTaskFinished ? TaskCompleteColor : NonCompleteColor; + if (Main.PlayerStates.TryGetValue(playerId, out PlayerState ps)) { NormalColor = ps.MainRole switch @@ -1279,40 +1133,19 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { SendMessage(GetString("CurrentActiveSettingsHelp") + ":", PlayerId); - if (Options.DisableDevices.GetBool()) - { - SendMessage(GetString("DisableDevicesInfo"), PlayerId); - } + if (Options.DisableDevices.GetBool()) SendMessage(GetString("DisableDevicesInfo"), PlayerId); - if (Options.SyncButtonMode.GetBool()) - { - SendMessage(GetString("SyncButtonModeInfo"), PlayerId); - } + if (Options.SyncButtonMode.GetBool()) SendMessage(GetString("SyncButtonModeInfo"), PlayerId); - if (Options.SabotageTimeControl.GetBool()) - { - SendMessage(GetString("SabotageTimeControlInfo"), PlayerId); - } + if (Options.SabotageTimeControl.GetBool()) SendMessage(GetString("SabotageTimeControlInfo"), PlayerId); - if (Options.RandomMapsMode.GetBool()) - { - SendMessage(GetString("RandomMapsModeInfo"), PlayerId); - } + if (Options.RandomMapsMode.GetBool()) SendMessage(GetString("RandomMapsModeInfo"), PlayerId); - if (Main.GM.Value) - { - SendMessage(GetRoleName(CustomRoles.GM) + GetString("GMInfoLong"), PlayerId); - } + if (Main.GM.Value) SendMessage(GetRoleName(CustomRoles.GM) + GetString("GMInfoLong"), PlayerId); - foreach (CustomRoles role in Enum.GetValues().Where(role => role.IsEnable() && !role.IsVanilla())) - { - SendMessage(GetRoleName(role) + GetRoleMode(role) + GetString(Enum.GetName(typeof(CustomRoles), role) + "InfoLong"), PlayerId); - } + foreach (CustomRoles role in Enum.GetValues().Where(role => role.IsEnable() && !role.IsVanilla())) SendMessage(GetRoleName(role) + GetRoleMode(role) + GetString(Enum.GetName(typeof(CustomRoles), role) + "InfoLong"), PlayerId); - if (Options.NoGameEnd.GetBool()) - { - SendMessage(GetString("NoGameEndInfo"), PlayerId); - } + if (Options.NoGameEnd.GetBool()) SendMessage(GetString("NoGameEndInfo"), PlayerId); } /// @@ -1342,20 +1175,22 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ StringBuilder sb = new(); sb.Append(" ★ " + GetString("TabGroup.SystemSettings")); + foreach (OptionItem opt in OptionItem.AllOptions.Where(x => x.GetBool() && x.Parent == null && x.Tab is TabGroup.SystemSettings && !x.IsHiddenOn(Options.CurrentGameMode))) { sb.Append($"\n{opt.GetName(true)}: {opt.GetString()}"); //ShowChildrenSettings(opt, ref sb); - string text = sb.ToString(); + var text = sb.ToString(); sb.Clear().Append(text.RemoveHtmlTags()); } sb.Append("\n\n ★ " + GetString("TabGroup.GameSettings")); + foreach (OptionItem opt in OptionItem.AllOptions.Where(x => x.GetBool() && x.Parent == null && x.Tab is TabGroup.GameSettings && !x.IsHiddenOn(Options.CurrentGameMode))) { sb.Append($"\n{opt.GetName(true)}: {opt.GetString()}"); //ShowChildrenSettings(opt, ref sb); - string text = sb.ToString(); + var text = sb.ToString(); sb.Clear().Append(text.RemoveHtmlTags()); } @@ -1379,14 +1214,13 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ StringBuilder sb = new(); sb.Append(GetString("Settings")).Append(':'); + foreach (KeyValuePair role in Options.CustomRoleCounts) { - if (!role.Key.IsEnable()) - { - continue; - } + if (!role.Key.IsEnable()) continue; string mode; + try { mode = !role.Key.IsAdditionRole() @@ -1402,7 +1236,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ sb.Append($"\n【{GetRoleName(role.Key)}:{mode} ×{role.Key.GetCount()}】\n"); ShowChildrenSettings(Options.CustomRoleSpawnChances[role.Key], ref sb); - string text = sb.ToString(); + var text = sb.ToString(); sb.Clear().Append(text.RemoveHtmlTags()); } @@ -1411,16 +1245,12 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ if (opt.GetBool() && opt.Parent == null && opt.Id is >= 80000 and < 640000 && !opt.IsHiddenOn(Options.CurrentGameMode)) { if (opt.Name is "KillFlashDuration" or "RoleAssigningAlgorithm") - { sb.Append($"\n【{opt.GetName(true)}: {opt.GetString()}】\n"); - } else - { sb.Append($"\n【{opt.GetName(true)}】\n"); - } ShowChildrenSettings(opt, ref sb); - string text = sb.ToString(); + var text = sb.ToString(); sb.Clear().Append(text.RemoveHtmlTags()); } } @@ -1431,6 +1261,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static void CopyCurrentSettings() { StringBuilder sb = new(); + if (Options.HideGameSettings.GetBool() && !AmongUsClient.Instance.AmHost) { ClipboardHelper.PutClipboardString(GetString("Message.HideGameSettings")); @@ -1438,14 +1269,13 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ } sb.Append($"━━━━━━━━━━━━【{GetString("Roles")}】━━━━━━━━━━━━"); + foreach (KeyValuePair role in Options.CustomRoleCounts) { - if (!role.Key.IsEnable()) - { - continue; - } + if (!role.Key.IsEnable()) continue; string mode; + try { mode = !role.Key.IsAdditionRole() @@ -1461,24 +1291,21 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ sb.Append($"\n【{GetRoleName(role.Key)}:{mode} ×{role.Key.GetCount()}】\n"); ShowChildrenSettings(Options.CustomRoleSpawnChances[role.Key], ref sb); - string text = sb.ToString(); + var text = sb.ToString(); sb.Clear().Append(text.RemoveHtmlTags()); } sb.Append($"━━━━━━━━━━━━【{GetString("Settings")}】━━━━━━━━━━━━"); + foreach (OptionItem opt in OptionItem.AllOptions.Where(x => x.GetBool() && x.Parent == null && x.Id is >= 80000 and < 640000 && !x.IsHiddenOn(Options.CurrentGameMode))) { if (opt.Name == "KillFlashDuration") - { sb.Append($"\n【{opt.GetName(true)}: {opt.GetString()}】\n"); - } else - { sb.Append($"\n【{opt.GetName(true)}】\n"); - } ShowChildrenSettings(opt, ref sb); - string text = sb.ToString(); + var text = sb.ToString(); sb.Clear().Append(text.RemoveHtmlTags()); } @@ -1506,6 +1333,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ foreach (CustomRoles role in Options.CurrentGameMode == CustomGameMode.HideAndSeek ? HnSManager.AllHnSRoles : Enum.GetValues().Except(HnSManager.AllHnSRoles)) { string mode; + try { mode = !role.IsAdditionRole() || role.IsGhostRole() @@ -1521,27 +1349,17 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ if (role.IsEnable()) { - string roleDisplay = $"\n{ColorString(GetRoleColor(role).ShadeColor(0.25f), GetString(role.ToString()))}: {mode} x{role.GetCount()}"; + var roleDisplay = $"\n{ColorString(GetRoleColor(role).ShadeColor(0.25f), GetString(role.ToString()))}: {mode} x{role.GetCount()}"; + if (role.IsGhostRole()) - { ghostsb.Append(roleDisplay); - } else if (role.IsAdditionRole()) - { addonsb.Append(roleDisplay); - } else if (role.IsCrewmate()) - { crewsb.Append(roleDisplay); - } else if (role.IsImpostor() || role.IsMadmate()) - { impsb.Append(roleDisplay); - } - else if (role.IsNeutral()) - { - neutralsb.Append(roleDisplay); - } + else if (role.IsNeutral()) neutralsb.Append(roleDisplay); } } @@ -1576,12 +1394,9 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ } string value = opt.Value.GetString().Replace("ON", "<#00ffa5>ON").Replace("OFF", "<#ff0000>OFF"); - string name = $"{opt.Value.GetName(disableColor).Replace("color=", string.Empty)}"; + var name = $"{opt.Value.GetName(disableColor).Replace("color=", string.Empty)}"; sb.Append($"{name}: <#ffff00>{value}\n"); - if (opt.Value.GetBool()) - { - ShowChildrenSettings(opt.Value, ref sb, deep + 1, disableColor: disableColor); - } + if (opt.Value.GetBool()) ShowChildrenSettings(opt.Value, ref sb, deep + 1, disableColor: disableColor); } } @@ -1598,14 +1413,12 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ sb.Append("<#ffffff>Role Summary:"); List cloneRoles = [.. Main.PlayerStates.Keys]; + foreach (byte id in Main.WinnerList) { try { - if (EndGamePatch.SummaryText[id].Contains("")) - { - continue; - } + if (EndGamePatch.SummaryText[id].Contains("")) continue; sb.Append("\n<#c4aa02>\u2605 ").Append(EndGamePatch.SummaryText[id] /*.RemoveHtmlTags()*/); cloneRoles.Remove(id); @@ -1623,6 +1436,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ list.AddRange(cloneRoles.Select(id => (SoloKombatManager.GetRankOfScore(id), id))); list.Sort(); + foreach ((int, byte) id in list) { try @@ -1641,6 +1455,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ list2.AddRange(cloneRoles.Select(id => (FFAManager.GetRankFromScore(id), id))); list2.Sort(); + foreach ((int, byte) id in list2) { try @@ -1659,6 +1474,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ list3.AddRange(cloneRoles.Select(id => (MoveAndStopManager.GetRankOfScore(id), id))); list3.Sort(); + foreach ((int, byte) id in list3) { try @@ -1696,15 +1512,9 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { try { - if (!EndGamePatch.SummaryText.TryGetValue(id, out string summaryText)) - { - continue; - } + if (!EndGamePatch.SummaryText.TryGetValue(id, out string summaryText)) continue; - if (summaryText.Contains("")) - { - continue; - } + if (summaryText.Contains("")) continue; sb.Append("\n\u3000 ").Append(summaryText); } @@ -1730,10 +1540,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ return; } - if (EndGamePatch.KillLog != string.Empty) - { - SendMessage(EndGamePatch.KillLog, PlayerId); - } + if (EndGamePatch.KillLog != string.Empty) SendMessage(EndGamePatch.KillLog, PlayerId); } public static void ShowLastResult(byte PlayerId = byte.MaxValue) @@ -1744,26 +1551,14 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ return; } - if (Options.CurrentGameMode != CustomGameMode.Standard) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.Standard) return; StringBuilder sb = new(); - if (SetEverythingUpPatch.LastWinsText != string.Empty) - { - sb.Append($"{GetString("LastResult")} {SetEverythingUpPatch.LastWinsText}"); - } + if (SetEverythingUpPatch.LastWinsText != string.Empty) sb.Append($"{GetString("LastResult")} {SetEverythingUpPatch.LastWinsText}"); - if (SetEverythingUpPatch.LastWinsReason != string.Empty) - { - sb.Append($"\n{GetString("LastEndReason")} {SetEverythingUpPatch.LastWinsReason}"); - } + if (SetEverythingUpPatch.LastWinsReason != string.Empty) sb.Append($"\n{GetString("LastEndReason")} {SetEverythingUpPatch.LastWinsReason}"); - if (sb.Length > 0) - { - SendMessage("\n", PlayerId, sb.ToString()); - } + if (sb.Length > 0) SendMessage("\n", PlayerId, sb.ToString()); } public static void ShowLastAddOns(byte PlayerId = byte.MaxValue) @@ -1774,10 +1569,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ return; } - if (Options.CurrentGameMode != CustomGameMode.Standard) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.Standard) return; string result = Main.LastAddOns.Values.Join(delimiter: "\n"); SendMessage("\n", PlayerId, result); @@ -1786,28 +1578,21 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static string GetSubRolesText(byte id, bool disableColor = false, bool intro = false, bool summary = false) { List SubRoles = Main.PlayerStates[id].SubRoles; - if (SubRoles.Count == 0) - { - return string.Empty; - } + if (SubRoles.Count == 0) return string.Empty; StringBuilder sb = new(); + if (intro) { bool isLovers = SubRoles.Contains(CustomRoles.Lovers) && Main.PlayerStates[id].MainRole is not CustomRoles.LovingCrewmate and not CustomRoles.LovingImpostor; SubRoles.RemoveAll(x => x is CustomRoles.NotAssigned or CustomRoles.LastImpostor or CustomRoles.Lovers); - if (isLovers) - { - sb.Append($"{ColorString(GetRoleColor(CustomRoles.Lovers), " ♥")}"); - } + if (isLovers) sb.Append($"{ColorString(GetRoleColor(CustomRoles.Lovers), " ♥")}"); - if (SubRoles.Count == 0) - { - return sb.ToString(); - } + if (SubRoles.Count == 0) return sb.ToString(); sb.Append(""); + if (SubRoles.Count == 1) { CustomRoles role = SubRoles[0]; @@ -1818,12 +1603,10 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ else { sb.Append($"{ColorString(Color.gray, GetString("Modifiers"))}"); - for (int i = 0; i < SubRoles.Count; i++) + + for (var i = 0; i < SubRoles.Count; i++) { - if (i != 0) - { - sb.Append(", "); - } + if (i != 0) sb.Append(", "); CustomRoles role = SubRoles[i]; @@ -1838,10 +1621,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { foreach (CustomRoles role in SubRoles) { - if (role is CustomRoles.NotAssigned or CustomRoles.LastImpostor) - { - continue; - } + if (role is CustomRoles.NotAssigned or CustomRoles.LastImpostor) continue; string RoleText = disableColor ? GetRoleName(role) : ColorString(GetRoleColor(role), GetRoleName(role)); sb.Append($"{ColorString(Color.gray, " + ")}{RoleText}"); @@ -1856,6 +1636,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ text = text.ToLowerInvariant(); text = text.Replace("色", string.Empty); int color; + try { color = int.Parse(text); @@ -1918,24 +1699,17 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static void CheckTerroristWin(NetworkedPlayerInfo Terrorist) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; TaskState taskState = GetPlayerById(Terrorist.PlayerId).GetTaskState(); + if (taskState.IsTaskFinished && (!Main.PlayerStates[Terrorist.PlayerId].IsSuicide || Options.CanTerroristSuicideWin.GetBool())) { foreach (PlayerControl pc in Main.AllPlayerControls) { if (pc.Is(CustomRoles.Terrorist)) - { Main.PlayerStates[pc.PlayerId].deathReason = Main.PlayerStates[pc.PlayerId].deathReason == PlayerState.DeathReason.Vote ? PlayerState.DeathReason.etc : PlayerState.DeathReason.Suicide; - } - else if (!pc.Data.IsDead) - { - pc.Suicide(PlayerState.DeathReason.Bombed, Terrorist.Object); - } + else if (!pc.Data.IsDead) pc.Suicide(PlayerState.DeathReason.Bombed, Terrorist.Object); } CustomWinnerHolder.ResetAndSetWinner(CustomWinner.Terrorist); @@ -1947,10 +1721,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { try { - if (Options.CurrentGameMode != CustomGameMode.Standard || deadPlayer == null || deadPlayer.Object.Is(CustomRoles.Refugee) || Main.HasJustStarted || !GameStates.InGame || !Options.SpawnAdditionalRefugeeOnImpsDead.GetBool() || Main.AllAlivePlayerControls.Length < Options.SpawnAdditionalRefugeeMinAlivePlayers.GetInt() || CustomRoles.Refugee.RoleExist(true) || Main.AllAlivePlayerControls == null || Main.AllAlivePlayerControls.Length == 0 || Main.AllAlivePlayerControls.Any(x => x.PlayerId != deadPlayer.PlayerId && (x.Is(CustomRoleTypes.Impostor) || (x.IsNeutralKiller() && !Options.SpawnAdditionalRefugeeWhenNKAlive.GetBool())))) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.Standard || deadPlayer == null || deadPlayer.Object.Is(CustomRoles.Refugee) || Main.HasJustStarted || !GameStates.InGame || !Options.SpawnAdditionalRefugeeOnImpsDead.GetBool() || Main.AllAlivePlayerControls.Length < Options.SpawnAdditionalRefugeeMinAlivePlayers.GetInt() || CustomRoles.Refugee.RoleExist(true) || Main.AllAlivePlayerControls == null || Main.AllAlivePlayerControls.Length == 0 || Main.AllAlivePlayerControls.Any(x => x.PlayerId != deadPlayer.PlayerId && (x.Is(CustomRoleTypes.Impostor) || (x.IsNeutralKiller() && !Options.SpawnAdditionalRefugeeWhenNKAlive.GetBool())))) return; PlayerControl[] ListToChooseFrom = Main.AllAlivePlayerControls.Where(x => x.PlayerId != deadPlayer.PlayerId && x.Is(CustomRoleTypes.Crewmate) && !x.Is(CustomRoles.Loyal)).ToArray(); @@ -1963,9 +1734,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ Logger.Warn($"{pc.GetRealName()} is now a Refugee since all Impostors are dead", "Add Refugee"); } else - { Logger.Msg("No Player to change to Refugee.", "Add Refugee"); - } } catch (Exception e) { @@ -1990,21 +1759,14 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ return; } - if (title == "") - { - title = "" + GetString("DefaultSystemMessageTitle") + ""; - } + if (title == "") title = "" + GetString("DefaultSystemMessageTitle") + ""; if (title.Count(x => x == '\u2605') == 2 && !title.Contains('\n')) { if (title.Contains('<') && title.Contains('>') && title.Contains('#')) - { title = $"{title[..(title.IndexOf('>') + 1)]}\u27a1{title.Replace("\u2605", "")[..(title.LastIndexOf('<') - 2)]}\u2b05"; - } else - { title = "\u27a1" + title.Replace("\u2605", "") + "\u2b05"; - } } text = text.Replace("color=", string.Empty); @@ -2012,7 +1774,8 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ if (text.Length >= 1200 && !noSplit) { string[] lines = text.Split('\n'); - string shortenedText = string.Empty; + var shortenedText = string.Empty; + foreach (string line in lines) { if (shortenedText.Length + line.Length < 1200) @@ -2022,13 +1785,9 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ } if (shortenedText.Length >= 1200) - { shortenedText.Chunk(1200).Do(x => SendMessage(new(x), sendTo, title, true)); - } else - { SendMessage(shortenedText, sendTo, title, true); - } string sentText = shortenedText; shortenedText = line + "\n"; @@ -2040,10 +1799,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ } } - if (shortenedText.Length > 0) - { - SendMessage(shortenedText, sendTo, title, true); - } + if (shortenedText.Length > 0) SendMessage(shortenedText, sendTo, title, true); return; } @@ -2062,60 +1818,36 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ text = text.RemoveHtmlTagsTemplate(); if (sendTo == byte.MaxValue) - { Main.MessagesToSend.Add((text, sendTo, title)); - } else - { ChatUpdatePatch.SendMessage(Main.AllAlivePlayerControls.MinBy(x => x.PlayerId) ?? Main.AllPlayerControls.MinBy(x => x.PlayerId) ?? PlayerControl.LocalPlayer, text, sendTo, title); - } } public static void ApplySuffix(PlayerControl player) { - if (!AmongUsClient.Instance.AmHost || player == null) - { - return; - } + if (!AmongUsClient.Instance.AmHost || player == null) return; - if (!player.AmOwner && !player.FriendCode.GetDevUser().HasTag() && !ChatCommands.IsPlayerModerator(player.FriendCode) && !ChatCommands.IsPlayerVIP(player.FriendCode)) - { - return; - } + if (!player.AmOwner && !player.FriendCode.GetDevUser().HasTag() && !ChatCommands.IsPlayerModerator(player.FriendCode) && !ChatCommands.IsPlayerVIP(player.FriendCode)) return; string name = Main.AllPlayerNames.TryGetValue(player.PlayerId, out string n) ? n : string.Empty; - if (Main.NickName != string.Empty && player.AmOwner) - { - name = Main.NickName; - } + if (Main.NickName != string.Empty && player.AmOwner) name = Main.NickName; - if (name == string.Empty) - { - return; - } + if (name == string.Empty) return; if (AmongUsClient.Instance.IsGameStarted) { - if (Options.FormatNameMode.GetInt() == 1 && Main.NickName == string.Empty) - { - name = Palette.GetColorName(player.Data.DefaultOutfit.ColorId); - } + if (Options.FormatNameMode.GetInt() == 1 && Main.NickName == string.Empty) name = Palette.GetColorName(player.Data.DefaultOutfit.ColorId); } else { - if (!GameStates.IsLobby) - { - return; - } + if (!GameStates.IsLobby) return; if (player.AmOwner) { - if (GameStates.IsOnlineGame || GameStates.IsLocalGame) - { - name = $"{GetString("HostText")}{GetString("Icon")}{name}"; - } + if (GameStates.IsOnlineGame || GameStates.IsLocalGame) name = $"{GetString("HostText")}{GetString("Icon")}{name}"; string modeText = GetString($"Mode{Options.CurrentGameMode}"); + name = Options.CurrentGameMode switch { CustomGameMode.SoloKombat => $"{modeText}\r\n{name}", @@ -2135,24 +1867,22 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ bool isMod = ChatCommands.IsPlayerModerator(player.FriendCode); bool isVIP = ChatCommands.IsPlayerVIP(player.FriendCode); bool hasTag = devUser.HasTag(); + if (hasTag || isMod || isVIP) { string tag = hasTag ? devUser.GetTag() : string.Empty; - if (tag == "null") - { - tag = string.Empty; - } + if (tag == "null") tag = string.Empty; if (player.AmOwner || player.IsModClient()) { - string modTagModded = $"{GetString("ModeratorTag")}\r\n"; - string vipTagModded = $"{GetString("VIPTag")}\r\n"; + var modTagModded = $"{GetString("ModeratorTag")}\r\n"; + var vipTagModded = $"{GetString("VIPTag")}\r\n"; name = $"{(hasTag ? tag : string.Empty)}{(isMod ? modTagModded : string.Empty)}{(isVIP ? vipTagModded : string.Empty)}{name}"; } else { - string modTagVanilla = $"{GetString("ModeratorTag")} - "; - string vipTagVanilla = $"{GetString("VIPTag")} - "; + var modTagVanilla = $"{GetString("ModeratorTag")} - "; + var vipTagVanilla = $"{GetString("VIPTag")} - "; name = $"{(hasTag ? tag.Replace("\r\n", " - ") : string.Empty)}{(isMod ? modTagVanilla : string.Empty)}{(isVIP ? vipTagVanilla : string.Empty)}{name}"; } } @@ -2174,45 +1904,28 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ } } - if (name != player.name && player.CurrentOutfitType == PlayerOutfitType.Default) - { - player.RpcSetName(name); - } + if (name != player.name && player.CurrentOutfitType == PlayerOutfitType.Default) player.RpcSetName(name); } public static Dictionary GetAllPlayerLocationsCount() { Dictionary playerRooms = []; + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId)) - { - return null; - } + if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId)) return null; Il2CppReferenceArray Rooms = ShipStatus.Instance.AllRooms; - if (Rooms == null) - { - return null; - } + if (Rooms == null) return null; foreach (PlainShipRoom room in Rooms) { - if (!room.roomArea) - { - continue; - } + if (!room.roomArea) continue; - if (!pc.Collider.IsTouching(room.roomArea)) - { - continue; - } + if (!pc.Collider.IsTouching(room.roomArea)) continue; string roomName = GetString($"{room.RoomId}"); - if (!playerRooms.TryAdd(roomName, 1)) - { - playerRooms[roomName]++; - } + if (!playerRooms.TryAdd(roomName, 1)) playerRooms[roomName]++; } } @@ -2224,12 +1937,15 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; Type[] types = Assembly.GetExecutingAssembly().GetTypes(); FieldInfo field = types.SelectMany(x => x.GetFields(flags)).FirstOrDefault(x => x.Name == $"{role}{settingName}"); + if (field == null) { FieldInfo tempField = null; + foreach (Type x in types) { - bool any = false; + var any = false; + foreach (FieldInfo f in x.GetFields(flags)) { if (f.Name.Contains(settingName)) @@ -2249,20 +1965,15 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ } float add; + if (field == null) - { add = float.MaxValue; - } else { if (field.GetValue(null) is OptionItem optionItem) - { add = optionItem.GetFloat(); - } else - { add = float.MaxValue; - } } return add; @@ -2280,15 +1991,9 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static PlayerControl GetPlayerById(int PlayerId, bool fast = true) { - if (PlayerId is > byte.MaxValue or < byte.MinValue) - { - return null; - } + if (PlayerId is > byte.MaxValue or < byte.MinValue) return null; - if (fast && GameStates.IsInGame && Main.PlayerStates.TryGetValue((byte)PlayerId, out PlayerState state) && state.Player != null) - { - return state.Player; - } + if (fast && GameStates.IsInGame && Main.PlayerStates.TryGetValue((byte)PlayerId, out PlayerState state) && state.Player != null) return state.Player; return Main.AllPlayerControls.FirstOrDefault(x => x.PlayerId == PlayerId); } @@ -2300,27 +2005,22 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static IEnumerator NotifyEveryoneAsync() { - int count = 0; + var count = 0; PlayerControl[] aapc = Main.AllAlivePlayerControls; + foreach (PlayerControl seer in aapc) { foreach (PlayerControl target in aapc) { NotifyRoles(SpecifySeer: seer, SpecifyTarget: target); - if (count++ % 2 == 0) - { - yield return null; - } + if (count++ % 2 == 0) yield return null; } } } public static void NotifyRoles(bool isForMeeting = false, PlayerControl SpecifySeer = null, PlayerControl SpecifyTarget = null, bool NoCache = false, bool ForceLoop = false, bool CamouflageIsForMeeting = false, bool GuesserIsForMeeting = false, bool MushroomMixup = false) { - if (!SetUpRoleTextPatch.IsInIntro && ((SpecifySeer != null && SpecifySeer.IsModClient() && (Options.CurrentGameMode == CustomGameMode.Standard || SpecifySeer.IsHost())) || !AmongUsClient.Instance.AmHost || Main.AllPlayerControls == null || (GameStates.IsMeeting && !isForMeeting))) - { - return; - } + if (!SetUpRoleTextPatch.IsInIntro && ((SpecifySeer != null && SpecifySeer.IsModClient() && (Options.CurrentGameMode == CustomGameMode.Standard || SpecifySeer.IsHost())) || !AmongUsClient.Instance.AmHost || Main.AllPlayerControls == null || (GameStates.IsMeeting && !isForMeeting))) return; DoNotifyRoles(isForMeeting, SpecifySeer, SpecifyTarget, NoCache, ForceLoop, CamouflageIsForMeeting, GuesserIsForMeeting, MushroomMixup); } @@ -2340,22 +2040,20 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { try { - if (seer == null || seer.Data.Disconnected || (seer.IsModClient() && (seer.IsHost() || Options.CurrentGameMode == CustomGameMode.Standard))) - { - continue; - } + if (seer == null || seer.Data.Disconnected || (seer.IsModClient() && (seer.IsHost() || Options.CurrentGameMode == CustomGameMode.Standard))) continue; // During intro scene, set team name for non-modded clients and skip the rest. string SelfName; Team seerTeam = seer.GetTeam(); CustomRoles seerRole = seer.GetCustomRole(); + if (SetUpRoleTextPatch.IsInIntro && (seerRole.IsDesyncRole() || seer.Is(CustomRoles.Bloodlust)) && Options.CurrentGameMode == CustomGameMode.Standard) { const string iconTextLeft = "\u21e8"; const string iconTextRight = "\u21e6"; const string roleNameUp = "\n \n"; - string selfTeamName = $"{iconTextLeft} {ColorString(seerTeam.GetTeamColor(), $"{seerTeam}")} {iconTextRight}\n \n"; + var selfTeamName = $"{iconTextLeft} {ColorString(seerTeam.GetTeamColor(), $"{seerTeam}")} {iconTextRight}\n \n"; SelfName = $"{selfTeamName}\r\n{seerRole.ToColoredString()}{roleNameUp}"; seer.RpcSetNamePrivate(SelfName, seer); @@ -2375,11 +2073,8 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ continue; } - string fontSize = "1.7"; - if (isForMeeting && (seer.GetClient().PlatformData.Platform == Platforms.Playstation || seer.GetClient().PlatformData.Platform == Platforms.Switch)) - { - fontSize = "70%"; - } + var fontSize = "1.7"; + if (isForMeeting && (seer.GetClient().PlatformData.Platform == Platforms.Playstation || seer.GetClient().PlatformData.Platform == Platforms.Switch)) fontSize = "70%"; // Text containing progress, such as tasks string SelfTaskText = GameStates.IsLobby ? string.Empty : GetProgressText(seer); @@ -2389,37 +2084,22 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ if (!GameStates.IsLobby) { - if (Options.CurrentGameMode != CustomGameMode.Standard) - { - goto GameMode0; - } + if (Options.CurrentGameMode != CustomGameMode.Standard) goto GameMode0; SelfMark.Append(Snitch.GetWarningArrow(seer)); - if (Main.LoversPlayers.Exists(x => x.PlayerId == seer.PlayerId)) - { - SelfMark.Append(ColorString(GetRoleColor(CustomRoles.Lovers), " ♥")); - } + if (Main.LoversPlayers.Exists(x => x.PlayerId == seer.PlayerId)) SelfMark.Append(ColorString(GetRoleColor(CustomRoles.Lovers), " ♥")); - if (BallLightning.IsGhost(seer)) - { - SelfMark.Append(ColorString(GetRoleColor(CustomRoles.BallLightning), "■")); - } + if (BallLightning.IsGhost(seer)) SelfMark.Append(ColorString(GetRoleColor(CustomRoles.BallLightning), "■")); SelfMark.Append(Medic.GetMark(seer, seer)); SelfMark.Append(Gaslighter.GetMark(seer, seer, isForMeeting)); SelfMark.Append(Gamer.TargetMark(seer, seer)); SelfMark.Append(Sniper.GetShotNotify(seer.PlayerId)); - if (Silencer.ForSilencer.Contains(seer.PlayerId)) - { - SelfMark.Append(ColorString(GetRoleColor(CustomRoles.Silencer), "╳")); - } + if (Silencer.ForSilencer.Contains(seer.PlayerId)) SelfMark.Append(ColorString(GetRoleColor(CustomRoles.Silencer), "╳")); GameMode0: - if (Options.CurrentGameMode is not CustomGameMode.Standard and not CustomGameMode.HideAndSeek) - { - goto GameMode; - } + if (Options.CurrentGameMode is not CustomGameMode.Standard and not CustomGameMode.HideAndSeek) goto GameMode; Main.PlayerStates.Values.Do(x => SelfSuffix.Append(x.Role.GetSuffix(seer, seer, meeting: isForMeeting))); @@ -2435,30 +2115,15 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ SelfSuffix.Append(string.Format(GetString("CDPT"), remainingCD > 60 ? "> 60" : remainingCD)); } - if (seer.Is(CustomRoles.Asthmatic)) - { - SelfSuffix.Append(Asthmatic.GetSuffixText(seer.PlayerId)); - } + if (seer.Is(CustomRoles.Asthmatic)) SelfSuffix.Append(Asthmatic.GetSuffixText(seer.PlayerId)); - if (seer.Is(CustomRoles.Sonar)) - { - SelfSuffix.Append(Sonar.GetSuffix(seer, isForMeeting)); - } + if (seer.Is(CustomRoles.Sonar)) SelfSuffix.Append(Sonar.GetSuffix(seer, isForMeeting)); - if (seer.Is(CustomRoles.Deadlined)) - { - SelfSuffix.Append(Deadlined.GetSuffix(seer)); - } + if (seer.Is(CustomRoles.Deadlined)) SelfSuffix.Append(Deadlined.GetSuffix(seer)); - if (seer.Is(CustomRoles.Introvert)) - { - SelfSuffix.Append(Introvert.GetSelfSuffix(seer)); - } + if (seer.Is(CustomRoles.Introvert)) SelfSuffix.Append(Introvert.GetSelfSuffix(seer)); - if (seer.Is(CustomRoles.Allergic)) - { - SelfSuffix.Append(Allergic.GetSelfSuffix(seer)); - } + if (seer.Is(CustomRoles.Allergic)) SelfSuffix.Append(Allergic.GetSelfSuffix(seer)); SelfSuffix.Append(Bloodmoon.GetSuffix(seer)); SelfSuffix.Append(Haunter.GetSuffix(seer)); @@ -2470,25 +2135,13 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ break; case CustomRoles.Monitor: case CustomRoles.AntiAdminer: - if (AntiAdminer.IsAdminWatch) - { - SelfSuffix.Append(GetString("AntiAdminerAD")); - } + if (AntiAdminer.IsAdminWatch) SelfSuffix.Append(GetString("AntiAdminerAD")); - if (AntiAdminer.IsVitalWatch) - { - SelfSuffix.Append(GetString("AntiAdminerVI")); - } + if (AntiAdminer.IsVitalWatch) SelfSuffix.Append(GetString("AntiAdminerVI")); - if (AntiAdminer.IsDoorLogWatch) - { - SelfSuffix.Append(GetString("AntiAdminerDL")); - } + if (AntiAdminer.IsDoorLogWatch) SelfSuffix.Append(GetString("AntiAdminerDL")); - if (AntiAdminer.IsCameraWatch) - { - SelfSuffix.Append(GetString("AntiAdminerCA")); - } + if (AntiAdminer.IsCameraWatch) SelfSuffix.Append(GetString("AntiAdminerCA")); break; } @@ -2496,10 +2149,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ else { SelfMark.Append(Witch.GetSpelledMark(seer.PlayerId, isForMeeting)); - if (isForMeeting) - { - SelfMark.Append(Wasp.GetStungMark(seer.PlayerId)); - } + if (isForMeeting) SelfMark.Append(Wasp.GetStungMark(seer.PlayerId)); } GameMode: @@ -2540,14 +2190,12 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ if (!GameStates.IsLobby) { - if (Options.CurrentGameMode == CustomGameMode.FFA && FFAManager.FFATeamMode.GetBool()) - { - SeerRealName = SeerRealName.ApplyNameColorData(seer, seer, isForMeeting); - } + if (Options.CurrentGameMode == CustomGameMode.FFA && FFAManager.FFATeamMode.GetBool()) SeerRealName = SeerRealName.ApplyNameColorData(seer, seer, isForMeeting); if (!isForMeeting && MeetingStates.FirstMeeting && Options.ChangeNameToRoleInfo.GetBool() && Options.CurrentGameMode is not CustomGameMode.FFA and not CustomGameMode.MoveAndStop and not CustomGameMode.HotPotato and not CustomGameMode.Speedrun and not CustomGameMode.CaptureTheFlag and not CustomGameMode.NaturalDisasters and not CustomGameMode.RoomRush) { CustomTeamManager.CustomTeam team = CustomTeamManager.GetCustomTeam(seer.PlayerId); + if (team != null) { SeerRealName = ColorString( @@ -2565,10 +2213,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ } else if (Options.CurrentGameMode == CustomGameMode.HideAndSeek) { - if (GameStartTimeStamp + 40 > now) - { - SeerRealName = HnSManager.GetRoleInfoText(seer); - } + if (GameStartTimeStamp + 40 > now) SeerRealName = HnSManager.GetRoleInfoText(seer); } else if (Options.ChangeNameToRoleInfo.GetBool()) { @@ -2592,10 +2237,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ string SelfDeathReason = seer.KnowDeathReason(seer) && !GameStates.IsLobby ? $"\n『{ColorString(GetRoleColor(CustomRoles.Doctor), GetVitalText(seer.PlayerId))}』" : string.Empty; SelfName = $"{ColorString(GameStates.IsLobby ? Color.white : seer.GetRoleColor(), SeerRealName)}{SelfDeathReason}{SelfMark}"; - if (Options.CurrentGameMode != CustomGameMode.Standard || GameStates.IsLobby) - { - goto GameMode2; - } + if (Options.CurrentGameMode != CustomGameMode.Standard || GameStates.IsLobby) goto GameMode2; SelfName = seerRole switch { @@ -2604,36 +2246,21 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ _ => SelfName }; - if (Pelican.IsEaten(seer.PlayerId)) - { - SelfName = $"{ColorString(GetRoleColor(CustomRoles.Pelican), GetString("EatenByPelican"))}"; - } + if (Pelican.IsEaten(seer.PlayerId)) SelfName = $"{ColorString(GetRoleColor(CustomRoles.Pelican), GetString("EatenByPelican"))}"; - if (Deathpact.IsInActiveDeathpact(seer)) - { - SelfName = Deathpact.GetDeathpactString(seer); - } + if (Deathpact.IsInActiveDeathpact(seer)) SelfName = Deathpact.GetDeathpactString(seer); // Devourer - if (Devourer.HideNameOfConsumedPlayer.GetBool() && Devourer.PlayerIdList.Any(x => Main.PlayerStates[x].Role is Devourer { IsEnable: true } dv && dv.PlayerSkinsCosumed.Contains(seer.PlayerId)) && !CamouflageIsForMeeting) - { - SelfName = GetString("DevouredName"); - } + if (Devourer.HideNameOfConsumedPlayer.GetBool() && Devourer.PlayerIdList.Any(x => Main.PlayerStates[x].Role is Devourer { IsEnable: true } dv && dv.PlayerSkinsCosumed.Contains(seer.PlayerId)) && !CamouflageIsForMeeting) SelfName = GetString("DevouredName"); // Camouflage - if (((IsActive(SystemTypes.Comms) && Options.CommsCamouflage.GetBool() && (Main.NormalOptions.MapId != 5 || !Options.CommsCamouflageDisableOnFungle.GetBool())) || Camouflager.IsActive) && !CamouflageIsForMeeting) - { - SelfName = $"{SelfName}"; - } + if (((IsActive(SystemTypes.Comms) && Options.CommsCamouflage.GetBool() && (Main.NormalOptions.MapId != 5 || !Options.CommsCamouflageDisableOnFungle.GetBool())) || Camouflager.IsActive) && !CamouflageIsForMeeting) SelfName = $"{SelfName}"; GameMode2: if (!GameStates.IsLobby) { - if (NameNotifyManager.GetNameNotify(seer, out string name) && name.Length > 0) - { - SelfName = name; - } + if (NameNotifyManager.GetNameNotify(seer, out string name) && name.Length > 0) SelfName = name; switch (Options.CurrentGameMode) { @@ -2650,10 +2277,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ } SelfName += SelfSuffix.ToString() == string.Empty ? string.Empty : $"\r\n{SelfSuffix}"; - if (!isForMeeting) - { - SelfName += "\r\n"; - } + if (!isForMeeting) SelfName += "\r\n"; } seer.RpcSetNamePrivate(SelfName, force: NoCache); @@ -2663,10 +2287,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { foreach (PlayerControl target in targetList) { - if (target.PlayerId == seer.PlayerId) - { - continue; - } + if (target.PlayerId == seer.PlayerId) continue; if (target.Is(CustomRoles.Car)) { @@ -2675,46 +2296,26 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ } if ((IsActive(SystemTypes.MushroomMixupSabotage) || MushroomMixup) && target.IsAlive() && !seer.Is(CustomRoleTypes.Impostor) && Main.ResetCamPlayerList.Contains(seer.PlayerId)) - { target.RpcSetNamePrivate("", force: NoCache); - } else { TargetMark.Clear(); - if (Options.CurrentGameMode != CustomGameMode.Standard || GameStates.IsLobby) - { - goto BeforeEnd2; - } + if (Options.CurrentGameMode != CustomGameMode.Standard || GameStates.IsLobby) goto BeforeEnd2; TargetMark.Append(Witch.GetSpelledMark(target.PlayerId, isForMeeting)); - if (isForMeeting) - { - TargetMark.Append(Wasp.GetStungMark(target.PlayerId)); - } + if (isForMeeting) TargetMark.Append(Wasp.GetStungMark(target.PlayerId)); - if (target.Is(CustomRoles.SuperStar) && Options.EveryOneKnowSuperStar.GetBool()) - { - TargetMark.Append(ColorString(GetRoleColor(CustomRoles.SuperStar), "★")); - } + if (target.Is(CustomRoles.SuperStar) && Options.EveryOneKnowSuperStar.GetBool()) TargetMark.Append(ColorString(GetRoleColor(CustomRoles.SuperStar), "★")); - if (BallLightning.IsGhost(target)) - { - TargetMark.Append(ColorString(GetRoleColor(CustomRoles.BallLightning), "■")); - } + if (BallLightning.IsGhost(target)) TargetMark.Append(ColorString(GetRoleColor(CustomRoles.BallLightning), "■")); TargetMark.Append(Snitch.GetWarningMark(seer, target)); TargetMark.Append(Marshall.GetWarningMark(seer, target)); - if ((seer.Data.IsDead || Main.LoversPlayers.Exists(x => x.PlayerId == seer.PlayerId)) && Main.LoversPlayers.Exists(x => x.PlayerId == target.PlayerId)) - { - TargetMark.Append($" ♥"); - } + if ((seer.Data.IsDead || Main.LoversPlayers.Exists(x => x.PlayerId == seer.PlayerId)) && Main.LoversPlayers.Exists(x => x.PlayerId == target.PlayerId)) TargetMark.Append($" ♥"); - if (Randomizer.IsShielded(target)) - { - TargetMark.Append(ColorString(GetRoleColor(CustomRoles.Randomizer), "✚")); - } + if (Randomizer.IsShielded(target)) TargetMark.Append(ColorString(GetRoleColor(CustomRoles.Randomizer), "✚")); switch (seerRole) { @@ -2728,47 +2329,27 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ break; case CustomRoles.Arsonist: if (seer.IsDousedPlayer(target)) - { TargetMark.Append($"▲"); - } - else if (Arsonist.ArsonistTimer.TryGetValue(seer.PlayerId, out (PlayerControl Player, float Timer) ar_kvp) && ar_kvp.Player == target) - { - TargetMark.Append($"△"); - } + else if (Arsonist.ArsonistTimer.TryGetValue(seer.PlayerId, out (PlayerControl Player, float Timer) ar_kvp) && ar_kvp.Player == target) TargetMark.Append($"△"); break; case CustomRoles.Revolutionist: - if (seer.IsDrawPlayer(target)) - { - TargetMark.Append($"●"); - } + if (seer.IsDrawPlayer(target)) TargetMark.Append($"●"); - if (Revolutionist.RevolutionistTimer.TryGetValue(seer.PlayerId, out (PlayerControl PLAYER, float TIMER) ar_kvp1) && ar_kvp1.PLAYER == target) - { - TargetMark.Append($"○"); - } + if (Revolutionist.RevolutionistTimer.TryGetValue(seer.PlayerId, out (PlayerControl PLAYER, float TIMER) ar_kvp1) && ar_kvp1.PLAYER == target) TargetMark.Append($"○"); break; case CustomRoles.Farseer: - if (Farseer.FarseerTimer.TryGetValue(seer.PlayerId, out (PlayerControl PLAYER, float TIMER) ar_kvp2) && ar_kvp2.PLAYER == target) - { - TargetMark.Append($"○"); - } + if (Farseer.FarseerTimer.TryGetValue(seer.PlayerId, out (PlayerControl PLAYER, float TIMER) ar_kvp2) && ar_kvp2.PLAYER == target) TargetMark.Append($"○"); break; case CustomRoles.Analyst: - if ((Main.PlayerStates[seer.PlayerId].Role as Analyst).CurrentTarget.ID == target.PlayerId) - { - TargetMark.Append($"○"); - } + if ((Main.PlayerStates[seer.PlayerId].Role as Analyst).CurrentTarget.ID == target.PlayerId) TargetMark.Append($"○"); break; case CustomRoles.Samurai: // Same as Analyst - if ((Main.PlayerStates[seer.PlayerId].Role as Samurai).Target.Id == target.PlayerId) - { - TargetMark.Append($"○"); - } + if ((Main.PlayerStates[seer.PlayerId].Role as Samurai).Target.Id == target.PlayerId) TargetMark.Append($"○"); break; case CustomRoles.Puppeteer when Puppeteer.PuppeteerList.ContainsValue(seer.PlayerId) && Puppeteer.PuppeteerList.ContainsKey(target.PlayerId): @@ -2808,15 +2389,9 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ ? $"{target.GetDisplayRoleName(seeTargetBetrayalAddons: shouldSeeTargetAddons)}{GetProgressText(target)}\r\n" : string.Empty; - if (CustomRoles.Altruist.RoleExist() && Main.DiedThisRound.Contains(seer.PlayerId)) - { - TargetRoleText = string.Empty; - } + if (CustomRoles.Altruist.RoleExist() && Main.DiedThisRound.Contains(seer.PlayerId)) TargetRoleText = string.Empty; - if (Options.CurrentGameMode is CustomGameMode.CaptureTheFlag or CustomGameMode.NaturalDisasters or CustomGameMode.RoomRush) - { - TargetRoleText = string.Empty; - } + if (Options.CurrentGameMode is CustomGameMode.CaptureTheFlag or CustomGameMode.NaturalDisasters or CustomGameMode.RoomRush) TargetRoleText = string.Empty; if (!GameStates.IsLobby) { @@ -2826,49 +2401,29 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ TargetRoleText += Farseer.GetTaskState(); } - if (Options.CurrentGameMode == CustomGameMode.SoloKombat) - { - TargetRoleText = $"{GetProgressText(target)}\r\n"; - } + if (Options.CurrentGameMode == CustomGameMode.SoloKombat) TargetRoleText = $"{GetProgressText(target)}\r\n"; } else - { TargetRoleText = string.Empty; - } string TargetPlayerName = target.GetRealName(isForMeeting); - if (GameStates.IsLobby) - { - goto End; - } + if (GameStates.IsLobby) goto End; - if (Options.CurrentGameMode != CustomGameMode.Standard) - { - goto BeforeEnd; - } + if (Options.CurrentGameMode != CustomGameMode.Standard) goto BeforeEnd; - if (GuesserIsForMeeting || isForMeeting || (seerRole == CustomRoles.Mafia && !seer.IsAlive() && Options.MafiaCanKillNum.GetInt() >= 1)) - { - TargetPlayerName = $"{ColorString(GetRoleColor(seerRole), target.PlayerId.ToString())} {TargetPlayerName}"; - } + if (GuesserIsForMeeting || isForMeeting || (seerRole == CustomRoles.Mafia && !seer.IsAlive() && Options.MafiaCanKillNum.GetInt() >= 1)) TargetPlayerName = $"{ColorString(GetRoleColor(seerRole), target.PlayerId.ToString())} {TargetPlayerName}"; switch (seerRole) { case CustomRoles.EvilTracker: TargetMark.Append(EvilTracker.GetTargetMark(seer, target)); - if (isForMeeting && EvilTracker.IsTrackTarget(seer, target) && EvilTracker.CanSeeLastRoomInMeeting) - { - TargetRoleText = $"{EvilTracker.GetArrowAndLastRoom(seer, target)}\r\n"; - } + if (isForMeeting && EvilTracker.IsTrackTarget(seer, target) && EvilTracker.CanSeeLastRoomInMeeting) TargetRoleText = $"{EvilTracker.GetArrowAndLastRoom(seer, target)}\r\n"; break; case CustomRoles.Scout: TargetMark.Append(Scout.GetTargetMark(seer, target)); - if (isForMeeting && Scout.IsTrackTarget(seer, target) && Scout.CanSeeLastRoomInMeeting) - { - TargetRoleText = $"{Scout.GetArrowAndLastRoom(seer, target)}\r\n"; - } + if (isForMeeting && Scout.IsTrackTarget(seer, target) && Scout.CanSeeLastRoomInMeeting) TargetRoleText = $"{Scout.GetArrowAndLastRoom(seer, target)}\r\n"; break; case CustomRoles.Psychic when seer.IsAlive() && Psychic.IsRedForPsy(target, seer) && isForMeeting: @@ -2889,20 +2444,11 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ TargetPlayerName = TargetPlayerName.ApplyNameColorData(seer, target, isForMeeting); - if (Options.CurrentGameMode != CustomGameMode.Standard) - { - goto End; - } + if (Options.CurrentGameMode != CustomGameMode.Standard) goto End; - if (seer.Is(CustomRoleTypes.Impostor) && target.Is(CustomRoles.Snitch) && target.Is(CustomRoles.Madmate) && target.GetTaskState().IsTaskFinished) - { - TargetMark.Append(ColorString(GetRoleColor(CustomRoles.Impostor), "★")); - } + if (seer.Is(CustomRoleTypes.Impostor) && target.Is(CustomRoles.Snitch) && target.Is(CustomRoles.Madmate) && target.GetTaskState().IsTaskFinished) TargetMark.Append(ColorString(GetRoleColor(CustomRoles.Impostor), "★")); - if (Marshall.CanSeeMarshall(seer) && target.Is(CustomRoles.Marshall) && target.GetTaskState().IsTaskFinished) - { - TargetMark.Append(ColorString(GetRoleColor(CustomRoles.Marshall), "★")); - } + if (Marshall.CanSeeMarshall(seer) && target.Is(CustomRoles.Marshall) && target.GetTaskState().IsTaskFinished) TargetMark.Append(ColorString(GetRoleColor(CustomRoles.Marshall), "★")); TargetMark.Append(Executioner.TargetMark(seer, target)); TargetMark.Append(Gamer.TargetMark(seer, target)); @@ -2935,33 +2481,21 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ Main.PlayerStates.Values.Do(x => TargetSuffix.Append(x.Role.GetSuffix(seer, target, meeting: isForMeeting))); - if (MeetingStates.FirstMeeting && Main.ShieldPlayer == target.FriendCode && !string.IsNullOrEmpty(target.FriendCode) && Options.CurrentGameMode is CustomGameMode.Standard or CustomGameMode.FFA or CustomGameMode.Speedrun) - { - TargetSuffix.Append(GetString("DiedR1Warning")); - } + if (MeetingStates.FirstMeeting && Main.ShieldPlayer == target.FriendCode && !string.IsNullOrEmpty(target.FriendCode) && Options.CurrentGameMode is CustomGameMode.Standard or CustomGameMode.FFA or CustomGameMode.Speedrun) TargetSuffix.Append(GetString("DiedR1Warning")); TargetSuffix.Append(AFKDetector.GetSuffix(seer, target)); } - string TargetDeathReason = string.Empty; - if (seer.KnowDeathReason(target) && !GameStates.IsLobby) - { - TargetDeathReason = $"\n({ColorString(GetRoleColor(CustomRoles.Doctor), GetVitalText(target.PlayerId))})"; - } + var TargetDeathReason = string.Empty; + if (seer.KnowDeathReason(target) && !GameStates.IsLobby) TargetDeathReason = $"\n({ColorString(GetRoleColor(CustomRoles.Doctor), GetVitalText(target.PlayerId))})"; // Devourer - if (Devourer.HideNameOfConsumedPlayer.GetBool() && !GameStates.IsLobby && Devourer.PlayerIdList.Any(x => Main.PlayerStates[x].Role is Devourer { IsEnable: true } dv && dv.PlayerSkinsCosumed.Contains(seer.PlayerId)) && !CamouflageIsForMeeting) - { - TargetPlayerName = GetString("DevouredName"); - } + if (Devourer.HideNameOfConsumedPlayer.GetBool() && !GameStates.IsLobby && Devourer.PlayerIdList.Any(x => Main.PlayerStates[x].Role is Devourer { IsEnable: true } dv && dv.PlayerSkinsCosumed.Contains(seer.PlayerId)) && !CamouflageIsForMeeting) TargetPlayerName = GetString("DevouredName"); // Camouflage - if (((IsActive(SystemTypes.Comms) && Options.CommsCamouflage.GetBool() && !GameStates.IsLobby && (Main.NormalOptions.MapId != 5 || !Options.CommsCamouflageDisableOnFungle.GetBool())) || Camouflager.IsActive) && !CamouflageIsForMeeting) - { - TargetPlayerName = $"{TargetPlayerName}"; - } + if (((IsActive(SystemTypes.Comms) && Options.CommsCamouflage.GetBool() && !GameStates.IsLobby && (Main.NormalOptions.MapId != 5 || !Options.CommsCamouflageDisableOnFungle.GetBool())) || Camouflager.IsActive) && !CamouflageIsForMeeting) TargetPlayerName = $"{TargetPlayerName}"; - string TargetName = $"{TargetRoleText}{TargetPlayerName}{TargetDeathReason}{TargetMark}"; + var TargetName = $"{TargetRoleText}{TargetPlayerName}{TargetDeathReason}{TargetMark}"; TargetName += GameStates.IsLobby || TargetSuffix.ToString() == string.Empty ? string.Empty : $"\r\n{TargetSuffix}"; target.RpcSetNamePrivate(TargetName, seer, NoCache); @@ -2978,28 +2512,17 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ LastNotifyRolesErrorTS = now; } else - { Logger.Error($"Error for {seer.GetNameWithRole()}: {ex}", "NR"); - } } } - if (Options.CurrentGameMode != CustomGameMode.Standard) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.Standard) return; string seers = seerList.Length == apc.Length ? "Everyone" : string.Join(", ", seerList.Select(x => x.GetRealName())); string targets = targetList.Length == apc.Length ? "Everyone" : string.Join(", ", targetList.Select(x => x.GetRealName())); - if (seers.Length == 0) - { - seers = "\u2205"; - } + if (seers.Length == 0) seers = "\u2205"; - if (targets.Length == 0) - { - targets = "\u2205"; - } + if (targets.Length == 0) targets = "\u2205"; Logger.Info($" Seers: {seers} ---- Targets: {targets}", "NR"); } @@ -3034,9 +2557,10 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { Camouflage.SetPetForOutfitIfNecessary(newOutfit); - CustomRpcSender sender = CustomRpcSender.Create($"Utils.RpcChangeSkin({pc.Data.PlayerName})"); + var sender = CustomRpcSender.Create($"Utils.RpcChangeSkin({pc.Data.PlayerName})"); pc.SetName(newOutfit.PlayerName); + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetName) .Write(pc.Data.NetId) .Write(newOutfit.PlayerName) @@ -3045,6 +2569,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ Main.AllPlayerNames[pc.PlayerId] = newOutfit.PlayerName; pc.SetColor(newOutfit.ColorId); + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetColor) .Write(pc.Data.NetId) .Write((byte)newOutfit.ColorId) @@ -3052,6 +2577,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ pc.SetHat(newOutfit.HatId, newOutfit.ColorId); pc.Data.DefaultOutfit.HatSequenceId += 10; + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetHatStr) .Write(newOutfit.HatId) .Write(pc.GetNextRpcSequenceId(RpcCalls.SetHatStr)) @@ -3059,6 +2585,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ pc.SetSkin(newOutfit.SkinId, newOutfit.ColorId); pc.Data.DefaultOutfit.SkinSequenceId += 10; + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetSkinStr) .Write(newOutfit.SkinId) .Write(pc.GetNextRpcSequenceId(RpcCalls.SetSkinStr)) @@ -3066,6 +2593,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ pc.SetVisor(newOutfit.VisorId, newOutfit.ColorId); pc.Data.DefaultOutfit.VisorSequenceId += 10; + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetVisorStr) .Write(newOutfit.VisorId) .Write(pc.GetNextRpcSequenceId(RpcCalls.SetVisorStr)) @@ -3073,6 +2601,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ pc.SetPet(newOutfit.PetId); pc.Data.DefaultOutfit.PetSequenceId += 10; + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetPetStr) .Write(newOutfit.PetId) .Write(pc.GetNextRpcSequenceId(RpcCalls.SetPetStr)) @@ -3080,6 +2609,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ pc.SetNamePlate(newOutfit.NamePlateId); pc.Data.DefaultOutfit.NamePlateSequenceId += 10; + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetNamePlateStr) .Write(newOutfit.NamePlateId) .Write(pc.GetNextRpcSequenceId(RpcCalls.SetNamePlateStr)) @@ -3092,58 +2622,29 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { Dictionary nums = Enum.GetValues().ToDictionary(x => x, _ => 0); - if (CustomRoles.Romantic.RoleExist(true)) - { - nums[Options.GameStateInfo.RomanticState] = 1; - } + if (CustomRoles.Romantic.RoleExist(true)) nums[Options.GameStateInfo.RomanticState] = 1; - if (Romantic.HasPickedPartner) - { - nums[Options.GameStateInfo.RomanticState] = 2; - } + if (Romantic.HasPickedPartner) nums[Options.GameStateInfo.RomanticState] = 2; foreach (PlayerControl pc in Main.AllAlivePlayerControls) { if (pc.IsMadmate()) - { nums[Options.GameStateInfo.MadmateCount]++; - } else if (pc.IsNeutralKiller()) - { nums[Options.GameStateInfo.NKCount]++; - } else if (pc.IsCrewmate()) - { nums[Options.GameStateInfo.CrewCount]++; - } else if (pc.Is(Team.Impostor)) - { nums[Options.GameStateInfo.ImpCount]++; - } - else if (pc.Is(Team.Neutral)) - { - nums[Options.GameStateInfo.NNKCount]++; - } + else if (pc.Is(Team.Neutral)) nums[Options.GameStateInfo.NNKCount]++; - if (pc.GetCustomSubRoles().Any(x => x.IsConverted())) - { - nums[Options.GameStateInfo.ConvertedCount]++; - } + if (pc.GetCustomSubRoles().Any(x => x.IsConverted())) nums[Options.GameStateInfo.ConvertedCount]++; - if (Main.LoversPlayers.Exists(x => x.PlayerId == pc.PlayerId)) - { - nums[Options.GameStateInfo.LoversState]++; - } + if (Main.LoversPlayers.Exists(x => x.PlayerId == pc.PlayerId)) nums[Options.GameStateInfo.LoversState]++; - if (pc.Is(CustomRoles.Romantic)) - { - nums[Options.GameStateInfo.RomanticState] *= 3; - } + if (pc.Is(CustomRoles.Romantic)) nums[Options.GameStateInfo.RomanticState] *= 3; - if (Romantic.PartnerId == pc.PlayerId) - { - nums[Options.GameStateInfo.RomanticState] *= 4; - } + if (Romantic.PartnerId == pc.PlayerId) nums[Options.GameStateInfo.RomanticState] *= 4; } // All possible results of RomanticState from the above code: @@ -3167,7 +2668,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { if (role.UsesPetInsteadOfKill()) { - int kcd = (int)Math.Round(Main.AllPlayerKillCooldown.TryGetValue(playerId, out float KCD) ? KCD : Options.DefaultKillCooldown); + var kcd = (int)Math.Round(Main.AllPlayerKillCooldown.TryGetValue(playerId, out float KCD) ? KCD : Options.DefaultKillCooldown); Main.AbilityCD[playerId] = (TimeStamp, kcd); SendRPC(CustomRPC.SyncAbilityCD, 1, playerId, kcd); return; @@ -3221,31 +2722,20 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ CustomRoles.Shifter => Shifter.KillCooldown.GetInt(), _ => -1 }; - if (CD == -1) - { - return; - } - if (Main.PlayerStates[playerId].SubRoles.Contains(CustomRoles.Energetic)) - { - CD = (int)Math.Round(CD * 0.75f); - } + if (CD == -1) return; + + if (Main.PlayerStates[playerId].SubRoles.Contains(CustomRoles.Energetic)) CD = (int)Math.Round(CD * 0.75f); Main.AbilityCD[playerId] = (TimeStamp, CD); SendRPC(CustomRPC.SyncAbilityCD, 1, playerId, CD); - if (Options.UseUnshiftTrigger.GetBool() && role.SimpleAbilityTrigger() && (!role.IsNeutral() || Options.UseUnshiftTriggerForNKs.GetBool()) && !role.AlwaysUsesUnshift()) - { - GetPlayerById(playerId)?.RpcResetAbilityCooldown(); - } + if (Options.UseUnshiftTrigger.GetBool() && role.SimpleAbilityTrigger() && (!role.IsNeutral() || Options.UseUnshiftTriggerForNKs.GetBool()) && !role.AlwaysUsesUnshift()) GetPlayerById(playerId)?.RpcResetAbilityCooldown(); } public static (RoleTypes RoleType, CustomRoles CustomRole) GetRoleMap(byte seerId, byte targetId = byte.MaxValue) { - if (targetId == byte.MaxValue) - { - targetId = seerId; - } + if (targetId == byte.MaxValue) targetId = seerId; return StartGameHostPatch.RpcSetRoleReplacer.RoleMap[(seerId, targetId)]; } @@ -3253,10 +2743,9 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static void AfterMeetingTasks() { bool loversChat = Lovers.PrivateChat.GetBool() && Main.LoversPlayers.TrueForAll(x => x.IsAlive()); + if (loversChat && Lovers.PrivateChatForLoversOnly.GetBool()) - { Main.LoversPlayers.ForEach(x => x.SetChatVisible()); - } else if (!Lovers.IsChatActivated && loversChat && !GameStates.IsEnded && Options.CurrentGameMode == CustomGameMode.Standard) { LateTask.New(SetChatVisibleForAll, 0.5f, log: false); @@ -3264,10 +2753,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ return; } - if (loversChat) - { - GameEndChecker.Prefix(); - } + if (loversChat) GameEndChecker.Prefix(); Lovers.IsChatActivated = false; AFKDetector.NumAFK = 0; @@ -3284,6 +2770,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ float beforeSpeed = Main.AllPlayerSpeed[pc.PlayerId]; Main.AllPlayerSpeed[pc.PlayerId] = Main.MinSpeed; pc.MarkDirtySettings(); + LateTask.New(() => { Main.AllPlayerSpeed[pc.PlayerId] = beforeSpeed; @@ -3291,10 +2778,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ }, Options.TruantWaitingTime.GetFloat(), $"Truant Waiting: {pc.GetNameWithRole()}"); } - if (Options.UsePets.GetBool()) - { - pc.AddAbilityCD(false); - } + if (Options.UsePets.GetBool()) pc.AddAbilityCD(false); pc.CheckAndSetUnshiftState(false); @@ -3305,18 +2789,12 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ else { TaskState taskState = pc.GetTaskState(); - if (pc.IsCrewmate() && !taskState.IsTaskFinished && taskState.HasTasks) - { - pc.Notify(GetString("DoYourTasksPlease"), 10f); - } + if (pc.IsCrewmate() && !taskState.IsTaskFinished && taskState.HasTasks) pc.Notify(GetString("DoYourTasksPlease"), 10f); GhostRolesManager.NotifyAboutGhostRole(pc); } - if (pc.Is(CustomRoles.Specter) || pc.Is(CustomRoles.Haunter)) - { - pc.RpcResetAbilityCooldown(); - } + if (pc.Is(CustomRoles.Specter) || pc.Is(CustomRoles.Haunter)) pc.RpcResetAbilityCooldown(); Main.CheckShapeshift[pc.PlayerId] = false; } @@ -3344,10 +2822,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ Circumvent.AfterMeetingTasks(); Deadlined.AfterMeetingTasks(); - if (Options.AirshipVariableElectrical.GetBool()) - { - AirshipElectricalDoors.Initialize(); - } + if (Options.AirshipVariableElectrical.GetBool()) AirshipElectricalDoors.Initialize(); Main.DontCancelVoteList.Clear(); @@ -3355,10 +2830,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ RoleBlockManager.Reset(); PhantomRolePatch.AfterMeeting(); - if ((MapNames)Main.NormalOptions.MapId == MapNames.Airship && AmongUsClient.Instance.AmHost && PlayerControl.LocalPlayer.Is(CustomRoles.GM)) - { - LateTask.New(() => { PlayerControl.LocalPlayer.NetTransform.SnapTo(new(15.5f, 0.0f), (ushort)(PlayerControl.LocalPlayer.NetTransform.lastSequenceId + 8)); }, 11f, "GM Auto-TP Failsafe"); // TP to Main Hall - } + if ((MapNames)Main.NormalOptions.MapId == MapNames.Airship && AmongUsClient.Instance.AmHost && PlayerControl.LocalPlayer.Is(CustomRoles.GM)) LateTask.New(() => { PlayerControl.LocalPlayer.NetTransform.SnapTo(new(15.5f, 0.0f), (ushort)(PlayerControl.LocalPlayer.NetTransform.lastSequenceId + 8)); }, 11f, "GM Auto-TP Failsafe"); // TP to Main Hall LateTask.New(() => Asthmatic.RunChecks = true, 2f, log: false); } @@ -3367,16 +2839,10 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { try { - if (!onMeeting) - { - Main.DiedThisRound.Add(target.PlayerId); - } + if (!onMeeting) Main.DiedThisRound.Add(target.PlayerId); // Record the first death - if (Main.FirstDied == string.Empty) - { - Main.FirstDied = target.FriendCode; - } + if (Main.FirstDied == string.Empty) Main.FirstDied = target.FriendCode; switch (target.GetCustomRole()) { @@ -3413,19 +2879,14 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { if ((!Options.ImpKnowCyberStarDead.GetBool() && pc.GetCustomRole().IsImpostor()) || (!Options.NeutralKnowCyberStarDead.GetBool() && pc.GetCustomRole().IsNeutral())) - { continue; - } SendMessage(string.Format(GetString("CyberStarDead"), target.GetRealName()), pc.PlayerId, ColorString(GetRoleColor(CustomRoles.CyberStar), GetString("CyberStarNewsTitle"))); } } else { - if (!Main.CyberStarDead.Contains(target.PlayerId)) - { - Main.CyberStarDead.Add(target.PlayerId); - } + if (!Main.CyberStarDead.Contains(target.PlayerId)) Main.CyberStarDead.Add(target.PlayerId); } break; @@ -3443,35 +2904,17 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ break; } - if (target == null) - { - return; - } + if (target == null) return; - if (!disconnect) - { - Randomizer.OnAnyoneDeath(target); - } + if (!disconnect) Randomizer.OnAnyoneDeath(target); - if (Executioner.Target.ContainsValue(target.PlayerId)) - { - Executioner.ChangeRoleByTarget(target); - } + if (Executioner.Target.ContainsValue(target.PlayerId)) Executioner.ChangeRoleByTarget(target); - if (Lawyer.Target.ContainsValue(target.PlayerId)) - { - Lawyer.ChangeRoleByTarget(target); - } + if (Lawyer.Target.ContainsValue(target.PlayerId)) Lawyer.ChangeRoleByTarget(target); - if (!disconnect && target.Is(CustomRoles.Stained)) - { - Stained.OnDeath(target, target.GetRealKiller()); - } + if (!disconnect && target.Is(CustomRoles.Stained)) Stained.OnDeath(target, target.GetRealKiller()); - if (!disconnect && target.Is(CustomRoles.Spurt)) - { - Spurt.DeathTask(target); - } + if (!disconnect && target.Is(CustomRoles.Spurt)) Spurt.DeathTask(target); Postman.CheckAndResetTargets(target, true); Hitman.CheckAndResetTargets(); @@ -3495,12 +2938,10 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ Adventurer.OnAnyoneDead(target); Whisperer.OnAnyoneDied(target); - if (QuizMaster.On) - { - QuizMaster.Data.NumPlayersDeadThisRound++; - } + if (QuizMaster.On) QuizMaster.Data.NumPlayersDeadThisRound++; FixedUpdatePatch.LoversSuicide(target.PlayerId, guess: onMeeting); + if (!target.HasGhostRole()) { Main.AllPlayerSpeed[target.PlayerId] = Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod); @@ -3517,6 +2958,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static void CountAlivePlayers(bool sendLog = false) { int AliveImpostorCount = Main.AllAlivePlayerControls.Count(pc => pc.Is(CustomRoleTypes.Impostor)); + if (Main.AliveImpostorCount != AliveImpostorCount) { Logger.Info("Number of living Impostors: " + AliveImpostorCount, "CountAliveImpostors"); @@ -3527,15 +2969,13 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ if (sendLog) { StringBuilder sb = new(100); + if (Options.CurrentGameMode == CustomGameMode.Standard) { foreach (CountTypes countTypes in Enum.GetValues()) { int playersCount = PlayersCount(countTypes); - if (playersCount == 0) - { - continue; - } + if (playersCount == 0) continue; sb.Append($"{countTypes}: {AlivePlayersCount(countTypes)}/{playersCount}, "); } @@ -3545,15 +2985,13 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ Logger.Info(sb.ToString(), "CountAlivePlayers"); } - if (AmongUsClient.Instance.AmHost && !Main.HasJustStarted) - { - GameEndChecker.Prefix(); - } + if (AmongUsClient.Instance.AmHost && !Main.HasJustStarted) GameEndChecker.Prefix(); } public static string GetVoteName(byte num) { PlayerControl player = GetPlayerById(num); + return num switch { < 15 when player != null => player.GetNameWithRole().RemoveHtmlTags(), @@ -3566,11 +3004,8 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static string PadRightV2(this object text, int num) { - string t = text.ToString(); - if (t == null) - { - return string.Empty; - } + var t = text.ToString(); + if (t == null) return string.Empty; int bc = t.Sum(c => Encoding.GetEncoding("UTF-8").GetByteCount(c.ToString()) == 1 ? 1 : 2); @@ -3579,46 +3014,33 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static void DumpLog(bool open = true) { - string f = $"{Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}/EHR_Logs/"; - string t = DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss"); - string filename = $"{f}EHR-v{Main.PluginVersion}-{t}.log"; - if (!Directory.Exists(f)) - { - Directory.CreateDirectory(f); - } + var f = $"{Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}/EHR_Logs/"; + var t = DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss"); + var filename = $"{f}EHR-v{Main.PluginVersion}-{t}.log"; + if (!Directory.Exists(f)) Directory.CreateDirectory(f); FileInfo file = new($"{Environment.CurrentDirectory}/BepInEx/LogOutput.log"); file.CopyTo(filename); - if (!open) - { - return; - } + if (!open) return; - if (PlayerControl.LocalPlayer != null) - { - HudManager.Instance?.Chat?.AddChat(PlayerControl.LocalPlayer, string.Format(GetString("Message.DumpfileSaved"), $"EHR v{Main.PluginVersion} {t}.log")); - } + if (PlayerControl.LocalPlayer != null) HudManager.Instance?.Chat?.AddChat(PlayerControl.LocalPlayer, string.Format(GetString("Message.DumpfileSaved"), $"EHR v{Main.PluginVersion} {t}.log")); ProcessStartInfo psi = new("Explorer.exe") { Arguments = "/e,/select," + filename.Replace("/", "\\") }; + Process.Start(psi); } public static (int, int) GetDousedPlayerCount(byte playerId) { int doused = 0, all = 0; + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (pc.PlayerId == playerId) - { - continue; - } + if (pc.PlayerId == playerId) continue; all++; - if (Arsonist.IsDoused.TryGetValue((playerId, pc.PlayerId), out bool isDoused) && isDoused) - { - doused++; - } + if (Arsonist.IsDoused.TryGetValue((playerId, pc.PlayerId), out bool isDoused) && isDoused) doused++; } return (doused, all); @@ -3626,19 +3048,13 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static (int, int) GetDrawPlayerCount(byte playerId, out List winnerList) { - int draw = 0; + var draw = 0; int all = Options.RevolutionistDrawCount.GetInt(); int max = Main.AllAlivePlayerControls.Length; - if (!Main.PlayerStates[playerId].IsDead) - { - max--; - } + if (!Main.PlayerStates[playerId].IsDead) max--; winnerList = []; - if (all > max) - { - all = max; - } + if (all > max) all = max; foreach (PlayerControl pc in Main.AllPlayerControls.Where(pc => Revolutionist.IsDraw.TryGetValue((playerId, pc.PlayerId), out bool isDraw) && isDraw).ToArray()) { @@ -3660,6 +3076,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ ChatController chat = DestroyableSingleton.Instance.Chat; NetworkedPlayerInfo data = PlayerControl.LocalPlayer.Data; ChatBubble bubble = chat.GetPooledBubble(); + try { bubble.transform.SetParent(chat.scroller.Inner); @@ -3678,10 +3095,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ bubble.transform.Find("ChatText (TMP)").GetComponent().color = new(1f, 1f, 1f, 1f); bubble.transform.Find("Background").GetComponent().color = new(0.05f, 0.05f, 0.05f, 1f); Transform xMark = bubble.transform.Find("PoolablePlayer/xMark"); - if (xMark && xMark.GetComponent().enabled) - { - bubble.transform.Find("Background").GetComponent().color = new(0.05f, 0.05f, 0.05f, 0.5f); - } + if (xMark && xMark.GetComponent().enabled) bubble.transform.Find("Background").GetComponent().color = new(0.05f, 0.05f, 0.05f, 0.5f); } catch (Exception e) { @@ -3695,29 +3109,25 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ //var RolePos = TranslationController.Instance.currentLanguage.languageID is SupportedLangs.English or SupportedLangs.Russian ? 37 : 34; //var KillsPos = TranslationController.Instance.currentLanguage.languageID is SupportedLangs.English or SupportedLangs.Russian ? 14 : 12; string name = Main.AllPlayerNames[id].RemoveHtmlTags().Replace("\r\n", string.Empty); + if (id == PlayerControl.LocalPlayer.PlayerId) - { name = DataManager.player.Customization.Name; - } else - { name = GetPlayerById(id)?.Data.PlayerName ?? name; - } TaskState taskState = Main.PlayerStates[id].TaskState; string TaskCount; + if (taskState.HasTasks) { NetworkedPlayerInfo info = GetPlayerInfoById(id); Color TaskCompleteColor = HasTasks(info) ? Color.green : Color.cyan; Color NonCompleteColor = HasTasks(info) ? Color.yellow : Color.white; - if (Workhorse.IsThisRole(id)) - { - NonCompleteColor = Workhorse.RoleColor; - } + if (Workhorse.IsThisRole(id)) NonCompleteColor = Workhorse.RoleColor; Color NormalColor = taskState.IsTaskFinished ? TaskCompleteColor : NonCompleteColor; + if (Main.PlayerStates.TryGetValue(id, out PlayerState ps)) { NormalColor = ps.MainRole switch @@ -3729,23 +3139,19 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ } Color TextColor = NormalColor; - string Completed = $"{taskState.CompletedTasksCount}"; + var Completed = $"{taskState.CompletedTasksCount}"; TaskCount = ColorString(TextColor, $" ({Completed}/{taskState.AllTasksCount})"); } else - { TaskCount = string.Empty; - } - string summary = $"{ColorString(Main.PlayerColors[id], name)} - {GetDisplayRoleName(id, true)}{TaskCount}{GetKillCountText(id)} ({GetVitalText(id, true)})"; + var summary = $"{ColorString(Main.PlayerColors[id], name)} - {GetDisplayRoleName(id, true)}{TaskCount}{GetKillCountText(id)} ({GetVitalText(id, true)})"; + switch (Options.CurrentGameMode) { case CustomGameMode.SoloKombat: summary = TranslationController.Instance.currentLanguage.languageID is SupportedLangs.SChinese or SupportedLangs.TChinese ? $"{GetProgressText(id)}\t{ColorString(Main.PlayerColors[id], name)}" : $"{ColorString(Main.PlayerColors[id], name)}{GetProgressText(id)}"; - if (GetProgressText(id).Trim() == string.Empty) - { - return string.Empty; - } + if (GetProgressText(id).Trim() == string.Empty) return string.Empty; break; case CustomGameMode.FFA: @@ -3769,10 +3175,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ break; case CustomGameMode.CaptureTheFlag: summary = $"{ColorString(Main.PlayerColors[id], name)}: {CTFManager.GetStatistics(id)}"; - if (CTFManager.IsDeathPossible) - { - summary += $" ({GetVitalText(id, true)})"; - } + if (CTFManager.IsDeathPossible) summary += $" ({GetVitalText(id, true)})"; break; } @@ -3786,21 +3189,16 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static string GetRemainingKillers(bool notify = false, bool president = false) { - int impnum = 0; - int neutralnum = 0; + var impnum = 0; + var neutralnum = 0; bool impShow = president || Options.ShowImpRemainOnEject.GetBool(); bool nkShow = president || Options.ShowNKRemainOnEject.GetBool(); foreach (PlayerControl pc in Main.AllAlivePlayerControls) { if (impShow && pc.Is(Team.Impostor)) - { impnum++; - } - else if (nkShow && pc.IsNeutralKiller()) - { - neutralnum++; - } + else if (nkShow && pc.IsNeutralKiller()) neutralnum++; } StringBuilder sb = new(); @@ -3838,10 +3236,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static bool CanMafiaKill() { - if (Main.PlayerStates == null) - { - return false; - } + if (Main.PlayerStates == null) return false; return !Main.AllAlivePlayerControls.Select(pc => pc.GetCustomRole()).Any(role => role != CustomRoles.Mafia && role.IsImpostor()); } @@ -3849,12 +3244,10 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static void FlashColor(Color color, float duration = 1f) { HudManager hud = DestroyableSingleton.Instance; - if (hud.FullScreen == null) - { - return; - } + if (hud.FullScreen == null) return; GameObject obj = hud.transform.FindChild("FlashColor_FullScreen")?.gameObject; + if (obj == null) { obj = Object.Instantiate(hud.FullScreen.gameObject, hud.transform); @@ -3872,10 +3265,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { try { - if (CachedSprites.TryGetValue(path + pixelsPerUnit, out Sprite sprite)) - { - return sprite; - } + if (CachedSprites.TryGetValue(path + pixelsPerUnit, out Sprite sprite)) return sprite; Texture2D texture = LoadTextureFromResources(path); sprite = Sprite.Create(texture, new(0, 0, texture.width, texture.height), new(0.5f, 0.5f), pixelsPerUnit); @@ -3920,10 +3310,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static Color ShadeColor(this Color color, float Darkness = 0) { bool IsDarker = Darkness >= 0; - if (!IsDarker) - { - Darkness = -Darkness; - } + if (!IsDarker) Darkness = -Darkness; float Weight = IsDarker ? 0 : Darkness; float R = (color.r + Weight) / (Darkness + 1); @@ -3934,10 +3321,7 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ public static void SetChatVisibleForAll() { - if (!GameStates.IsInGame) - { - return; - } + if (!GameStates.IsInGame) return; MeetingHud.Instance = Object.Instantiate(HudManager.Instance.MeetingPrefab); MeetingHud.Instance.ServerStart(PlayerControl.LocalPlayer.PlayerId); @@ -3983,39 +3367,26 @@ other: ∟ ⌠ ⌡ ╬ ╨ ▓ ▒ ░ « » █ ▄ ▌▀▐│ ┤ ╡ ╢ { // Official Modded Server if (Ip.Contains("au-eu")) - { name = "MEU"; - } else if (Ip.Contains("au-as")) - { name = "MAS"; - } - else if (Ip.Contains("www.")) - { - name = "MNA"; - } + else if (Ip.Contains("www.")) name = "MNA"; return name; } - if (name.Contains("nikocat233", StringComparison.OrdinalIgnoreCase)) - { - name = name.Replace("nikocat233", "Niko233", StringComparison.OrdinalIgnoreCase); - } + if (name.Contains("nikocat233", StringComparison.OrdinalIgnoreCase)) name = name.Replace("nikocat233", "Niko233", StringComparison.OrdinalIgnoreCase); return name; } private static int PlayersCount(CountTypes countTypes) { - int count = 0; + var count = 0; + foreach (PlayerState state in Main.PlayerStates.Values) - { if (state.countTypes == countTypes) - { count++; - } - } return count; } diff --git a/Modules/Zoom.cs b/Modules/Zoom.cs index 039f41ca0..fb4efa300 100644 --- a/Modules/Zoom.cs +++ b/Modules/Zoom.cs @@ -16,26 +16,17 @@ namespace EHR { try { - if (Camera.main == null) - { - return; - } + if (Camera.main == null) return; if (((GameStates.IsShip && !GameStates.IsMeeting && GameStates.IsCanMove && PlayerControl.LocalPlayer.Data != null && PlayerControl.LocalPlayer.Data.IsDead) || (GameStates.IsLobby && GameStates.IsCanMove)) && !InGameRoleInfoMenu.Showing) { - if (Camera.main.orthographicSize > 3.0f) - { - ResetButtons = true; - } + if (Camera.main.orthographicSize > 3.0f) ResetButtons = true; switch (Input.mouseScrollDelta.y) { case > 0: { - if (Camera.main.orthographicSize > 3.0f) - { - SetZoomSize(); - } + if (Camera.main.orthographicSize > 3.0f) SetZoomSize(); break; } @@ -43,12 +34,8 @@ namespace EHR { if (GameStates.IsDead || GameStates.IsFreePlay || DebugModeManager.AmDebugger || GameStates.IsLobby || PlayerControl.LocalPlayer.FriendCode.GetDevUser().DeBug) - { if (Camera.main.orthographicSize < 18.0f) - { SetZoomSize(true); - } - } break; } @@ -57,37 +44,24 @@ namespace EHR Flag.NewFlag("Zoom"); } else - { Flag.Run(() => { SetZoomSize(reset: true); }, "Zoom"); - } - } - catch - { } + catch { } } public static void SetZoomSize(bool times = false, bool reset = false) { - if (Camera.main == null) - { - return; - } + if (Camera.main == null) return; - float size = 1.5f; - if (!times) - { - size = 1 / size; - } + var size = 1.5f; + if (!times) size = 1 / size; if (reset) { Camera.main.orthographicSize = 3.0f; HudManager.Instance.UICamera.orthographicSize = 3.0f; HudManager.Instance.Chat.transform.localScale = Vector3.one; - if (GameStates.IsMeeting) - { - MeetingHud.Instance.transform.localScale = Vector3.one; - } + if (GameStates.IsMeeting) MeetingHud.Instance.transform.localScale = Vector3.one; } else { @@ -106,10 +80,7 @@ namespace EHR public static void OnFixedUpdate() { - if (Camera.main == null) - { - return; - } + if (Camera.main == null) return; DestroyableSingleton.Instance?.ShadowQuad?.gameObject.SetActive(Mathf.Approximately(Camera.main.orthographicSize, 3.0f) && PlayerControl.LocalPlayer.IsAlive()); } @@ -124,10 +95,7 @@ namespace EHR { if (OneTimeList.Contains(type) || (firstrun && !FirstRunList.Contains(type))) { - if (!FirstRunList.Contains(type)) - { - FirstRunList.Add(type); - } + if (!FirstRunList.Contains(type)) FirstRunList.Add(type); OneTimeList.Remove(type); action(); @@ -136,10 +104,7 @@ namespace EHR public static void NewFlag(string type) { - if (!OneTimeList.Contains(type)) - { - OneTimeList.Add(type); - } + if (!OneTimeList.Contains(type)) OneTimeList.Add(type); } /* diff --git a/Patches/AirShipElectricalDoors.cs b/Patches/AirShipElectricalDoors.cs index 6d264a872..96a495830 100644 --- a/Patches/AirShipElectricalDoors.cs +++ b/Patches/AirShipElectricalDoors.cs @@ -10,10 +10,7 @@ namespace EHR public static void Initialize() { - if (Main.NormalOptions.MapId != 4) - { - return; - } + if (Main.NormalOptions.MapId != 4) return; Instance.Initialize(); } @@ -21,18 +18,12 @@ namespace EHR public static byte[] GetClosedDoors() { List DoorsArray = []; - if (Instance.Doors == null || Instance.Doors.Length == 0) - { - return [.. DoorsArray]; - } + if (Instance.Doors == null || Instance.Doors.Length == 0) return [.. DoorsArray]; for (byte i = 0; i < Instance.Doors.Count; i++) { StaticDoor door = Instance.Doors[i]; - if (door != null && !door.IsOpen) - { - DoorsArray.Add(i); - } + if (door != null && !door.IsOpen) DoorsArray.Add(i); } return DoorsArray?.ToArray(); @@ -56,14 +47,12 @@ namespace EHR { public static void Postfix( /*ElectricalDoors __instance*/) { - if (!GameStates.IsInGame) - { - return; - } + if (!GameStates.IsInGame) return; - string closedoors = string.Empty; - bool isFirst = true; + var closedoors = string.Empty; + var isFirst = true; byte[] array = AirshipElectricalDoors.GetClosedDoors(); + foreach (byte num in array) { if (isFirst) @@ -72,9 +61,7 @@ namespace EHR closedoors += num.ToString(); } else - { closedoors += $", {num}"; - } } Logger.Info($"Closed Doors: {closedoors}", "ElectricalDoors Initialize"); diff --git a/Patches/AnnouncementPatch.cs b/Patches/AnnouncementPatch.cs index 56b639505..d1094e78e 100644 --- a/Patches/AnnouncementPatch.cs +++ b/Patches/AnnouncementPatch.cs @@ -47,7 +47,7 @@ namespace EHR // When creating new news, you can not delete old news { // EHR v2.4.3 - ModNews news = new ModNews + var news = new ModNews { Number = 100001, Title = "TownOfHostEdited v2.5.0", @@ -62,12 +62,13 @@ namespace EHR Date = "2023-7-14T00:00:00Z" }; + AllModNews.Add(news); } { // EHR v2.4.2 - ModNews news = new ModNews + var news = new ModNews { Number = 100000, Title = "TownOfHostEdited v2.4.2", @@ -86,6 +87,7 @@ namespace EHR Date = "2023-7-5T00:00:00Z" }; + AllModNews.Add(news); } } @@ -102,21 +104,15 @@ namespace EHR List FinalAllNews = []; AllModNews.Do(n => FinalAllNews.Add(n.ToAnnouncement())); + foreach (Announcement news in aRange.ToArray()) - { if (!AllModNews.Any(x => x.Number == news.Number)) - { FinalAllNews.Add(news); - } - } FinalAllNews.Sort((a1, a2) => { return DateTime.Compare(DateTime.Parse(a2.Date), DateTime.Parse(a1.Date)); }); aRange = new(FinalAllNews.Count); - for (int i = 0; i < FinalAllNews.Count; i++) - { - aRange[i] = FinalAllNews[i]; - } + for (var i = 0; i < FinalAllNews.Count; i++) aRange[i] = FinalAllNews[i]; return true; } diff --git a/Patches/AprilFoolsPatch.cs b/Patches/AprilFoolsPatch.cs index df0ca4db2..f4dbe755e 100644 --- a/Patches/AprilFoolsPatch.cs +++ b/Patches/AprilFoolsPatch.cs @@ -89,9 +89,7 @@ namespace EHR.Patches __result = PlayerBodyTypes.Normal; } } - catch - { - } + catch { } } } @@ -109,9 +107,7 @@ namespace EHR.Patches __instance.cosmeticLayer.OnCosmeticSet += (Action)__instance.OnCosmeticSet; __instance.gameObject.layer = 8; } - catch - { - } + catch { } return false; } @@ -123,25 +119,17 @@ namespace EHR.Patches try { __instance.ShouldLongAround = true; - if (__instance.hideCosmeticsQC) - { - __instance.cosmeticLayer.SetHatVisorVisible(false); - } + if (__instance.hideCosmeticsQC) __instance.cosmeticLayer.SetHatVisorVisible(false); __instance.SetupNeckGrowth(); + if (__instance.isExiledPlayer) { - ShipStatus instance = ShipStatus.Instance; - if (instance == null || instance.Type != ShipStatus.MapType.Fungle) - { - __instance.cosmeticLayer.AdjustCosmeticRotations(-17.75f); - } + var instance = ShipStatus.Instance; + if (instance == null || instance.Type != ShipStatus.MapType.Fungle) __instance.cosmeticLayer.AdjustCosmeticRotations(-17.75f); } - if (!__instance.isPoolablePlayer) - { - __instance.cosmeticLayer.ValidateCosmetics(); - } + if (!__instance.isPoolablePlayer) __instance.cosmeticLayer.ValidateCosmetics(); if (__instance.myPlayerControl) { @@ -149,9 +137,7 @@ namespace EHR.Patches __instance.SetHeightFromColor(__instance.myPlayerControl.Data.DefaultOutfit.ColorId); } } - catch - { - } + catch { } return false; } @@ -165,9 +151,7 @@ namespace EHR.Patches __instance.targetHeight = (distance / 10f) + 0.5f; __instance.SetupNeckGrowth(true); } - catch - { - } + catch { } return false; } diff --git a/Patches/ChatBubblePatch.cs b/Patches/ChatBubblePatch.cs index bdefc0c6a..f5244b8e6 100644 --- a/Patches/ChatBubblePatch.cs +++ b/Patches/ChatBubblePatch.cs @@ -9,10 +9,7 @@ namespace EHR.Patches { public static void Postfix(ChatBubble __instance) { - if (Main.IsChatCommand) - { - __instance.SetLeft(); - } + if (Main.IsChatCommand) __instance.SetLeft(); } } @@ -24,24 +21,15 @@ namespace EHR.Patches PlayerControl seer = PlayerControl.LocalPlayer; PlayerControl target = __instance.playerInfo.Object; - if (GameStates.IsInGame && !voted && seer.PlayerId == target.PlayerId) - { - __instance.NameText.color = seer.GetRoleColor(); - } + if (GameStates.IsInGame && !voted && seer.PlayerId == target.PlayerId) __instance.NameText.color = seer.GetRoleColor(); - if (seer.GetCustomRole().GetDYRole() is RoleTypes.Shapeshifter or RoleTypes.Phantom) - { - __instance.NameText.color = Color.white; - } + if (seer.GetCustomRole().GetDYRole() is RoleTypes.Shapeshifter or RoleTypes.Phantom) __instance.NameText.color = Color.white; if (Main.DarkTheme.Value) { __instance.Background.color = new(0.1f, 0.1f, 0.1f, 1f); __instance.TextArea.color = Color.white; - if (!__instance.playerInfo.Object.IsAlive() && GameStates.InGame) - { - __instance.Background.color = new(0.1f, 0.1f, 0.1f, 0.7f); - } + if (!__instance.playerInfo.Object.IsAlive() && GameStates.InGame) __instance.Background.color = new(0.1f, 0.1f, 0.1f, 0.7f); } } } diff --git a/Patches/ChatCommandPatch.cs b/Patches/ChatCommandPatch.cs index 2915c18bb..ad115e398 100644 --- a/Patches/ChatCommandPatch.cs +++ b/Patches/ChatCommandPatch.cs @@ -53,10 +53,7 @@ namespace EHR public bool IsThisCommand(string text) { - if (!text.StartsWith('/')) - { - return false; - } + if (!text.StartsWith('/')) return false; text = text.ToLower().Trim().TrimStart('/'); return CommandForms.Any(text.Split(' ')[0].Equals); @@ -64,15 +61,9 @@ namespace EHR public bool CanUseCommand(PlayerControl pc, bool checkTime = true) { - if (UsageLevel == UsageLevels.Everyone && UsageTime == UsageTimes.Always && !Lovers.PrivateChat.GetBool()) - { - return true; - } + if (UsageLevel == UsageLevels.Everyone && UsageTime == UsageTimes.Always && !Lovers.PrivateChat.GetBool()) return true; - if (Lovers.PrivateChat.GetBool() && GameStates.IsInTask && pc.IsAlive()) - { - return false; - } + if (Lovers.PrivateChat.GetBool() && GameStates.IsInTask && pc.IsAlive()) return false; switch (UsageLevel) { @@ -82,10 +73,7 @@ namespace EHR return false; } - if (!checkTime) - { - return true; - } + if (!checkTime) return true; switch (UsageTime) { @@ -204,12 +192,10 @@ namespace EHR // Function to check if a player is a moderator public static bool IsPlayerModerator(string friendCode) { - if (friendCode == "" || friendCode == string.Empty || !Options.ApplyModeratorList.GetBool()) - { - return false; - } + if (friendCode == "" || friendCode == string.Empty || !Options.ApplyModeratorList.GetBool()) return false; const string friendCodesFilePath = "./EHR_DATA/Moderators.txt"; + if (!File.Exists(friendCodesFilePath)) { File.WriteAllText(friendCodesFilePath, string.Empty); @@ -223,12 +209,10 @@ namespace EHR // Function to check if a player is a VIP public static bool IsPlayerVIP(string friendCode) { - if (friendCode == "" || friendCode == string.Empty || !Options.ApplyVIPList.GetBool()) - { - return false; - } + if (friendCode == "" || friendCode == string.Empty || !Options.ApplyVIPList.GetBool()) return false; const string friendCodesFilePath = "./EHR_DATA/VIPs.txt"; + if (!File.Exists(friendCodesFilePath)) { File.WriteAllText(friendCodesFilePath, string.Empty); @@ -241,70 +225,40 @@ namespace EHR public static bool Prefix(ChatController __instance) { - if (__instance.quickChatField.visible) - { - return true; - } + if (__instance.quickChatField.visible) return true; - if (__instance.freeChatField.textArea.text == string.Empty) - { - return false; - } + if (__instance.freeChatField.textArea.text == string.Empty) return false; __instance.timeSinceLastMessage = 3f; string text = __instance.freeChatField.textArea.text; - if (ChatHistory.Count == 0 || ChatHistory[^1] != text) - { - ChatHistory.Add(text); - } + if (ChatHistory.Count == 0 || ChatHistory[^1] != text) ChatHistory.Add(text); ChatControllerUpdatePatch.CurrentHistorySelection = ChatHistory.Count; string[] args = text.Split(' '); - bool canceled = false; - string cancelVal = string.Empty; + var canceled = false; + var cancelVal = string.Empty; Main.IsChatCommand = true; Logger.Info(text, "SendChat"); ChatManager.SendMessage(PlayerControl.LocalPlayer, text); - if (GuessManager.GuesserMsg(PlayerControl.LocalPlayer, text)) - { - goto Canceled; - } + if (GuessManager.GuesserMsg(PlayerControl.LocalPlayer, text)) goto Canceled; - if (Judge.TrialMsg(PlayerControl.LocalPlayer, text)) - { - goto Canceled; - } + if (Judge.TrialMsg(PlayerControl.LocalPlayer, text)) goto Canceled; - if (NiceSwapper.SwapMsg(PlayerControl.LocalPlayer, text)) - { - goto Canceled; - } + if (NiceSwapper.SwapMsg(PlayerControl.LocalPlayer, text)) goto Canceled; - if (ParityCop.ParityCheckMsg(PlayerControl.LocalPlayer, text)) - { - goto Canceled; - } + if (ParityCop.ParityCheckMsg(PlayerControl.LocalPlayer, text)) goto Canceled; - if (Councillor.MurderMsg(PlayerControl.LocalPlayer, text)) - { - goto Canceled; - } + if (Councillor.MurderMsg(PlayerControl.LocalPlayer, text)) goto Canceled; - if (Mediumshiper.MsMsg(PlayerControl.LocalPlayer, text)) - { - goto Canceled; - } + if (Mediumshiper.MsMsg(PlayerControl.LocalPlayer, text)) goto Canceled; - if (Mafia.MafiaMsgCheck(PlayerControl.LocalPlayer, text)) - { - goto Canceled; - } + if (Mafia.MafiaMsgCheck(PlayerControl.LocalPlayer, text)) goto Canceled; Main.IsChatCommand = false; @@ -312,13 +266,11 @@ namespace EHR { foreach (Command command in AllCommands) { - if (!command.IsThisCommand(text)) - { - continue; - } + if (!command.IsThisCommand(text)) continue; Logger.Info($" Recognized command: {text}", "ChatCommand"); Main.IsChatCommand = true; + if (!command.CanUseCommand(PlayerControl.LocalPlayer)) { Utils.SendMessage(GetString("Commands.NoAccess"), PlayerControl.LocalPlayer.PlayerId); @@ -326,24 +278,15 @@ namespace EHR } command.Action(__instance, PlayerControl.LocalPlayer, text, args); - if (command.IsCanceled) - { - goto Canceled; - } + if (command.IsCanceled) goto Canceled; break; } } - if (CheckMute(PlayerControl.LocalPlayer.PlayerId)) - { - goto Canceled; - } + if (CheckMute(PlayerControl.LocalPlayer.PlayerId)) goto Canceled; - if (GameStates.InGame && (Silencer.ForSilencer.Contains(PlayerControl.LocalPlayer.PlayerId) || (Main.PlayerStates[PlayerControl.LocalPlayer.PlayerId].Role is Dad { IsEnable: true } dad && dad.UsingAbilities.Contains(Dad.Ability.GoForMilk))) && PlayerControl.LocalPlayer.IsAlive()) - { - goto Canceled; - } + if (GameStates.InGame && (Silencer.ForSilencer.Contains(PlayerControl.LocalPlayer.PlayerId) || (Main.PlayerStates[PlayerControl.LocalPlayer.PlayerId].Role is Dad { IsEnable: true } dad && dad.UsingAbilities.Contains(Dad.Ability.GoForMilk))) && PlayerControl.LocalPlayer.IsAlive()) goto Canceled; if (GameStates.IsInGame && (PlayerControl.LocalPlayer.IsAlive() || ExileController.Instance) && Lovers.PrivateChat.GetBool() && (ExileController.Instance || !GameStates.IsMeeting)) { @@ -365,6 +308,7 @@ namespace EHR Main.IsChatCommand = false; canceled = true; Skip: + if (canceled) { Logger.Info("Command Canceled", "ChatCommand"); @@ -391,32 +335,24 @@ namespace EHR IEnumerator Countdown() { - float timer = 30f; + var timer = 30f; + while (timer > 0f) { - if (!GameStates.IsLobby) - { - yield break; - } + if (!GameStates.IsLobby) yield break; - if (Main.AllPlayerControls.Select(x => x.PlayerId).All(ReadyPlayers.Contains)) - { - break; - } + if (Main.AllPlayerControls.Select(x => x.PlayerId).All(ReadyPlayers.Contains)) break; timer -= Time.deltaTime; yield return null; } byte[] notReadyPlayers = Main.AllPlayerControls.Select(x => x.PlayerId).Except(ReadyPlayers).ToArray(); + if (notReadyPlayers.Length == 0) - { Utils.SendMessage("\n", player.PlayerId, GetString("EveryoneReadyTitle")); - } else - { Utils.SendMessage(string.Join(", ", notReadyPlayers.Select(x => x.ColoredPlayerName())), player.PlayerId, string.Format(GetString("PlayersNotReadyTitle"), notReadyPlayers.Length)); - } } } @@ -458,10 +394,7 @@ namespace EHR private static void DraftCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (DraftRoles.Count == 0 || !DraftRoles.TryGetValue(player.PlayerId, out List roles) || args.Length < 2 || !int.TryParse(args[1], out int chosenIndex) || roles.Count < chosenIndex) - { - return; - } + if (DraftRoles.Count == 0 || !DraftRoles.TryGetValue(player.PlayerId, out List roles) || args.Length < 2 || !int.TryParse(args[1], out int chosenIndex) || roles.Count < chosenIndex) return; CustomRoles role = roles[chosenIndex - 1]; DraftResult[player.PlayerId] = role; @@ -470,32 +403,20 @@ namespace EHR private static void MuteCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (!player.IsHost() && (GameStates.InGame || MutedPlayers.ContainsKey(player.PlayerId))) - { - return; - } + if (!player.IsHost() && (GameStates.InGame || MutedPlayers.ContainsKey(player.PlayerId))) return; - if (args.Length < 3 || !byte.TryParse(args[1], out byte id) || id.IsHost()) - { - return; - } + if (args.Length < 3 || !byte.TryParse(args[1], out byte id) || id.IsHost()) return; int duration = !int.TryParse(args[2], out int dur) ? 60 : dur; MutedPlayers[id] = (Utils.TimeStamp, duration); Utils.SendMessage("\n", player.PlayerId, string.Format(GetString("PlayerMuted"), id.ColoredPlayerName(), duration)); Utils.SendMessage("\n", id, string.Format(GetString("YouMuted"), player.PlayerId.ColoredPlayerName(), duration)); - if (!player.IsHost()) - { - Utils.SendMessage("\n", 0, string.Format(GetString("ModeratorMuted"), player.PlayerId.ColoredPlayerName(), id.ColoredPlayerName(), duration)); - } + if (!player.IsHost()) Utils.SendMessage("\n", 0, string.Format(GetString("ModeratorMuted"), player.PlayerId.ColoredPlayerName(), id.ColoredPlayerName(), duration)); } private static void UnmuteCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length < 2 || !byte.TryParse(args[1], out byte id)) - { - return; - } + if (args.Length < 2 || !byte.TryParse(args[1], out byte id)) return; MutedPlayers.Remove(id); Utils.SendMessage("\n", player.PlayerId, string.Format(GetString("PlayerUnmuted"), id.ColoredPlayerName())); @@ -504,45 +425,31 @@ namespace EHR private static void NegotiationCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (!Negotiator.On || !player.IsAlive() || args.Length < 2 || !int.TryParse(args[1], out int index)) - { - return; - } + if (!Negotiator.On || !player.IsAlive() || args.Length < 2 || !int.TryParse(args[1], out int index)) return; Negotiator.ReceiveCommand(player, index); } private static void OSCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (!GameStates.IsLobby || args.Length < 3 || !byte.TryParse(args[1], out byte chance) || chance > 100 || chance % 5 != 0 || !GetRoleByName(string.Join(' ', args[2..]), out CustomRoles role) || !Options.CustomRoleSpawnChances.TryGetValue(role, out StringOptionItem option)) - { - return; - } + if (!GameStates.IsLobby || args.Length < 3 || !byte.TryParse(args[1], out byte chance) || chance > 100 || chance % 5 != 0 || !GetRoleByName(string.Join(' ', args[2..]), out CustomRoles role) || !Options.CustomRoleSpawnChances.TryGetValue(role, out StringOptionItem option)) return; if (role.IsAdditionRole()) { option.SetValue(chance == 0 ? 0 : 1); - if (!Options.CustomAdtRoleSpawnRate.TryGetValue(role, out IntegerOptionItem adtOption)) - { - return; - } + if (!Options.CustomAdtRoleSpawnRate.TryGetValue(role, out IntegerOptionItem adtOption)) return; adtOption.SetValue(chance / 5); } else - { option.SetValue(chance / 5); - } } private static void NoteCommand(ChatController __instance, PlayerControl player, string text, string[] args) { if (player.Is(CustomRoles.Journalist) && player.IsAlive()) { - if (PlayerControl.LocalPlayer.PlayerId != player.PlayerId) - { - ChatManager.SendPreviousMessagesToAll(); - } + if (PlayerControl.LocalPlayer.PlayerId != player.PlayerId) ChatManager.SendPreviousMessagesToAll(); Journalist.OnReceiveCommand(player, args); } @@ -550,37 +457,22 @@ namespace EHR private static void AssumeCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length < 3 || !byte.TryParse(args[1], out byte id) || !int.TryParse(args[2], out int num) || !player.Is(CustomRoles.Assumer) || !player.IsAlive()) - { - return; - } + if (args.Length < 3 || !byte.TryParse(args[1], out byte id) || !int.TryParse(args[2], out int num) || !player.Is(CustomRoles.Assumer) || !player.IsAlive()) return; - if (PlayerControl.LocalPlayer.PlayerId != player.PlayerId) - { - ChatManager.SendPreviousMessagesToAll(); - } + if (PlayerControl.LocalPlayer.PlayerId != player.PlayerId) ChatManager.SendPreviousMessagesToAll(); Assumer.Assume(player.PlayerId, id, num); } private static void DeleteVIPCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length < 2 || !byte.TryParse(args[1], out byte VIPId)) - { - return; - } + if (args.Length < 2 || !byte.TryParse(args[1], out byte VIPId)) return; PlayerControl VIPPc = Utils.GetPlayerById(VIPId); - if (VIPPc == null) - { - return; - } + if (VIPPc == null) return; string fc = VIPPc.FriendCode; - if (!IsPlayerVIP(fc)) - { - Utils.SendMessage(GetString("PlayerNotVIP"), player.PlayerId); - } + if (!IsPlayerVIP(fc)) Utils.SendMessage(GetString("PlayerNotVIP"), player.PlayerId); string[] lines = File.ReadAllLines("./EHR_DATA/VIPs.txt").Where(line => !line.Contains(fc)).ToArray(); File.WriteAllLines("./EHR_DATA/VIPs.txt", lines); @@ -589,22 +481,13 @@ namespace EHR private static void AddVIPCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length < 2 || !byte.TryParse(args[1], out byte newVIPId)) - { - return; - } + if (args.Length < 2 || !byte.TryParse(args[1], out byte newVIPId)) return; PlayerControl newVIPPc = Utils.GetPlayerById(newVIPId); - if (newVIPPc == null) - { - return; - } + if (newVIPPc == null) return; string fc = newVIPPc.FriendCode; - if (IsPlayerVIP(fc)) - { - Utils.SendMessage(GetString("PlayerAlreadyVIP"), player.PlayerId); - } + if (IsPlayerVIP(fc)) Utils.SendMessage(GetString("PlayerAlreadyVIP"), player.PlayerId); File.AppendAllText("./EHR_DATA/VIPs.txt", $"\n{fc}"); Utils.SendMessage(GetString("PlayerAddedToVIPList"), player.PlayerId); @@ -612,15 +495,9 @@ namespace EHR private static void DecreeCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (!player.Is(CustomRoles.President)) - { - return; - } + if (!player.Is(CustomRoles.President)) return; - if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) - { - ChatManager.SendPreviousMessagesToAll(); - } + if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) ChatManager.SendPreviousMessagesToAll(); LateTask.New(() => { @@ -636,10 +513,7 @@ namespace EHR private static void HMCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (Messenger.Sent.Contains(player.PlayerId) || args.Length < 2 || !int.TryParse(args[1], out int id) || id is > 3 or < 1) - { - return; - } + if (Messenger.Sent.Contains(player.PlayerId) || args.Length < 2 || !int.TryParse(args[1], out int id) || id is > 3 or < 1) return; Main.Instance.StartCoroutine(SendOnMeeting()); return; @@ -647,23 +521,15 @@ namespace EHR IEnumerator SendOnMeeting() { bool meeting = GameStates.IsMeeting; - while (!GameStates.IsMeeting) - { - yield return null; - } + while (!GameStates.IsMeeting) yield return null; - if (!meeting) - { - yield return new WaitForSeconds(7f); - } + if (!meeting) yield return new WaitForSeconds(7f); PlayerControl killer = player.GetRealKiller(); - if (killer == null && id != 3) - { - yield break; - } + if (killer == null && id != 3) yield break; Team team = player.GetTeam(); + string message = id switch { 1 => string.Format(GetString("MessengerMessage.1"), GetString(Main.PlayerStates[killer.PlayerId].LastRoom.RoomId.ToString())), @@ -695,9 +561,10 @@ namespace EHR string[] answers = args.Skip(splitIndex).ToArray(); string msg = string.Join(" ", args.Take(splitIndex).Skip(1)) + "\n"; - for (int i = 0; i < Math.Clamp(answers.Length, 2, 5); i++) + + for (var i = 0; i < Math.Clamp(answers.Length, 2, 5); i++) { - char choiceLetter = (char)(i + 65); + var choiceLetter = (char)(i + 65); msg += Utils.ColorString(RandomColor(), $"{char.ToUpper(choiceLetter)}) {answers[i]}\n"); PollVotes[choiceLetter] = 0; PollAnswers[choiceLetter] = $"〖 {answers[i]} 〗"; @@ -712,19 +579,18 @@ namespace EHR IEnumerator StartPollCountdown() { - if (PollVotes.Count == 0) - { - yield break; - } + if (PollVotes.Count == 0) yield break; bool playervoted = Main.AllPlayerControls.Length - 1 > PollVotes.Values.Sum(); - float resendTimer = 0f; + var resendTimer = 0f; + while (playervoted && PollTimer > 0f) { playervoted = Main.AllPlayerControls.Length - 1 > PollVotes.Values.Sum(); PollTimer -= Time.deltaTime; resendTimer += Time.deltaTime; + if (resendTimer >= 15f) { resendTimer = 0f; @@ -741,6 +607,7 @@ namespace EHR { int maxVotes = PollVotes.Values.Max(); KeyValuePair[] winners = PollVotes.Where(x => x.Value == maxVotes).ToArray(); + string msg = winners.Length == 1 ? string.Format(GetString("Poll.Winner"), winners[0].Key, PollAnswers[winners[0].Key], winners[0].Value) + PollVotes.Where(x => x.Key != winners[0].Key).Aggregate("", (s, t) => s + $"{t.Key} / {t.Value} {PollAnswers[t.Key]}\n") @@ -806,6 +673,7 @@ namespace EHR } string subArgs = args.Length != 2 ? "" : args[1]; + if (subArgs == "" || !int.TryParse(subArgs, out int guessedNo)) { Utils.SendMessage(GetString("GNoCommandInfo"), player.PlayerId); @@ -819,14 +687,16 @@ namespace EHR } int targetNumber = Main.GuessNumber[player.PlayerId][0]; + if (Main.GuessNumber[player.PlayerId][0] == -1) { - IRandom rand = IRandom.Instance; + var rand = IRandom.Instance; Main.GuessNumber[player.PlayerId][0] = rand.Next(0, 100); targetNumber = Main.GuessNumber[player.PlayerId][0]; } Main.GuessNumber[player.PlayerId][1]--; + if (Main.GuessNumber[player.PlayerId][1] == 0 && guessedNo != targetNumber) { Main.GuessNumber[player.PlayerId][0] = -1; @@ -854,10 +724,7 @@ namespace EHR private static void SDCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length < 1 || !int.TryParse(args[1], out int sound1)) - { - return; - } + if (args.Length < 1 || !int.TryParse(args[1], out int sound1)) return; RPC.PlaySoundRPC(player.PlayerId, (Sounds)sound1); } @@ -871,13 +738,9 @@ namespace EHR private static void MTHYCommand(ChatController __instance, PlayerControl player, string text, string[] args) { if (GameStates.IsMeeting) - { MeetingHud.Instance.RpcClose(); - } else - { player.NoCheckStartMeeting(null, true); - } } private static void CosIDCommand(ChatController __instance, PlayerControl player, string text, string[] args) @@ -899,34 +762,24 @@ namespace EHR private static void ChangeRoleCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (GameStates.IsLobby || !player.FriendCode.GetDevUser().IsUp) - { - return; - } + if (GameStates.IsLobby || !player.FriendCode.GetDevUser().IsUp) return; string subArgs = text.Remove(0, 8); string setRole = FixRoleNameInput(subArgs.Trim()); + foreach (CustomRoles rl in Enum.GetValues()) { - if (rl.IsVanilla()) - { - continue; - } + if (rl.IsVanilla()) continue; string roleName = GetString(rl.ToString()).ToLower().Trim(); + if (setRole.Contains(roleName)) { - if (!rl.IsAdditionRole()) - { - player.SetRole(rl.GetRoleTypes()); - } + if (!rl.IsAdditionRole()) player.SetRole(rl.GetRoleTypes()); player.RpcSetCustomRole(rl); - if (rl.IsGhostRole()) - { - GhostRolesManager.SpecificAssignGhostRole(player.PlayerId, rl, true); - } + if (rl.IsGhostRole()) GhostRolesManager.SpecificAssignGhostRole(player.PlayerId, rl, true); Main.PlayerStates[player.PlayerId].RemoveSubRole(CustomRoles.NotAssigned); Main.ChangedRole = true; @@ -951,10 +804,7 @@ namespace EHR return; } - foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { - pc.RpcSetNameEx(pc.GetRealName(true)); - } + foreach (PlayerControl pc in Main.AllAlivePlayerControls) pc.RpcSetNameEx(pc.GetRealName(true)); ChatUpdatePatch.DoBlockChat = false; Utils.NotifyRoles(GameStates.IsMeeting, NoCache: true); @@ -977,6 +827,7 @@ namespace EHR string subArgs = args.Length < 2 ? string.Empty : args[1]; byte color = Utils.MsgToColor(subArgs, true); + if (color == byte.MaxValue) { Utils.SendMessage(GetString("IllegalColor"), player.PlayerId); @@ -995,23 +846,18 @@ namespace EHR return; } - if (args.Length < 2 || !int.TryParse(args[1], out int id2)) - { - return; - } + if (args.Length < 2 || !int.TryParse(args[1], out int id2)) return; PlayerControl target = Utils.GetPlayerById(id2); + if (target != null) { target.Kill(target); + if (target.AmOwner) - { Utils.SendMessage(GetString("HostKillSelfByCommand"), title: $"{GetString("DefaultSystemMessageTitle")}"); - } else - { Utils.SendMessage(string.Format(GetString("Message.Executed"), target.Data.PlayerName)); - } } } @@ -1023,26 +869,21 @@ namespace EHR return; } - if (args.Length < 2 || !int.TryParse(args[1], out int id)) - { - return; - } + if (args.Length < 2 || !int.TryParse(args[1], out int id)) return; PlayerControl pc = Utils.GetPlayerById(id); + if (pc != null) { pc.Data.IsDead = true; Main.PlayerStates[pc.PlayerId].deathReason = PlayerState.DeathReason.etc; pc.RpcExileV2(); Main.PlayerStates[pc.PlayerId].SetDead(); + if (pc.AmOwner) - { Utils.SendMessage(GetString("HostKillSelfByCommand"), title: $"{GetString("DefaultSystemMessageTitle")}"); - } else - { Utils.SendMessage(string.Format(GetString("Message.Executed"), pc.Data.PlayerName)); - } } } @@ -1063,6 +904,7 @@ namespace EHR } string subArgs = args.Length < 2 ? string.Empty : args[1]; + if (string.IsNullOrEmpty(subArgs) || !byte.TryParse(subArgs, out byte kickPlayerId)) { Utils.SendMessage(GetString("KickCommandInvalidID"), player.PlayerId); @@ -1076,6 +918,7 @@ namespace EHR } PlayerControl kickedPlayer = Utils.GetPlayerById(kickPlayerId); + if (kickedPlayer == null) { Utils.SendMessage(GetString("KickCommandInvalidID"), player.PlayerId); @@ -1092,37 +935,22 @@ namespace EHR // Kick the specified player AmongUsClient.Instance.KickPlayer(kickedPlayer.GetClientId(), args[0] == "/ban"); string kickedPlayerName = kickedPlayer.GetRealName(); - string textToSend = $"{kickedPlayerName} {GetString("KickCommandKicked")}"; - if (GameStates.IsInGame) - { - textToSend += $"{GetString("KickCommandKickedRole")} {kickedPlayer.GetCustomRole().ToColoredString()}"; - } + var textToSend = $"{kickedPlayerName} {GetString("KickCommandKicked")}"; + if (GameStates.IsInGame) textToSend += $"{GetString("KickCommandKickedRole")} {kickedPlayer.GetCustomRole().ToColoredString()}"; Utils.SendMessage(textToSend); } private static void CheckCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (!player.IsAlive() || !player.Is(CustomRoles.Inquirer) || player.GetAbilityUseLimit() < 1) - { - return; - } + if (!player.IsAlive() || !player.Is(CustomRoles.Inquirer) || player.GetAbilityUseLimit() < 1) return; - if (args.Length < 3 || !GuessManager.MsgToPlayerAndRole(text[6..], out byte checkId, out CustomRoles checkRole, out _)) - { - return; - } + if (args.Length < 3 || !GuessManager.MsgToPlayerAndRole(text[6..], out byte checkId, out CustomRoles checkRole, out _)) return; bool hasRole = Utils.GetPlayerById(checkId).Is(checkRole); - if (IRandom.Instance.Next(100) < Inquirer.FailChance.GetInt()) - { - hasRole = !hasRole; - } + if (IRandom.Instance.Next(100) < Inquirer.FailChance.GetInt()) hasRole = !hasRole; - if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) - { - ChatManager.SendPreviousMessagesToAll(); - } + if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) ChatManager.SendPreviousMessagesToAll(); LateTask.New(() => Utils.SendMessage(GetString(hasRole ? "Inquirer.MessageTrue" : "Inquirer.MessageFalse"), player.PlayerId), 0.2f, log: false); player.RpcRemoveAbilityUse(); @@ -1130,21 +958,12 @@ namespace EHR private static void ChatCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (!Ventriloquist.On || !player.IsAlive() || !player.Is(CustomRoles.Ventriloquist) || player.PlayerId.GetAbilityUseLimit() < 1) - { - return; - } + if (!Ventriloquist.On || !player.IsAlive() || !player.Is(CustomRoles.Ventriloquist) || player.PlayerId.GetAbilityUseLimit() < 1) return; - Ventriloquist vl2 = (Ventriloquist)Main.PlayerStates[player.PlayerId].Role; - if (vl2.Target == byte.MaxValue) - { - return; - } + var vl2 = (Ventriloquist)Main.PlayerStates[player.PlayerId].Role; + if (vl2.Target == byte.MaxValue) return; - if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) - { - ChatManager.SendPreviousMessagesToAll(); - } + if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) ChatManager.SendPreviousMessagesToAll(); LateTask.New(() => Utils.GetPlayerById(vl2.Target)?.RpcSendChat(text[6..]), 0.2f, log: false); player.RpcRemoveAbilityUse(); @@ -1152,125 +971,77 @@ namespace EHR private static void TargetCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (!Ventriloquist.On || !player.IsAlive() || !player.Is(CustomRoles.Ventriloquist) || player.PlayerId.GetAbilityUseLimit() < 1) - { - return; - } + if (!Ventriloquist.On || !player.IsAlive() || !player.Is(CustomRoles.Ventriloquist) || player.PlayerId.GetAbilityUseLimit() < 1) return; - Ventriloquist vl = (Ventriloquist)Main.PlayerStates[player.PlayerId].Role; + var vl = (Ventriloquist)Main.PlayerStates[player.PlayerId].Role; vl.Target = args.Length < 2 ? byte.MaxValue : byte.TryParse(args[1], out byte targetId) ? targetId : byte.MaxValue; - if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) - { - ChatManager.SendPreviousMessagesToAll(); - } + if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) ChatManager.SendPreviousMessagesToAll(); } private static void QSCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (!QuizMaster.On || !player.IsAlive()) - { - return; - } + if (!QuizMaster.On || !player.IsAlive()) return; - QuizMaster qm2 = (QuizMaster)Main.PlayerStates.Values.First(x => x.Role is QuizMaster).Role; - if (qm2.Target != player.PlayerId || !QuizMaster.MessagesToSend.TryGetValue(player.PlayerId, out string msg)) - { - return; - } + var qm2 = (QuizMaster)Main.PlayerStates.Values.First(x => x.Role is QuizMaster).Role; + if (qm2.Target != player.PlayerId || !QuizMaster.MessagesToSend.TryGetValue(player.PlayerId, out string msg)) return; Utils.SendMessage(msg, player.PlayerId, GetString("QuizMaster.QuestionSample.Title")); } private static void QACommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length < 2 || !QuizMaster.On || !player.IsAlive()) - { - return; - } + if (args.Length < 2 || !QuizMaster.On || !player.IsAlive()) return; - QuizMaster qm = (QuizMaster)Main.PlayerStates.Values.First(x => x.Role is QuizMaster).Role; - if (qm.Target != player.PlayerId) - { - return; - } + var qm = (QuizMaster)Main.PlayerStates.Values.First(x => x.Role is QuizMaster).Role; + if (qm.Target != player.PlayerId) return; qm.Answer(args[1].ToUpper()); } private static void AnswerCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length < 2) - { - return; - } + if (args.Length < 2) return; Mathematician.Reply(player, args[1]); } private static void AskCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length < 3 || !player.Is(CustomRoles.Mathematician)) - { - return; - } + if (args.Length < 3 || !player.Is(CustomRoles.Mathematician)) return; - if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) - { - ChatManager.SendPreviousMessagesToAll(); - } + if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) ChatManager.SendPreviousMessagesToAll(); Mathematician.Ask(player, args[1], args[2]); } private static void VoteCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (text.Length < 6 || !GameStates.IsMeeting) - { - return; - } + if (text.Length < 6 || !GameStates.IsMeeting) return; string toVote = text[6..].Replace(" ", string.Empty); - if (!byte.TryParse(toVote, out byte voteId) || MeetingHud.Instance?.playerStates?.FirstOrDefault(x => x.TargetPlayerId == player.PlayerId)?.DidVote == true) - { - return; - } + if (!byte.TryParse(toVote, out byte voteId) || MeetingHud.Instance?.playerStates?.FirstOrDefault(x => x.TargetPlayerId == player.PlayerId)?.DidVote == true) return; - if (voteId > Main.AllPlayerControls.Length) - { - return; - } + if (voteId > Main.AllPlayerControls.Length) return; - if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) - { - ChatManager.SendPreviousMessagesToAll(); - } + if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) ChatManager.SendPreviousMessagesToAll(); if (!player.IsHost()) - { MeetingHud.Instance?.CastVote(player.PlayerId, voteId); - } else - { MeetingHud.Instance?.CmdCastVote(player.PlayerId, voteId); - } } private static void SayCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length > 1) - { - Utils.SendMessage(args.Skip(1).Join(delimiter: " "), title: $"{GetString(player.IsHost() ? "MessageFromTheHost" : "SayTitle")}"); - } + if (args.Length > 1) Utils.SendMessage(args.Skip(1).Join(delimiter: " "), title: $"{GetString(player.IsHost() ? "MessageFromTheHost" : "SayTitle")}"); } private static void DeathCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (!GameStates.IsInGame) - { - return; - } + if (!GameStates.IsInGame) return; PlayerControl killer = player.GetRealKiller(); + if (killer == null) { Utils.SendMessage("\n", player.PlayerId, GetString("DeathCommandFail")); @@ -1288,9 +1059,7 @@ namespace EHR Utils.SendMessage(string.Format(GetString("Message.SetToSeconds"), sec), 0); } else - { Utils.SendMessage($"{GetString("Message.MessageWaitHelp")}\n{GetString("ForExample")}:\n{args[0]} 3", 0); - } } private static void TemplateCommand(ChatController __instance, PlayerControl player, string text, string[] args) @@ -1298,43 +1067,29 @@ namespace EHR if (player.PlayerId == PlayerControl.LocalPlayer.PlayerId) { if (args.Length > 1) - { TemplateManager.SendTemplate(args[1]); - } else - { HudManager.Instance.Chat.AddChat(player, (player.FriendCode.GetDevUser().HasTag() ? "\n" : string.Empty) + $"{GetString("ForExample")}:\n{args[0]} test"); - } } else { if (args.Length > 1) - { TemplateManager.SendTemplate(args[1], player.PlayerId); - } else - { Utils.SendMessage($"{GetString("ForExample")}:\n{args[0]} test", player.PlayerId); - } } } private static void TPInCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (!GameStates.IsLobby || !Options.PlayerCanTPInAndOut.GetBool()) - { - return; - } + if (!GameStates.IsLobby || !Options.PlayerCanTPInAndOut.GetBool()) return; player.TP(new Vector2(-0.2f, 1.3f)); } private static void TPOutCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (!GameStates.IsLobby || !Options.PlayerCanTPInAndOut.GetBool()) - { - return; - } + if (!GameStates.IsLobby || !Options.PlayerCanTPInAndOut.GetBool()) return; player.TP(new Vector2(0.1f, 3.8f)); } @@ -1342,6 +1097,7 @@ namespace EHR private static void MyRoleCommand(ChatController __instance, PlayerControl player, string text, string[] args) { CustomRoles role = player.GetCustomRole(); + if (GameStates.IsInGame) { StringBuilder sb = new(); @@ -1351,21 +1107,16 @@ namespace EHR titleSb.Append($"{role.ToColoredString()} {Utils.GetRoleMode(role)}"); sb.Append(""); sb.Append(player.GetRoleInfo(true).TrimStart()); - if (Options.CustomRoleSpawnChances.TryGetValue(role, out StringOptionItem opt)) - { - Utils.ShowChildrenSettings(opt, ref settings, disableColor: false); - } + if (Options.CustomRoleSpawnChances.TryGetValue(role, out StringOptionItem opt)) Utils.ShowChildrenSettings(opt, ref settings, disableColor: false); settings.Append(""); - if (role.PetActivatedAbility()) - { - sb.Append($"{GetString("SupportsPetMessage")}"); - } + if (role.PetActivatedAbility()) sb.Append($"{GetString("SupportsPetMessage")}"); string searchStr = GetString(role.ToString()); sb.Replace(searchStr, role.ToColoredString()); sb.Replace(searchStr.ToLower(), role.ToColoredString()); sb.Append(""); + foreach (CustomRoles subRole in Main.PlayerStates[player.PlayerId].SubRoles) { sb.Append($"\n\n{subRole.ToColoredString()} {Utils.GetRoleMode(subRole)} {GetString($"{subRole}InfoLong")}"); @@ -1374,29 +1125,18 @@ namespace EHR sb.Replace(searchSubStr.ToLower(), subRole.ToColoredString()); } - if (settings.Length > 0) - { - Utils.SendMessage("\n", player.PlayerId, settings.ToString()); - } + if (settings.Length > 0) Utils.SendMessage("\n", player.PlayerId, settings.ToString()); Utils.SendMessage(sb.Append("").ToString(), player.PlayerId, titleSb.ToString()); - if (role.UsesPetInsteadOfKill()) - { - Utils.SendMessage("\n", player.PlayerId, GetString("UsesPetInsteadOfKillNotice")); - } + if (role.UsesPetInsteadOfKill()) Utils.SendMessage("\n", player.PlayerId, GetString("UsesPetInsteadOfKillNotice")); } else - { Utils.SendMessage((player.FriendCode.GetDevUser().HasTag() ? "\n" : string.Empty) + GetString("Message.CanNotUseInLobby"), player.PlayerId); - } } private static void AFKExemptCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length < 2 || !byte.TryParse(args[1], out byte afkId)) - { - return; - } + if (args.Length < 2 || !byte.TryParse(args[1], out byte afkId)) return; AFKDetector.ExemptedPlayers.Add(afkId); Utils.SendMessage("\n", player.PlayerId, string.Format(GetString("PlayerExemptedFromAFK"), afkId.ColoredPlayerName())); @@ -1404,28 +1144,20 @@ namespace EHR private static void EffectCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length < 2 || !GameStates.IsInTask || !Randomizer.Exists) - { - return; - } + if (args.Length < 2 || !GameStates.IsInTask || !Randomizer.Exists) return; - if (Enum.TryParse(args[1], true, out Randomizer.Effect effect)) - { - effect.Apply(player); - } + if (Enum.TryParse(args[1], true, out Randomizer.Effect effect)) effect.Apply(player); } private static void ComboCommand(ChatController __instance, PlayerControl player, string text, string[] args) { if (args.Length < 4) { - if (Main.AlwaysSpawnTogetherCombos.Count == 0 && Main.NeverSpawnTogetherCombos.Count == 0) - { - return; - } + if (Main.AlwaysSpawnTogetherCombos.Count == 0 && Main.NeverSpawnTogetherCombos.Count == 0) return; StringBuilder sb = new(); sb.Append(""); + if (Main.AlwaysSpawnTogetherCombos.TryGetValue(OptionItem.CurrentPreset, out Dictionary> alwaysList) && alwaysList.Count > 0) { sb.AppendLine(GetString("AlwaysComboListTitle")); @@ -1452,90 +1184,49 @@ namespace EHR case "ban": if (GetRoleByName(args[2], out CustomRoles mainRole) && GetRoleByName(args[3], out CustomRoles addOn)) { - if (mainRole.IsAdditionRole() || !addOn.IsAdditionRole() || (addOn == CustomRoles.Lovers && args[1] == "add")) - { - break; - } + if (mainRole.IsAdditionRole() || !addOn.IsAdditionRole() || (addOn == CustomRoles.Lovers && args[1] == "add")) break; if (args[1] == "add") { - if (!Main.AlwaysSpawnTogetherCombos.ContainsKey(OptionItem.CurrentPreset)) - { - Main.AlwaysSpawnTogetherCombos[OptionItem.CurrentPreset] = []; - } + if (!Main.AlwaysSpawnTogetherCombos.ContainsKey(OptionItem.CurrentPreset)) Main.AlwaysSpawnTogetherCombos[OptionItem.CurrentPreset] = []; if (!Main.AlwaysSpawnTogetherCombos[OptionItem.CurrentPreset].TryGetValue(mainRole, out List list1)) - { Main.AlwaysSpawnTogetherCombos[OptionItem.CurrentPreset][mainRole] = [addOn]; - } - else if (!list1.Contains(addOn)) - { - list1.Add(addOn); - } + else if (!list1.Contains(addOn)) list1.Add(addOn); if (text.EndsWith(" all")) { - for (int preset = 0; preset < OptionItem.NumPresets; preset++) + for (var preset = 0; preset < OptionItem.NumPresets; preset++) { - if (preset == OptionItem.CurrentPreset) - { - continue; - } + if (preset == OptionItem.CurrentPreset) continue; - if (!Main.AlwaysSpawnTogetherCombos.ContainsKey(preset)) - { - Main.AlwaysSpawnTogetherCombos[preset] = []; - } + if (!Main.AlwaysSpawnTogetherCombos.ContainsKey(preset)) Main.AlwaysSpawnTogetherCombos[preset] = []; if (!Main.AlwaysSpawnTogetherCombos[preset].TryGetValue(mainRole, out List list2)) - { Main.AlwaysSpawnTogetherCombos[preset][mainRole] = [addOn]; - } - else if (!list2.Contains(addOn)) - { - list2.Add(addOn); - } + else if (!list2.Contains(addOn)) list2.Add(addOn); } } } else { - if (!Main.NeverSpawnTogetherCombos.ContainsKey(OptionItem.CurrentPreset)) - { - Main.NeverSpawnTogetherCombos[OptionItem.CurrentPreset] = []; - } + if (!Main.NeverSpawnTogetherCombos.ContainsKey(OptionItem.CurrentPreset)) Main.NeverSpawnTogetherCombos[OptionItem.CurrentPreset] = []; if (!Main.NeverSpawnTogetherCombos[OptionItem.CurrentPreset].TryGetValue(mainRole, out List list2)) - { Main.NeverSpawnTogetherCombos[OptionItem.CurrentPreset][mainRole] = [addOn]; - } - else if (!list2.Contains(addOn)) - { - list2.Add(addOn); - } + else if (!list2.Contains(addOn)) list2.Add(addOn); if (text.EndsWith(" all")) { - for (int preset = 0; preset < OptionItem.NumPresets; preset++) + for (var preset = 0; preset < OptionItem.NumPresets; preset++) { - if (preset == OptionItem.CurrentPreset) - { - continue; - } + if (preset == OptionItem.CurrentPreset) continue; - if (!Main.NeverSpawnTogetherCombos.ContainsKey(preset)) - { - Main.NeverSpawnTogetherCombos[preset] = []; - } + if (!Main.NeverSpawnTogetherCombos.ContainsKey(preset)) Main.NeverSpawnTogetherCombos[preset] = []; if (!Main.NeverSpawnTogetherCombos[preset].TryGetValue(mainRole, out List list3)) - { Main.NeverSpawnTogetherCombos[preset][mainRole] = [addOn]; - } - else if (!list3.Contains(addOn)) - { - list3.Add(addOn); - } + else if (!list3.Contains(addOn)) list3.Add(addOn); } } } @@ -1549,29 +1240,20 @@ namespace EHR case "allow": if (GetRoleByName(args[2], out CustomRoles mainRole2) && GetRoleByName(args[3], out CustomRoles addOn2)) { - if (mainRole2.IsAdditionRole() || !addOn2.IsAdditionRole()) - { - break; - } + if (mainRole2.IsAdditionRole() || !addOn2.IsAdditionRole()) break; if (text.EndsWith(" all")) { - for (int preset = 0; preset < OptionItem.NumPresets; preset++) + for (var preset = 0; preset < OptionItem.NumPresets; preset++) { if (Main.AlwaysSpawnTogetherCombos.TryGetValue(preset, out Dictionary> list1)) { if (list1.TryGetValue(mainRole2, out List list2)) { list2.Remove(addOn2); - if (list2.Count == 0) - { - list1.Remove(mainRole2); - } + if (list2.Count == 0) list1.Remove(mainRole2); - if (list1.Count == 0) - { - Main.AlwaysSpawnTogetherCombos.Remove(preset); - } + if (list1.Count == 0) Main.AlwaysSpawnTogetherCombos.Remove(preset); } } @@ -1580,15 +1262,9 @@ namespace EHR if (list3.TryGetValue(mainRole2, out List list4)) { list4.Remove(addOn2); - if (list4.Count == 0) - { - list3.Remove(mainRole2); - } + if (list4.Count == 0) list3.Remove(mainRole2); - if (list3.Count == 0) - { - Main.NeverSpawnTogetherCombos.Remove(preset); - } + if (list3.Count == 0) Main.NeverSpawnTogetherCombos.Remove(preset); } } } @@ -1601,10 +1277,7 @@ namespace EHR if (args[1] == "remove" && Main.AlwaysSpawnTogetherCombos.TryGetValue(OptionItem.CurrentPreset, out Dictionary> alwaysList) && alwaysList.TryGetValue(mainRole2, out List list3)) { list3.Remove(addOn2); - if (list3.Count == 0) - { - alwaysList.Remove(mainRole2); - } + if (list3.Count == 0) alwaysList.Remove(mainRole2); Utils.SendMessage(string.Format(GetString("ComboRemove"), GetString(mainRole2.ToString()), GetString(addOn2.ToString())), player.PlayerId); Utils.SaveComboInfo(); @@ -1612,10 +1285,7 @@ namespace EHR else if (Main.NeverSpawnTogetherCombos.TryGetValue(OptionItem.CurrentPreset, out Dictionary> neverList) && neverList.TryGetValue(mainRole2, out List list4)) { list4.Remove(addOn2); - if (list4.Count == 0) - { - neverList.Remove(mainRole2); - } + if (list4.Count == 0) neverList.Remove(mainRole2); Utils.SendMessage(string.Format(GetString("ComboAllow"), GetString(mainRole2.ToString()), GetString(addOn2.ToString())), player.PlayerId); Utils.SaveComboInfo(); @@ -1629,22 +1299,13 @@ namespace EHR private static void DeleteModCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length < 2 || !byte.TryParse(args[1], out byte remModId)) - { - return; - } + if (args.Length < 2 || !byte.TryParse(args[1], out byte remModId)) return; PlayerControl remModPc = Utils.GetPlayerById(remModId); - if (remModPc == null) - { - return; - } + if (remModPc == null) return; string remFc = remModPc.FriendCode; - if (!IsPlayerModerator(remFc)) - { - Utils.SendMessage(GetString("PlayerNotMod"), player.PlayerId); - } + if (!IsPlayerModerator(remFc)) Utils.SendMessage(GetString("PlayerNotMod"), player.PlayerId); File.WriteAllLines("./EHR_DATA/Moderators.txt", File.ReadAllLines("./EHR_DATA/Moderators.txt").Where(x => !x.Contains(remFc))); Utils.SendMessage(GetString("PlayerRemovedFromModList"), player.PlayerId); @@ -1652,22 +1313,13 @@ namespace EHR private static void AddModCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length < 2 || !byte.TryParse(args[1], out byte newModId)) - { - return; - } + if (args.Length < 2 || !byte.TryParse(args[1], out byte newModId)) return; PlayerControl newModPc = Utils.GetPlayerById(newModId); - if (newModPc == null) - { - return; - } + if (newModPc == null) return; string fc = newModPc.FriendCode; - if (IsPlayerModerator(fc)) - { - Utils.SendMessage(GetString("PlayerAlreadyMod"), player.PlayerId); - } + if (IsPlayerModerator(fc)) Utils.SendMessage(GetString("PlayerAlreadyMod"), player.PlayerId); File.AppendAllText("./EHR_DATA/Moderators.txt", $"\n{fc}"); Utils.SendMessage(GetString("PlayerAddedToModList"), player.PlayerId); @@ -1675,10 +1327,7 @@ namespace EHR private static void KCountCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (GameStates.IsLobby || !Options.EnableKillerLeftCommand.GetBool() || Main.AllAlivePlayerControls.Length < Options.MinPlayersForGameStateCommand.GetInt()) - { - return; - } + if (GameStates.IsLobby || !Options.EnableKillerLeftCommand.GetBool() || Main.AllAlivePlayerControls.Length < Options.MinPlayersForGameStateCommand.GetInt()) return; Utils.SendMessage("\n", player.PlayerId, Utils.GetGameStateData()); } @@ -1706,34 +1355,22 @@ namespace EHR } PlayerControl targetPc = Utils.GetPlayerById(resultId); - if (targetPc == null) - { - return; - } + if (targetPc == null) return; if (roleToSet.IsAdditionRole()) { - if (!Main.SetAddOns.ContainsKey(resultId)) - { - Main.SetAddOns[resultId] = []; - } + if (!Main.SetAddOns.ContainsKey(resultId)) Main.SetAddOns[resultId] = []; if (Main.SetAddOns[resultId].Contains(roleToSet)) - { Main.SetAddOns[resultId].Remove(roleToSet); - } else - { Main.SetAddOns[resultId].Add(roleToSet); - } } else - { Main.SetRoles[targetPc.PlayerId] = roleToSet; - } - string playername = $"{Utils.ColorString(Main.PlayerColors.TryGetValue(resultId, out Color32 textColor) ? textColor : Color.white, targetPc.GetRealName())}"; - string rolename = $" {GetString(roleToSet.ToString())} "; + var playername = $"{Utils.ColorString(Main.PlayerColors.TryGetValue(resultId, out Color32 textColor) ? textColor : Color.white, targetPc.GetRealName())}"; + var rolename = $" {GetString(roleToSet.ToString())} "; Utils.SendMessage("\n", player.PlayerId, string.Format(GetString("RoleSelected"), playername, rolename)); } @@ -1751,6 +1388,7 @@ namespace EHR private static void DisconnectCommand(ChatController __instance, PlayerControl player, string text, string[] args) { string subArgs = args.Length < 2 ? string.Empty : args[1]; + switch (subArgs) { case "crew": @@ -1774,6 +1412,7 @@ namespace EHR private static void NowCommand(ChatController __instance, PlayerControl player, string text, string[] args) { string subArgs = args.Length < 2 ? string.Empty : args[1]; + switch (subArgs) { case "r": @@ -1795,19 +1434,21 @@ namespace EHR string subArgs = args.Length < 2 ? string.Empty : args[1]; Utils.SendMessage(string.Format(GetString("Message.SetLevel"), subArgs), player.PlayerId); _ = int.TryParse(subArgs, out int input); + if (input is < 1 or > 999) { Utils.SendMessage(GetString("Message.AllowLevelRange"), player.PlayerId); return; } - uint number = Convert.ToUInt32(input); + var number = Convert.ToUInt32(input); player.RpcSetLevel(number - 1); } private static void HideNameCommand(ChatController __instance, PlayerControl player, string text, string[] args) { Main.HideName.Value = args.Length > 1 ? args.Skip(1).Join(delimiter: " ") : Main.HideName.DefaultValue.ToString(); + GameStartManagerPatch.GameStartManagerStartPatch.HideName.text = ColorUtility.TryParseHtmlString(Main.HideColor.Value, out _) ? $"{Main.HideName.Value}" @@ -1816,27 +1457,17 @@ namespace EHR private static void RenameCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (args.Length < 2) - { - return; - } + if (args.Length < 2) return; if (args[1].Length is > 50 or < 1) - { Utils.SendMessage(GetString("Message.AllowNameLength"), player.PlayerId); - } else { if (player.PlayerId == PlayerControl.LocalPlayer.PlayerId) - { Main.NickName = args[1]; - } else { - if (!Options.PlayerCanSetName.GetBool() && !IsPlayerVIP(player.FriendCode)) - { - return; - } + if (!Options.PlayerCanSetName.GetBool() && !IsPlayerVIP(player.FriendCode)) return; if (GameStates.IsInGame) { @@ -1845,6 +1476,7 @@ namespace EHR } string name = args.Skip(1).Join(delimiter: " "); + if (name.Length is > 50 or < 1) { Utils.SendMessage(GetString("Message.AllowNameLength"), player.PlayerId); @@ -1868,22 +1500,20 @@ namespace EHR private static void WinnerCommand(ChatController __instance, PlayerControl player, string text, string[] args) { if (Main.WinnerNameList.Count == 0) - { Utils.SendMessage(GetString("NoInfoExists")); - } else - { Utils.SendMessage("Winners:\n" + string.Join(", ", Main.WinnerNameList)); - } } private static void ChangeSettingCommand(ChatController __instance, PlayerControl player, string text, string[] args) { string subArgs = args.Length < 2 ? "" : args[1]; + switch (subArgs) { case "map": subArgs = args.Length < 3 ? "" : args[2]; + switch (subArgs) { case "theskeld": @@ -1923,6 +1553,7 @@ namespace EHR break; case "recommended": subArgs = args.Length < 3 ? "" : args[2]; + switch (subArgs) { case "on": @@ -1936,6 +1567,7 @@ namespace EHR break; case "confirmejects": subArgs = args.Length < 3 ? "" : args[2]; + switch (subArgs) { case "on": @@ -1953,6 +1585,7 @@ namespace EHR break; case "anonymousvotes": subArgs = args.Length < 3 ? "" : args[2]; + switch (subArgs) { case "on": @@ -1994,6 +1627,7 @@ namespace EHR break; case "killdistance": subArgs = args.Length < 3 ? "" : args[2]; + switch (subArgs) { case "short": @@ -2014,6 +1648,7 @@ namespace EHR break; case "taskbarupdates": subArgs = args.Length < 3 ? "" : args[2]; + GameOptionsManager.Instance.currentNormalGameOptions.TaskBarMode = subArgs switch { "always" => AmongUs.GameOptions.TaskBarMode.Normal, @@ -2025,6 +1660,7 @@ namespace EHR break; case "visualtasks": subArgs = args.Length < 3 ? "" : args[2]; + switch (subArgs) { case "on": @@ -2098,6 +1734,7 @@ namespace EHR break; case "protectvisibletoimpostors": subArgs = args.Length < 3 ? "" : args[2]; + switch (subArgs) { case "on": @@ -2127,6 +1764,7 @@ namespace EHR break; case "leaveshapeshiftevidence": subArgs = args.Length < 3 ? "" : args[2]; + switch (subArgs) { case "on": @@ -2164,6 +1802,7 @@ namespace EHR break; case "noisemakerimpostoralert": subArgs = args.Length < 3 ? "" : args[2]; + switch (subArgs) { case "on": @@ -2201,6 +1840,7 @@ namespace EHR break; case "ghostdotasks": subArgs = args.Length < 3 ? "" : args[2]; + switch (subArgs) { case "on": @@ -2224,27 +1864,18 @@ namespace EHR private static void VersionCommand(ChatController __instance, PlayerControl player, string text, string[] args) { string version_text = Main.PlayerVersion.OrderBy(pair => pair.Key).Aggregate(string.Empty, (current, kvp) => current + $"{kvp.Key}: ({Main.AllPlayerNames[kvp.Key]}) {kvp.Value.forkId}/{kvp.Value.version}({kvp.Value.tag})\n"); - if (version_text != string.Empty) - { - HudManager.Instance.Chat.AddChat(player, (player.FriendCode.GetDevUser().HasTag() ? "\n" : string.Empty) + version_text); - } + if (version_text != string.Empty) HudManager.Instance.Chat.AddChat(player, (player.FriendCode.GetDevUser().HasTag() ? "\n" : string.Empty) + version_text); } private static void LTCommand(ChatController __instance, PlayerControl player, string text, string[] args) { - if (!GameStates.IsLobby) - { - return; - } + if (!GameStates.IsLobby) return; float timer = GameStartManagerPatch.Timer; int minutes = (int)timer / 60; int seconds = (int)timer % 60; string lt = string.Format(GetString("LobbyCloseTimer"), $"{minutes:00}:{seconds:00}"); - if (timer <= 60) - { - lt = Utils.ColorString(Color.red, lt); - } + if (timer <= 60) lt = Utils.ColorString(Color.red, lt); Utils.SendMessage(lt, player.PlayerId); } @@ -2253,12 +1884,10 @@ namespace EHR private static bool CheckMute(byte id) { - if (!MutedPlayers.TryGetValue(id, out (long MuteTimeStamp, int Duration) mute)) - { - return false; - } + if (!MutedPlayers.TryGetValue(id, out (long MuteTimeStamp, int Duration) mute)) return false; long timeLeft = mute.Duration - (Utils.TimeStamp - mute.MuteTimeStamp); + if (timeLeft <= 0) { MutedPlayers.Remove(id); @@ -2272,6 +1901,7 @@ namespace EHR public static string FixRoleNameInput(string text) { text = text.Replace("着", "者").Trim().ToLower(); + return text switch { "管理員" or "管理" or "gm" => GetString("GM"), @@ -2400,22 +2030,17 @@ namespace EHR public static bool GetRoleByName(string name, out CustomRoles role) { role = new(); - if (name == "") - { - return false; - } + if (name == "") return false; if ((TranslationController.InstanceExists ? TranslationController.Instance.currentLanguage.languageID : SupportedLangs.SChinese) == SupportedLangs.SChinese) { Regex r = new("[\u4e00-\u9fa5]+$"); MatchCollection mc = r.Matches(name); - string result = string.Empty; - for (int i = 0; i < mc.Count; i++) + var result = string.Empty; + + for (var i = 0; i < mc.Count; i++) { - if (mc[i].ToString() == "是") - { - continue; - } + if (mc[i].ToString() == "是") continue; result += mc[i]; //匹配结果是完整的数字,此处可以不做拼接的 } @@ -2423,19 +2048,15 @@ namespace EHR name = FixRoleNameInput(result.Replace("是", string.Empty).Trim()); } else - { name = name.Trim().ToLower(); - } foreach (CustomRoles rl in Enum.GetValues()) { - if (rl.IsVanilla()) - { - continue; - } + if (rl.IsVanilla()) continue; string roleName = GetString(rl.ToString()).ToLower().Trim().Replace(" ", string.Empty); string nameWithoutId = Regex.Replace(name.Replace(" ", string.Empty), @"^\d+", string.Empty); + if (nameWithoutId == roleName) { role = rl; @@ -2451,32 +2072,17 @@ namespace EHR if (Options.CurrentGameMode != CustomGameMode.Standard) { Utils.SendMessage(GetString($"ModeDescribe.{Options.CurrentGameMode}"), playerId); - if (Options.CurrentGameMode != CustomGameMode.HideAndSeek) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.HideAndSeek) return; } role = role.Trim().ToLower(); - if (role.StartsWith("/r")) - { - _ = role.Replace("/r", string.Empty); - } + if (role.StartsWith("/r")) _ = role.Replace("/r", string.Empty); - if (role.StartsWith("/up")) - { - _ = role.Replace("/up", string.Empty); - } + if (role.StartsWith("/up")) _ = role.Replace("/up", string.Empty); - if (role.EndsWith("\r\n")) - { - _ = role.Replace("\r\n", string.Empty); - } + if (role.EndsWith("\r\n")) _ = role.Replace("\r\n", string.Empty); - if (role.EndsWith("\n")) - { - _ = role.Replace("\n", string.Empty); - } + if (role.EndsWith("\n")) _ = role.Replace("\n", string.Empty); if (role == "") { @@ -2488,31 +2094,20 @@ namespace EHR foreach (CustomRoles rl in Enum.GetValues()) { - if (rl.IsVanilla()) - { - continue; - } + if (rl.IsVanilla()) continue; string roleName = GetString(rl.ToString()); + if (role == roleName.ToLower().Trim().TrimStart('*').Replace(" ", string.Empty)) { if ((isDev || isUp) && GameStates.IsLobby) { - string devMark = "▲"; - if (rl.IsAdditionRole() || rl is CustomRoles.GM) - { - devMark = string.Empty; - } + var devMark = "▲"; + if (rl.IsAdditionRole() || rl is CustomRoles.GM) devMark = string.Empty; - if (rl.GetCount() < 1 || rl.GetMode() == 0) - { - devMark = string.Empty; - } + if (rl.GetCount() < 1 || rl.GetMode() == 0) devMark = string.Empty; - if (isUp) - { - Utils.SendMessage(devMark == "▲" ? string.Format(GetString("Message.YTPlanSelected"), roleName) : string.Format(GetString("Message.YTPlanSelectFailed"), roleName), playerId); - } + if (isUp) Utils.SendMessage(devMark == "▲" ? string.Format(GetString("Message.YTPlanSelected"), roleName) : string.Format(GetString("Message.YTPlanSelectFailed"), roleName), playerId); //if (devMark == "▲") //{ @@ -2521,38 +2116,23 @@ namespace EHR // Main.DevRole.Add(pid, rl); //} - if (isUp) - { - return; - } + if (isUp) return; } StringBuilder sb = new(); - string title = $"<{Main.RoleColors[rl]}>{roleName} {Utils.GetRoleMode(rl)}"; + var title = $"<{Main.RoleColors[rl]}>{roleName} {Utils.GetRoleMode(rl)}"; StringBuilder settings = new(); sb.Append(GetString($"{rl}InfoLong").TrimStart()); - if (Options.CustomRoleSpawnChances.TryGetValue(rl, out StringOptionItem chance)) - { - AddSettings(chance); - } + if (Options.CustomRoleSpawnChances.TryGetValue(rl, out StringOptionItem chance)) AddSettings(chance); - if (rl is CustomRoles.LovingCrewmate or CustomRoles.LovingImpostor && Options.CustomRoleSpawnChances.TryGetValue(CustomRoles.Lovers, out chance)) - { - AddSettings(chance); - } + if (rl is CustomRoles.LovingCrewmate or CustomRoles.LovingImpostor && Options.CustomRoleSpawnChances.TryGetValue(CustomRoles.Lovers, out chance)) AddSettings(chance); string txt = $"{sb}".Replace(roleName, rl.ToColoredString()).Replace(roleName.ToLower(), rl.ToColoredString()); sb.Clear().Append(txt); - if (rl.PetActivatedAbility()) - { - sb.Append($"{GetString("SupportsPetMessage")}"); - } + if (rl.PetActivatedAbility()) sb.Append($"{GetString("SupportsPetMessage")}"); - if (settings.Length > 0) - { - Utils.SendMessage("\n", playerId, settings.ToString()); - } + if (settings.Length > 0) Utils.SendMessage("\n", playerId, settings.ToString()); Utils.SendMessage(sb.ToString(), playerId, title); return; @@ -2570,6 +2150,7 @@ namespace EHR { string gmString = GetString(gameMode.ToString()); string match = gmString.ToLower().Trim().TrimStart('*').Replace(" ", string.Empty); + if (role.Equals(match, StringComparison.OrdinalIgnoreCase)) { Utils.SendMessage(GetString($"ModeDescribe.{gameMode}"), playerId, gmString); @@ -2585,27 +2166,19 @@ namespace EHR public static void OnReceiveChat(PlayerControl player, string text, out bool canceled) { canceled = false; - if (!AmongUsClient.Instance.AmHost || player.IsHost()) - { - return; - } + if (!AmongUsClient.Instance.AmHost || player.IsHost()) return; long now = Utils.TimeStamp; + if (LastSentCommand.TryGetValue(player.PlayerId, out long ts) && ts + 2 >= now) { Logger.Warn("Chat message ignored, it was sent too soon after their last message", "ReceiveChat"); return; } - if (!CheckMute(player.PlayerId)) - { - ChatManager.SendMessage(player, text); - } + if (!CheckMute(player.PlayerId)) ChatManager.SendMessage(player, text); - if (text.StartsWith("\n")) - { - text = text[1..]; - } + if (text.StartsWith("\n")) text = text[1..]; string[] args = text.Split(' '); @@ -2626,19 +2199,17 @@ namespace EHR return; } - bool isCommand = false; + var isCommand = false; if (text.StartsWith('/')) { foreach (Command command in AllCommands) { - if (!command.IsThisCommand(text)) - { - continue; - } + if (!command.IsThisCommand(text)) continue; Logger.Info($" Recognized command: {text}", "ReceiveChat"); isCommand = true; + if (!command.CanUseCommand(player)) { Utils.SendMessage(GetString("Commands.NoAccess"), player.PlayerId); @@ -2647,10 +2218,7 @@ namespace EHR } command.Action(null, player, text, args); - if (command.IsCanceled) - { - canceled = true; - } + if (command.IsCanceled) canceled = true; break; } @@ -2675,9 +2243,11 @@ namespace EHR { ChatManager.SendPreviousMessagesToAll(true); canceled = true; + if (player.Is(CustomRoles.Lovers) || player.GetCustomRole() is CustomRoles.LovingCrewmate or CustomRoles.LovingImpostor) { PlayerControl otherLover = Main.LoversPlayers.First(x => x.PlayerId != player.PlayerId); + LateTask.New(() => { string title = player.GetRealName(); @@ -2688,15 +2258,10 @@ namespace EHR }, 0.2f, log: false); } else - { LateTask.New(() => Utils.SendMessage(GetString("LoversChatCannotTalkMsg"), player.PlayerId, GetString("LoversChatCannotTalkTitle")), 0.5f, log: false); - } } - if (isCommand) - { - LastSentCommand[player.PlayerId] = now; - } + if (isCommand) LastSentCommand[player.PlayerId] = now; SpamManager.CheckSpam(player, text); } @@ -2712,8 +2277,9 @@ namespace EHR public static void Postfix(ChatController __instance) { - ChatBubble chatBubble = __instance.chatBubblePool.Prefab.Cast(); + var chatBubble = __instance.chatBubblePool.Prefab.Cast(); chatBubble.TextArea.overrideColorTags = false; + if (Main.DarkTheme.Value) { chatBubble.TextArea.color = Color.white; @@ -2722,16 +2288,10 @@ namespace EHR LastMessages.RemoveAll(x => Utils.TimeStamp - x.SendTimeStamp > 10); - if (!AmongUsClient.Instance.AmHost || Main.MessagesToSend.Count == 0 || (Main.MessagesToSend[0].ReceiverID == byte.MaxValue && Main.MessageWait.Value > __instance.timeSinceLastMessage) || DoBlockChat) - { - return; - } + if (!AmongUsClient.Instance.AmHost || Main.MessagesToSend.Count == 0 || (Main.MessagesToSend[0].ReceiverID == byte.MaxValue && Main.MessageWait.Value > __instance.timeSinceLastMessage) || DoBlockChat) return; PlayerControl player = Main.AllAlivePlayerControls.MinBy(x => x.PlayerId) ?? Main.AllPlayerControls.MinBy(x => x.PlayerId) ?? PlayerControl.LocalPlayer; - if (player == null) - { - return; - } + if (player == null) return; (string msg, byte sendTo, string title) = Main.MessagesToSend[0]; Main.MessagesToSend.RemoveAt(0); @@ -2746,15 +2306,9 @@ namespace EHR internal static void SendLastMessages() { PlayerControl player = Main.AllAlivePlayerControls.MinBy(x => x.PlayerId) ?? Main.AllPlayerControls.MinBy(x => x.PlayerId) ?? PlayerControl.LocalPlayer; - if (player == null) - { - return; - } + if (player == null) return; - foreach ((string msg, byte sendTo, string title, _) in LastMessages) - { - SendMessage(player, msg, sendTo, title); - } + foreach ((string msg, byte sendTo, string title, _) in LastMessages) SendMessage(player, msg, sendTo, title); } internal static void SendMessage(PlayerControl player, string msg, byte sendTo, string title) @@ -2770,19 +2324,23 @@ namespace EHR player.SetName(name); } - CustomRpcSender writer = CustomRpcSender.Create("MessagesToSend"); + var writer = CustomRpcSender.Create("MessagesToSend"); writer.StartMessage(clientId); + writer.StartRpc(player.NetId, (byte)RpcCalls.SetName) .Write(player.Data.NetId) .Write(title) .EndRpc(); + writer.StartRpc(player.NetId, (byte)RpcCalls.SendChat) .Write(msg) .EndRpc(); + writer.StartRpc(player.NetId, (byte)RpcCalls.SetName) .Write(player.Data.NetId) .Write(player.Data.PlayerName) .EndRpc(); + writer.EndMessage(); writer.SendMessage(); } @@ -2796,18 +2354,13 @@ namespace EHR int length = __instance.textArea.text.Length; __instance.charCountText.SetText(length <= 0 ? GetString("ThankYouForUsingEHR") : $"{length}/{__instance.textArea.characterLimit}"); __instance.charCountText.enableWordWrapping = false; + if (length < (AmongUsClient.Instance.AmHost ? 1700 : 250)) - { __instance.charCountText.color = Color.black; - } else if (length < (AmongUsClient.Instance.AmHost ? 2000 : 500)) - { __instance.charCountText.color = new(1f, 1f, 0f, 1f); - } else - { __instance.charCountText.color = Color.red; - } } } @@ -2824,15 +2377,9 @@ namespace EHR int return_count = PlayerControl.LocalPlayer.name.Count(x => x == '\n'); chatText = new StringBuilder(chatText).Insert(0, "\n", return_count).ToString(); - if (AmongUsClient.Instance.AmClient && DestroyableSingleton.Instance) - { - DestroyableSingleton.Instance.Chat.AddChat(__instance, chatText); - } + if (AmongUsClient.Instance.AmClient && DestroyableSingleton.Instance) DestroyableSingleton.Instance.Chat.AddChat(__instance, chatText); - if (chatText.Contains("who", StringComparison.OrdinalIgnoreCase)) - { - DestroyableSingleton.Instance.SendWho(); - } + if (chatText.Contains("who", StringComparison.OrdinalIgnoreCase)) DestroyableSingleton.Instance.SendWho(); MessageWriter messageWriter = AmongUsClient.Instance.StartRpc(__instance.NetId, (byte)RpcCalls.SendChat, SendOption.None); messageWriter.Write(chatText); diff --git a/Patches/ChatControlPatch.cs b/Patches/ChatControlPatch.cs index 4b1402085..adc658530 100644 --- a/Patches/ChatControlPatch.cs +++ b/Patches/ChatControlPatch.cs @@ -21,10 +21,7 @@ namespace EHR public static void Prefix() { - if (AmongUsClient.Instance.AmHost && DataManager.Settings.Multiplayer.ChatMode == QuickChatModes.QuickChatOnly) - { - DataManager.Settings.Multiplayer.ChatMode = QuickChatModes.FreeChatOrQuickChat; - } + if (AmongUsClient.Instance.AmHost && DataManager.Settings.Multiplayer.ChatMode == QuickChatModes.QuickChatOnly) DataManager.Settings.Multiplayer.ChatMode = QuickChatModes.FreeChatOrQuickChat; } public static void Postfix(ChatController __instance) @@ -32,6 +29,7 @@ namespace EHR if (Main.DarkTheme.Value) { __instance.freeChatField.background.color = new Color32(40, 40, 40, byte.MaxValue); + if (!TextBoxTMPSetTextPatch.IsInvalidCommand) { __instance.freeChatField.textArea.compoText.Color(Color.white); @@ -42,58 +40,32 @@ namespace EHR __instance.quickChatField.text.color = Color.white; if (QuickChatIcon == null) - { QuickChatIcon = GameObject.Find("QuickChatIcon")?.transform.GetComponent(); - } else - { QuickChatIcon.sprite = Utils.LoadSprite("EHR.Resources.Images.DarkQuickChat.png", 100f); - } if (OpenBanMenuIcon == null) - { OpenBanMenuIcon = GameObject.Find("OpenBanMenuIcon")?.transform.GetComponent(); - } else - { OpenBanMenuIcon.sprite = Utils.LoadSprite("EHR.Resources.Images.DarkReport.png", 100f); - } if (OpenKeyboardIcon == null) - { OpenKeyboardIcon = GameObject.Find("OpenKeyboardIcon")?.transform.GetComponent(); - } else - { OpenKeyboardIcon.sprite = Utils.LoadSprite("EHR.Resources.Images.DarkKeyboard.png", 100f); - } } else - { __instance.freeChatField.textArea.outputText.color = Color.black; - } - if (!__instance.freeChatField.textArea.hasFocus) - { - return; - } + if (!__instance.freeChatField.textArea.hasFocus) return; __instance.freeChatField.textArea.characterLimit = AmongUsClient.Instance.AmHost ? 2000 : 300; - if (Input.GetKeyDown(KeyCode.Tab)) - { - TextBoxTMPSetTextPatch.OnTabPress(__instance); - } + if (Input.GetKeyDown(KeyCode.Tab)) TextBoxTMPSetTextPatch.OnTabPress(__instance); - if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && Input.GetKeyDown(KeyCode.C)) - { - ClipboardHelper.PutClipboardString(__instance.freeChatField.textArea.text); - } + if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && Input.GetKeyDown(KeyCode.C)) ClipboardHelper.PutClipboardString(__instance.freeChatField.textArea.text); - if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && Input.GetKeyDown(KeyCode.V)) - { - __instance.freeChatField.textArea.SetText(__instance.freeChatField.textArea.text + GUIUtility.systemCopyBuffer); - } + if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && Input.GetKeyDown(KeyCode.V)) __instance.freeChatField.textArea.SetText(__instance.freeChatField.textArea.text + GUIUtility.systemCopyBuffer); if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && Input.GetKeyDown(KeyCode.X)) { @@ -138,14 +110,12 @@ namespace EHR private static bool CheckCommand(ref string msg, string command, bool exact = true) { string[] comList = command.Split('|'); + foreach (string str in comList) { if (exact) { - if (msg == "/" + str) - { - return true; - } + if (msg == "/" + str) return true; } else { @@ -163,18 +133,17 @@ namespace EHR private static bool CheckName(ref string msg, string command, bool exact = true) { string[] comList = command.Split('|'); + foreach (string com in comList) { if (exact) { - if (msg.Contains(com)) - { - return true; - } + if (msg.Contains(com)) return true; } else { int index = msg.IndexOf(com, StringComparison.Ordinal); + if (index != -1) { msg = msg.Remove(index, com.Length); @@ -191,10 +160,7 @@ namespace EHR string playername = player.GetNameWithRole(); message = message.ToLower().TrimStart().TrimEnd(); - if (!player.IsAlive() || !AmongUsClient.Instance.AmHost || (Silencer.ForSilencer.Contains(player.PlayerId) && player.IsAlive())) - { - return; - } + if (!player.IsAlive() || !AmongUsClient.Instance.AmHost || (Silencer.ForSilencer.Contains(player.PlayerId) && player.IsAlive())) return; int operate = message switch { @@ -208,10 +174,7 @@ namespace EHR { case 1 when player.IsAlive(): // Guessing Command & Such Logger.Info("Special Command", "ChatManager"); - if (player.PlayerId == PlayerControl.LocalPlayer.PlayerId) - { - break; - } + if (player.PlayerId == PlayerControl.LocalPlayer.PlayerId) break; LateTask.New(() => { @@ -221,21 +184,17 @@ namespace EHR Logger.Info("Delayed Guess", "ChatManager"); } else - { Logger.Info("Delayed Guess was not necessary", "ChatManager"); - } }, 0.3f, "Trying Delayed Guess"); + break; case 2: // /up and role ability commands Logger.Info($"Command: {message}", "ChatManager"); break; case 3: // In Lobby & Evertything Else - string chatEntry = $"{player.PlayerId}: {message}"; + var chatEntry = $"{player.PlayerId}: {message}"; ChatHistory.Add(chatEntry); - if (ChatHistory.Count > MaxHistorySize) - { - ChatHistory.RemoveAt(0); - } + if (ChatHistory.Count > MaxHistorySize) ChatHistory.RemoveAt(0); break; case 4: // /r, /n, /m @@ -244,32 +203,24 @@ namespace EHR break; } - if (Options.CurrentGameMode == CustomGameMode.FFA && !message.StartsWith('/')) - { - FFAManager.UpdateLastChatMessage(player.GetRealName(), message); - } + if (Options.CurrentGameMode == CustomGameMode.FFA && !message.StartsWith('/')) FFAManager.UpdateLastChatMessage(player.GetRealName(), message); } public static void SendPreviousMessagesToAll(bool clear = false) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; ChatUpdatePatch.DoBlockChat = true; Logger.Info($" clear: {clear}", "ChatManager.SendPreviousMessagesToAll"); + try { string msg = Utils.EmptyMessage; int totalAlive = Main.AllAlivePlayerControls.Length; - if (totalAlive == 0) - { - return; - } + if (totalAlive == 0) return; PlayerControl[] x = Main.AllAlivePlayerControls; - IRandom r = IRandom.Instance; + var r = IRandom.Instance; string[] filtered = ChatHistory.SkipLast(1).Where(a => Utils.GetPlayerById(Convert.ToByte(a.Split(':')[0].Trim())).IsAlive()).ToArray(); @@ -287,16 +238,10 @@ namespace EHR string[] entryParts = str.Split(':'); string senderId = entryParts[0].Trim(); string senderMessage = entryParts[1].Trim(); - for (int j = 2; j < entryParts.Length; j++) - { - senderMessage += ':' + entryParts[j].Trim(); - } + for (var j = 2; j < entryParts.Length; j++) senderMessage += ':' + entryParts[j].Trim(); PlayerControl senderPlayer = Utils.GetPlayerById(Convert.ToByte(senderId)); - if (senderPlayer == null) - { - continue; - } + if (senderPlayer == null) continue; DestroyableSingleton.Instance.Chat.AddChat(senderPlayer, senderMessage); SendRPC(senderPlayer, senderMessage); @@ -313,11 +258,13 @@ namespace EHR private static void SendRPC(InnerNetObject senderPlayer, string senderMessage) { - CustomRpcSender writer = CustomRpcSender.Create("MessagesToSend"); + var writer = CustomRpcSender.Create("MessagesToSend"); writer.StartMessage(); + writer.StartRpc(senderPlayer.NetId, (byte)RpcCalls.SendChat) .Write(senderMessage) .EndRpc(); + writer.EndMessage(); writer.SendMessage(); } diff --git a/Patches/CheckGameEndPatch.cs b/Patches/CheckGameEndPatch.cs index 410743366..f325411f9 100644 --- a/Patches/CheckGameEndPatch.cs +++ b/Patches/CheckGameEndPatch.cs @@ -30,20 +30,11 @@ namespace EHR public static bool Prefix() { - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; - if (Predicate == null || ShouldNotCheck || Main.HasJustStarted) - { - return false; - } + if (Predicate == null || ShouldNotCheck || Main.HasJustStarted) return false; - if (Options.NoGameEnd.GetBool() && WinnerTeam is not CustomWinner.Draw and not CustomWinner.Error) - { - return false; - } + if (Options.NoGameEnd.GetBool() && WinnerTeam is not CustomWinner.Draw and not CustomWinner.Error) return false; Ended = false; @@ -86,36 +77,43 @@ namespace EHR WinnerIds.UnionWith(Main.AllPlayerControls .Where(pc => (pc.Is(CustomRoleTypes.Crewmate) || (pc.Is(CustomRoles.Haunter) && Haunter.CanWinWithCrew(pc))) && !pc.IsMadmate() && !pc.IsConverted() && !pc.Is(CustomRoles.EvilSpirit)) .Select(pc => pc.PlayerId)); + break; case CustomWinner.Impostor: WinnerIds.UnionWith(Main.AllPlayerControls .Where(pc => ((pc.Is(CustomRoleTypes.Impostor) && (!pc.Is(CustomRoles.DeadlyQuota) || Main.PlayerStates.Count(x => x.Value.GetRealKiller() == pc.PlayerId) >= Options.DQNumOfKillsNeeded.GetInt())) || pc.IsMadmate()) && !pc.IsConverted() && !pc.Is(CustomRoles.EvilSpirit)) .Select(pc => pc.PlayerId)); + break; case CustomWinner.Succubus: WinnerIds.UnionWith(Main.AllPlayerControls .Where(pc => pc.Is(CustomRoles.Succubus) || pc.Is(CustomRoles.Charmed)) .Select(pc => pc.PlayerId)); + break; case CustomWinner.Necromancer: WinnerIds.UnionWith(Main.AllPlayerControls .Where(pc => pc.Is(CustomRoles.Necromancer) || pc.Is(CustomRoles.Deathknight) || pc.Is(CustomRoles.Undead)) .Select(pc => pc.PlayerId)); + break; case CustomWinner.Virus: WinnerIds.UnionWith(Main.AllPlayerControls .Where(pc => pc.Is(CustomRoles.Virus) || pc.Is(CustomRoles.Contagious)) .Select(pc => pc.PlayerId)); + break; case CustomWinner.Jackal: WinnerIds.UnionWith(Main.AllPlayerControls .Where(pc => pc.Is(CustomRoles.Jackal) || pc.Is(CustomRoles.Sidekick) || pc.Is(CustomRoles.Recruit)) .Select(pc => pc.PlayerId)); + break; case CustomWinner.Spiritcaller: WinnerIds.UnionWith(Main.AllPlayerControls .Where(pc => pc.Is(CustomRoles.Spiritcaller) || pc.Is(CustomRoles.EvilSpirit)) .Select(pc => pc.PlayerId)); + WinnerRoles.Add(CustomRoles.Spiritcaller); break; case CustomWinner.RuthlessRomantic: @@ -249,6 +247,7 @@ namespace EHR } byte[] winningSpecters = GhostRolesManager.AssignedGhostRoles.Where(x => x.Value.Instance is Specter { IsWon: true }).Select(x => x.Key).ToArray(); + if (winningSpecters.Length > 0) { AdditionalWinnerTeams.Add(AdditionalWinners.Specter); @@ -258,6 +257,7 @@ namespace EHR if (CustomRoles.God.RoleExist()) { ResetAndSetWinner(CustomWinner.God); + Main.AllPlayerControls .Where(p => p.Is(CustomRoles.God) && p.IsAlive()) .Do(p => WinnerIds.Add(p.PlayerId)); @@ -273,54 +273,36 @@ namespace EHR .Do(x => { bool canWin = CustomTeamManager.IsSettingEnabledForTeam(x.Key, CTAOption.WinWithOriginalTeam); + if (!canWin) - { WinnerIds.ExceptWith(x.Value); - } else - { WinnerIds.UnionWith(x.Value); - } }); } if ((WinnerTeam == CustomWinner.Lovers || WinnerIds.Any(x => Main.PlayerStates[x].SubRoles.Contains(CustomRoles.Lovers))) && Main.LoversPlayers.TrueForAll(x => x.IsAlive()) && reason != GameOverReason.HumansByTask) { - if (WinnerTeam != CustomWinner.Lovers) - { - AdditionalWinnerTeams.Add(AdditionalWinners.Lovers); - } + if (WinnerTeam != CustomWinner.Lovers) AdditionalWinnerTeams.Add(AdditionalWinners.Lovers); WinnerIds.UnionWith(Main.LoversPlayers.Select(x => x.PlayerId)); } if (Options.NeutralWinTogether.GetBool() && (WinnerRoles.Any(x => x.IsNeutral()) || WinnerIds.Select(x => GetPlayerById(x)).Any(x => x != null && x.GetCustomRole().IsNeutral() && !x.IsMadmate()))) - { WinnerIds.UnionWith(Main.AllPlayerControls.Where(x => x.GetCustomRole().IsNeutral()).Select(x => x.PlayerId)); - } else if (Options.NeutralRoleWinTogether.GetBool()) { foreach (byte id in WinnerIds.ToArray()) { PlayerControl pc = GetPlayerById(id); - if (pc == null || !pc.GetCustomRole().IsNeutral()) - { - continue; - } + if (pc == null || !pc.GetCustomRole().IsNeutral()) continue; foreach (PlayerControl tar in Main.AllPlayerControls) - { if (!WinnerIds.Contains(tar.PlayerId) && tar.GetCustomRole() == pc.GetCustomRole()) - { WinnerIds.Add(tar.PlayerId); - } - } } - foreach (CustomRoles role in WinnerRoles) - { - WinnerIds.UnionWith(Main.AllPlayerControls.Where(x => x.GetCustomRole() == role).Select(x => x.PlayerId)); - } + foreach (CustomRoles role in WinnerRoles) WinnerIds.UnionWith(Main.AllPlayerControls.Where(x => x.GetCustomRole() == role).Select(x => x.PlayerId)); } WinnerIds.RemoveWhere(x => Main.PlayerStates[x].MainRole == CustomRoles.Shifter); @@ -338,12 +320,13 @@ namespace EHR private static void StartEndGame(GameOverReason reason) { string msg = GetString("NotifyGameEnding"); + Main.AllPlayerControls.DoIf( x => x.GetClient() != null && !x.Data.Disconnected, x => ChatUpdatePatch.SendMessage(PlayerControl.LocalPlayer, "\n", x.PlayerId, msg)); SetEverythingUpPatch.LastWinsReason = WinnerTeam is CustomWinner.Crewmate or CustomWinner.Impostor ? GetString($"GameOverReason.{reason}") : string.Empty; - AmongUsClient self = AmongUsClient.Instance; + var self = AmongUsClient.Instance; self.StartCoroutine(CoEndGame(self, reason).WrapToIl2Cpp()); } @@ -354,6 +337,7 @@ namespace EHR // Set ghost role List ReviveRequiredPlayerIds = []; CustomWinner winner = WinnerTeam; + foreach (PlayerControl pc in Main.AllPlayerControls) { if (winner == CustomWinner.Draw) @@ -369,10 +353,7 @@ namespace EHR void SetGhostRole(bool ToGhostImpostor) { - if (!pc.Data.IsDead) - { - ReviveRequiredPlayerIds.Add(pc.PlayerId); - } + if (!pc.Data.IsDead) ReviveRequiredPlayerIds.Add(pc.PlayerId); if (ToGhostImpostor) { @@ -471,10 +452,7 @@ namespace EHR public override bool CheckForGameEnd(out GameOverReason reason) { reason = GameOverReason.ImpostorByKill; - if (WinnerTeam != CustomWinner.Default) - { - return false; - } + if (WinnerTeam != CustomWinner.Default) return false; return CheckGameEndBySabotage(out reason) || CheckGameEndByTask(out reason) || CheckGameEndByLivingPlayers(out reason); } @@ -483,22 +461,13 @@ namespace EHR { reason = GameOverReason.ImpostorByKill; - if (Main.HasJustStarted) - { - return false; - } + if (Main.HasJustStarted) return false; PlayerControl[] aapc = Main.AllAlivePlayerControls; - if (CustomRoles.Sunnyboy.RoleExist() && aapc.Length > 1) - { - return false; - } + if (CustomRoles.Sunnyboy.RoleExist() && aapc.Length > 1) return false; - if (CustomTeamManager.CheckCustomTeamGameEnd()) - { - return true; - } + if (CustomTeamManager.CheckCustomTeamGameEnd()) return true; if (aapc.All(x => Main.LoversPlayers.Exists(l => l.PlayerId == x.PlayerId)) && (!Main.LoversPlayers.TrueForAll(x => x.Is(Team.Crewmate)) || !Lovers.CrewLoversWinWithCrew.GetBool())) { @@ -516,19 +485,13 @@ namespace EHR foreach (CustomRoles role in Enum.GetValues()) { - if ((!role.IsNK() && role is not CustomRoles.Bloodlust and not CustomRoles.Gaslighter) || role.IsMadmate() || role is CustomRoles.Sidekick) - { - continue; - } + if ((!role.IsNK() && role is not CustomRoles.Bloodlust and not CustomRoles.Gaslighter) || role.IsMadmate() || role is CustomRoles.Sidekick) continue; CountTypes countTypes = role.GetCountTypes(); - if (countTypes is CountTypes.Crew or CountTypes.Impostor or CountTypes.None or CountTypes.OutOfGame or CountTypes.CustomTeam) - { - continue; - } + if (countTypes is CountTypes.Crew or CountTypes.Impostor or CountTypes.None or CountTypes.OutOfGame or CountTypes.CustomTeam) continue; CustomRoles? keyRole = role.IsRecruitingRole() ? null : role; - CustomWinner keyWinner = (CustomWinner)role; + var keyWinner = (CustomWinner)role; int value = AlivePlayersCount(countTypes); roleCounts[(keyRole, keyWinner)] = value; @@ -538,44 +501,21 @@ namespace EHR { foreach (PlayerControl x in aapc) { - if (!x.Is(CustomRoles.DualPersonality)) - { - continue; - } + if (!x.Is(CustomRoles.DualPersonality)) continue; if (x.Is(Team.Impostor)) - { Imp++; - } - else if (x.Is(Team.Crewmate)) - { - Crew++; - } + else if (x.Is(Team.Crewmate)) Crew++; - if (x.Is(CustomRoles.Charmed)) - { - roleCounts[(null, CustomWinner.Succubus)]++; - } + if (x.Is(CustomRoles.Charmed)) roleCounts[(null, CustomWinner.Succubus)]++; - if (x.Is(CustomRoles.Undead)) - { - roleCounts[(null, CustomWinner.Necromancer)]++; - } + if (x.Is(CustomRoles.Undead)) roleCounts[(null, CustomWinner.Necromancer)]++; - if (x.Is(CustomRoles.Sidekick)) - { - roleCounts[(null, CustomWinner.Jackal)]++; - } + if (x.Is(CustomRoles.Sidekick)) roleCounts[(null, CustomWinner.Jackal)]++; - if (x.Is(CustomRoles.Recruit)) - { - roleCounts[(null, CustomWinner.Jackal)]++; - } + if (x.Is(CustomRoles.Recruit)) roleCounts[(null, CustomWinner.Jackal)]++; - if (x.Is(CustomRoles.Contagious)) - { - roleCounts[(null, CustomWinner.Virus)]++; - } + if (x.Is(CustomRoles.Contagious)) roleCounts[(null, CustomWinner.Virus)]++; } } @@ -602,27 +542,20 @@ namespace EHR winner = CustomWinner.Crewmate; } else - { return false; - } Logger.Info($"Crew: {Crew}, Imp: {Imp}", "CheckGameEndPatch.CheckGameEndByLivingPlayers"); ResetAndSetWinner((CustomWinner)winner); return true; } - if (Imp >= 1) - { - return false; // both imps and NKs are alive, game must continue - } + if (Imp >= 1) return false; // both imps and NKs are alive, game must continue - if (Crew > totalNKAlive) - { - return false; // Imps are dead, but crew still outnumbers NKs, game must continue - } + if (Crew > totalNKAlive) return false; // Imps are dead, but crew still outnumbers NKs, game must continue // Imps dead, Crew <= NK, Checking if all NKs alive are in 1 team List aliveCounts = roleCounts.Values.Where(x => x > 0).ToList(); + switch (aliveCounts.Count) { // There are multiple types of NKs alive, game must continue @@ -634,10 +567,7 @@ namespace EHR // There is only one type of NK alive, they've won case 1: { - if (aliveCounts[0] != roleCounts.Values.Max()) - { - Logger.Warn("There is something wrong here.", "CheckGameEndPatch"); - } + if (aliveCounts[0] != roleCounts.Values.Max()) Logger.Warn("There is something wrong here.", "CheckGameEndPatch"); foreach (KeyValuePair<(CustomRoles? ROLE, CustomWinner WINNER), int> keyValuePair in roleCounts.Where(keyValuePair => keyValuePair.Value == aliveCounts[0])) { @@ -656,15 +586,9 @@ namespace EHR return true; } - if (winner != null) - { - ResetAndSetWinner((CustomWinner)winner); - } + if (winner != null) ResetAndSetWinner((CustomWinner)winner); - if (rl != null) - { - WinnerRoles.Add((CustomRoles)rl); - } + if (rl != null) WinnerRoles.Add((CustomRoles)rl); return true; } @@ -682,10 +606,7 @@ namespace EHR { reason = GameOverReason.ImpostorByKill; - if (SoloKombatManager.RoundTime > 0) - { - return false; - } + if (SoloKombatManager.RoundTime > 0) return false; PlayerControl winner = Main.AllPlayerControls.FirstOrDefault(x => !x.Is(CustomRoles.GM) && SoloKombatManager.GetRankOfScore(x.PlayerId) == 1) ?? Main.AllAlivePlayerControls[0]; @@ -938,6 +859,7 @@ namespace EHR reason = GameOverReason.ImpostorByKill; PlayerControl[] appc = Main.AllAlivePlayerControls; + switch (appc.Length) { case 1: @@ -967,20 +889,11 @@ namespace EHR public virtual bool CheckGameEndByTask(out GameOverReason reason) { reason = GameOverReason.ImpostorByKill; - if (Options.DisableTaskWin.GetBool() || TaskState.InitialTotalTasks == 0) - { - return false; - } + if (Options.DisableTaskWin.GetBool() || TaskState.InitialTotalTasks == 0) return false; - if (Options.DisableTaskWinIfAllCrewsAreDead.GetBool() && !Main.AllAlivePlayerControls.Any(x => x.Is(CustomRoleTypes.Crewmate))) - { - return false; - } + if (Options.DisableTaskWinIfAllCrewsAreDead.GetBool() && !Main.AllAlivePlayerControls.Any(x => x.Is(CustomRoleTypes.Crewmate))) return false; - if (Options.DisableTaskWinIfAllCrewsAreConverted.GetBool() && Main.AllAlivePlayerControls.Where(x => x.Is(Team.Crewmate) && x.GetRoleTypes() is RoleTypes.Crewmate or RoleTypes.Engineer or RoleTypes.Scientist or RoleTypes.Noisemaker or RoleTypes.Tracker or RoleTypes.CrewmateGhost or RoleTypes.GuardianAngel).All(x => x.IsConverted())) - { - return false; - } + if (Options.DisableTaskWinIfAllCrewsAreConverted.GetBool() && Main.AllAlivePlayerControls.Where(x => x.Is(Team.Crewmate) && x.GetRoleTypes() is RoleTypes.Crewmate or RoleTypes.Engineer or RoleTypes.Scientist or RoleTypes.Noisemaker or RoleTypes.Tracker or RoleTypes.CrewmateGhost or RoleTypes.GuardianAngel).All(x => x.IsConverted())) return false; if (GameData.Instance.TotalTasks <= GameData.Instance.CompletedTasks) { @@ -996,14 +909,12 @@ namespace EHR public virtual bool CheckGameEndBySabotage(out GameOverReason reason) { reason = GameOverReason.ImpostorByKill; - if (ShipStatus.Instance.Systems == null) - { - return false; - } + if (ShipStatus.Instance.Systems == null) return false; // TryGetValue is not available Il2CppSystem.Collections.Generic.Dictionary systems = ShipStatus.Instance.Systems; LifeSuppSystemType LifeSupp; + if (systems.ContainsKey(SystemTypes.LifeSupp) && // Confirmation of sabotage existence (LifeSupp = systems[SystemTypes.LifeSupp].TryCast()) != null && // Confirmation that cast is possible LifeSupp.Countdown <= 0f) // Time up confirmation @@ -1016,20 +927,15 @@ namespace EHR } ISystemType sys = null; + if (systems.ContainsKey(SystemTypes.Reactor)) - { sys = systems[SystemTypes.Reactor]; - } else if (systems.ContainsKey(SystemTypes.Laboratory)) - { sys = systems[SystemTypes.Laboratory]; - } - else if (systems.ContainsKey(SystemTypes.HeliSabotage)) - { - sys = systems[SystemTypes.HeliSabotage]; - } + else if (systems.ContainsKey(SystemTypes.HeliSabotage)) sys = systems[SystemTypes.HeliSabotage]; ICriticalSabotage critical; + if (sys != null && // Confirmation of sabotage existence (critical = sys.TryCast()) != null && // Confirmation that cast is possible critical.Countdown <= 0f) // Time up confirmation diff --git a/Patches/ClientOptionsPatch.cs b/Patches/ClientOptionsPatch.cs index f9cb02208..e9f96feaa 100644 --- a/Patches/ClientOptionsPatch.cs +++ b/Patches/ClientOptionsPatch.cs @@ -27,10 +27,7 @@ namespace EHR public static void Postfix(OptionsMenuBehaviour __instance) { - if (__instance.DisableMouseMovement == null) - { - return; - } + if (__instance.DisableMouseMovement == null) return; Main.SwitchVanilla.Value = false; @@ -46,10 +43,7 @@ namespace EHR static void GMButtonToggle() { - if (Main.GM.Value) - { - HudManager.Instance.ShowPopUp(Translator.GetString("EnabledGMWarning")); - } + if (Main.GM.Value) HudManager.Instance.ShowPopUp(Translator.GetString("EnabledGMWarning")); } } @@ -78,25 +72,13 @@ namespace EHR } } - if (ForceOwnLanguage == null || ForceOwnLanguage.ToggleButton == null) - { - ForceOwnLanguage = ClientOptionItem.Create("ForceOwnLanguage", Main.ForceOwnLanguage, __instance); - } + if (ForceOwnLanguage == null || ForceOwnLanguage.ToggleButton == null) ForceOwnLanguage = ClientOptionItem.Create("ForceOwnLanguage", Main.ForceOwnLanguage, __instance); - if (ForceOwnLanguageRoleName == null || ForceOwnLanguageRoleName.ToggleButton == null) - { - ForceOwnLanguageRoleName = ClientOptionItem.Create("ForceOwnLanguageRoleName", Main.ForceOwnLanguageRoleName, __instance); - } + if (ForceOwnLanguageRoleName == null || ForceOwnLanguageRoleName.ToggleButton == null) ForceOwnLanguageRoleName = ClientOptionItem.Create("ForceOwnLanguageRoleName", Main.ForceOwnLanguageRoleName, __instance); - if (EnableCustomButton == null || EnableCustomButton.ToggleButton == null) - { - EnableCustomButton = ClientOptionItem.Create("EnableCustomButton", Main.EnableCustomButton, __instance); - } + if (EnableCustomButton == null || EnableCustomButton.ToggleButton == null) EnableCustomButton = ClientOptionItem.Create("EnableCustomButton", Main.EnableCustomButton, __instance); - if (EnableCustomSoundEffect == null || EnableCustomSoundEffect.ToggleButton == null) - { - EnableCustomSoundEffect = ClientOptionItem.Create("EnableCustomSoundEffect", Main.EnableCustomSoundEffect, __instance); - } + if (EnableCustomSoundEffect == null || EnableCustomSoundEffect.ToggleButton == null) EnableCustomSoundEffect = ClientOptionItem.Create("EnableCustomSoundEffect", Main.EnableCustomSoundEffect, __instance); if (SwitchVanilla == null || SwitchVanilla.ToggleButton == null) { @@ -113,9 +95,7 @@ namespace EHR LateTask.New(Unload, 2f, log: false); } else - { Unload(); - } return; @@ -129,10 +109,7 @@ namespace EHR } } - if (DarkTheme == null || DarkTheme.ToggleButton == null) - { - DarkTheme = ClientOptionItem.Create("EnableDarkTheme", Main.DarkTheme, __instance); - } + if (DarkTheme == null || DarkTheme.ToggleButton == null) DarkTheme = ClientOptionItem.Create("EnableDarkTheme", Main.DarkTheme, __instance); if (HorseMode == null || HorseMode.ToggleButton == null) { @@ -143,13 +120,11 @@ namespace EHR Main.LongMode.Value = false; HorseMode.UpdateToggle(); LongMode.UpdateToggle(); + foreach (PlayerControl pc in Main.AllPlayerControls) { pc.MyPhysics.SetBodyType(pc.BodyType); - if (pc.BodyType == PlayerBodyTypes.Normal) - { - pc.cosmetics.currentBodySprite.BodySprite.transform.localScale = new(0.5f, 0.5f, 1f); - } + if (pc.BodyType == PlayerBodyTypes.Normal) pc.cosmetics.currentBodySprite.BodySprite.transform.localScale = new(0.5f, 0.5f, 1f); } } } @@ -163,21 +138,16 @@ namespace EHR Main.HorseMode.Value = false; HorseMode.UpdateToggle(); LongMode.UpdateToggle(); + foreach (PlayerControl pc in Main.AllPlayerControls) { pc.MyPhysics.SetBodyType(pc.BodyType); - if (pc.BodyType == PlayerBodyTypes.Normal) - { - pc.cosmetics.currentBodySprite.BodySprite.transform.localScale = new(0.5f, 0.5f, 1f); - } + if (pc.BodyType == PlayerBodyTypes.Normal) pc.cosmetics.currentBodySprite.BodySprite.transform.localScale = new(0.5f, 0.5f, 1f); } } } - if (ShowPlayerInfoInLobby == null || ShowPlayerInfoInLobby.ToggleButton == null) - { - ShowPlayerInfoInLobby = ClientOptionItem.Create("ShowPlayerInfoInLobby", Main.ShowPlayerInfoInLobby, __instance); - } + if (ShowPlayerInfoInLobby == null || ShowPlayerInfoInLobby.ToggleButton == null) ShowPlayerInfoInLobby = ClientOptionItem.Create("ShowPlayerInfoInLobby", Main.ShowPlayerInfoInLobby, __instance); if (LobbyMusic == null || LobbyMusic.ToggleButton == null) { @@ -188,6 +158,7 @@ namespace EHR if (!Main.LobbyMusic.Value && GameStates.IsLobby) { SoundManager.Instance.StopAllSound(); + LateTask.New(() => { Main.LobbyMusic.Value = true; @@ -197,10 +168,7 @@ namespace EHR } } - if (EnableCommandHelper == null || EnableCommandHelper.ToggleButton == null) - { - EnableCommandHelper = ClientOptionItem.Create("EnableCommandHelper", Main.EnableCommandHelper, __instance); - } + if (EnableCommandHelper == null || EnableCommandHelper.ToggleButton == null) EnableCommandHelper = ClientOptionItem.Create("EnableCommandHelper", Main.EnableCommandHelper, __instance); #if DEBUG if ((GodMode == null || GodMode.ToggleButton == null) && DebugModeManager.AmDebugger) @@ -218,9 +186,7 @@ namespace EHR { ClientOptionItem.CustomBackground?.gameObject.SetActive(false); - if (GameStates.InGame && GameStates.IsVoting && !DestroyableSingleton.Instance.Chat.IsOpenOrOpening) - { - } + if (GameStates.InGame && GameStates.IsVoting && !DestroyableSingleton.Instance.Chat.IsOpenOrOpening) { } } } } \ No newline at end of file diff --git a/Patches/ClientPatch.cs b/Patches/ClientPatch.cs index c25cc877a..57febb073 100644 --- a/Patches/ClientPatch.cs +++ b/Patches/ClientPatch.cs @@ -19,21 +19,12 @@ namespace EHR { if (ModUpdater.IsBroken || (ModUpdater.HasUpdate && ModUpdater.ForceUpdate) || !VersionChecker.IsSupported) { - string message = string.Empty; - if (!VersionChecker.IsSupported) - { - message = GetString("UnsupportedVersion"); - } + var message = string.Empty; + if (!VersionChecker.IsSupported) message = GetString("UnsupportedVersion"); - if (ModUpdater.IsBroken) - { - message = GetString("ModBrokenMessage"); - } + if (ModUpdater.IsBroken) message = GetString("ModBrokenMessage"); - if (ModUpdater.HasUpdate) - { - message = GetString("CanNotJoinPublicRoomNoLatest"); - } + if (ModUpdater.HasUpdate) message = GetString("CanNotJoinPublicRoomNoLatest"); Logger.Info(message, "MakePublicPatch"); Logger.SendInGame(message); @@ -50,21 +41,21 @@ namespace EHR { public static void Postfix() { - if (!((ModUpdater.HasUpdate && ModUpdater.ForceUpdate) || ModUpdater.IsBroken)) - { - return; - } + if (!((ModUpdater.HasUpdate && ModUpdater.ForceUpdate) || ModUpdater.IsBroken)) return; GameObject obj = GameObject.Find("FindGameButton"); + if (obj) { obj.SetActive(false); TextMeshPro textObj = Object.Instantiate(obj.transform.FindChild("Text_TMP").GetComponent()); textObj.transform.position = new(1f, -0.3f, 0); textObj.name = "CanNotJoinPublic"; + string message = ModUpdater.IsBroken ? $"{Utils.ColorString(Color.red, GetString("ModBrokenMessage"))}" : $"{Utils.ColorString(Color.red, GetString("CanNotJoinPublicRoomNoLatest"))}"; + LateTask.New(() => { textObj.text = message; }, 0.01f, "CanNotJoinPublic"); } } @@ -87,10 +78,7 @@ namespace EHR public static void Prefix(ref bool canOnline) { - if (DebugModeManager.AmDebugger) - { - canOnline = true; - } + if (DebugModeManager.AmDebugger) canOnline = true; } } @@ -99,10 +87,7 @@ namespace EHR { public static bool Prefix(BanMenu __instance, bool show) { - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; show &= PlayerControl.LocalPlayer && PlayerControl.LocalPlayer.Data != null; __instance.BanButton.gameObject.SetActive(AmongUsClient.Instance.CanBan()); @@ -127,10 +112,7 @@ namespace EHR { public static bool Prefix( /*InnerNetClient __instance,*/ int clientId, bool ban) { - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; if (AmongUsClient.Instance.ClientId == clientId) { @@ -139,10 +121,7 @@ namespace EHR return false; } - if (ban) - { - BanManager.AddBanPlayer(AmongUsClient.Instance.GetRecentClient(clientId)); - } + if (ban) BanManager.AddBanPlayer(AmongUsClient.Instance.GetRecentClient(clientId)); return true; } @@ -153,10 +132,7 @@ namespace EHR { public static void Postfix() { - if (MainMenuManagerPatch.UpdateButton != null) - { - MainMenuManagerPatch.UpdateButton.transform.localPosition = MainMenuManagerPatch.Template.transform.localPosition + new Vector3(0.25f, 0.75f); - } + if (MainMenuManagerPatch.UpdateButton != null) MainMenuManagerPatch.UpdateButton.transform.localPosition = MainMenuManagerPatch.Template.transform.localPosition + new Vector3(0.25f, 0.75f); } } @@ -165,10 +141,7 @@ namespace EHR { public static void Prefix() { - if (AmongUsClient.Instance.AmHost) - { - Main.Instance.StartCoroutine(GameOptionsSender.SendAllGameOptionsAsync()); - } + if (AmongUsClient.Instance.AmHost) Main.Instance.StartCoroutine(GameOptionsSender.SendAllGameOptionsAsync()); } } @@ -180,10 +153,7 @@ namespace EHR [HarmonyPrefix] public static bool SendInitialDataPrefix(InnerNetClient __instance, int clientId) { - if (!Constants.IsVersionModded() || GameStates.IsInGame || __instance.NetworkMode != NetworkModes.OnlineGame) - { - return true; - } + if (!Constants.IsVersionModded() || GameStates.IsInGame || __instance.NetworkMode != NetworkModes.OnlineGame) return true; // We make sure other stuff like PlayerControl and LobbyBehavior is spawned properly // Then we spawn the networked data for new clients @@ -192,25 +162,24 @@ namespace EHR messageWriter.Write(__instance.GameId); messageWriter.WritePacked(clientId); List obj = __instance.allObjects; + lock (obj) { System.Collections.Generic.HashSet hashSet = []; - for (int i = 0; i < __instance.allObjects.Count; i++) + + for (var i = 0; i < __instance.allObjects.Count; i++) { InnerNetObject innerNetObject = __instance.allObjects[i]; // False error + if (innerNetObject && (innerNetObject.OwnerId != -4 || __instance.AmModdedHost) && hashSet.Add(innerNetObject.gameObject)) { - GameManager gameManager = innerNetObject as GameManager; + var gameManager = innerNetObject as GameManager; + if (gameManager != null) - { __instance.SendGameManager(clientId, gameManager); - } else { - if (innerNetObject is not NetworkedPlayerInfo) - { - __instance.WriteSpawnMessage(innerNetObject, innerNetObject.OwnerId, innerNetObject.SpawnFlags, messageWriter); - } + if (innerNetObject is not NetworkedPlayerInfo) __instance.WriteSpawnMessage(innerNetObject, innerNetObject.OwnerId, innerNetObject.SpawnFlags, messageWriter); } } } @@ -248,39 +217,32 @@ namespace EHR [HarmonyPrefix] public static bool SendAllStreamedObjectsPrefix(InnerNetClient __instance, ref bool __result) { - if (!Constants.IsVersionModded() || __instance.NetworkMode != NetworkModes.OnlineGame) - { - return true; - } + if (!Constants.IsVersionModded() || __instance.NetworkMode != NetworkModes.OnlineGame) return true; // Bypass all NetworkedData here. __result = false; List obj = __instance.allObjects; + lock (obj) { - for (int i = 0; i < __instance.allObjects.Count; i++) + for (var i = 0; i < __instance.allObjects.Count; i++) { InnerNetObject innerNetObject = __instance.allObjects[i]; // False error + if (innerNetObject && innerNetObject is not NetworkedPlayerInfo && innerNetObject.IsDirty && (innerNetObject.AmOwner || (innerNetObject.OwnerId == -2 && __instance.AmHost))) { MessageWriter messageWriter = __instance.Streams[(int)innerNetObject.sendMode]; messageWriter.StartMessage(1); messageWriter.WritePacked(innerNetObject.NetId); + try { if (innerNetObject.Serialize(messageWriter, false)) - { messageWriter.EndMessage(); - } else - { messageWriter.CancelMessage(); - } - if (innerNetObject.Chunked && innerNetObject.IsDirty) - { - __result = true; - } + if (innerNetObject.Chunked && innerNetObject.IsDirty) __result = true; } catch (Exception ex) { @@ -291,9 +253,10 @@ namespace EHR } } - for (int j = 0; j < __instance.Streams.Length; j++) + for (var j = 0; j < __instance.Streams.Length; j++) { MessageWriter messageWriter2 = __instance.Streams[j]; + if (messageWriter2.HasBytes(7)) { messageWriter2.EndMessage(); @@ -311,10 +274,7 @@ namespace EHR [HarmonyPostfix] public static void FixedUpdatePostfix(InnerNetClient __instance) { - if (!Constants.IsVersionModded() || GameStates.IsInGame || !__instance.AmHost || __instance.Streams == null || __instance.NetworkMode != NetworkModes.OnlineGame) - { - return; - } + if (!Constants.IsVersionModded() || GameStates.IsInGame || !__instance.AmHost || __instance.Streams == null || __instance.NetworkMode != NetworkModes.OnlineGame) return; if (Timer == 0) { @@ -323,6 +283,7 @@ namespace EHR } NetworkedPlayerInfo player = GameData.Instance.AllPlayers.ToArray().FirstOrDefault(x => x.IsDirty); + if (player != null) { Timer = 0; @@ -331,12 +292,11 @@ namespace EHR messageWriter.Write(__instance.GameId); messageWriter.StartMessage(1); messageWriter.WritePacked(player.NetId); + try { if (player.Serialize(messageWriter, false)) - { messageWriter.EndMessage(); - } else { messageWriter.CancelMessage(); @@ -368,10 +328,7 @@ namespace EHR // https://github.com/NuclearPowered/Reactor/blob/master/Reactor/Patches/Miscellaneous/CustomServersPatch.cs public static bool CoWaitforNoncePrefix(ref bool __result) { - if (GameStates.IsVanillaServer) - { - return true; - } + if (GameStates.IsVanillaServer) return true; __result = false; return false; @@ -387,6 +344,7 @@ namespace EHR if (__instance.__1__state == 0 && !ServerManager.Instance.IsHttp) { __instance.__1__state = 1; + __instance.__8__1 = new() { matchmakerToken = string.Empty diff --git a/Patches/ControlPatch.cs b/Patches/ControlPatch.cs index 70a40902f..925282880 100644 --- a/Patches/ControlPatch.cs +++ b/Patches/ControlPatch.cs @@ -23,63 +23,37 @@ namespace EHR { if (GameStates.IsLobby) { - if (Input.GetKeyDown(KeyCode.Tab)) - { - OptionShower.Next(); - } + if (Input.GetKeyDown(KeyCode.Tab)) OptionShower.Next(); - for (int i = 0; i < 9; i++) - { + for (var i = 0; i < 9; i++) if (OrGetKeysDown(KeyCode.Alpha1 + i, KeyCode.Keypad1 + i) && OptionShower.Pages.Count >= i + 1) - { OptionShower.CurrentPage = i; - } - } - if (KeysDown(KeyCode.Return) && GameSettingMenu.Instance != null && GameSettingMenu.Instance.isActiveAndEnabled) - { - GameSettingMenuPatch.SearchForOptionsAction?.Invoke(); - } + if (KeysDown(KeyCode.Return) && GameSettingMenu.Instance != null && GameSettingMenu.Instance.isActiveAndEnabled) GameSettingMenuPatch.SearchForOptionsAction?.Invoke(); } - if (KeysDown(KeyCode.LeftShift, KeyCode.LeftControl, KeyCode.X)) - { - ExileController.Instance?.ReEnableGameplay(); - } + if (KeysDown(KeyCode.LeftShift, KeyCode.LeftControl, KeyCode.X)) ExileController.Instance?.ReEnableGameplay(); - if (KeysDown(KeyCode.LeftAlt, KeyCode.Return)) - { - LateTask.New(SetResolutionManager.Postfix, 0.01f, "Fix Button Position"); - } + if (KeysDown(KeyCode.LeftAlt, KeyCode.Return)) LateTask.New(SetResolutionManager.Postfix, 0.01f, "Fix Button Position"); if (GameStates.IsInGame && (GameStates.IsCanMove || GameStates.IsMeeting) && Options.CurrentGameMode == CustomGameMode.Standard) { if (Input.GetKey(KeyCode.F1)) { - if (!InGameRoleInfoMenu.Showing) - { - InGameRoleInfoMenu.SetRoleInfoRef(PlayerControl.LocalPlayer); - } + if (!InGameRoleInfoMenu.Showing) InGameRoleInfoMenu.SetRoleInfoRef(PlayerControl.LocalPlayer); InGameRoleInfoMenu.Show(); } else - { InGameRoleInfoMenu.Hide(); - } } else - { InGameRoleInfoMenu.Hide(); - } if (Input.GetKeyDown(KeyCode.F11)) { ResolutionIndex++; - if (ResolutionIndex >= Resolutions.Length) - { - ResolutionIndex = 0; - } + if (ResolutionIndex >= Resolutions.Length) ResolutionIndex = 0; ResolutionManager.SetResolution(Resolutions[ResolutionIndex].Item1, Resolutions[ResolutionIndex].Item2, false); SetResolutionManager.Postfix(); @@ -105,20 +79,11 @@ namespace EHR Utils.DumpLog(); } - if (KeysDown(KeyCode.LeftAlt, KeyCode.C) && !Input.GetKey(KeyCode.LeftShift) && !GameStates.IsNotJoined) - { - Utils.CopyCurrentSettings(); - } + if (KeysDown(KeyCode.LeftAlt, KeyCode.C) && !Input.GetKey(KeyCode.LeftShift) && !GameStates.IsNotJoined) Utils.CopyCurrentSettings(); - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; - if (KeysDown(KeyCode.Return, KeyCode.C, KeyCode.LeftShift)) - { - HudManager.Instance.Chat.SetVisible(true); - } + if (KeysDown(KeyCode.Return, KeyCode.C, KeyCode.LeftShift)) HudManager.Instance.Chat.SetVisible(true); if (KeysDown(KeyCode.Return, KeyCode.L, KeyCode.LeftShift) && GameStates.IsInGame) { @@ -129,13 +94,9 @@ namespace EHR if (KeysDown(KeyCode.Return, KeyCode.M, KeyCode.LeftShift) && GameStates.IsInGame) { if (GameStates.IsMeeting) - { MeetingHud.Instance.RpcClose(); - } else - { PlayerControl.LocalPlayer.NoCheckStartMeeting(null, true); - } } if (Input.GetKeyDown(KeyCode.LeftShift) && GameStates.IsCountDown && !HudManager.Instance.Chat.IsOpenOrOpening) @@ -169,18 +130,12 @@ namespace EHR IEnumerator Reset() { - for (int index = 0; index < OptionItem.AllOptions.Count; index++) + for (var index = 0; index < OptionItem.AllOptions.Count; index++) { OptionItem option = OptionItem.AllOptions[index]; - if (option.Id > 0) - { - option.SetValue(option.DefaultValue); - } + if (option.Id > 0) option.SetValue(option.DefaultValue); - if (index % 100 == 0) - { - yield return null; - } + if (index % 100 == 0) yield return null; } IsResetting = false; @@ -202,10 +157,7 @@ namespace EHR Logger.SendInGame($"In-game output log:{Logger.IsAlsoInGame}"); } - if (!Options.NoGameEnd.GetBool()) - { - return; - } + if (!Options.NoGameEnd.GetBool()) return; #if RELEASE return; @@ -214,10 +166,7 @@ namespace EHR if (KeysDown(KeyCode.Return, KeyCode.F, KeyCode.LeftShift)) { Utils.FlashColor(new(1f, 0f, 0f, 0.3f)); - if (Constants.ShouldPlaySfx()) - { - RPC.PlaySound(PlayerControl.LocalPlayer.PlayerId, Sounds.KillSound); - } + if (Constants.ShouldPlaySfx()) RPC.PlaySound(PlayerControl.LocalPlayer.PlayerId, Sounds.KillSound); } if (KeysDown(KeyCode.Return, KeyCode.G, KeyCode.LeftShift) && GameStates.IsInGame) @@ -226,10 +175,7 @@ namespace EHR HudManager.Instance.StartCoroutine(DestroyableSingleton.Instance.CoShowIntro()); } - if (KeysDown(KeyCode.Return, KeyCode.V, KeyCode.LeftShift) && GameStates.IsMeeting) - { - MeetingHud.Instance.RpcClearVote(AmongUsClient.Instance.ClientId); - } + if (KeysDown(KeyCode.Return, KeyCode.V, KeyCode.LeftShift) && GameStates.IsMeeting) MeetingHud.Instance.RpcClearVote(AmongUsClient.Instance.ClientId); if (KeysDown(KeyCode.Return, KeyCode.D, KeyCode.LeftShift) && GameStates.IsInGame) { @@ -246,12 +192,8 @@ namespace EHR } if (KeysDown(KeyCode.Return, KeyCode.T, KeyCode.LeftShift) && GameStates.IsInGame) - { foreach (PlayerTask task in PlayerControl.LocalPlayer.myTasks) - { PlayerControl.LocalPlayer.RpcCompleteTask(task.Id); - } - } if (Input.GetKeyDown(KeyCode.Y) && !GameStates.IsMeeting) { @@ -274,17 +216,14 @@ namespace EHR if (Input.GetKeyDown(KeyCode.C) && !GameStates.IsMeeting) { foreach (PlayerControl pc in PlayerControl.AllPlayerControls) - { if (!pc.AmOwner) - { pc.MyPhysics.RpcEnterVent(2); - } - } } if (Input.GetKeyDown(KeyCode.V) && !GameStates.IsMeeting) { Vector2 pos = PlayerControl.LocalPlayer.NetTransform.transform.position; + foreach (PlayerControl pc in PlayerControl.AllPlayerControls) { if (!pc.AmOwner) @@ -298,18 +237,11 @@ namespace EHR if (Input.GetKeyDown(KeyCode.B) && !GameStates.IsMeeting) { foreach (PlayerControl pc in PlayerControl.AllPlayerControls) - { if (!pc.AmOwner) - { pc.MyPhysics.RpcExitVent(2); - } - } } - if (Input.GetKeyDown(KeyCode.N) && !GameStates.IsMeeting) - { - VentilationSystem.Update(VentilationSystem.Operation.StartCleaning, 0); - } + if (Input.GetKeyDown(KeyCode.N) && !GameStates.IsMeeting) VentilationSystem.Update(VentilationSystem.Operation.StartCleaning, 0); } private static bool KeysDown(params KeyCode[] keys) @@ -354,16 +286,12 @@ namespace EHR if (player.GetButtonDown(8) && // 8: Kill button actionId PlayerControl.LocalPlayer.Data?.Role?.IsImpostor == false && PlayerControl.LocalPlayer.CanUseKillButton()) - { DestroyableSingleton.Instance.KillButton.DoClick(); - } if (player.GetButtonDown(50) && // 50: Impostor vent button actionId PlayerControl.LocalPlayer.Data?.Role?.IsImpostor == false && PlayerControl.LocalPlayer.CanUseImpostorVentButton()) - { DestroyableSingleton.Instance.ImpostorVentButton.DoClick(); - } } } @@ -417,15 +345,9 @@ namespace EHR public static void SetRoleInfoRef(PlayerControl player) { - if (player == null) - { - return; - } + if (player == null) return; - if (!Fill || !Menu) - { - Init(); - } + if (!Fill || !Menu) Init(); CustomRoles role = player.GetCustomRole(); StringBuilder sb = new(); @@ -436,33 +358,22 @@ namespace EHR titleSb.Append($"{role.ToColoredString()} {Utils.GetRoleMode(role)}"); sb.Append(""); sb.Append(player.GetRoleInfo(true).TrimStart()); - if (Options.CustomRoleSpawnChances.TryGetValue(role, out StringOptionItem opt)) - { - Utils.ShowChildrenSettings(opt, ref settings, f1: true, disableColor: false); - } + if (Options.CustomRoleSpawnChances.TryGetValue(role, out StringOptionItem opt)) Utils.ShowChildrenSettings(opt, ref settings, f1: true, disableColor: false); settings.Append(""); - if (settings.Length > 0) - { - addons.Append($"{settings}\n\n"); - } + if (settings.Length > 0) addons.Append($"{settings}\n\n"); - if (role.PetActivatedAbility()) - { - sb.Append($"{GetString("SupportsPetMessage")}"); - } + if (role.PetActivatedAbility()) sb.Append($"{GetString("SupportsPetMessage")}"); string searchStr = GetString(role.ToString()); sb.Replace(searchStr, role.ToColoredString()); sb.Replace(searchStr.ToLower(), role.ToColoredString()); sb.Append(""); List subRoles = Main.PlayerStates[player.PlayerId].SubRoles; - if (subRoles.Count > 0) - { - addons.Append(GetString("AddonListTitle")); - } + if (subRoles.Count > 0) addons.Append(GetString("AddonListTitle")); addons.Append(""); + subRoles.ForEach(subRole => { addons.Append($"\n\n{subRole.ToColoredString()} {Utils.GetRoleMode(subRole)} {GetString($"{subRole}InfoLong")}"); @@ -470,11 +381,9 @@ namespace EHR addons.Replace(searchSubStr, subRole.ToColoredString()); addons.Replace(searchSubStr.ToLower(), subRole.ToColoredString()); }); + addons.Append(""); - if (role.UsesPetInsteadOfKill()) - { - sb.Append($"\n\n{GetString("UsesPetInsteadOfKillNotice")}"); - } + if (role.UsesPetInsteadOfKill()) sb.Append($"\n\n{GetString("UsesPetInsteadOfKillNotice")}"); sb.Insert(0, $"{titleSb}\n"); @@ -484,19 +393,14 @@ namespace EHR public static void Show() { - if (!Fill || !Menu) - { - Init(); - } + if (!Fill || !Menu) Init(); if (!Showing) { Fill?.SetActive(true); Menu?.SetActive(true); - if (GameStates.IsMeeting) - { - } + if (GameStates.IsMeeting) { } } } @@ -507,9 +411,7 @@ namespace EHR Fill?.SetActive(false); Menu?.SetActive(false); - if (GameStates.IsVoting) - { - } + if (GameStates.IsVoting) { } } } } diff --git a/Patches/CredentialsPatch.cs b/Patches/CredentialsPatch.cs index c2e4e19a8..eb8174871 100644 --- a/Patches/CredentialsPatch.cs +++ b/Patches/CredentialsPatch.cs @@ -26,23 +26,18 @@ namespace EHR Instance.text.text = Sb.ToString(); long now = Utils.TimeStamp; - if (now + Delay <= LastUpdate) - { - return; // Only update every 2 seconds - } + if (now + Delay <= LastUpdate) return; // Only update every 2 seconds LastUpdate = now; Sb.Clear(); - if (GameStates.IsLobby) - { - Sb.Append("\r\n"); - } + if (GameStates.IsLobby) Sb.Append("\r\n"); Sb.Append(Main.CredentialsText); int ping = AmongUsClient.Instance.Ping; + string color = ping switch { < 30 => "#44dfcc", @@ -51,14 +46,12 @@ namespace EHR < 400 => "#ff146e", _ => "#ff4500" }; + Sb.Append(GameStates.InGame ? " - " : "\r\n"); Sb.Append($"{GetString("PingText")}: {ping} ms"); Sb.Append(GameStates.InGame ? " - " : "\r\n"); Sb.Append(string.Format(GetString("Server"), Utils.GetRegionName())); - if (GameStates.InGame) - { - Sb.Append("\r\n."); - } + if (GameStates.InGame) Sb.Append("\r\n."); // if (Options.NoGameEnd.GetBool()) Sb.Append("\r\n").Append(Utils.ColorString(Color.red, GetString("NoGameEnd"))).Append(""); // if (!GameStates.IsModHost) Sb.Append("\r\n").Append(Utils.ColorString(Color.red, GetString("Warning.NoModHost"))).Append(""); @@ -79,12 +72,9 @@ namespace EHR #pragma warning restore CS0162 // Unreachable code detected Main.CredentialsText = $"Endless Host Roles v{Main.PluginDisplayVersion}{testBuildIndicator} by Gurge44"; - string menuText = $"Endless Host Roles v{Main.PluginDisplayVersion}{testBuildIndicator}\r\nBy Gurge44"; + var menuText = $"Endless Host Roles v{Main.PluginDisplayVersion}{testBuildIndicator}\r\nBy Gurge44"; - if (Main.IsAprilFools) - { - Main.CredentialsText = "Endless Madness v11.45.14 by No one"; - } + if (Main.IsAprilFools) Main.CredentialsText = "Endless Madness v11.45.14 by No one"; TextMeshPro credentials = Object.Instantiate(__instance.text); credentials.text = menuText; @@ -93,10 +83,7 @@ namespace EHR credentials.fontSize = credentials.fontSizeMax = credentials.fontSizeMin = 2f; ErrorText.Create(__instance.text); - if (Main.HasArgumentException && ErrorText.Instance != null) - { - ErrorText.Instance.AddError(ErrorCode.Main_DictionaryError); - } + if (Main.HasArgumentException && ErrorText.Instance != null) ErrorText.Instance.AddError(ErrorCode.Main_DictionaryError); VersionChecker.Check(); } @@ -123,14 +110,12 @@ namespace EHR { GameObject.Find("BackgroundTexture")?.SetActive(!MainMenuManagerPatch.ShowedBak); - if (!(ModStamp = GameObject.Find("ModStamp"))) - { - return; - } + if (!(ModStamp = GameObject.Find("ModStamp"))) return; ModStamp.transform.localScale = new(0.3f, 0.3f, 0.3f); Ambience = GameObject.Find("Ambience"); + if (Ambience != null) { try @@ -143,10 +128,7 @@ namespace EHR } } - if (!(LeftPanel = GameObject.Find("LeftPanel"))) - { - return; - } + if (!(LeftPanel = GameObject.Find("LeftPanel"))) return; LeftPanel.transform.localScale = new(0.7f, 0.7f, 0.7f); LeftPanel.ForEachChild((Il2CppSystem.Action)ResetParent); @@ -163,31 +145,20 @@ namespace EHR { [__instance.creditsButton, __instance.quitButton], (minorActiveSprite, new(0.526f, 1f, 0.792f, 0.8f), shade, Color.white, Color.white) } }; - foreach (KeyValuePair, (Sprite, Color, Color, Color, Color)> kvp in mainButtons) - { - kvp.Key.Do(button => FormatButtonColor(button, kvp.Value.Item2, kvp.Value.Item3, kvp.Value.Item4, kvp.Value.Item5)); - } + foreach (KeyValuePair, (Sprite, Color, Color, Color, Color)> kvp in mainButtons) kvp.Key.Do(button => FormatButtonColor(button, kvp.Value.Item2, kvp.Value.Item3, kvp.Value.Item4, kvp.Value.Item5)); try { mainButtons.Keys.Flatten().DoIf(x => x != null, x => x.buttonText.color = Color.white); } - catch - { - } + catch { } GameObject.Find("Divider")?.SetActive(false); - if (!(RightPanel = GameObject.Find("RightPanel"))) - { - return; - } + if (!(RightPanel = GameObject.Find("RightPanel"))) return; - AspectPosition rpap = RightPanel.GetComponent(); - if (rpap) - { - Object.Destroy(rpap); - } + var rpap = RightPanel.GetComponent(); + if (rpap) Object.Destroy(rpap); RightPanelOp = RightPanel.transform.localPosition; RightPanel.transform.localPosition = RightPanelOp + new Vector3(10f, 0f, 0f); @@ -198,10 +169,10 @@ namespace EHR CloseRightButton.transform.localPosition = new(-4.78f, 1.3f, 1f); CloseRightButton.transform.localScale = new(1f, 1f, 1f); CloseRightButton.AddComponent().size = new(0.6f, 1.5f); - SpriteRenderer closeRightSpriteRenderer = CloseRightButton.AddComponent(); + var closeRightSpriteRenderer = CloseRightButton.AddComponent(); closeRightSpriteRenderer.sprite = Utils.LoadSprite("EHR.Resources.Images.RightPanelCloseButton.png", 100f); closeRightSpriteRenderer.color = new(1f, 0.78f, 0.9f, 1f); - PassiveButton closeRightPassiveButton = CloseRightButton.AddComponent(); + var closeRightPassiveButton = CloseRightButton.AddComponent(); closeRightPassiveButton.OnClick = new(); closeRightPassiveButton.OnClick.AddListener((Action)MainMenuManagerPatch.HideRightPanel); closeRightPassiveButton.OnMouseOut = new(); @@ -210,11 +181,8 @@ namespace EHR closeRightPassiveButton.OnMouseOver.AddListener((Action)(() => closeRightSpriteRenderer.color = new(1f, 0.68f, 0.99f, 1f))); Tint = __instance.screenTint.gameObject; - AspectPosition ttap = Tint.GetComponent(); - if (ttap) - { - Object.Destroy(ttap); - } + var ttap = Tint.GetComponent(); + if (ttap) Object.Destroy(ttap); Tint.transform.SetParent(RightPanel.transform); Tint.transform.localPosition = new(-0.0824f, 0.0513f, Tint.transform.localPosition.z); @@ -222,10 +190,7 @@ namespace EHR __instance.howToPlayButton.gameObject.SetActive(false); __instance.howToPlayButton.transform.parent.Find("FreePlayButton").gameObject.SetActive(false); - if (!(BottomButtonBounds = GameObject.Find("BottomButtonBounds"))) - { - return; - } + if (!(BottomButtonBounds = GameObject.Find("BottomButtonBounds"))) return; BottomButtonBounds.transform.localPosition -= new Vector3(0f, 0.1f, 0f); @@ -240,8 +205,8 @@ namespace EHR { button.activeSprites.transform.FindChild("Shine")?.gameObject.SetActive(false); button.inactiveSprites.transform.FindChild("Shine")?.gameObject.SetActive(false); - SpriteRenderer activeRenderer = button.activeSprites.GetComponent(); - SpriteRenderer inActiveRenderer = button.inactiveSprites.GetComponent(); + var activeRenderer = button.activeSprites.GetComponent(); + var inActiveRenderer = button.inactiveSprites.GetComponent(); activeRenderer.sprite = minorActiveSprite; inActiveRenderer.sprite = minorActiveSprite; activeRenderer.color = activeColor.a == 0f ? new(inActiveColor.r, inActiveColor.g, inActiveColor.b, 1f) : activeColor; @@ -268,9 +233,11 @@ namespace EHR public static void Postfix(ModManager __instance) { __instance.localCamera = !DestroyableSingleton.InstanceExists ? Camera.main : DestroyableSingleton.Instance.GetComponentInChildren(); + if (__instance.localCamera != null) { float offsetY = HudManager.InstanceExists ? 1.1f : 0.9f; + __instance.ModStamp.transform.position = AspectPosition.ComputeWorldPosition( __instance.localCamera, AspectPosition.EdgeAlignments.RightTop, new(0.4f, offsetY, __instance.localCamera.nearClipPlane + 0.1f)); @@ -285,40 +252,27 @@ namespace EHR { try { - if (DestroyableSingleton.InstanceExists && !DestroyableSingleton.Instance.SettingsButton.activeSelf) - { - return false; - } - } - catch - { + if (DestroyableSingleton.InstanceExists && !DestroyableSingleton.Instance.SettingsButton.activeSelf) return false; } + catch { } __instance.ResetText(); + if (__instance.gameObject.activeSelf) { - if (!__instance.Toggle) - { - return false; - } + if (!__instance.Toggle) return false; __instance.GetComponent().Close(); } else { - if (Minigame.Instance != null) - { - Minigame.Instance.Close(); - } + if (Minigame.Instance != null) Minigame.Instance.Close(); __instance.OpenTabGroup(0); __instance.UpdateButtons(); __instance.gameObject.SetActive(true); __instance.MenuButton?.SelectButton(true); - if (DestroyableSingleton.InstanceExists) - { - ConsoleJoystick.SetMode_MenuAdditive(); - } + if (DestroyableSingleton.InstanceExists) ConsoleJoystick.SetMode_MenuAdditive(); if (!__instance.grabbedControllerButtons) { @@ -334,9 +288,7 @@ namespace EHR public static void Postfix() { - if (GameStates.InGame && GameStates.IsMeeting) - { - } + if (GameStates.InGame && GameStates.IsMeeting) { } } } } \ No newline at end of file diff --git a/Patches/DeconSystemPatch.cs b/Patches/DeconSystemPatch.cs index 70f55911a..8a02f1d8b 100644 --- a/Patches/DeconSystemPatch.cs +++ b/Patches/DeconSystemPatch.cs @@ -7,10 +7,7 @@ namespace EHR.Patches { public static void Prefix(DeconSystem __instance) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; if (Options.ChangeDecontaminationTime.GetBool()) { diff --git a/Patches/DisconnectPatch.cs b/Patches/DisconnectPatch.cs index 27bb2599d..2b1a6d59d 100644 --- a/Patches/DisconnectPatch.cs +++ b/Patches/DisconnectPatch.cs @@ -63,21 +63,13 @@ namespace EHR break; case DisconnectReasons.Error: //if (StringReason.Contains("Couldn't find self")) __instance.SetText(GetString("DCNotify.DCFromServer")); - if (StringReason.Contains("Failed to send message")) - { - __instance.SetText(GetString("DCNotify.DCFromServer")); - } + if (StringReason.Contains("Failed to send message")) __instance.SetText(GetString("DCNotify.DCFromServer")); break; case DisconnectReasons.Custom: if (StringReason.Contains("Reliable packet")) - { __instance.SetText(GetString("DCNotify.DCFromServer")); - } - else if (StringReason.Contains("remote has not responded to")) - { - __instance.SetText(GetString("DCNotify.DCFromServer")); - } + else if (StringReason.Contains("remote has not responded to")) __instance.SetText(GetString("DCNotify.DCFromServer")); break; case DisconnectReasons.ExitGame: @@ -144,9 +136,7 @@ namespace EHR break; } } - catch - { - } + catch { } } }, 0.01f, "Override Disconnect Text"); } diff --git a/Patches/DisconnectPenaltyPatch.cs b/Patches/DisconnectPenaltyPatch.cs index 2d2e89b25..6db3da289 100644 --- a/Patches/DisconnectPenaltyPatch.cs +++ b/Patches/DisconnectPenaltyPatch.cs @@ -7,10 +7,7 @@ namespace EHR.Patches { public static bool Prefix(StatsManager __instance, ref int __result) { - if (!DebugModeManager.AmDebugger) - { - return true; - } + if (!DebugModeManager.AmDebugger) return true; if (__instance.BanPoints != 0f) { diff --git a/Patches/DiscordPatch.cs b/Patches/DiscordPatch.cs index 93a9e0c0d..872deb8b6 100644 --- a/Patches/DiscordPatch.cs +++ b/Patches/DiscordPatch.cs @@ -14,12 +14,9 @@ namespace EHR.Patches public static void Prefix([HarmonyArgument(0)] Activity activity) { - if (activity == null) - { - return; - } + if (activity == null) return; - string details = $"EHR v{Main.PluginDisplayVersion}"; + var details = $"EHR v{Main.PluginDisplayVersion}"; activity.Details = details; try @@ -34,15 +31,10 @@ namespace EHR.Patches Region = Utils.GetRegionName(); } - if (Lobbycode != "" && Region != "") - { - details = $"EHR - {Lobbycode} ({Region})"; - } + if (Lobbycode != "" && Region != "") details = $"EHR - {Lobbycode} ({Region})"; } else - { details = $"EHR v{Main.PluginDisplayVersion}"; - } activity.Details = details; } diff --git a/Patches/DleksPatch.cs b/Patches/DleksPatch.cs index 6204b1955..53776d38f 100644 --- a/Patches/DleksPatch.cs +++ b/Patches/DleksPatch.cs @@ -14,10 +14,7 @@ namespace EHR { try { - if (__instance == null) - { - return; - } + if (__instance == null) return; LateTask.New(() => { @@ -26,10 +23,7 @@ namespace EHR Main.NormalOptions.MapId = 0; __instance.UpdateMapImage(MapNames.Skeld); - if (!Options.RandomMapsMode.GetBool()) - { - CreateOptionsPickerPatch.SetDleks = true; - } + if (!Options.RandomMapsMode.GetBool()) CreateOptionsPickerPatch.SetDleks = true; } }, AmongUsClient.Instance.AmHost ? 1f : 4f, "Set Skeld Icon For Dleks Map"); @@ -51,16 +45,10 @@ namespace EHR { public static bool Prefix(AmongUsClient._CoStartGameHost_d__32 __instance, ref bool __result) { - if (__instance.__1__state != 0) - { - return true; - } + if (__instance.__1__state != 0) return true; __instance.__1__state = -1; - if (LobbyBehaviour.Instance) - { - LobbyBehaviour.Instance.Despawn(); - } + if (LobbyBehaviour.Instance) LobbyBehaviour.Instance.Despawn(); if (ShipStatus.Instance) { @@ -91,10 +79,7 @@ namespace EHR if (Main.CurrentMap == MapNames.Dleks && Main.IntroDestroyed) { enabled = false; - if (GameStates.IsMeeting) - { - ShowButtons = false; - } + if (GameStates.IsMeeting) ShowButtons = false; } return true; @@ -102,17 +87,12 @@ namespace EHR public static void Postfix(Vent __instance, [HarmonyArgument(0)] bool enabled) { - if (Main.CurrentMap != MapNames.Dleks) - { - return; - } + if (Main.CurrentMap != MapNames.Dleks) return; - if (enabled || !Main.IntroDestroyed) - { - return; - } + if (enabled || !Main.IntroDestroyed) return; bool setActive = ShowButtons || (!PlayerControl.LocalPlayer.inVent && !GameStates.IsMeeting); + switch (__instance.Id) { case 0: @@ -146,10 +126,7 @@ namespace EHR // Update arrows buttons when player move to vents private static void Postfix(Vent __instance, [HarmonyArgument(0)] Vent otherVent) { - if (__instance == null || otherVent == null || Main.CurrentMap != MapNames.Dleks) - { - return; - } + if (__instance == null || otherVent == null || Main.CurrentMap != MapNames.Dleks) return; VentSetButtonsPatch.ShowButtons = true; VentSetButtonsPatch.Postfix(otherVent, false); diff --git a/Patches/EHROnlySearch.cs b/Patches/EHROnlySearch.cs index e38540929..1d2399c75 100644 --- a/Patches/EHROnlySearch.cs +++ b/Patches/EHROnlySearch.cs @@ -28,23 +28,18 @@ namespace EHR { __instance.targetOpts.FilterTags = new(); __instance.targetOpts.FilterTags.Add(FilterText); - foreach (UiElement btn in __instance.controllerSelectable) - { - btn.GetComponent().SetSelected(false); - } + foreach (UiElement btn in __instance.controllerSelectable) btn.GetComponent().SetSelected(false); button.SetSelected(true); } else { __instance.targetOpts.FilterTags.Remove(FilterText); + foreach (UiElement btn in __instance.controllerSelectable) { - ChatLanguageButton LangBtn = btn.GetComponent(); - if (LangBtn.Text.text == FilterText) - { - LangBtn.SetSelected(false); - } + var LangBtn = btn.GetComponent(); + if (LangBtn.Text.text == FilterText) LangBtn.SetSelected(false); } } diff --git a/Patches/EndGameManagerPatch.cs b/Patches/EndGameManagerPatch.cs index 212814aae..8c61400ec 100644 --- a/Patches/EndGameManagerPatch.cs +++ b/Patches/EndGameManagerPatch.cs @@ -13,10 +13,7 @@ namespace EHR.Patches public static void Postfix(EndGameManager __instance) { - if (!AmongUsClient.Instance.AmHost || !Options.AutoPlayAgain.GetBool()) - { - return; - } + if (!AmongUsClient.Instance.AmHost || !Options.AutoPlayAgain.GetBool()) return; IsRestarting = false; @@ -35,34 +32,25 @@ namespace EHR.Patches private static void BeginAutoPlayAgainCountdown(EndGameManager endGameManager, int seconds) { - if (!IsRestarting) - { - return; - } + if (!IsRestarting) return; - if (endGameManager == null) - { - return; - } + if (endGameManager == null) return; EndGameNavigation navigation = endGameManager.Navigation; - if (navigation == null) - { - return; - } + if (navigation == null) return; if (seconds == Options.AutoPlayAgainCountdown.GetInt()) { CountdownText = new("CountdownText"); CountdownText.transform.position = new(0f, 2.5f, 10f); - TextMeshPro CountdownTextText = CountdownText.AddComponent(); + var CountdownTextText = CountdownText.AddComponent(); CountdownTextText.text = string.Format(GetString("CountdownText"), seconds); CountdownTextText.alignment = TextAlignmentOptions.Center; CountdownTextText.fontSize = 3f; } else { - TextMeshPro CountdownTextText = CountdownText.GetComponent(); + var CountdownTextText = CountdownText.GetComponent(); CountdownTextText.text = string.Format(GetString("CountdownText"), seconds); } @@ -72,9 +60,7 @@ namespace EHR.Patches CountdownText.transform.DestroyChildren(); } else - { LateTask.New(() => { BeginAutoPlayAgainCountdown(endGameManager, seconds - 1); }, 1f, log: false); - } } } } \ No newline at end of file diff --git a/Patches/ExilePatch.cs b/Patches/ExilePatch.cs index f0292a856..3d86e04a2 100644 --- a/Patches/ExilePatch.cs +++ b/Patches/ExilePatch.cs @@ -17,14 +17,12 @@ namespace EHR.Patches private static void WrapUpPostfix(NetworkedPlayerInfo exiled) { - bool DecidedWinner = false; - if (!AmongUsClient.Instance.AmHost) - { - return; - } + var DecidedWinner = false; + if (!AmongUsClient.Instance.AmHost) return; AntiBlackout.RestoreIsDead(false); AntiBlackoutLastExiled = exiled; + if (!Collector.CollectorWin(false) && exiled != null) { exiled.IsDead = true; @@ -34,32 +32,26 @@ namespace EHR.Patches if (Main.AllPlayerControls.Any(x => x.Is(CustomRoles.Innocent) && !x.IsAlive() && x.GetRealKiller()?.PlayerId == exiled.PlayerId)) { if (!Options.InnocentCanWinByImp.GetBool() && role.IsImpostor()) - { Logger.Info("The exiled player is an impostor, but the Innocent cannot win due to the settings", "Exeiled Winner Check"); - } else { CustomWinnerHolder.ResetAndSetWinner(CustomWinner.Innocent); + Main.AllPlayerControls .Where(x => x.Is(CustomRoles.Innocent) && !x.IsAlive() && x.GetRealKiller()?.PlayerId == exiled.PlayerId) .Do(x => CustomWinnerHolder.WinnerIds.Add(x.PlayerId)); + DecidedWinner = true; } } if (role.Is(Team.Impostor) || role.Is(Team.Neutral)) - { Stressed.OnNonCrewmateEjected(); - } else - { Stressed.OnCrewmateEjected(); - } if (role.Is(Team.Impostor)) - { Damocles.OnImpostorEjected(); - } else { Cantankerous.OnCrewmateEjected(); @@ -71,13 +63,9 @@ namespace EHR.Patches { case CustomRoles.Jester: if (DecidedWinner) - { CustomWinnerHolder.ShiftWinnerAndSetWinner(CustomWinner.Jester); - } else - { CustomWinnerHolder.ResetAndSetWinner(CustomWinner.Jester); - } CustomWinnerHolder.WinnerIds.Add(exiled.PlayerId); DecidedWinner = true; @@ -93,26 +81,14 @@ namespace EHR.Patches break; } - if (Executioner.CheckExileTarget(exiled)) - { - DecidedWinner = true; - } + if (Executioner.CheckExileTarget(exiled)) DecidedWinner = true; - if (Lawyer.CheckExileTarget(exiled /*, DecidedWinner*/)) - { - DecidedWinner = false; - } + if (Lawyer.CheckExileTarget(exiled /*, DecidedWinner*/)) DecidedWinner = false; - if (CustomWinnerHolder.WinnerTeam != CustomWinner.Terrorist) - { - Main.PlayerStates[exiled.PlayerId].SetDead(); - } + if (CustomWinnerHolder.WinnerTeam != CustomWinner.Terrorist) Main.PlayerStates[exiled.PlayerId].SetDead(); } - if (AmongUsClient.Instance.AmHost && Main.IsFixedCooldown) - { - Main.RefixCooldownDelay = Options.DefaultKillCooldown - 3f; - } + if (AmongUsClient.Instance.AmHost && Main.IsFixedCooldown) Main.RefixCooldownDelay = Options.DefaultKillCooldown - 3f; Witch.RemoveSpelledPlayer(); @@ -142,10 +118,8 @@ namespace EHR.Patches 5 => new RandomSpawn.FungleSpawnMap(), _ => null }; - if (map != null) - { - Main.AllAlivePlayerControls.Do(map.RandomTeleport); - } + + if (map != null) Main.AllAlivePlayerControls.Do(map.RandomTeleport); } FallFromLadder.Reset(); @@ -162,6 +136,7 @@ namespace EHR.Patches AntiBlackout.SendGameData(); AntiBlackout.SetRealPlayerRoles(); }, 0.7f, "Restore IsDead Task"); + LateTask.New(() => { Main.AfterMeetingDeathPlayers.Do(x => @@ -172,13 +147,11 @@ namespace EHR.Patches state.deathReason = x.Value; state.SetDead(); player?.RpcExileV2(); - if (x.Value == PlayerState.DeathReason.Suicide) - { - player?.SetRealKiller(player, true); - } + if (x.Value == PlayerState.DeathReason.Suicide) player?.SetRealKiller(player, true); Utils.AfterPlayerDeathTasks(player); }); + Main.AfterMeetingDeathPlayers.Clear(); Utils.AfterMeetingTasks(); Utils.SyncAllSettings(); @@ -189,10 +162,7 @@ namespace EHR.Patches LateTask.New(() => { - if (GameStates.IsEnded) - { - return; - } + if (GameStates.IsEnded) return; AntiBlackout.ResetAfterMeeting(); }, 2f, "Reset Cooldown After Meeting"); @@ -202,32 +172,25 @@ namespace EHR.Patches SoundManager.Instance.ChangeAmbienceVolume(DataManager.Settings.Audio.AmbienceVolume); Logger.Info("Start task phase", "Phase"); - if (Lovers.IsChatActivated && Lovers.PrivateChat.GetBool()) - { - return; - } + if (Lovers.IsChatActivated && Lovers.PrivateChat.GetBool()) return; bool showRemainingKillers = Options.EnableKillerLeftCommand.GetBool() && Options.ShowImpRemainOnEject.GetBool(); bool appendEjectionNotify = CheckForEndVotingPatch.EjectionText != string.Empty; Logger.Msg($"Ejection Text: {CheckForEndVotingPatch.EjectionText}", "ExilePatch"); + if ((showRemainingKillers || appendEjectionNotify) && Options.CurrentGameMode == CustomGameMode.Standard) { string text = showRemainingKillers ? Utils.GetRemainingKillers(true) : string.Empty; text = $"<#ffffff>{text}"; - IRandom r = IRandom.Instance; + var r = IRandom.Instance; + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { string finalText = text; - if (appendEjectionNotify && !finalText.Contains(CheckForEndVotingPatch.EjectionText, StringComparison.OrdinalIgnoreCase)) - { - finalText = $"\n<#ffffff>{CheckForEndVotingPatch.EjectionText}\n{finalText}"; - } + if (appendEjectionNotify && !finalText.Contains(CheckForEndVotingPatch.EjectionText, StringComparison.OrdinalIgnoreCase)) finalText = $"\n<#ffffff>{CheckForEndVotingPatch.EjectionText}\n{finalText}"; - if (!showRemainingKillers) - { - finalText = finalText.TrimStart(); - } + if (!showRemainingKillers) finalText = finalText.TrimStart(); pc.Notify(finalText, r.Next(7, 13)); } diff --git a/Patches/GameManagerPatch.cs b/Patches/GameManagerPatch.cs index c4ae125c7..92ad5d0e6 100644 --- a/Patches/GameManagerPatch.cs +++ b/Patches/GameManagerPatch.cs @@ -8,23 +8,22 @@ namespace EHR { public static bool Prefix(GameManager __instance, [HarmonyArgument(0)] MessageWriter writer, [HarmonyArgument(1)] bool initialState, ref bool __result) { - bool flag = false; - for (int index = 0; index < __instance.LogicComponents.Count; ++index) + var flag = false; + + for (var index = 0; index < __instance.LogicComponents.Count; ++index) { GameLogicComponent logicComponent = __instance.LogicComponents[index]; + if (initialState || logicComponent.IsDirty) { flag = true; writer.StartMessage((byte)index); bool hasBody = logicComponent.Serialize(writer, initialState); + if (hasBody) - { writer.EndMessage(); - } else - { writer.CancelMessage(); - } logicComponent.ClearDirtyFlag(); } diff --git a/Patches/GameOptionsMenuPatch.cs b/Patches/GameOptionsMenuPatch.cs index 1c8304a96..8f28fbd99 100644 --- a/Patches/GameOptionsMenuPatch.cs +++ b/Patches/GameOptionsMenuPatch.cs @@ -32,10 +32,7 @@ namespace EHR private static bool InitializePrefix(GameOptionsMenu __instance) { Instance ??= __instance; - if (ModGameOptionsMenu.TabIndex < 3) - { - return true; - } + if (ModGameOptionsMenu.TabIndex < 3) return true; if (__instance.Children == null || __instance.Children.Count == 0) { @@ -60,10 +57,7 @@ namespace EHR LateTask.New(() => { Transform menuDescription = optionMenu?.transform.FindChild("What Is This?"); - if (menuDescription == null) - { - return; - } + if (menuDescription == null) return; Transform infoImage = menuDescription.transform.FindChild("InfoImage"); infoImage.transform.localPosition = new(-4.65f, 0.16f, -1f); @@ -83,10 +77,7 @@ namespace EHR [HarmonyPrefix] private static bool CreateSettingsPrefix(GameOptionsMenu __instance) { - if (ModGameOptionsMenu.TabIndex < 3) - { - return true; - } + if (ModGameOptionsMenu.TabIndex < 3) return true; __instance.scrollBar.SetYBoundsMax(CalculateScrollBarYBoundsMax()); __instance.StartCoroutine(CoRoutine().WrapToIl2Cpp()); @@ -94,18 +85,16 @@ namespace EHR IEnumerator CoRoutine() { - TabGroup modTab = (TabGroup)(ModGameOptionsMenu.TabIndex - 3); + var modTab = (TabGroup)(ModGameOptionsMenu.TabIndex - 3); - float num = 2.0f; + var num = 2.0f; const float posX = 0.952f; const float posZ = -2.0f; - for (int index = 0; index < OptionItem.AllOptions.Count; index++) + + for (var index = 0; index < OptionItem.AllOptions.Count; index++) { OptionItem option = OptionItem.AllOptions[index]; - if (option.Tab != modTab) - { - continue; - } + if (option.Tab != modTab) continue; bool enabled = !option.IsHiddenOn(Options.CurrentGameMode) && (option.Parent == null || (!option.Parent.IsHiddenOn(Options.CurrentGameMode) && option.Parent.GetBool())) && (option.Parent?.Parent == null || (!option.Parent.Parent.IsHiddenOn(Options.CurrentGameMode) && option.Parent.Parent.GetBool())) && (option.Parent?.Parent?.Parent == null || (!option.Parent.Parent.Parent.IsHiddenOn(Options.CurrentGameMode) && option.Parent.Parent.Parent.GetBool())); @@ -116,32 +105,20 @@ namespace EHR categoryHeaderMasked.Title.text = option.GetName(); categoryHeaderMasked.transform.localScale = Vector3.one * 0.63f; categoryHeaderMasked.transform.localPosition = new(-0.903f, num, posZ); - TextMeshPro chmText = categoryHeaderMasked.transform.FindChild("HeaderText").GetComponent(); + var chmText = categoryHeaderMasked.transform.FindChild("HeaderText").GetComponent(); chmText.fontStyle = FontStyles.Bold; chmText.outlineWidth = 0.17f; categoryHeaderMasked.gameObject.SetActive(enabled); ModGameOptionsMenu.CategoryHeaderList.TryAdd(index, categoryHeaderMasked); - if (enabled) - { - num -= 0.63f; - } - } - else if (option.IsHeader && enabled) - { - num -= 0.25f; + if (enabled) num -= 0.63f; } + else if (option.IsHeader && enabled) num -= 0.25f; - if (option is TextOptionItem) - { - continue; - } + if (option is TextOptionItem) continue; BaseGameSetting baseGameSetting = GetSetting(option); - if (baseGameSetting == null) - { - continue; - } + if (baseGameSetting == null) continue; OptionBehaviour optionBehaviour; @@ -167,10 +144,7 @@ namespace EHR OptionBehaviourSetSizeAndPosition(optionBehaviour, option, baseGameSetting.Type); - if (option.Name == "GameMode" && !ModGameOptionsMenu.OptionList.ContainsValue(index)) - { - GameSettingMenuPatch.GameModeBehaviour = (StringOption)optionBehaviour; - } + if (option.Name == "GameMode" && !ModGameOptionsMenu.OptionList.ContainsValue(index)) GameSettingMenuPatch.GameModeBehaviour = (StringOption)optionBehaviour; optionBehaviour.SetClickMask(__instance.ButtonClickMask); optionBehaviour.SetUpFromData(baseGameSetting, 20); @@ -185,10 +159,7 @@ namespace EHR OptionBehaviourSetSizeAndPosition(optionBehaviour, option, baseGameSetting.Type); - if (option.Name == "Preset" && !ModGameOptionsMenu.OptionList.ContainsValue(index)) - { - GameSettingMenuPatch.PresetBehaviour = (NumberOption)optionBehaviour; - } + if (option.Name == "Preset" && !ModGameOptionsMenu.OptionList.ContainsValue(index)) GameSettingMenuPatch.PresetBehaviour = (NumberOption)optionBehaviour; optionBehaviour.SetClickMask(__instance.ButtonClickMask); optionBehaviour.SetUpFromData(baseGameSetting, 20); @@ -210,48 +181,32 @@ namespace EHR option.OptionBehaviour = optionBehaviour; - if (enabled) - { - num -= 0.45f; - } + if (enabled) num -= 0.45f; - if (index % 50 == 0) - { - yield return null; - } + if (index % 50 == 0) yield return null; } yield return null; __instance.ControllerSelectable.Clear(); - foreach (UiElement x in __instance.scrollBar.GetComponentsInChildren()) - { - __instance.ControllerSelectable.Add(x); - } + foreach (UiElement x in __instance.scrollBar.GetComponentsInChildren()) __instance.ControllerSelectable.Add(x); } float CalculateScrollBarYBoundsMax() { - float num = 2.0f; + var num = 2.0f; + foreach (OptionItem option in OptionItem.AllOptions) { - if (option.Tab != (TabGroup)(ModGameOptionsMenu.TabIndex - 3)) - { - continue; - } + if (option.Tab != (TabGroup)(ModGameOptionsMenu.TabIndex - 3)) continue; bool enabled = !option.IsHiddenOn(Options.CurrentGameMode) && (option.Parent == null || (!option.Parent.IsHiddenOn(Options.CurrentGameMode) && option.Parent.GetBool())); if (option is TextOptionItem) - { num -= 0.63f; - } else if (enabled) { - if (option.IsHeader) - { - num -= 0.25f; - } + if (option.IsHeader) num -= 0.25f; num -= 0.45f; } @@ -266,7 +221,7 @@ namespace EHR Vector3 positionOffset = new(0f, 0f, 0f); Vector3 scaleOffset = new(0f, 0f, 0f); Color color = new(0.35f, 0.35f, 0.35f); - float sizeDelta_x = 5.7f; + var sizeDelta_x = 5.7f; if (option.Parent?.Parent?.Parent != null) { @@ -298,7 +253,7 @@ namespace EHR Transform titleText = optionBehaviour.transform.FindChild("Title Text"); titleText.localPosition += new Vector3(-0.4f, 0f, 0f) + positionOffset; titleText.GetComponent().sizeDelta = new(sizeDelta_x, 0.37f); - TextMeshPro textMeshPro = titleText.GetComponent(); + var textMeshPro = titleText.GetComponent(); textMeshPro.alignment = TextAlignmentOptions.MidlineLeft; textMeshPro.fontStyle = FontStyles.Bold; textMeshPro.outlineWidth = 0.17f; @@ -338,18 +293,12 @@ namespace EHR [HarmonyPrefix] private static bool ValueChangedPrefix(GameOptionsMenu __instance, OptionBehaviour option) { - if (ModGameOptionsMenu.TabIndex < 3) - { - return true; - } + if (ModGameOptionsMenu.TabIndex < 3) return true; if (ModGameOptionsMenu.OptionList.TryGetValue(option, out int index)) { OptionItem item = OptionItem.AllOptions[index]; - if (item != null && item.Children.Count > 0) - { - ReCreateSettings(__instance); - } + if (item != null && item.Children.Count > 0) ReCreateSettings(__instance); } return false; @@ -357,21 +306,16 @@ namespace EHR public static void ReCreateSettings(GameOptionsMenu __instance) { - if (ModGameOptionsMenu.TabIndex < 3) - { - return; - } + if (ModGameOptionsMenu.TabIndex < 3) return; - TabGroup modTab = (TabGroup)(ModGameOptionsMenu.TabIndex - 3); + var modTab = (TabGroup)(ModGameOptionsMenu.TabIndex - 3); - float num = 2.0f; - for (int index = 0; index < OptionItem.AllOptions.Count; index++) + var num = 2.0f; + + for (var index = 0; index < OptionItem.AllOptions.Count; index++) { OptionItem option = OptionItem.AllOptions[index]; - if (option.Tab != modTab) - { - continue; - } + if (option.Tab != modTab) continue; bool enabled = !option.IsHiddenOn(Options.CurrentGameMode) && (option.Parent == null || (!option.Parent.IsHiddenOn(Options.CurrentGameMode) && option.Parent.GetBool())); @@ -379,32 +323,20 @@ namespace EHR { categoryHeaderMasked.transform.localPosition = new(-0.903f, num, -2f); categoryHeaderMasked.gameObject.SetActive(enabled); - if (enabled) - { - num -= 0.63f; - } - } - else if (option.IsHeader && enabled) - { - num -= 0.25f; + if (enabled) num -= 0.63f; } + else if (option.IsHeader && enabled) num -= 0.25f; if (ModGameOptionsMenu.BehaviourList.TryGetValue(index, out OptionBehaviour optionBehaviour)) { optionBehaviour.transform.localPosition = new(0.952f, num, -2f); optionBehaviour.gameObject.SetActive(enabled); - if (enabled) - { - num -= 0.45f; - } + if (enabled) num -= 0.45f; } } __instance.ControllerSelectable.Clear(); - foreach (UiElement x in __instance.scrollBar.GetComponentsInChildren()) - { - __instance.ControllerSelectable.Add(x); - } + foreach (UiElement x in __instance.scrollBar.GetComponentsInChildren()) __instance.ControllerSelectable.Add(x); __instance.scrollBar.SetYBoundsMax(-num - 1.65f); } @@ -412,15 +344,16 @@ namespace EHR private static BaseGameSetting GetSetting(OptionItem item) { BaseGameSetting baseGameSetting; + switch (item) { case BooleanOptionItem: - CheckboxGameSetting checkboxGameSetting = ScriptableObject.CreateInstance(); + var checkboxGameSetting = ScriptableObject.CreateInstance(); checkboxGameSetting.Type = OptionTypes.Checkbox; baseGameSetting = checkboxGameSetting; break; case IntegerOptionItem integerOptionItem: - IntGameSetting intGameSetting = ScriptableObject.CreateInstance(); + var intGameSetting = ScriptableObject.CreateInstance(); intGameSetting.Type = OptionTypes.Int; intGameSetting.Value = integerOptionItem.GetInt(); intGameSetting.Increment = integerOptionItem.Rule.Step; @@ -431,7 +364,7 @@ namespace EHR baseGameSetting = intGameSetting; break; case FloatOptionItem floatOptionItem: - FloatGameSetting floatGameSetting = ScriptableObject.CreateInstance(); + var floatGameSetting = ScriptableObject.CreateInstance(); floatGameSetting.Type = OptionTypes.Float; floatGameSetting.Value = floatOptionItem.GetFloat(); floatGameSetting.Increment = floatOptionItem.Rule.Step; @@ -442,14 +375,14 @@ namespace EHR baseGameSetting = floatGameSetting; break; case StringOptionItem stringOptionItem: - StringGameSetting stringGameSetting = ScriptableObject.CreateInstance(); + var stringGameSetting = ScriptableObject.CreateInstance(); stringGameSetting.Type = OptionTypes.String; stringGameSetting.Values = new StringNames[stringOptionItem.Selections.Count]; stringGameSetting.Index = stringOptionItem.GetInt(); baseGameSetting = stringGameSetting; break; case PresetOptionItem presetOptionItem: - IntGameSetting presetIntGameSetting = ScriptableObject.CreateInstance(); + var presetIntGameSetting = ScriptableObject.CreateInstance(); presetIntGameSetting.Type = OptionTypes.Int; presetIntGameSetting.Value = presetOptionItem.GetInt(); presetIntGameSetting.Increment = presetOptionItem.Rule.Step; @@ -464,10 +397,7 @@ namespace EHR break; } - if (baseGameSetting != null) - { - baseGameSetting.Title = StringNames.Accept; - } + if (baseGameSetting != null) baseGameSetting.Title = StringNames.Accept; return baseGameSetting; } @@ -475,13 +405,12 @@ namespace EHR public static void ReloadUI(int index) { GameSettingMenu.Instance?.Close(); + LateTask.New(() => { - if (GameStates.IsLobby) - { - GameObject.Find("Host Buttons")?.transform.FindChild("Edit")?.GetComponent()?.ReceiveClickDown(); - } + if (GameStates.IsLobby) GameObject.Find("Host Buttons")?.transform.FindChild("Edit")?.GetComponent()?.ReceiveClickDown(); }, 0.1f, log: false); + LateTask.New(() => { if (GameStates.IsLobby) @@ -535,15 +464,9 @@ namespace EHR { get { - if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) - { - return 5; - } + if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) return 5; - if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) - { - return 10; - } + if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) return 10; return 1; } @@ -579,10 +502,7 @@ namespace EHR case StringNames.GameNumImpostors: __instance.ValidRange = new(1, Crowded.MaxImpostors); __instance.Value = (float)Math.Round(__instance.Value, 2); - if (DebugModeManager.AmDebugger) - { - __instance.ValidRange.min = 0; - } + if (DebugModeManager.AmDebugger) __instance.ValidRange.min = 0; break; } @@ -650,10 +570,7 @@ namespace EHR private static string GetValueString(NumberOption __instance, float value, OptionItem item) { - if (__instance.ZeroIsInfinity && Mathf.Abs(value) < 0.0001f) - { - return "∞"; - } + if (__instance.ZeroIsInfinity && Mathf.Abs(value) < 0.0001f) return "∞"; return item == null ? value.ToString(__instance.FormatString) : item.GetString(); } @@ -671,6 +588,7 @@ namespace EHR } float increment = IncrementMultiplier * __instance.Increment; + if (__instance.Value + increment < __instance.ValidRange.max) { __instance.Value += increment; @@ -695,6 +613,7 @@ namespace EHR } float increment = IncrementMultiplier * __instance.Increment; + if (__instance.Value - increment > __instance.ValidRange.min) { __instance.Value -= increment; @@ -720,28 +639,17 @@ namespace EHR string name = item.GetName(); item.OptionBehaviour = __instance; string name1 = name; + if (Enum.GetValues().FindFirst(x => Translator.GetString($"{x}") == name1.RemoveHtmlTags(), out CustomRoles role)) { - if (role.ToString().Contains("GuardianAngel")) - { - role = CustomRoles.GA; - } + if (role.ToString().Contains("GuardianAngel")) role = CustomRoles.GA; name = name.RemoveHtmlTags(); - if (Options.UsePets.GetBool() && role.PetActivatedAbility()) - { - name += Translator.GetString("SupportsPetIndicator"); - } + if (Options.UsePets.GetBool() && role.PetActivatedAbility()) name += Translator.GetString("SupportsPetIndicator"); - if (!Options.UsePets.GetBool() && role.OnlySpawnsWithPets()) - { - name += Translator.GetString("RequiresPetIndicator"); - } + if (!Options.UsePets.GetBool() && role.OnlySpawnsWithPets()) name += Translator.GetString("RequiresPetIndicator"); - if (role.IsGhostRole()) - { - name += GetGhostRoleTeam(role); - } + if (role.IsGhostRole()) name += GetGhostRoleTeam(role); __instance.TitleText.fontWeight = FontWeight.Black; __instance.TitleText.outlineColor = new(255, 255, 255, 255); @@ -764,23 +672,26 @@ namespace EHR Transform template = option.transform.FindChild("MinusButton"); Transform icon = Object.Instantiate(template, template.parent, true); icon.name = $"{role}HelpIcon"; - TextMeshPro text = icon.GetComponentInChildren(); + var text = icon.GetComponentInChildren(); text.text = "?"; text.color = Color.white; icon.FindChild("ButtonSprite").GetComponent().color = Color.black; - GameOptionButton gameOptionButton = icon.GetComponent(); + var gameOptionButton = icon.GetComponent(); gameOptionButton.OnClick = new(); + gameOptionButton.OnClick.AddListener((Action)(() => { if (ModGameOptionsMenu.OptionList.TryGetValue(option, out int index)) { OptionItem item = OptionItem.AllOptions[index]; string name = item.GetName(); + if (Enum.GetValues().FindFirst(x => Translator.GetString($"{x}") == name.RemoveHtmlTags(), out CustomRoles value)) { string roleName = value.IsVanilla() ? value + "EHR" : value.ToString(); string str = Translator.GetString($"{roleName}InfoLong"); string infoLong; + try { infoLong = HnSManager.AllHnSRoles.Contains(value) ? str : str[(str.IndexOf('\n') + 1)..str.Split("\n\n")[0].Length]; @@ -790,11 +701,12 @@ namespace EHR infoLong = str; } - string info = $"{value.ToColoredString()}: {infoLong}"; + var info = $"{value.ToColoredString()}: {infoLong}"; GameSettingMenu.Instance.MenuDescriptionText.text = info; } } })); + gameOptionButton.interactableColor = Color.black; gameOptionButton.interactableHoveredColor = Color.blue; icon.localPosition += new Vector3(-0.8f, 0f, 0f); @@ -804,16 +716,10 @@ namespace EHR private static string GetGhostRoleTeam(CustomRoles role) { IGhostRole instance = GhostRolesManager.CreateGhostRoleInstance(role); - if (instance == null) - { - return string.Empty; - } + if (instance == null) return string.Empty; Team team = instance.Team; - if ((int)team is 1 or 2 or 4) - { - return $" {GetColoredShortTeamName(team)}"; - } + if ((int)team is 1 or 2 or 4) return $" {GetColoredShortTeamName(team)}"; Team[] teams = (int)team switch { @@ -823,6 +729,7 @@ namespace EHR 7 => [Team.Impostor, Team.Neutral, Team.Crewmate], _ => [] }; + return $" {string.Join('/', teams.Select(GetColoredShortTeamName))}"; string GetColoredShortTeamName(Team t) @@ -840,34 +747,20 @@ namespace EHR OptionItem item = OptionItem.AllOptions[index]; item.SetValue(__instance.GetInt()); string name = item.GetName(); - if (item.Name == "GameMode") - { - GameOptionsMenuPatch.ReloadUI(ModGameOptionsMenu.TabIndex); - } + if (item.Name == "GameMode") GameOptionsMenuPatch.ReloadUI(ModGameOptionsMenu.TabIndex); string name1 = name; + if (Enum.GetValues().FindFirst(x => Translator.GetString($"{x}") == name1.RemoveHtmlTags(), out CustomRoles role)) { - if (role.ToString().Contains("GuardianAngel")) - { - role = CustomRoles.GA; - } + if (role.ToString().Contains("GuardianAngel")) role = CustomRoles.GA; name = name.RemoveHtmlTags(); - if (Options.UsePets.GetBool() && role.PetActivatedAbility()) - { - name += Translator.GetString("SupportsPetIndicator"); - } + if (Options.UsePets.GetBool() && role.PetActivatedAbility()) name += Translator.GetString("SupportsPetIndicator"); - if (!Options.UsePets.GetBool() && role.OnlySpawnsWithPets()) - { - name += Translator.GetString("RequiresPetIndicator"); - } + if (!Options.UsePets.GetBool() && role.OnlySpawnsWithPets()) name += Translator.GetString("RequiresPetIndicator"); - if (role.IsGhostRole()) - { - name += GetGhostRoleTeam(role); - } + if (role.IsGhostRole()) name += GetGhostRoleTeam(role); __instance.TitleText.fontWeight = FontWeight.Black; __instance.TitleText.outlineColor = new(255, 255, 255, 255); @@ -878,9 +771,7 @@ namespace EHR NotificationPopperPatch.AddRoleSettingsChangeMessage(index, item, role, true); } else - { NotificationPopperPatch.AddSettingsChangeMessage(index, item, true); - } __instance.TitleText.text = name; return false; @@ -903,6 +794,7 @@ namespace EHR if (__instance.oldValue != __instance.Value) { __instance.oldValue = __instance.Value; + __instance.ValueText.text = stringOptionItem.noTranslation ? stringOptionItem.Selections[stringOptionItem.Rule.GetValueByIndex(__instance.Value)] : Translator.GetString(stringOptionItem.Selections[stringOptionItem.Rule.GetValueByIndex(__instance.Value)]); @@ -974,12 +866,13 @@ namespace EHR public static void StartPostfix(GameSettingMenu __instance) { ModSettingsButtons = []; + foreach (TabGroup tab in Enum.GetValues()) { PassiveButton button = Object.Instantiate(TemplateGameSettingsButton, __instance.GameSettingsButton.transform.parent); button.gameObject.SetActive(true); button.name = "Button_" + tab; - TextMeshPro label = button.GetComponentInChildren(); + var label = button.GetComponentInChildren(); label.DestroyTranslator(); label.text = Translator.GetString($"TabGroup.{tab}"); label.color = Color.white; @@ -1002,6 +895,7 @@ namespace EHR TabGroup.OtherRoles => new(0.4f, 0.4f, 0.4f), _ => new(0.3f, 0.3f, 0.3f) }; + button.inactiveSprites.GetComponent().color = color; button.activeSprites.GetComponent().color = color; button.selectedSprites.GetComponent().color = color; @@ -1011,7 +905,7 @@ namespace EHR button.transform.localPosition = (((int)tab + 1) % 2 == 0 ? ButtonPositionLeft : ButtonPositionRight) - offset; button.transform.localScale = ButtonSize; - PassiveButton buttonComponent = button.GetComponent(); + var buttonComponent = button.GetComponent(); buttonComponent.OnClick = new(); buttonComponent.OnClick.AddListener((Action)(() => __instance.ChangeTab((int)tab + 3, false))); @@ -1019,6 +913,7 @@ namespace EHR } ModSettingsTabs = []; + foreach (TabGroup tab in Enum.GetValues()) { GameOptionsMenu setTab = Object.Instantiate(TemplateGameOptionsMenu, __instance.GameSettingsTab.transform.parent); @@ -1029,12 +924,8 @@ namespace EHR } foreach (TabGroup tab in Enum.GetValues()) - { if (ModSettingsButtons.TryGetValue(tab, out PassiveButton button)) - { __instance.ControllerSelectable.Add(button); - } - } HiddenBySearch.Do(x => x.SetHidden(false)); HiddenBySearch.Clear(); @@ -1050,11 +941,11 @@ namespace EHR preset.transform.localPosition = new(-1.83f, 0.1f, -2f); preset.transform.localScale = new(0.65f, 0.63f, 1f); - SpriteRenderer renderer = preset.GetComponentInChildren(); + var renderer = preset.GetComponentInChildren(); renderer.color = Color.white; renderer.sprite = null; - TextMeshPro presetTmp = preset.GetComponentInChildren(); + var presetTmp = preset.GetComponentInChildren(); presetTmp.DestroyTranslator(); presetTmp.text = Translator.GetString($"Preset_{OptionItem.CurrentPreset + 1}"); @@ -1068,7 +959,7 @@ namespace EHR gMinus.gameObject.SetActive(true); gMinus.transform.localScale = new(0.08f, 0.4f, 1f); - TextMeshPro mLabel = gMinus.transform.Find("FontPlacer/Text_TMP").GetComponent(); + var mLabel = gMinus.transform.Find("FontPlacer/Text_TMP").GetComponent(); mLabel.alignment = TextAlignmentOptions.Center; mLabel.DestroyTranslator(); mLabel.text = "-"; @@ -1077,17 +968,16 @@ namespace EHR mLabel.SetFaceColor(new Color(255f, 255f, 255f)); mLabel.transform.localScale = new(12f, 4f, 1f); - PassiveButton minus = gMinus.GetComponent(); + var minus = gMinus.GetComponent(); minus.OnClick.RemoveAllListeners(); + minus.OnClick.AddListener((Action)(() => { - if (PresetBehaviour == null) - { - __instance.ChangeTab(3, false); - } + if (PresetBehaviour == null) __instance.ChangeTab(3, false); PresetBehaviour.Decrease(); })); + minus.activeTextColor = minus.inactiveTextColor = minus.disabledTextColor = minus.selectedTextColor = Color.white; minus.transform.localPosition = new(-2f, -3.37f, -4f); @@ -1101,7 +991,7 @@ namespace EHR GameObject plusFab = Object.Instantiate(gMinus, preset.transform); - TextMeshPro plusLabel = plusFab.transform.Find("FontPlacer/Text_TMP").GetComponent(); + var plusLabel = plusFab.transform.Find("FontPlacer/Text_TMP").GetComponent(); plusLabel.alignment = TextAlignmentOptions.Center; plusLabel.DestroyTranslator(); plusLabel.text = "+"; @@ -1109,30 +999,27 @@ namespace EHR plusLabel.transform.localPosition = new(plusLabel.transform.localPosition.x, plusLabel.transform.localPosition.y + 0.26f, plusLabel.transform.localPosition.z); plusLabel.transform.localScale = new(18f, 4f, 1f); - PassiveButton plus = plusFab.GetComponent(); + var plus = plusFab.GetComponent(); plus.OnClick.RemoveAllListeners(); + plus.OnClick.AddListener((Action)(() => { - if (PresetBehaviour == null) - { - __instance.ChangeTab(3, false); - } + if (PresetBehaviour == null) __instance.ChangeTab(3, false); PresetBehaviour.Increase(); })); + plus.activeTextColor = plus.inactiveTextColor = plus.disabledTextColor = plus.selectedTextColor = Color.white; plus.transform.localPosition = new(-0.4f, -3.37f, -4f); - TextMeshPro gameSettingsLabel = __instance.GameSettingsButton.transform.parent.parent.FindChild("GameSettingsLabel").GetComponent(); + var gameSettingsLabel = __instance.GameSettingsButton.transform.parent.parent.FindChild("GameSettingsLabel").GetComponent(); gameSettingsLabel.DestroyTranslator(); string gameModeText = Translator.GetString($"Mode{Options.CurrentGameMode}").Split(':').Last().TrimStart(' '); - if (gameModeText.Length >= 15) - { - gameModeText = $"{gameModeText}"; - } + if (gameModeText.Length >= 15) gameModeText = $"{gameModeText}"; gameSettingsLabel.text = gameModeText; + if (russian) { gameSettingsLabel.transform.localScale = new(0.7f, 0.7f, 1f); @@ -1145,7 +1032,7 @@ namespace EHR gmCycler.transform.localScale = new(0.25f, 0.7f, 1f); gmCycler.transform.localPosition = new(gameSettingsLabelPos.x + 0.8f, gameSettingsLabelPos.y - 2.9f, gameSettingsLabelPos.z); - TextMeshPro gmTmp = gmCycler.transform.Find("FontPlacer/Text_TMP").GetComponent(); + var gmTmp = gmCycler.transform.Find("FontPlacer/Text_TMP").GetComponent(); gmTmp.alignment = TextAlignmentOptions.Center; gmTmp.DestroyTranslator(); gmTmp.text = "\u21c4"; @@ -1154,17 +1041,16 @@ namespace EHR gmTmp.transform.localPosition = new(gameSettingsLabelPos.x + Offset2, gameSettingsLabelPos.y - 1.52f, gameSettingsLabelPos.z); gmTmp.transform.localScale = new(4f, 1.5f, 1f); - PassiveButton cycle = gmCycler.GetComponent(); + var cycle = gmCycler.GetComponent(); cycle.OnClick.RemoveAllListeners(); + cycle.OnClick.AddListener((Action)(() => { - if (GameModeBehaviour == null) - { - __instance.ChangeTab(4, false); - } + if (GameModeBehaviour == null) __instance.ChangeTab(4, false); GameModeBehaviour.Increase(); })); + float Offset = !russian ? 1.15f : 2.25f; cycle.activeTextColor = cycle.inactiveTextColor = cycle.disabledTextColor = cycle.selectedTextColor = Color.white; cycle.transform.localPosition = new(Offset, 0.08f, 1f); @@ -1199,27 +1085,21 @@ namespace EHR } - PassiveButton passiveButton = button.GetComponent(); + var passiveButton = button.GetComponent(); passiveButton.OnClick = new(); passiveButton.OnClick.AddListener((Action)(() => SearchForOptions(field))); SearchForOptionsAction = () => { - if (field.textArea.text != string.Empty) - { - SearchForOptions(field); - } + if (field.textArea.text != string.Empty) SearchForOptions(field); }; return; static void SearchForOptions(FreeChatInputField textField) { - if (ModGameOptionsMenu.TabIndex < 3) - { - return; - } + if (ModGameOptionsMenu.TabIndex < 3) return; HiddenBySearch.Do(x => x.SetHidden(false)); string text = textField.textArea.text.Trim().ToLower(); @@ -1248,7 +1128,7 @@ namespace EHR PassiveButton gameSettingButton = __instance.GameSettingsButton; gameSettingButton.transform.localPosition = new(-3f, -0.4f, 0f); - TextMeshPro textLabel = gameSettingButton.GetComponentInChildren(); + var textLabel = gameSettingButton.GetComponentInChildren(); textLabel.DestroyTranslator(); textLabel.text = Translator.GetString("TabGroup.VanillaSettings"); @@ -1276,18 +1156,12 @@ namespace EHR if (HiddenBySearch.Any()) { HiddenBySearch.Do(x => x.SetHidden(false)); - if (ModSettingsTabs.TryGetValue((TabGroup)(ModGameOptionsMenu.TabIndex - 3), out GameOptionsMenu GameSettings) && GameSettings != null) - { - GameOptionsMenuPatch.ReCreateSettings(GameSettings); - } + if (ModSettingsTabs.TryGetValue((TabGroup)(ModGameOptionsMenu.TabIndex - 3), out GameOptionsMenu GameSettings) && GameSettings != null) GameOptionsMenuPatch.ReCreateSettings(GameSettings); HiddenBySearch.Clear(); } - if (!previewOnly || tabNum != 1) - { - ModGameOptionsMenu.TabIndex = tabNum; - } + if (!previewOnly || tabNum != 1) ModGameOptionsMenu.TabIndex = tabNum; GameOptionsMenu settingsTab; PassiveButton button; @@ -1295,28 +1169,18 @@ namespace EHR if ((previewOnly && Controller.currentTouchType == Controller.TouchType.Joystick) || !previewOnly) { foreach (TabGroup tab in Enum.GetValues()) - { if (ModSettingsTabs.TryGetValue(tab, out settingsTab) && settingsTab != null) - { settingsTab.gameObject.SetActive(false); - } - } foreach (TabGroup tab in Enum.GetValues()) - { if (ModSettingsButtons.TryGetValue(tab, out button) && button != null) - { button.SelectButton(false); - } - } } - if (tabNum < 3) - { - return true; - } + if (tabNum < 3) return true; + + var tabGroup = (TabGroup)(tabNum - 3); - TabGroup tabGroup = (TabGroup)(tabNum - 3); if ((previewOnly && Controller.currentTouchType == Controller.TouchType.Joystick) || !previewOnly) { __instance.PresetsTab.gameObject.SetActive(false); @@ -1344,10 +1208,7 @@ namespace EHR __instance.ToggleLeftSideDarkener(true); __instance.ToggleRightSideDarkener(false); - if (ModSettingsButtons.TryGetValue(tabGroup, out button) && button != null) - { - button.SelectButton(true); - } + if (ModSettingsButtons.TryGetValue(tabGroup, out button) && button != null) button.SelectButton(true); return false; } @@ -1376,10 +1237,7 @@ namespace EHR ControllerManager.Instance.OpenOverlayMenu(__instance.name, __instance.BackButton, __instance.DefaultButtonSelected, __instance.ControllerSelectable); DestroyableSingleton.Instance.menuNavigationPrompts.SetActive(false); - if (Controller.currentTouchType != Controller.TouchType.Joystick) - { - __instance.ChangeTab(1, false); - } + if (Controller.currentTouchType != Controller.TouchType.Joystick) __instance.ChangeTab(1, false); __instance.StartCoroutine(__instance.CoSelectDefault()); @@ -1390,15 +1248,9 @@ namespace EHR [HarmonyPostfix] public static void ClosePostfix() { - foreach (PassiveButton button in ModSettingsButtons.Values) - { - Object.Destroy(button); - } + foreach (PassiveButton button in ModSettingsButtons.Values) Object.Destroy(button); - foreach (GameOptionsMenu tab in ModSettingsTabs.Values) - { - Object.Destroy(tab); - } + foreach (GameOptionsMenu tab in ModSettingsTabs.Values) Object.Destroy(tab); ModSettingsButtons = []; ModSettingsTabs = []; @@ -1427,12 +1279,10 @@ namespace EHR { public static void Postfix() { - if (!GameSettingMenu.Instance) - { - return; - } + if (!GameSettingMenu.Instance) return; FreeChatInputField field = GameSettingMenuPatch.InputField; + if (field != null) { field.background.color = new Color32(40, 40, 40, byte.MaxValue); diff --git a/Patches/GameOptionsPatch.cs b/Patches/GameOptionsPatch.cs index 49ce9fb71..55c138c88 100644 --- a/Patches/GameOptionsPatch.cs +++ b/Patches/GameOptionsPatch.cs @@ -11,10 +11,7 @@ namespace EHR.Patches public static bool Prefix(GameModes gameMode) { - if ((!AmongUsClient.Instance.AmHost && PlayerControl.LocalPlayer != null) || gameMode != GameModes.HideNSeek || Warned) - { - return true; - } + if ((!AmongUsClient.Instance.AmHost && PlayerControl.LocalPlayer != null) || gameMode != GameModes.HideNSeek || Warned) return true; HudManager.Instance.ShowPopUp(Translator.GetString("HnSUnloadWarning")); return false; @@ -22,10 +19,7 @@ namespace EHR.Patches public static void Postfix(GameModes gameMode) { - if ((!AmongUsClient.Instance.AmHost && PlayerControl.LocalPlayer != null) || gameMode != GameModes.HideNSeek) - { - return; - } + if ((!AmongUsClient.Instance.AmHost && PlayerControl.LocalPlayer != null) || gameMode != GameModes.HideNSeek) return; if (!Warned) { diff --git a/Patches/GameStartManagerPatch.cs b/Patches/GameStartManagerPatch.cs index 370f91de1..70ab06255 100644 --- a/Patches/GameStartManagerPatch.cs +++ b/Patches/GameStartManagerPatch.cs @@ -45,10 +45,7 @@ namespace EHR { try { - if (__instance == null) - { - return; - } + if (__instance == null) return; TextMeshPro temp = __instance.PlayerCounter; GameCountdown = Object.Instantiate(temp, AmongUsClient.Instance.AmHost ? __instance.StartButton.transform : __instance.HostInfoPanel.transform); @@ -72,24 +69,19 @@ namespace EHR __instance.HostViewButton.inactiveSprites.transform.Find("Shine").GetComponent().color = new(0f, 1f, 1f, 0.5f); } - if (AmongUsClient.Instance == null || AmongUsClient.Instance.IsGameStarted || GameStates.IsInGame || __instance.startState == GameStartManager.StartingStates.Starting) - { - return; - } + if (AmongUsClient.Instance == null || AmongUsClient.Instance.IsGameStarted || GameStates.IsInGame || __instance.startState == GameStartManager.StartingStates.Starting) return; __instance.GameRoomNameCode.text = GameCode.IntToGameName(AmongUsClient.Instance.GameId); // Reset lobby countdown timer Timer = 600f; HideName = Object.Instantiate(__instance.GameRoomNameCode, __instance.GameRoomNameCode.transform); + HideName.text = ColorUtility.TryParseHtmlString(Main.HideColor.Value, out _) ? $"{Main.HideName.Value}" : $"{Main.HideName.Value}"; - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; if (ModUpdater.IsBroken || (ModUpdater.HasUpdate && ModUpdater.ForceUpdate) || !Main.AllowPublicRoom) { @@ -97,16 +89,10 @@ namespace EHR // __instance.privatePublicText.color = Palette.DisabledClear; } - if (Main.NormalOptions.KillCooldown == 0f) - { - Main.NormalOptions.KillCooldown = Main.LastKillCooldown.Value; - } + if (Main.NormalOptions.KillCooldown == 0f) Main.NormalOptions.KillCooldown = Main.LastKillCooldown.Value; AURoleOptions.SetOpt(Main.NormalOptions.Cast()); - if (AURoleOptions.ShapeshifterCooldown == 0f) - { - AURoleOptions.ShapeshifterCooldown = Main.LastShapeshifterCooldown.Value; - } + if (AURoleOptions.ShapeshifterCooldown == 0f) AURoleOptions.ShapeshifterCooldown = Main.LastShapeshifterCooldown.Value; AURoleOptions.GuardianAngelCooldown = Spiritcaller.SpiritAbilityCooldown.GetFloat(); AURoleOptions.ProtectionDurationSeconds = 0f; @@ -129,66 +115,45 @@ namespace EHR { try { - if (AmongUsClient.Instance == null) - { - return false; - } + if (AmongUsClient.Instance == null) return false; - if (AmongUsClient.Instance.AmHost) - { - VanillaUpdate(__instance); - } + if (AmongUsClient.Instance.AmHost) VanillaUpdate(__instance); - if (AmongUsClient.Instance.IsGameStarted || GameStates.IsInGame || __instance == null || __instance.startState == GameStartManager.StartingStates.Starting) - { - return false; - } + if (AmongUsClient.Instance.IsGameStarted || GameStates.IsInGame || __instance == null || __instance.startState == GameStartManager.StartingStates.Starting) return false; MinWait = Options.MinWaitAutoStart.GetFloat(); MaxWait = Options.MaxWaitAutoStart.GetFloat(); MinPlayer = Options.PlayerAutoStart.GetInt(); MinWait = 600f - (MinWait * 60f); MaxWait *= 60f; + // Lobby code if (DataManager.Settings != null && DataManager.Settings.Gameplay != null) { if (DataManager.Settings.Gameplay.StreamerMode) { - if (__instance != null && __instance.GameRoomNameCode != null) - { - __instance.GameRoomNameCode.color = new(255, 255, 255, 0); - } + if (__instance != null && __instance.GameRoomNameCode != null) __instance.GameRoomNameCode.color = new(255, 255, 255, 0); - if (GameStartManagerStartPatch.HideName != null) - { - GameStartManagerStartPatch.HideName.enabled = true; - } + if (GameStartManagerStartPatch.HideName != null) GameStartManagerStartPatch.HideName.enabled = true; } else { - if (__instance != null && __instance.GameRoomNameCode != null) - { - __instance.GameRoomNameCode.color = new(255, 255, 255, 255); - } + if (__instance != null && __instance.GameRoomNameCode != null) __instance.GameRoomNameCode.color = new(255, 255, 255, 255); - if (GameStartManagerStartPatch.HideName != null) - { - GameStartManagerStartPatch.HideName.enabled = false; - } + if (GameStartManagerStartPatch.HideName != null) GameStartManagerStartPatch.HideName.enabled = false; } } - if (AmongUsClient.Instance == null || GameData.Instance == null || !AmongUsClient.Instance.AmHost || !GameData.Instance) - { - return true; - } + if (AmongUsClient.Instance == null || GameData.Instance == null || !AmongUsClient.Instance.AmHost || !GameData.Instance) return true; if (Main.AutoStart != null && Main.AutoStart.Value) { Main.UpdateTime++; + if (Main.UpdateTime >= 50) { Main.UpdateTime = 0; + if (((GameData.Instance?.PlayerCount >= MinPlayer && Timer <= MinWait) || Timer <= MaxWait) && !GameStates.IsCountDown) { PlayerControl[] invalidColor = Main.AllPlayerControls.Where(p => p.Data.DefaultOutfit.ColorId < 0 || Palette.PlayerColors.Length <= p.Data.DefaultOutfit.ColorId).ToArray(); @@ -210,14 +175,11 @@ namespace EHR Main.NormalOptions.MapId = GameStartRandomMap.SelectRandomMap(); CreateOptionsPickerPatch.SetDleks = Main.CurrentMap == MapNames.Dleks; } - else if (CreateOptionsPickerPatch.SetDleks) - { - Main.NormalOptions.MapId = 3; - } + else if (CreateOptionsPickerPatch.SetDleks) Main.NormalOptions.MapId = 3; if (Main.CurrentMap == MapNames.Dleks) { - IGameOptions opt = Main.NormalOptions.Cast(); + var opt = Main.NormalOptions.Cast(); Options.DefaultKillCooldown = Main.NormalOptions.KillCooldown; Main.LastKillCooldown.Value = Main.NormalOptions.KillCooldown; @@ -239,9 +201,7 @@ namespace EHR } } } - catch (NullReferenceException) - { - } + catch (NullReferenceException) { } catch (Exception ex) { Logger.Error(ex.ToString(), "GameStartManagerUpdatePatch.Prefix (2)"); @@ -252,10 +212,7 @@ namespace EHR private static void VanillaUpdate(GameStartManager instance) { - if (!GameData.Instance || !GameManager.Instance || !AmongUsClient.Instance.AmHost) - { - return; - } + if (!GameData.Instance || !GameManager.Instance || !AmongUsClient.Instance.AmHost) return; try { @@ -270,54 +227,37 @@ namespace EHR instance.CheckSettingsDiffs(); instance.StartButton.gameObject.SetActive(true); instance.RulesPresetText.text = DestroyableSingleton.Instance.GetString(GameOptionsManager.Instance.CurrentGameOptions.GetRulesPresetTitle()); + if (GameCode.IntToGameName(AmongUsClient.Instance.GameId) == null) - { instance.privatePublicPanelText.text = DestroyableSingleton.Instance.GetString(StringNames.LocalButton); - } else if (AmongUsClient.Instance.IsGamePublic) - { instance.privatePublicPanelText.text = DestroyableSingleton.Instance.GetString(StringNames.PublicHeader); - } else - { instance.privatePublicPanelText.text = DestroyableSingleton.Instance.GetString(StringNames.PrivateHeader); - } instance.HostPrivateButton.gameObject.SetActive(!AmongUsClient.Instance.IsGamePublic); instance.HostPublicButton.gameObject.SetActive(AmongUsClient.Instance.IsGamePublic); - if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && Input.GetKeyDown(KeyCode.C)) - { - ClipboardHelper.PutClipboardString(GameCode.IntToGameName(AmongUsClient.Instance.GameId)); - } + if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && Input.GetKeyDown(KeyCode.C)) ClipboardHelper.PutClipboardString(GameCode.IntToGameName(AmongUsClient.Instance.GameId)); if (GameData.Instance.PlayerCount != instance.LastPlayerCount) { instance.LastPlayerCount = GameData.Instance.PlayerCount; - string text = ""; - if (instance.LastPlayerCount > instance.MinPlayers) - { - text = ""; - } + var text = ""; + if (instance.LastPlayerCount > instance.MinPlayers) text = ""; - if (instance.LastPlayerCount == instance.MinPlayers) - { - text = ""; - } + if (instance.LastPlayerCount == instance.MinPlayers) text = ""; instance.PlayerCounter.text = $"{text}{instance.LastPlayerCount}/{(AmongUsClient.Instance.NetworkMode == NetworkModes.LocalGame ? 15 : GameManager.Instance.LogicOptions.MaxPlayers)}"; instance.StartButton.SetButtonEnableState(instance.LastPlayerCount >= instance.MinPlayers); ActionMapGlyphDisplay startButtonGlyph = instance.StartButtonGlyph; startButtonGlyph?.SetColor(instance.LastPlayerCount >= instance.MinPlayers ? Palette.EnabledColor : Palette.DisabledClear); + if (DestroyableSingleton.InstanceExists) { if (AmongUsClient.Instance.AmHost && AmongUsClient.Instance.NetworkMode == NetworkModes.OnlineGame) - { DestroyableSingleton.Instance.SetInLobbyHost(instance.LastPlayerCount, GameManager.Instance.LogicOptions.MaxPlayers, AmongUsClient.Instance.GameId); - } else - { DestroyableSingleton.Instance.SetInLobbyClient(instance.LastPlayerCount, GameManager.Instance.LogicOptions.MaxPlayers, AmongUsClient.Instance.GameId); - } } } @@ -334,22 +274,13 @@ namespace EHR int num = Mathf.CeilToInt(instance.countDownTimer); instance.countDownTimer -= Time.deltaTime; int num2 = Mathf.CeilToInt(instance.countDownTimer); - if (!instance.GameStartTextParent.activeSelf) - { - SoundManager.Instance.PlaySound(instance.gameStartSound, false); - } + if (!instance.GameStartTextParent.activeSelf) SoundManager.Instance.PlaySound(instance.gameStartSound, false); instance.GameStartTextParent.SetActive(true); instance.GameStartText.text = DestroyableSingleton.Instance.GetString(StringNames.GameStarting, num2); - if (num != num2) - { - PlayerControl.LocalPlayer.RpcSetStartCounter(num2); - } + if (num != num2) PlayerControl.LocalPlayer.RpcSetStartCounter(num2); - if (num2 <= 0) - { - instance.FinallyBegin(); - } + if (num2 <= 0) instance.FinallyBegin(); } else { @@ -363,10 +294,7 @@ namespace EHR } } - if (instance.LobbyInfoPane.gameObject.activeSelf && DestroyableSingleton.Instance.Chat.IsOpenOrOpening) - { - instance.LobbyInfoPane.DeactivatePane(); - } + if (instance.LobbyInfoPane.gameObject.activeSelf && DestroyableSingleton.Instance.Chat.IsOpenOrOpening) instance.LobbyInfoPane.DeactivatePane(); instance.LobbyInfoPane.gameObject.SetActive(!DestroyableSingleton.Instance.Chat.IsOpenOrOpening); } @@ -375,47 +303,32 @@ namespace EHR { try { - if (AmongUsClient.Instance == null || AmongUsClient.Instance.IsGameStarted || GameStates.IsInGame || __instance == null || __instance.startState == GameStartManager.StartingStates.Starting) - { - return; - } + if (AmongUsClient.Instance == null || AmongUsClient.Instance.IsGameStarted || GameStates.IsInGame || __instance == null || __instance.startState == GameStartManager.StartingStates.Starting) return; if (AmongUsClient.Instance.AmHost) { - bool canStartGame = true; + var canStartGame = true; + foreach (ClientData client in AmongUsClient.Instance.allClients) { - if (client.Character == null) - { - continue; - } + if (client.Character == null) continue; - DummyBehaviour dummyComponent = client.Character.GetComponent(); - if (dummyComponent != null && dummyComponent.enabled) - { - continue; - } + var dummyComponent = client.Character.GetComponent(); + if (dummyComponent != null && dummyComponent.enabled) continue; - if (!MatchVersions(client.Character.PlayerId, true)) - { - canStartGame = false; - } + if (!MatchVersions(client.Character.PlayerId, true)) canStartGame = false; } - if (!canStartGame) - { - __instance.StartButton.gameObject.SetActive(false); - } + if (!canStartGame) __instance.StartButton.gameObject.SetActive(false); } else { if (MatchVersions(0, true)) - { ExitTimer = 0; - } else { ExitTimer += Time.deltaTime; + if (ExitTimer >= 5) { ExitTimer = 0; @@ -428,19 +341,13 @@ namespace EHR __instance.RulesPresetText.text = GetString($"Preset_{OptionItem.CurrentPreset + 1}"); // Lobby timer - if (!GameData.Instance || AmongUsClient.Instance.NetworkMode == NetworkModes.LocalGame) - { - return; - } + if (!GameData.Instance || AmongUsClient.Instance.NetworkMode == NetworkModes.LocalGame) return; Timer = Mathf.Max(0f, Timer -= Time.deltaTime); int minutes = (int)Timer / 60; int seconds = (int)Timer % 60; - string suffix = $"{minutes:00}:{seconds:00}"; - if (Timer <= 60) - { - suffix = Utils.ColorString((int)Timer % 2 == 0 ? Color.yellow : Color.red, suffix); - } + var suffix = $"{minutes:00}:{seconds:00}"; + if (Timer <= 60) suffix = Utils.ColorString((int)Timer % 2 == 0 ? Color.yellow : Color.red, suffix); TextMeshPro tmp = GameStartManagerStartPatch.GameCountdown; @@ -459,9 +366,7 @@ namespace EHR tmp.text = suffix; } - catch (NullReferenceException) - { - } + catch (NullReferenceException) { } catch (Exception e) { Logger.Error(e.ToString(), "GameStartManagerUpdatePatch.Postfix (3)"); @@ -470,10 +375,7 @@ namespace EHR private static bool MatchVersions(byte playerId, bool acceptVanilla = false) { - if (!Main.PlayerVersion.TryGetValue(playerId, out PlayerVersion version)) - { - return acceptVanilla; - } + if (!Main.PlayerVersion.TryGetValue(playerId, out PlayerVersion version)) return acceptVanilla; return Main.ForkId == version.forkId && Main.Version.CompareTo(version.version) == 0 @@ -486,10 +388,7 @@ namespace EHR { private static void Postfix(TextBoxTMP __instance) { - if (__instance.name == "GameIdText") - { - __instance.outputText.text = new('*', __instance.text.Length); - } + if (__instance.name == "GameIdText") __instance.outputText.text = new('*', __instance.text.Length); } } } @@ -500,6 +399,7 @@ namespace EHR public static bool Prefix(GameStartManager __instance) { PlayerControl[] invalidColor = Main.AllPlayerControls.Where(p => p.Data.DefaultOutfit.ColorId < 0 || Palette.PlayerColors.Length <= p.Data.DefaultOutfit.ColorId).ToArray(); + if (invalidColor.Length > 0) { Logger.SendInGame(GetString("Error.InvalidColorPreventStart")); @@ -510,9 +410,7 @@ namespace EHR } if (__instance.startState == GameStartManager.StartingStates.Countdown) - { Main.NormalOptions.KillCooldown = Options.DefaultKillCooldown; - } else { Options.DefaultKillCooldown = Main.NormalOptions.KillCooldown; @@ -520,13 +418,11 @@ namespace EHR Main.NormalOptions.KillCooldown = 0f; } - IGameOptions opt = Main.NormalOptions.Cast(); + var opt = Main.NormalOptions.Cast(); AURoleOptions.SetOpt(opt); if (__instance.startState == GameStartManager.StartingStates.Countdown) - { AURoleOptions.ShapeshifterCooldown = Main.LastShapeshifterCooldown.Value; - } else { Main.LastShapeshifterCooldown.Value = AURoleOptions.ShapeshifterCooldown; @@ -546,48 +442,27 @@ namespace EHR Main.NormalOptions.MapId = SelectRandomMap(); CreateOptionsPickerPatch.SetDleks = Main.CurrentMap == MapNames.Dleks; } - else if (CreateOptionsPickerPatch.SetDleks) - { - Main.NormalOptions.MapId = 3; - } + else if (CreateOptionsPickerPatch.SetDleks) Main.NormalOptions.MapId = 3; } public static byte SelectRandomMap() { - IRandom rand = IRandom.Instance; + var rand = IRandom.Instance; List randomMaps = []; int tempRand = rand.Next(1, 100); - if (tempRand <= Options.SkeldChance.GetInt()) - { - randomMaps.Add(0); - } + if (tempRand <= Options.SkeldChance.GetInt()) randomMaps.Add(0); - if (tempRand <= Options.MiraChance.GetInt()) - { - randomMaps.Add(1); - } + if (tempRand <= Options.MiraChance.GetInt()) randomMaps.Add(1); - if (tempRand <= Options.PolusChance.GetInt()) - { - randomMaps.Add(2); - } + if (tempRand <= Options.PolusChance.GetInt()) randomMaps.Add(2); - if (tempRand <= Options.DleksChance.GetInt()) - { - randomMaps.Add(3); - } + if (tempRand <= Options.DleksChance.GetInt()) randomMaps.Add(3); - if (tempRand <= Options.AirshipChance.GetInt()) - { - randomMaps.Add(4); - } + if (tempRand <= Options.AirshipChance.GetInt()) randomMaps.Add(4); - if (tempRand <= Options.FungleChance.GetInt()) - { - randomMaps.Add(5); - } + if (tempRand <= Options.FungleChance.GetInt()) randomMaps.Add(5); if (randomMaps.Count > 0) { @@ -598,35 +473,17 @@ namespace EHR } else { - if (Options.SkeldChance.GetInt() > 0) - { - randomMaps.Add(0); - } + if (Options.SkeldChance.GetInt() > 0) randomMaps.Add(0); - if (Options.MiraChance.GetInt() > 0) - { - randomMaps.Add(1); - } + if (Options.MiraChance.GetInt() > 0) randomMaps.Add(1); - if (Options.PolusChance.GetInt() > 0) - { - randomMaps.Add(2); - } + if (Options.PolusChance.GetInt() > 0) randomMaps.Add(2); - if (Options.DleksChance.GetInt() > 0) - { - randomMaps.Add(3); - } + if (Options.DleksChance.GetInt() > 0) randomMaps.Add(3); - if (Options.AirshipChance.GetInt() > 0) - { - randomMaps.Add(4); - } + if (Options.AirshipChance.GetInt() > 0) randomMaps.Add(4); - if (Options.FungleChance.GetInt() > 0) - { - randomMaps.Add(5); - } + if (Options.FungleChance.GetInt() > 0) randomMaps.Add(5); byte mapsId = randomMaps.RandomElement(); @@ -668,10 +525,7 @@ namespace EHR { public static bool Prefix(GameStartManager __instance) { - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; if (__instance.startState == GameStartManager.StartingStates.Countdown) { diff --git a/Patches/HashRandomPatch.cs b/Patches/HashRandomPatch.cs index 41564a665..c56e36cbc 100644 --- a/Patches/HashRandomPatch.cs +++ b/Patches/HashRandomPatch.cs @@ -9,10 +9,7 @@ namespace EHR [HarmonyPrefix] private static bool FastNext([HarmonyArgument(0)] int maxInt, ref int __result) { - if (IRandom.Instance is HashRandomWrapper) - { - return true; - } + if (IRandom.Instance is HashRandomWrapper) return true; __result = IRandom.Instance.Next(maxInt); @@ -23,10 +20,7 @@ namespace EHR [HarmonyPrefix] private static bool MaxNext([HarmonyArgument(0)] int maxInt, ref int __result) { - if (IRandom.Instance is HashRandomWrapper) - { - return true; - } + if (IRandom.Instance is HashRandomWrapper) return true; __result = IRandom.Instance.Next(maxInt); @@ -37,10 +31,7 @@ namespace EHR [HarmonyPrefix] private static bool MinMaxNext([HarmonyArgument(0)] int minInt, [HarmonyArgument(1)] int maxInt, ref int __result) { - if (IRandom.Instance is HashRandomWrapper) - { - return true; - } + if (IRandom.Instance is HashRandomWrapper) return true; __result = IRandom.Instance.Next(minInt, maxInt); diff --git a/Patches/HideBanButtonPatch.cs b/Patches/HideBanButtonPatch.cs index cc7fe8087..d13beb58e 100644 --- a/Patches/HideBanButtonPatch.cs +++ b/Patches/HideBanButtonPatch.cs @@ -7,10 +7,7 @@ namespace EHR { public static void Prefix(ChatController __instance) { - if (__instance.IsOpenOrOpening && !__instance.IsAnimating) - { - __instance.banButton.SetVisible(false); - } + if (__instance.IsOpenOrOpening && !__instance.IsAnimating) __instance.banButton.SetVisible(false); } } } \ No newline at end of file diff --git a/Patches/HudPatch.cs b/Patches/HudPatch.cs index 07f98d857..716a0987d 100644 --- a/Patches/HudPatch.cs +++ b/Patches/HudPatch.cs @@ -27,16 +27,10 @@ namespace EHR.Patches public static bool Prefix(HudManager __instance) { - if (PlayerControl.LocalPlayer != null) - { - return true; - } + if (PlayerControl.LocalPlayer != null) return true; __instance.taskDirtyTimer += Time.deltaTime; - if (__instance.taskDirtyTimer <= 0.25) - { - return false; - } + if (__instance.taskDirtyTimer <= 0.25) return false; __instance.taskDirtyTimer = 0.0f; __instance.TaskPanel?.SetTaskText(string.Empty); @@ -50,40 +44,23 @@ namespace EHR.Patches LoadingScreen.Update(); PlayerControl player = PlayerControl.LocalPlayer; - if (player == null) - { - return; - } + if (player == null) return; if (Input.GetKeyDown(KeyCode.LeftControl)) - { if ((!AmongUsClient.Instance.IsGameStarted || !GameStates.IsOnlineGame) && player.CanMove) - { player.Collider.offset = new(0f, 127f); - } - } if (Math.Abs(player.Collider.offset.y - 127f) < 0.1f) - { if (!Input.GetKey(KeyCode.LeftControl) || (AmongUsClient.Instance.IsGameStarted && GameStates.IsOnlineGame)) - { player.Collider.offset = new(0f, -0.3636f); - } - } - if (__instance == null) - { - return; - } + if (__instance == null) return; if (GameStates.IsLobby) { if (PingTrackerUpdatePatch.Instance != null) { - if (SettingsText != null) - { - Object.Destroy(SettingsText.gameObject); - } + if (SettingsText != null) Object.Destroy(SettingsText.gameObject); SettingsText = Object.Instantiate(PingTrackerUpdatePatch.Instance.text, __instance.transform, true); SettingsText.alignment = TextAlignmentOptions.TopLeft; @@ -98,10 +75,7 @@ namespace EHR.Patches SettingsText.enabled = SettingsText.text != string.Empty; } } - else if (SettingsText != null) - { - Object.Destroy(SettingsText.gameObject); - } + else if (SettingsText != null) Object.Destroy(SettingsText.gameObject); if (AmongUsClient.Instance.AmHost) { @@ -120,35 +94,34 @@ namespace EHR.Patches if (Main.SetRoles.Count > 0 || Main.SetAddOns.Count > 0) { Dictionary resultText = []; - bool first = true; + var first = true; + foreach (KeyValuePair item in Main.SetRoles) { PlayerControl pc = Utils.GetPlayerById(item.Key); string prefix = first ? string.Empty : "\n"; - string text = $"{prefix}{(item.Key == 0 ? "Host" : $"{(pc == null ? $"ID {item.Key}" : $"{pc.GetRealName()}")}")} - {GetString(item.Value.ToString())}"; + var text = $"{prefix}{(item.Key == 0 ? "Host" : $"{(pc == null ? $"ID {item.Key}" : $"{pc.GetRealName()}")}")} - {GetString(item.Value.ToString())}"; resultText[item.Key] = text; first = false; } - if (Main.SetRoles.Count == 0) - { - first = true; - } + if (Main.SetRoles.Count == 0) first = true; foreach (KeyValuePair> item in Main.SetAddOns) { foreach (CustomRoles role in item.Value) { PlayerControl pc = Utils.GetPlayerById(item.Key); + if (resultText.ContainsKey(item.Key)) { - string text = $" <#ffffff>({GetString(role.ToString())}<#ffffff>)"; + var text = $" <#ffffff>({GetString(role.ToString())}<#ffffff>)"; resultText[item.Key] += text; } else { string prefix = first ? string.Empty : "\n"; - string text = $"{prefix}{(item.Key == 0 ? "Host" : $"{(pc == null ? $"ID {item.Key}" : $"{pc.GetRealName()}")}")} - <#ffffff>({GetString(role.ToString())}<#ffffff>)"; + var text = $"{prefix}{(item.Key == 0 ? "Host" : $"{(pc == null ? $"ID {item.Key}" : $"{pc.GetRealName()}")}")} - <#ffffff>({GetString(role.ToString())}<#ffffff>)"; resultText[item.Key] = text; first = false; } @@ -158,9 +131,7 @@ namespace EHR.Patches OverriddenRolesText.text = string.Join(string.Empty, resultText.Values); } else - { OverriddenRolesText.text = string.Empty; - } OverriddenRolesText.enabled = OverriddenRolesText.text != string.Empty; } @@ -175,16 +146,10 @@ namespace EHR.Patches __instance.SabotageButton }.Do(x => x?.Hide()); } - else if (Options.CurrentGameMode != CustomGameMode.Standard) - { - __instance.ReportButton?.Hide(); - } + else if (Options.CurrentGameMode != CustomGameMode.Standard) __instance.ReportButton?.Hide(); // The following will not be executed unless the game is in progress - if (!AmongUsClient.Instance.IsGameStarted) - { - return; - } + if (!AmongUsClient.Instance.IsGameStarted) return; Utils.CountAlivePlayers(); @@ -198,6 +163,7 @@ namespace EHR.Patches { float timer = shapeshifting ? ssrole.durationSecondsRemaining : ssrole.cooldownSecondsRemaining; AbilityButton button = __instance.AbilityButton; + if (timer > 0f) { Color color = shapeshifting ? Color.green : Color.white; @@ -209,16 +175,10 @@ namespace EHR.Patches CustomRoles role = player.GetCustomRole(); bool usesPetInsteadOfKill = role.UsesPetInsteadOfKill(); - if (usesPetInsteadOfKill) - { - __instance.PetButton?.OverrideText(GetString("KillButtonText")); - } + if (usesPetInsteadOfKill) __instance.PetButton?.OverrideText(GetString("KillButtonText")); ActionButton usedButton = __instance.KillButton; - if (usesPetInsteadOfKill) - { - usedButton = __instance.PetButton; - } + if (usesPetInsteadOfKill) usedButton = __instance.PetButton; __instance.KillButton?.OverrideText(GetString("KillButtonText")); __instance.ReportButton?.OverrideText(GetString("ReportButtonText")); @@ -262,10 +222,7 @@ namespace EHR.Patches break; } - if (role.PetActivatedAbility() && Options.CurrentGameMode == CustomGameMode.Standard && !player.GetCustomSubRoles().Any(StartGameHostPatch.BasisChangingAddons.ContainsKey)) - { - __instance.AbilityButton?.Hide(); - } + if (role.PetActivatedAbility() && Options.CurrentGameMode == CustomGameMode.Standard && !player.GetCustomSubRoles().Any(StartGameHostPatch.BasisChangingAddons.ContainsKey)) __instance.AbilityButton?.Hide(); if (LowerInfoText == null) { @@ -300,6 +257,7 @@ namespace EHR.Patches CustomRoles.Introvert => Introvert.GetSelfSuffix(player), _ => string.Empty }); + return string.Join(string.Empty, suffixes); } @@ -308,24 +266,20 @@ namespace EHR.Patches : string.Format(GetString("CDPT"), CD.TotalCooldown - (Utils.TimeStamp - CD.StartTimeStamp) + 1); bool hasCD = CD_HUDText != string.Empty; + if (hasCD) { - if (CooldownTimerFlashColor.HasValue) - { - CD_HUDText = $"{Utils.ColorString(CooldownTimerFlashColor.Value, CD_HUDText.RemoveHtmlTags())}"; - } + if (CooldownTimerFlashColor.HasValue) CD_HUDText = $"{Utils.ColorString(CooldownTimerFlashColor.Value, CD_HUDText.RemoveHtmlTags())}"; LowerInfoText.text = $"{CD_HUDText}\n{LowerInfoText.text}"; } LowerInfoText.enabled = hasCD || LowerInfoText.text != string.Empty; - if ((!AmongUsClient.Instance.IsGameStarted && AmongUsClient.Instance.NetworkMode != NetworkModes.FreePlay) || GameStates.IsMeeting) - { - LowerInfoText.enabled = false; - } + if ((!AmongUsClient.Instance.IsGameStarted && AmongUsClient.Instance.NetworkMode != NetworkModes.FreePlay) || GameStates.IsMeeting) LowerInfoText.enabled = false; bool allowedRole = role is CustomRoles.Necromancer or CustomRoles.Deathknight or CustomRoles.Refugee or CustomRoles.Sidekick; + if (player.CanUseKillButton() && (allowedRole || !role.UsesPetInsteadOfKill())) { __instance.KillButton?.ToggleVisible(player.IsAlive() && GameStates.IsInTask); @@ -340,10 +294,7 @@ namespace EHR.Patches __instance.ImpostorVentButton?.ToggleVisible((player.CanUseImpostorVentButton() || (player.inVent && player.GetRoleTypes() != RoleTypes.Engineer)) && GameStates.IsInTask); player.Data.Role.CanVent = player.CanUseVent(); - if ((usesPetInsteadOfKill && player.Is(CustomRoles.Nimble) && player.GetRoleTypes() == RoleTypes.Engineer) || player.Is(CustomRoles.GM)) - { - __instance.AbilityButton.SetEnabled(); - } + if ((usesPetInsteadOfKill && player.Is(CustomRoles.Nimble) && player.GetRoleTypes() == RoleTypes.Engineer) || player.Is(CustomRoles.GM)) __instance.AbilityButton.SetEnabled(); } else { @@ -363,6 +314,7 @@ namespace EHR.Patches Mode = MapOptions.Modes.Sabotage, AllowMovementWhileMapOpen = true }); + if (player.AmOwner) { player.MyPhysics.inputHandler.enabled = true; @@ -370,10 +322,7 @@ namespace EHR.Patches } } - if (AmongUsClient.Instance.NetworkMode == NetworkModes.OnlineGame) - { - RepairSender.Enabled = false; - } + if (AmongUsClient.Instance.NetworkMode == NetworkModes.OnlineGame) RepairSender.Enabled = false; if (Input.GetKeyDown(KeyCode.RightShift) && AmongUsClient.Instance.NetworkMode != NetworkModes.OnlineGame) { @@ -383,68 +332,32 @@ namespace EHR.Patches if (RepairSender.Enabled && AmongUsClient.Instance.NetworkMode != NetworkModes.OnlineGame) { - if (Input.GetKeyDown(KeyCode.Alpha0)) - { - RepairSender.Input(0); - } + if (Input.GetKeyDown(KeyCode.Alpha0)) RepairSender.Input(0); - if (Input.GetKeyDown(KeyCode.Alpha1)) - { - RepairSender.Input(1); - } + if (Input.GetKeyDown(KeyCode.Alpha1)) RepairSender.Input(1); - if (Input.GetKeyDown(KeyCode.Alpha2)) - { - RepairSender.Input(2); - } + if (Input.GetKeyDown(KeyCode.Alpha2)) RepairSender.Input(2); - if (Input.GetKeyDown(KeyCode.Alpha3)) - { - RepairSender.Input(3); - } + if (Input.GetKeyDown(KeyCode.Alpha3)) RepairSender.Input(3); - if (Input.GetKeyDown(KeyCode.Alpha4)) - { - RepairSender.Input(4); - } + if (Input.GetKeyDown(KeyCode.Alpha4)) RepairSender.Input(4); - if (Input.GetKeyDown(KeyCode.Alpha5)) - { - RepairSender.Input(5); - } + if (Input.GetKeyDown(KeyCode.Alpha5)) RepairSender.Input(5); - if (Input.GetKeyDown(KeyCode.Alpha6)) - { - RepairSender.Input(6); - } + if (Input.GetKeyDown(KeyCode.Alpha6)) RepairSender.Input(6); - if (Input.GetKeyDown(KeyCode.Alpha7)) - { - RepairSender.Input(7); - } + if (Input.GetKeyDown(KeyCode.Alpha7)) RepairSender.Input(7); - if (Input.GetKeyDown(KeyCode.Alpha8)) - { - RepairSender.Input(8); - } + if (Input.GetKeyDown(KeyCode.Alpha8)) RepairSender.Input(8); - if (Input.GetKeyDown(KeyCode.Alpha9)) - { - RepairSender.Input(9); - } + if (Input.GetKeyDown(KeyCode.Alpha9)) RepairSender.Input(9); - if (Input.GetKeyDown(KeyCode.Return)) - { - RepairSender.InputEnter(); - } + if (Input.GetKeyDown(KeyCode.Return)) RepairSender.InputEnter(); } } catch (NullReferenceException e) { - if (LastNullError >= Utils.TimeStamp) - { - return; - } + if (LastNullError >= Utils.TimeStamp) return; LastNullError = Utils.TimeStamp + 2; Utils.ThrowException(e); @@ -464,12 +377,14 @@ namespace EHR.Patches if (__instance.isCoolingDown && timer is <= 90f and > 0f) { RoleTypes roleType = PlayerControl.LocalPlayer.GetRoleTypes(); + bool usingAbility = roleType switch { RoleTypes.Engineer => PlayerControl.LocalPlayer.inVent || VentButtonDoClickPatch.Animating, RoleTypes.Shapeshifter => PlayerControl.LocalPlayer.IsShifted(), _ => false }; + Color color = usingAbility ? Color.green : Color.white; __instance.cooldownTimerText.text = Utils.ColorString(color, Mathf.CeilToInt(timer).ToString()); __instance.cooldownTimerText.gameObject.SetActive(true); @@ -484,17 +399,11 @@ namespace EHR.Patches public static void Postfix(PlayerControl __instance /*[HarmonyArgument(0)] bool active,*/ /*[HarmonyArgument(1)] RoleTeamTypes team*/) { - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; PlayerControl player = PlayerControl.LocalPlayer; - if (player.CanUseKillButton()) - { - __instance.cosmetics.currentBodySprite.BodySprite.material.SetColor(OutlineColor, Utils.GetRoleColor(player.GetCustomRole())); - } + if (player.CanUseKillButton()) __instance.cosmetics.currentBodySprite.BodySprite.material.SetColor(OutlineColor, Utils.GetRoleColor(player.GetCustomRole())); } } @@ -525,6 +434,7 @@ namespace EHR.Patches public static void Postfix(HudManager __instance, [HarmonyArgument(2)] bool isActive) { __instance?.ReportButton?.ToggleVisible(!GameStates.IsLobby && isActive); + if (__instance == null) { Logger.Fatal("HudManager __instance ended up being null", "SetHudActivePatch.Postfix"); @@ -532,10 +442,7 @@ namespace EHR.Patches } IsActive = isActive; - if (!isActive) - { - return; - } + if (!isActive) return; switch (Options.CurrentGameMode) { @@ -563,10 +470,7 @@ namespace EHR.Patches } PlayerControl player = PlayerControl.LocalPlayer; - if (player == null) - { - return; - } + if (player == null) return; switch (player.GetCustomRole()) { @@ -600,10 +504,7 @@ namespace EHR.Patches break; } - if (Main.PlayerStates.TryGetValue(player.PlayerId, out PlayerState ps) && ps.SubRoles.Contains(CustomRoles.Oblivious)) - { - __instance.ReportButton?.ToggleVisible(false); - } + if (Main.PlayerStates.TryGetValue(player.PlayerId, out PlayerState ps) && ps.SubRoles.Contains(CustomRoles.Oblivious)) __instance.ReportButton?.ToggleVisible(false); __instance.KillButton?.ToggleVisible(player.CanUseKillButton()); __instance.ImpostorVentButton?.ToggleVisible(player.CanUseImpostorVentButton()); @@ -628,10 +529,7 @@ namespace EHR.Patches { public static bool Prefix(MapBehaviour __instance, ref MapOptions opts) { - if (GameStates.IsMeeting) - { - return true; - } + if (GameStates.IsMeeting) return true; PlayerControl player = PlayerControl.LocalPlayer; @@ -643,19 +541,12 @@ namespace EHR.Patches else if (opts.Mode is MapOptions.Modes.Normal or MapOptions.Modes.Sabotage) { if (player.Is(CustomRoleTypes.Impostor) || player.CanUseSabotage() || player.Is(CustomRoles.Glitch) || player.Is(CustomRoles.WeaponMaster) || player.Is(CustomRoles.Magician) || player.Is(CustomRoles.Parasite) || player.Is(CustomRoles.Refugee) || (player.Is(CustomRoles.Jackal) && Jackal.CanSabotage.GetBool()) || (player.Is(CustomRoles.Traitor) && Traitor.CanSabotage.GetBool())) - { opts.Mode = MapOptions.Modes.Sabotage; - } else - { opts.Mode = MapOptions.Modes.Normal; - } } - if (Main.GodMode.Value) - { - opts.ShowLivePlayerPosition = true; - } + if (Main.GodMode.Value) opts.ShowLivePlayerPosition = true; return true; } @@ -670,21 +561,16 @@ namespace EHR.Patches { float perc = __instance.sabSystem.PercentCool; int total = __instance.sabSystem.initialCooldown ? 10 : 30; - if (SabotageSystemTypeRepairDamagePatch.IsCooldownModificationEnabled) - { - total = (int)SabotageSystemTypeRepairDamagePatch.ModifiedCooldownSec; - } + if (SabotageSystemTypeRepairDamagePatch.IsCooldownModificationEnabled) total = (int)SabotageSystemTypeRepairDamagePatch.ModifiedCooldownSec; int remaining = Math.Clamp(total - (int)Math.Ceiling((1f - perc) * total) + 1, 0, total); foreach (MapRoom mr in __instance.rooms) { - if (mr.special == null || mr.special.transform == null) - { - continue; - } + if (mr.special == null || mr.special.transform == null) continue; SystemTypes room = mr.room; + if (!TimerTexts.ContainsKey(room)) { TimerTexts[room] = Object.Instantiate(HudManager.Instance.KillButton.cooldownTimerText, mr.special.transform, true); @@ -715,19 +601,19 @@ namespace EHR.Patches PlayerControl player = PlayerControl.LocalPlayer; string taskText = __instance.taskText.text; - if (taskText == "None" || GameStates.IsLobby || player == null) - { - return; - } + if (taskText == "None" || GameStates.IsLobby || player == null) return; CustomRoles role = player.GetCustomRole(); + if (!role.IsVanilla()) { string roleInfo = player.GetRoleInfo(); - string RoleWithInfo = $"{role.ToColoredString()}:\r\n{roleInfo}"; + var RoleWithInfo = $"{role.ToColoredString()}:\r\n{roleInfo}"; + if (Options.CurrentGameMode != CustomGameMode.Standard) { string[] splitted = roleInfo.Split(' '); + RoleWithInfo = splitted.Length <= 3 ? $"{roleInfo}\r\n" : $"{string.Join(' ', splitted[..3])}\r\n{string.Join(' ', splitted[3..])}\r\n"; @@ -746,27 +632,23 @@ namespace EHR.Patches case CustomGameMode.Standard: List subRoles = player.GetCustomSubRoles(); + if (subRoles.Count > 0) { const int max = 3; IEnumerable s = subRoles.Take(max).Select(x => Utils.ColorString(Utils.GetRoleColor(x), $"\r\n\r\n{x.ToColoredString()}:\r\n{GetString($"{x}Info")}")); finalText += s.Aggregate("", (current, next) => current + next) + ""; int chunk = subRoles.Any(x => GetString(x.ToString()).Contains(' ')) ? 3 : 4; - if (subRoles.Count > max) - { - finalText += $"\r\n....\r\n({subRoles.Skip(max).Chunk(chunk).Select(x => x.Join(r => r.ToColoredString())).Join(delimiter: ",\r\n")})"; - } + if (subRoles.Count > max) finalText += $"\r\n....\r\n({subRoles.Skip(max).Chunk(chunk).Select(x => x.Join(r => r.ToColoredString())).Join(delimiter: ",\r\n")})"; } string[] lines = taskText.Split("\r\n\n")[0].Split("\r\n\n")[0].Split("\r\n"); StringBuilder sb = new(); + foreach (string eachLine in lines) { string line = eachLine.Trim(); - if ((line.StartsWith("") || line.StartsWith("")) && sb.Length < 1 && !line.Contains('(') && !line.Contains(DestroyableSingleton.Instance.GetString(TaskTypes.FixComms))) - { - continue; - } + if ((line.StartsWith("") || line.StartsWith("")) && sb.Length < 1 && !line.Contains('(') && !line.Contains(DestroyableSingleton.Instance.GetString(TaskTypes.FixComms))) continue; sb.Append(line + "\r\n"); } @@ -774,23 +656,16 @@ namespace EHR.Patches if (sb.Length > 1) { string text = sb.ToString().TrimEnd('\n').TrimEnd('\r'); + if (!Utils.HasTasks(player.Data, false) && sb.ToString().Count(s => s == '\n') >= 2) - { text = $"{Utils.ColorString(Utils.GetRoleColor(role).ShadeColor(0.2f), GetString("FakeTask"))}\r\n{text}"; - } - else if (player.myTasks.ToArray().Any(x => x.TaskType == TaskTypes.FixComms)) - { - goto Skip; - } + else if (player.myTasks.ToArray().Any(x => x.TaskType == TaskTypes.FixComms)) goto Skip; finalText += $"\r\n\r\n{text}"; } Skip: - if (MeetingStates.FirstMeeting) - { - finalText += $"\r\n\r\n{GetString("PressF1ShowMainRoleDes")}"; - } + if (MeetingStates.FirstMeeting) finalText += $"\r\n\r\n{GetString("PressF1ShowMainRoleDes")}"; break; @@ -819,27 +694,23 @@ namespace EHR.Patches case CustomGameMode.MoveAndStop: Dictionary SummaryText3 = []; + foreach (byte id in Main.PlayerStates.Keys.ToArray()) { string name = Main.AllPlayerNames[id].RemoveHtmlTags().Replace("\r\n", string.Empty); - string summary = $"{Utils.GetProgressText(id)} {Utils.ColorString(Main.PlayerColors[id], name)}"; - if (Utils.GetProgressText(id).Trim() == string.Empty) - { - continue; - } + var summary = $"{Utils.GetProgressText(id)} {Utils.ColorString(Main.PlayerColors[id], name)}"; + if (Utils.GetProgressText(id).Trim() == string.Empty) continue; SummaryText3[id] = summary; } string[] lines1 = taskText.Split("\r\n\n")[0].Split("\r\n\n")[0].Split("\r\n"); StringBuilder sb1 = new(); + foreach (string eachLine in lines1) { string line = eachLine.Trim(); - if ((line.StartsWith("") || line.StartsWith("")) && sb1.Length < 1 && !line.Contains('(')) - { - continue; - } + if ((line.StartsWith("") || line.StartsWith("")) && sb1.Length < 1 && !line.Contains('(')) continue; sb1.Append(line + "\r\n"); } @@ -847,22 +718,17 @@ namespace EHR.Patches if (sb1.Length > 1) { string text = sb1.ToString().TrimEnd('\n').TrimEnd('\r'); - if (!Utils.HasTasks(player.Data, false) && sb1.ToString().Count(s => s == '\n') >= 2) - { - text = $"{Utils.ColorString(Utils.GetRoleColor(role).ShadeColor(0.2f), GetString("FakeTask"))}\r\n{text}"; - } + if (!Utils.HasTasks(player.Data, false) && sb1.ToString().Count(s => s == '\n') >= 2) text = $"{Utils.ColorString(Utils.GetRoleColor(role).ShadeColor(0.2f), GetString("FakeTask"))}\r\n{text}"; finalText += $"\r\n{text}\r\n"; } List<(int, byte)> list3 = []; - foreach (byte id in Main.PlayerStates.Keys) - { - list3.Add((MoveAndStopManager.GetRankOfScore(id), id)); - } + foreach (byte id in Main.PlayerStates.Keys) list3.Add((MoveAndStopManager.GetRankOfScore(id), id)); list3.Sort(); list3 = [.. list3.OrderBy(x => !Utils.GetPlayerById(x.Item2).IsAlive())]; + foreach ((int, byte) id in list3.Where(x => SummaryText3.ContainsKey(x.Item2)).ToArray()) { bool alive = Utils.GetPlayerById(id.Item2).IsAlive(); @@ -890,13 +756,11 @@ namespace EHR.Patches string[] lines2 = taskText.Split("\r\n\n")[0].Split("\r\n\n")[0].Split("\r\n"); StringBuilder sb2 = new(); + foreach (string eachLine in lines2) { string line = eachLine.Trim(); - if ((line.StartsWith("") || line.StartsWith("")) && sb2.Length < 1 && !line.Contains('(')) - { - continue; - } + if ((line.StartsWith("") || line.StartsWith("")) && sb2.Length < 1 && !line.Contains('(')) continue; sb2.Append(line + "\r\n"); } @@ -904,10 +768,7 @@ namespace EHR.Patches if (sb2.Length > 1) { string text = sb2.ToString().TrimEnd('\n').TrimEnd('\r'); - if (!Utils.HasTasks(player.Data, false) && sb2.ToString().Count(s => s == '\n') >= 2) - { - text = $"{Utils.ColorString(Utils.GetRoleColor(role).ShadeColor(0.2f), GetString("FakeTask"))}\r\n{text}"; - } + if (!Utils.HasTasks(player.Data, false) && sb2.ToString().Count(s => s == '\n') >= 2) text = $"{Utils.ColorString(Utils.GetRoleColor(role).ShadeColor(0.2f), GetString("FakeTask"))}\r\n{text}"; finalText += $"\r\n{text}\r\n"; } @@ -942,10 +803,7 @@ namespace EHR.Patches __instance.taskText.text = finalText; } - if (RepairSender.Enabled && AmongUsClient.Instance.NetworkMode != NetworkModes.OnlineGame) - { - __instance.taskText.text = RepairSender.GetText(); - } + if (RepairSender.Enabled && AmongUsClient.Instance.NetworkMode != NetworkModes.OnlineGame) __instance.taskText.text = RepairSender.GetText(); } } @@ -955,15 +813,9 @@ namespace EHR.Patches public static bool Prefix(DialogueBox __instance, [HarmonyArgument(0)] string dialogue) { __instance.target.text = dialogue; - if (Minigame.Instance != null) - { - Minigame.Instance.Close(); - } + if (Minigame.Instance != null) Minigame.Instance.Close(); - if (Minigame.Instance != null) - { - Minigame.Instance.Close(); - } + if (Minigame.Instance != null) Minigame.Instance.Close(); __instance.gameObject.SetActive(true); return false; @@ -977,10 +829,7 @@ namespace EHR.Patches public static void Prefix() { - if (!AmongUsClient.Instance.AmHost || !GameStates.IsModHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost || !GameStates.IsModHost) return; IntroStarted = true; @@ -990,10 +839,7 @@ namespace EHR.Patches { StartGameHostPatch.RpcSetDisconnected(false); - if (!AmongUsClient.Instance.IsGameOver) - { - DestroyableSingleton.Instance.SetHudActive(true); - } + if (!AmongUsClient.Instance.IsGameOver) DestroyableSingleton.Instance.SetHudActive(true); } }, 0.6f, "Set Disconnected"); @@ -1009,10 +855,7 @@ namespace EHR.Patches ShipStatus.Instance.Begin(); GameOptionsSender.AllSenders.Clear(); - foreach (PlayerControl pc in Main.AllPlayerControls) - { - GameOptionsSender.AllSenders.Add(new PlayerGameOptionsSender(pc)); - } + foreach (PlayerControl pc in Main.AllPlayerControls) GameOptionsSender.AllSenders.Add(new PlayerGameOptionsSender(pc)); Utils.SyncAllSettings(); } @@ -1050,13 +893,9 @@ namespace EHR.Patches public static void InputEnter() { if (!TypingAmount) - { TypingAmount = true; - } else - { Send(); - } } private static void Send() diff --git a/Patches/HudSpritePatch.cs b/Patches/HudSpritePatch.cs index 1f8ce3216..637ad0d7b 100644 --- a/Patches/HudSpritePatch.cs +++ b/Patches/HudSpritePatch.cs @@ -34,20 +34,11 @@ namespace EHR try { PlayerControl player = PlayerControl.LocalPlayer; - if (player == null) - { - return; - } + if (player == null) return; - if (!Main.EnableCustomButton.Value || !Main.ProcessShapeshifts || Mastermind.ManipulatedPlayers.ContainsKey(player.PlayerId)) - { - return; - } + if (!Main.EnableCustomButton.Value || !Main.ProcessShapeshifts || Mastermind.ManipulatedPlayers.ContainsKey(player.PlayerId)) return; - if (!SetHudActivePatch.IsActive || !player.IsAlive()) - { - return; - } + if (!SetHudActivePatch.IsActive || !player.IsAlive()) return; if (!AmongUsClient.Instance.IsGameStarted || !Main.IntroDestroyed) { @@ -62,35 +53,17 @@ namespace EHR bool shapeshifting = player.IsShifted(); - if (!Kill) - { - Kill = __instance.KillButton.graphic.sprite; - } + if (!Kill) Kill = __instance.KillButton.graphic.sprite; - if (!Ability) - { - Ability = __instance.AbilityButton.graphic.sprite; - } + if (!Ability) Ability = __instance.AbilityButton.graphic.sprite; - if (!Vent) - { - Vent = __instance.ImpostorVentButton.graphic.sprite; - } + if (!Vent) Vent = __instance.ImpostorVentButton.graphic.sprite; - if (!Sabotage) - { - Sabotage = __instance.SabotageButton.graphic.sprite; - } + if (!Sabotage) Sabotage = __instance.SabotageButton.graphic.sprite; - if (!Pet) - { - Pet = __instance.PetButton.graphic.sprite; - } + if (!Pet) Pet = __instance.PetButton.graphic.sprite; - if (!Report) - { - Report = __instance.ReportButton.graphic.sprite; - } + if (!Report) Report = __instance.ReportButton.graphic.sprite; Sprite newKillButton = Kill; Sprite newAbilityButton = Ability; @@ -103,13 +76,9 @@ namespace EHR { case CustomRoles.Enderman: if (Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("abscond"); - } else - { newSabotageButton = CustomButton.Get("abscond"); - } break; case CustomRoles.Wizard: @@ -130,14 +99,11 @@ namespace EHR break; case CustomRoles.Changeling: newAbilityButton = CustomButton.Get("GlitchMimic"); + if (Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("Swap"); - } else - { newVentButton = CustomButton.Get("Swap"); - } break; case CustomRoles.Vulture: @@ -151,39 +117,26 @@ namespace EHR break; case CustomRoles.Amnesiac: if (Amnesiac.RememberMode.GetValue() == 1) - { newKillButton = CustomButton.Get("AmnesiacKill"); - } else - { newReportButton = CustomButton.Get("AmnesiacReport"); - } break; case CustomRoles.Assassin: case CustomRoles.Undertaker: - if (Main.PlayerStates[player.PlayerId].Role is not Assassin assassin) - { - break; - } + if (Main.PlayerStates[player.PlayerId].Role is not Assassin assassin) break; if (Options.UsePets.GetBool()) { newKillButton = CustomButton.Get("Mark"); - if (assassin.MarkedPlayer != byte.MaxValue) - { - newPetButton = CustomButton.Get("Assassinate"); - } + if (assassin.MarkedPlayer != byte.MaxValue) newPetButton = CustomButton.Get("Assassinate"); } else { if (!shapeshifting) { newKillButton = CustomButton.Get("Mark"); - if (assassin.MarkedPlayer != byte.MaxValue) - { - newAbilityButton = CustomButton.Get("Assassinate"); - } + if (assassin.MarkedPlayer != byte.MaxValue) newAbilityButton = CustomButton.Get("Assassinate"); } } @@ -196,15 +149,9 @@ namespace EHR newKillButton = CustomButton.Get("GlitchHack"); break; case CustomRoles.Glitch: - if (Main.PlayerStates[player.PlayerId].Role is not Glitch gc) - { - break; - } + if (Main.PlayerStates[player.PlayerId].Role is not Glitch gc) break; - if (gc.KCDTimer > 0 && gc.HackCDTimer <= 0) - { - newKillButton = CustomButton.Get("GlitchHack"); - } + if (gc.KCDTimer > 0 && gc.HackCDTimer <= 0) newKillButton = CustomButton.Get("GlitchHack"); newSabotageButton = CustomButton.Get("GlitchMimic"); break; @@ -216,25 +163,15 @@ namespace EHR break; case CustomRoles.Disperser: if (Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("Disperse"); - } - else if (!shapeshifting) - { - newAbilityButton = CustomButton.Get("Disperse"); - } + else if (!shapeshifting) newAbilityButton = CustomButton.Get("Disperse"); break; case CustomRoles.ImperiusCurse: case CustomRoles.Twister: if (player.Is(CustomRoles.Twister) && Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("Transport"); - } - else if (!shapeshifting) - { - newAbilityButton = CustomButton.Get("Transport"); - } + else if (!shapeshifting) newAbilityButton = CustomButton.Get("Transport"); break; case CustomRoles.Deputy: @@ -245,13 +182,9 @@ namespace EHR break; case CustomRoles.Alchemist: if (Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("Drink"); - } else - { newAbilityButton = CustomButton.Get("Drink"); - } break; case CustomRoles.Jailor: @@ -270,13 +203,9 @@ namespace EHR case CustomRoles.Bomber: case CustomRoles.Nuker: if (Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("Bomb"); - } else - { newAbilityButton = CustomButton.Get("Bomb"); - } break; case CustomRoles.Camouflager: @@ -287,16 +216,13 @@ namespace EHR break; case CustomRoles.Arsonist: newKillButton = CustomButton.Get("Douse"); + if (player.IsDouseDone() || (Options.ArsonistCanIgniteAnytime.GetBool() && Utils.GetDousedPlayerCount(player.PlayerId).Item1 >= Options.ArsonistMinPlayersToIgnite.GetInt())) { if (Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("Ignite"); - } else - { newVentButton = CustomButton.Get("Ignite"); - } } break; @@ -304,10 +230,7 @@ namespace EHR newKillButton = CustomButton.Get("Pyromaniac"); break; case CustomRoles.FireWorks: - if (Main.PlayerStates[player.PlayerId].Role is not FireWorks fw) - { - break; - } + if (Main.PlayerStates[player.PlayerId].Role is not FireWorks fw) break; newAbilityButton = CustomButton.Get(fw.nowFireWorksCount == 0 ? "FireworkD" : "FireworkP"); break; @@ -315,32 +238,21 @@ namespace EHR newAbilityButton = CustomButton.Get("Hack"); break; case CustomRoles.Hangman: - if (shapeshifting) - { - newAbilityButton = CustomButton.Get("Hangman"); - } + if (shapeshifting) newAbilityButton = CustomButton.Get("Hangman"); break; case CustomRoles.Paranoia: if (Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("Paranoid"); - } else - { newAbilityButton = CustomButton.Get("Paranoid"); - } break; case CustomRoles.Mayor when Mayor.MayorHasPortableButton.GetBool(): if (Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("Button"); - } else - { newAbilityButton = CustomButton.Get("Button"); - } break; case CustomRoles.Puppeteer: @@ -351,10 +263,7 @@ namespace EHR newKillButton = CustomButton.Get("Shield"); break; case CustomRoles.Gangster: - if (Gangster.CanRecruit(player.PlayerId)) - { - newKillButton = CustomButton.Get("Sidekick"); - } + if (Gangster.CanRecruit(player.PlayerId)) newKillButton = CustomButton.Get("Sidekick"); break; case CustomRoles.Succubus: @@ -371,35 +280,23 @@ namespace EHR break; case CustomRoles.Veteran: if (Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("Veteran"); - } else - { newAbilityButton = CustomButton.Get("Veteran"); - } break; case CustomRoles.Lighter: if (Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("Lighter"); - } else - { newAbilityButton = CustomButton.Get("Lighter"); - } break; case CustomRoles.SecurityGuard: if (Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("BlockSabo"); - } else - { newAbilityButton = CustomButton.Get("BlockSabo"); - } break; case CustomRoles.Ventguard: @@ -413,13 +310,9 @@ namespace EHR break; case CustomRoles.Miner: if (!Options.UsePets.GetBool()) - { newAbilityButton = CustomButton.Get("Mine"); - } else - { newPetButton = CustomButton.Get("Mine"); - } break; case CustomRoles.Analyst: @@ -434,13 +327,9 @@ namespace EHR break; case CustomRoles.TimeMaster: if (Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("Time Master"); - } else - { newAbilityButton = CustomButton.Get("Time Master"); - } break; case CustomRoles.Sheriff: @@ -448,13 +337,9 @@ namespace EHR break; case CustomRoles.Swiftclaw: if (Options.UsePets.GetBool() && !Options.UseUnshiftTrigger.GetBool()) - { newPetButton = CustomButton.Get("Dash"); - } else - { newAbilityButton = CustomButton.Get("Dash"); - } break; case CustomRoles.Swooper: @@ -467,13 +352,9 @@ namespace EHR break; case CustomRoles.Escapee: if (Options.UsePets.GetBool()) - { newPetButton = CustomButton.Get("abscond"); - } else - { newAbilityButton = CustomButton.Get("abscond"); - } break; case CustomRoles.Tunneler: @@ -486,27 +367,18 @@ namespace EHR if (Options.UsePets.GetBool()) { newKillButton = CustomButton.Get("Curse"); - if (Warlock.IsCurseAndKill.TryGetValue(player.PlayerId, out bool curse) && curse) - { - newAbilityButton = CustomButton.Get("CurseKill"); - } + if (Warlock.IsCurseAndKill.TryGetValue(player.PlayerId, out bool curse) && curse) newAbilityButton = CustomButton.Get("CurseKill"); } else if (!shapeshifting) { newKillButton = CustomButton.Get("Curse"); - if (Warlock.IsCurseAndKill.TryGetValue(player.PlayerId, out bool curse) && curse) - { - newAbilityButton = CustomButton.Get("CurseKill"); - } + if (Warlock.IsCurseAndKill.TryGetValue(player.PlayerId, out bool curse) && curse) newAbilityButton = CustomButton.Get("CurseKill"); } break; } - if (player.GetCustomRole().UsesPetInsteadOfKill()) - { - newPetButton = newKillButton; - } + if (player.GetCustomRole().UsesPetInsteadOfKill()) newPetButton = newKillButton; __instance.KillButton.graphic.sprite = newKillButton; diff --git a/Patches/IntroPatch.cs b/Patches/IntroPatch.cs index d0754ad93..201d28dd6 100644 --- a/Patches/IntroPatch.cs +++ b/Patches/IntroPatch.cs @@ -113,6 +113,7 @@ namespace EHR default: { CustomRoles role = lp.GetCustomRole(); + if (!role.IsVanilla()) { __instance.YouAreText.color = Utils.GetRoleColor(role); @@ -124,10 +125,7 @@ namespace EHR foreach (CustomRoles subRole in Main.PlayerStates[lp.PlayerId].SubRoles) { - if (role is CustomRoles.LovingCrewmate or CustomRoles.LovingImpostor && subRole == CustomRoles.Lovers) - { - continue; - } + if (role is CustomRoles.LovingCrewmate or CustomRoles.LovingImpostor && subRole == CustomRoles.Lovers) continue; __instance.RoleBlurbText.text += "\n" + Utils.ColorString(Utils.GetRoleColor(subRole), GetString($"{subRole}Info")); } @@ -142,10 +140,7 @@ namespace EHR { LateTask.New(() => { - if (AmongUsClient.Instance.IsGameOver || GameStates.IsLobby || lp == null) - { - return; - } + if (AmongUsClient.Instance.IsGameOver || GameStates.IsLobby || lp == null) return; lp.SetName(Main.AllPlayerNames[lp.PlayerId]); }, 1f, "Reset Name For Modded Client"); @@ -160,6 +155,7 @@ namespace EHR { StringBuilder sb = new(); sb.Append("------------Display Names------------\n"); + foreach (PlayerControl pc in Main.AllPlayerControls) { sb.Append($"{(pc.AmOwner ? "[*]" : string.Empty),-3}{pc.PlayerId,-2}:{pc.name.PadRightV2(20)}:{pc.cosmetics.nameText.text} ({Palette.ColorNames[pc.Data.DefaultOutfit.ColorId].ToString().Replace("Color", string.Empty)})\n"); @@ -167,26 +163,21 @@ namespace EHR } sb.Append("------------Roles------------\n"); - foreach (PlayerControl pc in Main.AllPlayerControls) - { - sb.Append($"{(pc.AmOwner ? "[*]" : string.Empty),-3}{pc.PlayerId,-2}:{pc.Data?.PlayerName?.PadRightV2(20)}:{pc.GetAllRoleName().RemoveHtmlTags().Replace("\n", " + ")}\n"); - } + foreach (PlayerControl pc in Main.AllPlayerControls) sb.Append($"{(pc.AmOwner ? "[*]" : string.Empty),-3}{pc.PlayerId,-2}:{pc.Data?.PlayerName?.PadRightV2(20)}:{pc.GetAllRoleName().RemoveHtmlTags().Replace("\n", " + ")}\n"); sb.Append("------------Platforms------------\n"); + foreach (PlayerControl pc in Main.AllPlayerControls) { try { string text = pc.AmOwner ? "[*]" : " "; text += $"{pc.PlayerId,-2}:{pc.Data?.PlayerName?.PadRightV2(20)}:{pc.GetClient()?.PlatformData?.Platform.ToString().Replace("Standalone", string.Empty),-11}"; + if (Main.PlayerVersion.TryGetValue(pc.PlayerId, out PlayerVersion pv)) - { text += $":Mod({pv.forkId}/{pv.version}:{pv.tag})"; - } else - { text += ":Vanilla"; - } sb.Append(text + "\n"); } @@ -198,19 +189,13 @@ namespace EHR sb.Append("------------Vanilla Settings------------\n"); System.Collections.Generic.IEnumerable tmp = GameOptionsManager.Instance.CurrentGameOptions.ToHudString(GameData.Instance ? GameData.Instance.PlayerCount : 10).Split("\r\n").Skip(1); - foreach (string t in tmp) - { - sb.Append(t + "\n"); - } + foreach (string t in tmp) sb.Append(t + "\n"); sb.Append("------------Modded Settings------------\n"); + foreach (OptionItem o in OptionItem.AllOptions) - { if (!o.IsHiddenOn(Options.CurrentGameMode) && (o.Parent?.GetBool() ?? !o.GetString().Equals("0%"))) - { sb.Append($"{(o.Parent == null ? o.GetName(true, true).RemoveHtmlTags().PadRightV2(40) : $"┗ {o.GetName(true, true).RemoveHtmlTags()}".PadRightV2(41))}:{o.GetString().RemoveHtmlTags()}\n"); - } - } sb.Append("-------------Other Information-------------\n"); sb.Append($"Number of players: {Main.AllPlayerControls.Length}\n"); @@ -235,16 +220,15 @@ namespace EHR Utils.LongRoleDescriptions.Clear(); int charsInOneLine = GetUserTrueLang() is SupportedLangs.Russian or SupportedLangs.SChinese or SupportedLangs.TChinese or SupportedLangs.Japanese or SupportedLangs.Korean ? 35 : 50; + foreach (PlayerControl seer in Main.AllPlayerControls) { string longInfo = seer.GetRoleInfo(true).Split("\n\n")[0]; - if (longInfo.Contains("):\n")) - { - longInfo = longInfo.Split("):\n")[1]; - } + if (longInfo.Contains("):\n")) longInfo = longInfo.Split("):\n")[1]; - bool tooLong = false; + var tooLong = false; bool showLongInfo = Options.ShowLongInfo.GetBool(); + if (showLongInfo) { if (longInfo.Length > 296) @@ -256,16 +240,10 @@ namespace EHR for (int i = charsInOneLine; i < longInfo.Length; i += charsInOneLine) { - if (tooLong && i > 296) - { - break; - } + if (tooLong && i > 296) break; int index = longInfo.LastIndexOf(' ', i); - if (index != -1) - { - longInfo = longInfo.Insert(index + 1, "\n"); - } + if (index != -1) longInfo = longInfo.Insert(index + 1, "\n"); } } @@ -290,12 +268,14 @@ namespace EHR public static bool Prefix(IntroCutscene __instance, ref List teamToDisplay) { CustomRoles role = PlayerControl.LocalPlayer.GetCustomRole(); + if (PlayerControl.LocalPlayer.Is(CustomRoleTypes.Neutral) && !role.IsMadmate()) { teamToDisplay = new(); teamToDisplay.Add(PlayerControl.LocalPlayer); byte id = PlayerControl.LocalPlayer.PlayerId; + switch (Main.PlayerStates[id].Role) { case Lawyer: @@ -321,37 +301,29 @@ namespace EHR teamToDisplay.Add(PlayerControl.LocalPlayer); teamToDisplay.Add(Main.LoversPlayers.FirstOrDefault(x => x.PlayerId != PlayerControl.LocalPlayer.PlayerId)); } - else if (role == CustomRoles.LovingImpostor) - { - teamToDisplay.Add(Main.LoversPlayers.FirstOrDefault(x => x.PlayerId != PlayerControl.LocalPlayer.PlayerId)); - } + else if (role == CustomRoles.LovingImpostor) teamToDisplay.Add(Main.LoversPlayers.FirstOrDefault(x => x.PlayerId != PlayerControl.LocalPlayer.PlayerId)); if (CustomTeamManager.EnabledCustomTeams.Count > 0) { CustomTeamManager.CustomTeam team = CustomTeamManager.GetCustomTeam(PlayerControl.LocalPlayer.PlayerId); + if (team != null) { teamToDisplay = new(); + foreach (PlayerControl pc in Main.AllPlayerControls) - { if (CustomTeamManager.AreInSameCustomTeam(pc.PlayerId, PlayerControl.LocalPlayer.PlayerId)) - { teamToDisplay.Add(pc); - } - } } } if (Options.CurrentGameMode == CustomGameMode.FFA && FFAManager.FFATeamMode.GetBool() && FFAManager.PlayerTeams.TryGetValue(PlayerControl.LocalPlayer.PlayerId, out int ffaTeam)) { teamToDisplay = new(); + foreach (PlayerControl pc in Main.AllPlayerControls) - { if (FFAManager.PlayerTeams.TryGetValue(pc.PlayerId, out int team) && team == ffaTeam) - { teamToDisplay.Add(pc); - } - } } return true; @@ -594,28 +566,19 @@ namespace EHR if (CustomTeamManager.EnabledCustomTeams.Count > 0) { CustomTeamManager.CustomTeam team = CustomTeamManager.GetCustomTeam(PlayerControl.LocalPlayer.PlayerId); + if (team != null) { - if (team.RoleRevealScreenTitle != "*") - { - __instance.TeamTitle.text = team.RoleRevealScreenTitle; - } + if (team.RoleRevealScreenTitle != "*") __instance.TeamTitle.text = team.RoleRevealScreenTitle; - if (team.RoleRevealScreenBackgroundColor != "*" && ColorUtility.TryParseHtmlString(team.RoleRevealScreenBackgroundColor, out Color bgColor)) - { - __instance.TeamTitle.color = __instance.BackgroundBar.material.color = bgColor; - } + if (team.RoleRevealScreenBackgroundColor != "*" && ColorUtility.TryParseHtmlString(team.RoleRevealScreenBackgroundColor, out Color bgColor)) __instance.TeamTitle.color = __instance.BackgroundBar.material.color = bgColor; __instance.ImpostorText.gameObject.SetActive(team.RoleRevealScreenSubtitle != "*"); __instance.ImpostorText.text = team.RoleRevealScreenSubtitle; foreach (PlayerControl pc in Main.AllPlayerControls) - { if (CustomTeamManager.AreInSameCustomTeam(pc.PlayerId, PlayerControl.LocalPlayer.PlayerId)) - { teamToDisplay.Add(pc); - } - } } } @@ -773,6 +736,7 @@ namespace EHR public static bool Prefix(IntroCutscene __instance, ref List yourTeam) { CustomRoles role = PlayerControl.LocalPlayer.GetCustomRole(); + if (PlayerControl.LocalPlayer.Is(CustomRoles.Madmate) || role.IsMadmate()) { yourTeam = new(); @@ -785,10 +749,7 @@ namespace EHR { yourTeam = new(); yourTeam.Add(PlayerControl.LocalPlayer); - foreach (PlayerControl pc in Main.AllPlayerControls.Where(x => !x.AmOwner)) - { - yourTeam.Add(pc); - } + foreach (PlayerControl pc in Main.AllPlayerControls.Where(x => !x.AmOwner)) yourTeam.Add(pc); __instance.BeginCrewmate(yourTeam); __instance.overlayHandle.color = Palette.CrewmateBlue; @@ -799,10 +760,7 @@ namespace EHR { yourTeam = new(); yourTeam.Add(PlayerControl.LocalPlayer); - foreach (PlayerControl pc in Main.AllPlayerControls.Where(x => !x.AmOwner)) - { - yourTeam.Add(pc); - } + foreach (PlayerControl pc in Main.AllPlayerControls.Where(x => !x.AmOwner)) yourTeam.Add(pc); __instance.BeginCrewmate(yourTeam); __instance.overlayHandle.color = new Color32(255, 171, 27, byte.MaxValue); @@ -824,10 +782,7 @@ namespace EHR { public static void Postfix( /*IntroCutscene __instance*/) { - if (!GameStates.IsInGame) - { - return; - } + if (!GameStates.IsInGame) return; Main.IntroDestroyed = true; @@ -845,19 +800,17 @@ namespace EHR { pc.SyncSettings(); pc.RpcResetAbilityCooldown(); + if (pc.GetCustomRole().UsesPetInsteadOfKill()) - { pc.AddAbilityCD(10); - } else - { pc.AddAbilityCD(false); - } Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc, NoCache: true); } int kcd = Options.StartingKillCooldown.GetInt(); + if (kcd is not 10 and > 0 && Options.CurrentGameMode != CustomGameMode.FFA) { LateTask.New(() => @@ -890,10 +843,7 @@ namespace EHR PlayerControl lp = PlayerControl.LocalPlayer; - if (lp.GetRoleTypes() == RoleTypes.Shapeshifter) - { - lp.RpcChangeRoleBasis(lp.GetCustomRole()); - } + if (lp.GetRoleTypes() == RoleTypes.Shapeshifter) lp.RpcChangeRoleBasis(lp.GetCustomRole()); if (Options.UsePets.GetBool()) { @@ -902,16 +852,13 @@ namespace EHR string[] pets = Options.PetToAssign; string pet = pets[Options.PetToAssignToEveryone.GetValue()]; - IRandom r = IRandom.Instance; + var r = IRandom.Instance; LateTask.New(() => { foreach (PlayerControl pc in aapc) { - if (pc.Is(CustomRoles.GM)) - { - continue; - } + if (pc.Is(CustomRoles.GM)) continue; string petId = pet == "pet_RANDOM_FOR_EVERYONE" ? pets[r.Next(0, pets.Length - 1)] : pet; pc.RpcSetPetDesync(petId, pc); @@ -920,6 +867,7 @@ namespace EHR AntiBlackout.SendGameData(); }, 0.3f, "Grant Pet For Everyone"); + try { LateTask.New(() => @@ -927,12 +875,10 @@ namespace EHR try { lp.Notify(GetString("GLHF"), 2f); + foreach (PlayerControl pc in aapc) { - if (pc.IsHost()) - { - continue; // Skip the host - } + if (pc.IsHost()) continue; // Skip the host try { @@ -951,17 +897,12 @@ namespace EHR } }, 0.4f, "Show Pet For Everyone"); } - catch - { - } + catch { } LateTask.New(() => Main.ProcessShapeshifts = true, 1f, "Enable SS Processing"); } - if (Options.UseUnshiftTrigger.GetBool() || Main.PlayerStates.Values.Any(x => x.MainRole.AlwaysUsesUnshift())) - { - LateTask.New(() => aapc.Do(x => x.CheckAndSetUnshiftState()), 2f, "UnshiftTrigger SS"); - } + if (Options.UseUnshiftTrigger.GetBool() || Main.PlayerStates.Values.Any(x => x.MainRole.AlwaysUsesUnshift())) LateTask.New(() => aapc.Do(x => x.CheckAndSetUnshiftState()), 2f, "UnshiftTrigger SS"); if (Main.GM.Value && lp.Is(CustomRoles.GM)) { @@ -983,15 +924,14 @@ namespace EHR 5 => new RandomSpawn.FungleSpawnMap(), _ => null }; - if (map != null && AmongUsClient.Instance.AmHost) - { - aapc.Do(map.RandomTeleport); - } + + if (map != null && AmongUsClient.Instance.AmHost) aapc.Do(map.RandomTeleport); } if (lp.HasDesyncRole()) { lp.Data.Role.AffectedByLightAffectors = false; + foreach (PlayerControl target in Main.AllPlayerControls) { // Set all players as killable players @@ -1005,20 +945,13 @@ namespace EHR Utils.CheckAndSetVentInteractions(); - if (AFKDetector.ActivateOnStart.GetBool()) - { - LateTask.New(() => aapc.Do(AFKDetector.RecordPosition), 1f, log: false); - } + if (AFKDetector.ActivateOnStart.GetBool()) LateTask.New(() => aapc.Do(AFKDetector.RecordPosition), 1f, log: false); LateTask.New(() => Main.Instance.StartCoroutine(Utils.NotifyEveryoneAsync()), 3f, log: false); } else - { foreach (PlayerControl player in Main.AllPlayerControls) - { Main.PlayerStates[player.PlayerId].InitTask(player); - } - } Logger.Info("OnDestroy", "IntroCutscene"); } diff --git a/Patches/JoinGameButtonPatch.cs b/Patches/JoinGameButtonPatch.cs index 93a6048d9..4ba9710eb 100644 --- a/Patches/JoinGameButtonPatch.cs +++ b/Patches/JoinGameButtonPatch.cs @@ -9,10 +9,7 @@ namespace EHR { public static void Prefix(JoinGameButton __instance) { - if (__instance.GameIdText == null) - { - return; - } + if (__instance.GameIdText == null) return; if (__instance.GameIdText.text == "" && Regex.IsMatch(GUIUtility.systemCopyBuffer.Trim('\r', '\n'), @"^[A-Z]{6}$")) { diff --git a/Patches/LadderPatch.cs b/Patches/LadderPatch.cs index a948b9fb9..354acdf38 100644 --- a/Patches/LadderPatch.cs +++ b/Patches/LadderPatch.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using HarmonyLib; -using Hazel; using UnityEngine; namespace EHR @@ -17,10 +16,7 @@ namespace EHR public static void OnClimbLadder(PlayerPhysics player, Ladder source) { - if (!Options.LadderDeath.GetBool()) - { - return; - } + if (!Options.LadderDeath.GetBool()) return; Vector3 sourcePos = source.transform.position; Vector3 targetPos = source.Destination.transform.position; @@ -28,43 +24,38 @@ namespace EHR if (sourcePos.y > targetPos.y) { int chance = IRandom.Instance.Next(1, 101); - if (chance <= Chance) - { - TargetLadderData[player.myPlayer.PlayerId] = targetPos; - } + if (chance <= Chance) TargetLadderData[player.myPlayer.PlayerId] = targetPos; } } public static void FixedUpdate(PlayerControl player) { - if (player.Data.Disconnected) - { - return; - } + if (player.Data.Disconnected) return; if (TargetLadderData.ContainsKey(player.PlayerId) && Vector2.Distance(TargetLadderData[player.PlayerId], player.transform.position) < 0.5f) { - if (player.Data.IsDead) - { - return; - } + if (player.Data.IsDead) return; // In order to insert LateTask, first enter the death judgment. player.Data.IsDead = true; + LateTask.New(() => { Vector2 targetPos = (Vector2)TargetLadderData[player.PlayerId] + new Vector2(0.1f, 0f); - ushort num = (ushort)(NetHelpers.XRange.ReverseLerp(targetPos.x) * 65535f); - ushort num2 = (ushort)(NetHelpers.YRange.ReverseLerp(targetPos.y) * 65535f); - CustomRpcSender sender = CustomRpcSender.Create("LadderFallRpc", SendOption.None); + var num = (ushort)(NetHelpers.XRange.ReverseLerp(targetPos.x) * 65535f); + var num2 = (ushort)(NetHelpers.YRange.ReverseLerp(targetPos.y) * 65535f); + var sender = CustomRpcSender.Create("LadderFallRpc"); + sender.AutoStartRpc(player.NetTransform.NetId, (byte)RpcCalls.SnapTo) .Write(num) .Write(num2) .EndRpc(); + sender.AutoStartRpc(player.NetId, (byte)RpcCalls.MurderPlayer) .WriteNetObject(player) .Write((byte)ExtendedPlayerControl.ResultFlags) .EndRpc(); + sender.SendMessage(); player.NetTransform.SnapTo(targetPos); player.MurderPlayer(player, ExtendedPlayerControl.ResultFlags); diff --git a/Patches/LobbyListPatch.cs b/Patches/LobbyListPatch.cs index 33f0f965a..e9090150c 100644 --- a/Patches/LobbyListPatch.cs +++ b/Patches/LobbyListPatch.cs @@ -15,21 +15,12 @@ namespace EHR public static void Postfix(FindAGameManager __instance) { - if ((RefreshButton = GameObject.Find("RefreshButton")) != null) - { - RefreshButton.transform.localPosition = new(100f, 100f, 100f); - } + if ((RefreshButton = GameObject.Find("RefreshButton")) != null) RefreshButton.transform.localPosition = new(100f, 100f, 100f); - if ((InputDisplayGlyph = GameObject.Find("InputDisplayGlyph")) != null) - { - InputDisplayGlyph.transform.localPosition = new(100f, 100f, 100f); - } + if ((InputDisplayGlyph = GameObject.Find("InputDisplayGlyph")) != null) InputDisplayGlyph.transform.localPosition = new(100f, 100f, 100f); buffer--; - if (buffer > 0) - { - return; - } + if (buffer > 0) return; buffer = 80; __instance.RefreshList(); @@ -47,10 +38,7 @@ namespace EHR foreach (GameListing game in games) { - if (game.Language.ToString().Length > 9) - { - continue; - } + if (game.Language.ToString().Length > 9) continue; string color = game.Platform switch { @@ -70,7 +58,7 @@ namespace EHR _ => "#ffffff" }; - string str = Math.Abs(game.GameId).ToString(); + var str = Math.Abs(game.GameId).ToString(); int id = Math.Min(Math.Max(int.Parse(str.Substring(str.Length - 2, 2)), 1) * nameList.Count / 100, nameList.Count); game.HostName = $"{nameList[id]}"; diff --git a/Patches/LobbyPatch.cs b/Patches/LobbyPatch.cs index 9ec3795c7..4b0363a05 100644 --- a/Patches/LobbyPatch.cs +++ b/Patches/LobbyPatch.cs @@ -16,12 +16,13 @@ namespace EHR if (Paint == null) { GameObject LeftBox = GameObject.Find("Leftbox"); + if (LeftBox != null) { Paint = Object.Instantiate(LeftBox, LeftBox.transform.parent.transform); Paint.name = "Lobby Paint"; Paint.transform.localPosition = new(0.042f, -2.59f, -10.5f); - SpriteRenderer renderer = Paint.GetComponent(); + var renderer = Paint.GetComponent(); renderer.sprite = Utils.LoadSprite("EHR.Resources.Images.LobbyPaint.png", 290f); } } @@ -35,21 +36,16 @@ namespace EHR public static void Postfix(HostInfoPanel __instance) { - if (HostText == null) - { - HostText = __instance.content.transform.FindChild("Name").GetComponent(); - } + if (HostText == null) HostText = __instance.content.transform.FindChild("Name").GetComponent(); string icon = Translator.GetString("Icon"); string name = GameData.Instance?.GetHost()?.PlayerName?.RemoveHtmlTags()?.Split('\n').FirstOrDefault(x => x.Contains(icon))?.Split(icon)[^1] ?? string.Empty; - if (name == string.Empty) - { - return; - } + if (name == string.Empty) return; string text = AmongUsClient.Instance.AmHost ? Translator.GetString("YouAreHostSuffix") : name; + HostText.text = Utils.ColorString(Palette.PlayerColors[__instance.player.ColorId], text); } } diff --git a/Patches/LogoAndStampPatch.cs b/Patches/LogoAndStampPatch.cs index fb83fe65d..200fd7753 100644 --- a/Patches/LogoAndStampPatch.cs +++ b/Patches/LogoAndStampPatch.cs @@ -23,6 +23,7 @@ namespace EHR while (true) { yield return new WaitForSeconds(1f); + if (__instance != null) { // ViewBoosterPatch(__instance); diff --git a/Patches/MainMenuManagerPatch.cs b/Patches/MainMenuManagerPatch.cs index a892c0ee5..3cd6e2878 100644 --- a/Patches/MainMenuManagerPatch.cs +++ b/Patches/MainMenuManagerPatch.cs @@ -61,15 +61,9 @@ namespace EHR [HarmonyPrefix] public static void Start_Prefix(MainMenuManager __instance) { - if (Template == null) - { - Template = __instance.quitButton; - } + if (Template == null) Template = __instance.quitButton; - if (Template == null) - { - return; - } + if (Template == null) return; if (UpdateButton == null) { @@ -80,6 +74,7 @@ namespace EHR new(255, 200, 0, byte.MaxValue), () => ModUpdater.StartUpdate(ModUpdater.DownloadUrl, true), Translator.GetString("updateButton")); + UpdateButton.transform.localScale = Vector3.one; } @@ -92,42 +87,29 @@ namespace EHR [HarmonyPostfix] public static void MainMenuManager_LateUpdate(MainMenuManager __instance) { - if (GameObject.Find("MainUI") == null) - { - ShowingPanel = false; - } + if (GameObject.Find("MainUI") == null) ShowingPanel = false; if (TitleLogoPatch.RightPanel != null) { Vector3 pos1 = TitleLogoPatch.RightPanel.transform.localPosition; Vector3 lerp1 = Vector3.Lerp(pos1, TitleLogoPatch.RightPanelOp + new Vector3(ShowingPanel ? 0f : 10f, 0f, 0f), Time.deltaTime * (ShowingPanel ? 3f : 2f)); + if (ShowingPanel ? TitleLogoPatch.RightPanel.transform.localPosition.x > TitleLogoPatch.RightPanelOp.x + 0.03f : TitleLogoPatch.RightPanel.transform.localPosition.x < TitleLogoPatch.RightPanelOp.x + 9f ) - { TitleLogoPatch.RightPanel.transform.localPosition = lerp1; - } } - if (ShowedBak || !IsOnline) - { - return; - } + if (ShowedBak || !IsOnline) return; GameObject bak = GameObject.Find("BackgroundTexture"); - if (bak == null || !bak.active) - { - return; - } + if (bak == null || !bak.active) return; Vector3 pos2 = bak.transform.position; Vector3 lerp2 = Vector3.Lerp(pos2, new(pos2.x, 7.1f, pos2.z), Time.deltaTime * 1.4f); bak.transform.position = lerp2; - if (pos2.y > 7f) - { - ShowedBak = true; - } + if (pos2.y > 7f) ShowedBak = true; } [HarmonyPatch(typeof(MainMenuManager), nameof(MainMenuManager.Start))] @@ -138,7 +120,7 @@ namespace EHR Instance = __instance; SimpleButton.SetBase(__instance.quitButton); - GameObject logoObject = new GameObject("titleLogo_MG"); + var logoObject = new GameObject("titleLogo_MG"); Transform logoTransform = logoObject.transform; MgLogo = logoObject.AddComponent(); logoTransform.localPosition = new(2f, -0.5f, 1f); @@ -191,7 +173,7 @@ namespace EHR foreach (string buttonName in new[] { "SettingsButton", "Inventory Button", "CreditsButton", "ExitGameButton" }) { - TMP_Text buttonText = GameObject.Find(buttonName).transform.Find("FontPlacer/Text_TMP").GetComponent(); + var buttonText = GameObject.Find(buttonName).transform.Find("FontPlacer/Text_TMP").GetComponent(); buttonText.DestroyTranslator(); buttonText.text = Translator.GetString($"MainMenu.{buttonName.Replace(" ", "")}"); } @@ -209,13 +191,13 @@ namespace EHR button.OnClick = new(); button.OnClick.AddListener(action); - TMP_Text buttonText = button.transform.Find("FontPlacer/Text_TMP").GetComponent(); + var buttonText = button.transform.Find("FontPlacer/Text_TMP").GetComponent(); buttonText.DestroyTranslator(); buttonText.fontSize = buttonText.fontSizeMax = buttonText.fontSizeMin = 3.5f; buttonText.enableWordWrapping = false; buttonText.text = label; - SpriteRenderer normalSprite = button.inactiveSprites.GetComponent(); - SpriteRenderer hoverSprite = button.activeSprites.GetComponent(); + var normalSprite = button.inactiveSprites.GetComponent(); + var hoverSprite = button.activeSprites.GetComponent(); normalSprite.color = normalColor; hoverSprite.color = hoverColor; @@ -226,11 +208,8 @@ namespace EHR buttonText.transform.SetLocalX(0f); buttonText.horizontalAlignment = HorizontalAlignmentOptions.Center; - BoxCollider2D buttonCollider = button.GetComponent(); - if (scale.HasValue) - { - normalSprite.size = hoverSprite.size = buttonCollider.size = scale.Value; - } + var buttonCollider = button.GetComponent(); + if (scale.HasValue) normalSprite.size = hoverSprite.size = buttonCollider.size = scale.Value; buttonCollider.offset = new(0f, 0f); diff --git a/Patches/MapPickerMenuPatch.cs b/Patches/MapPickerMenuPatch.cs index 7169429e4..0573df5ae 100644 --- a/Patches/MapPickerMenuPatch.cs +++ b/Patches/MapPickerMenuPatch.cs @@ -27,18 +27,16 @@ namespace EHR.Patches GameObject dlekS_ehT = Object.Instantiate(AllMapButton[0].gameObject, __instance.transform); dlekS_ehT.transform.position = AllMapButton[dleksPos].transform.position; dlekS_ehT.transform.SetSiblingIndex(dleksPos + 2); - MapSelectButton dlekS_ehT_MapButton = dlekS_ehT.GetComponent(); + var dlekS_ehT_MapButton = dlekS_ehT.GetComponent(); DleksButton = dlekS_ehT_MapButton; dlekS_ehT_MapButton.MapIcon.transform.localScale = new(-1f, 1f, 1f); dlekS_ehT_MapButton.Button.OnClick.RemoveAllListeners(); + dlekS_ehT_MapButton.Button.OnClick.AddListener((Action)(() => { __instance.SelectMap(__instance.AllMapIcons[0]); - if (__instance.selectedButton) - { - __instance.selectedButton.Button.SelectButton(false); - } + if (__instance.selectedButton) __instance.selectedButton.Button.SelectButton(false); __instance.selectedButton = dlekS_ehT_MapButton; __instance.selectedButton.Button.SelectButton(true); @@ -50,19 +48,13 @@ namespace EHR.Patches __instance.MapName.sprite = Utils.LoadSprite("EHR.Resources.Images.DleksBanner-Wordart.png", 100f); })); - for (int i = dleksPos; i < AllMapButton.Length; i++) - { - AllMapButton[i].transform.localPosition += new Vector3(0.625f, 0f, 0f); - } + for (int i = dleksPos; i < AllMapButton.Length; i++) AllMapButton[i].transform.localPosition += new Vector3(0.625f, 0f, 0f); if (DleksButton != null) { if (SetDleks) { - if (__instance.selectedButton) - { - __instance.selectedButton.Button.SelectButton(false); - } + if (__instance.selectedButton) __instance.selectedButton.Button.SelectButton(false); DleksButton.Button.SelectButton(true); __instance.selectedButton = DleksButton; @@ -72,9 +64,7 @@ namespace EHR.Patches __instance.MapName.sprite = Utils.LoadSprite("EHR.Resources.Images.DleksBanner-Wordart.png", 100f); } else - { DleksButton.Button.SelectButton(false); - } } } } @@ -83,10 +73,7 @@ namespace EHR.Patches [HarmonyPrefix] public static bool Prefix_FixedUpdate(GameOptionsMapPicker __instance) { - if (DleksButton != null) - { - SetDleks = __instance.selectedMapId == 3; - } + if (DleksButton != null) SetDleks = __instance.selectedMapId == 3; return __instance.selectedMapId != 3; } @@ -98,7 +85,7 @@ namespace EHR.Patches public static void Postfix(CreateOptionsPicker __instance) { Transform mapPickerTransform = __instance.transform.Find("MapPicker"); - MapPickerMenu mapPickerMenu = mapPickerTransform.Find("Map Picker Menu").GetComponent(); + var mapPickerMenu = mapPickerTransform.Find("Map Picker Menu").GetComponent(); MapFilterButton airhipIconInMenu = __instance.MapMenu.MapButtons[3]; MapFilterButton fungleIconInMenu = __instance.MapMenu.MapButtons[4]; @@ -112,10 +99,10 @@ namespace EHR.Patches Transform dleksMenuButtonCopy = Object.Instantiate(airshipMenuButton, airshipMenuButton.parent); // Set mapid for Dleks button - PassiveButton dleksButton = dleksMenuButtonCopy.GetComponent(); + var dleksButton = dleksMenuButtonCopy.GetComponent(); dleksButton.OnClick.m_PersistentCalls.m_Calls._items[0].arguments.intArgument = (int)MapNames.Dleks; - SpriteRenderer dleksImage = dleksMenuButtonCopy.Find("Image").GetComponent(); + var dleksImage = dleksMenuButtonCopy.Find("Image").GetComponent(); dleksImage.sprite = skeldMenuButton.Find("Image").GetComponent().sprite; dleksIconInMenuCopy.name = "Dleks"; @@ -134,7 +121,8 @@ namespace EHR.Patches __instance.MapMenu.MapButtons = __instance.MapMenu.MapButtons.AddItem(dleksIconInMenuCopy).ToArray(); float xPos = -1f; - for (int index = 0; index < 6; ++index) + + for (var index = 0; index < 6; ++index) { __instance.MapMenu.MapButtons[index].transform.SetLocalX(xPos); xPos += 0.34f; diff --git a/Patches/MeetingHudPatch.cs b/Patches/MeetingHudPatch.cs index 4ba59a9e9..26b186203 100644 --- a/Patches/MeetingHudPatch.cs +++ b/Patches/MeetingHudPatch.cs @@ -26,36 +26,26 @@ namespace EHR.Patches public static bool Prefix(MeetingHud __instance) { - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; - if (Medic.PlayerIdList.Count > 0) - { - Medic.OnCheckMark(); - } + if (Medic.PlayerIdList.Count > 0) Medic.OnCheckMark(); //Meeting Skip with vote counting on keystroke (m + delete) bool shouldSkip = Input.GetKeyDown(KeyCode.F6); LogHandler voteLog = Logger.Handler("Vote"); + try { List statesList = []; MeetingHud.VoterState[] states; + foreach (PlayerVoteArea pva in __instance.playerStates) { - if (pva == null) - { - continue; - } + if (pva == null) continue; PlayerControl pc = Utils.GetPlayerById(pva.TargetPlayerId); - if (pc == null) - { - continue; - } + if (pc == null) continue; // Dictators who are not dead have already voted. // Take the initiative to rebel @@ -75,11 +65,13 @@ namespace EHR.Patches { PlayerControl voteTarget = Utils.GetPlayerById(pva.VotedFor); TryAddAfterMeetingDeathPlayers(PlayerState.DeathReason.Suicide, pc.PlayerId); + statesList.Add(new() { VoterId = pva.TargetPlayerId, VotedForId = pva.VotedFor }); + states = [.. statesList]; __instance.RpcVotingComplete(states.ToArray(), voteTarget.Data, false); @@ -89,10 +81,7 @@ namespace EHR.Patches voteTarget.SetRealKiller(pc); Main.LastVotedPlayerInfo = voteTarget.Data; AntiBlackout.ExilePlayerId = voteTarget.PlayerId; - if (Main.LastVotedPlayerInfo != null) - { - ConfirmEjections(Main.LastVotedPlayerInfo, false); - } + if (Main.LastVotedPlayerInfo != null) ConfirmEjections(Main.LastVotedPlayerInfo, false); return true; } @@ -100,6 +89,7 @@ namespace EHR.Patches if (pva.DidVote && pva.VotedFor < 253 && pc.IsAlive()) { PlayerControl voteTarget = Utils.GetPlayerById(pva.VotedFor); + if (voteTarget == null || !voteTarget.IsAlive() || voteTarget.Data == null || voteTarget.Data.Disconnected) { pva.UnsetVote(); @@ -108,38 +98,24 @@ namespace EHR.Patches pva.VotedFor = byte.MaxValue; } else if (voteTarget != null && !pc.GetCustomRole().CancelsVote()) - { Main.PlayerStates[pc.PlayerId].Role.OnVote(pc, voteTarget); - } - else if (pc.Is(CustomRoles.Godfather)) - { - Godfather.GodfatherTarget = byte.MaxValue; - } + else if (pc.Is(CustomRoles.Godfather)) Godfather.GodfatherTarget = byte.MaxValue; } } - if (!shouldSkip && !__instance.playerStates.All(ps => ps == null || !Main.PlayerStates.TryGetValue(ps.TargetPlayerId, out PlayerState st) || st.IsDead || ps.DidVote || Utils.GetPlayerById(ps.TargetPlayerId) == null || Utils.GetPlayerById(ps.TargetPlayerId).Data == null || Utils.GetPlayerById(ps.TargetPlayerId).Data.Disconnected)) - { - return false; - } + if (!shouldSkip && !__instance.playerStates.All(ps => ps == null || !Main.PlayerStates.TryGetValue(ps.TargetPlayerId, out PlayerState st) || st.IsDead || ps.DidVote || Utils.GetPlayerById(ps.TargetPlayerId) == null || Utils.GetPlayerById(ps.TargetPlayerId).Data == null || Utils.GetPlayerById(ps.TargetPlayerId).Data.Disconnected)) return false; NetworkedPlayerInfo exiledPlayer = PlayerControl.LocalPlayer.Data; - bool tie = false; + var tie = false; EjectionText = string.Empty; foreach (PlayerVoteArea ps in __instance.playerStates) { - if (ps == null) - { - continue; - } + if (ps == null) continue; voteLog.Info($"{ps.TargetPlayerId,-2}{$"({Utils.GetVoteName(ps.TargetPlayerId)})".PadRightV2(40)}:{ps.VotedFor,-3}({Utils.GetVoteName(ps.VotedFor)})"); PlayerControl voter = Utils.GetPlayerById(ps.TargetPlayerId); - if (voter == null || voter.Data == null || voter.Data.Disconnected) - { - continue; - } + if (voter == null || voter.Data == null || voter.Data.Disconnected) continue; if (Options.VoteMode.GetBool()) { @@ -182,57 +158,27 @@ namespace EHR.Patches } } - if (CheckRole(ps.TargetPlayerId, CustomRoles.Divinator) && Divinator.HideVote.GetBool()) - { - continue; - } + if (CheckRole(ps.TargetPlayerId, CustomRoles.Divinator) && Divinator.HideVote.GetBool()) continue; - if (CheckRole(ps.TargetPlayerId, CustomRoles.Eraser) && Eraser.HideVote.GetBool()) - { - continue; - } + if (CheckRole(ps.TargetPlayerId, CustomRoles.Eraser) && Eraser.HideVote.GetBool()) continue; - if (CheckRole(ps.TargetPlayerId, CustomRoles.NiceEraser) && NiceEraser.HideVote.GetBool()) - { - continue; - } + if (CheckRole(ps.TargetPlayerId, CustomRoles.NiceEraser) && NiceEraser.HideVote.GetBool()) continue; - if (CheckRole(ps.TargetPlayerId, CustomRoles.Scout) && Scout.HideVote.GetBool()) - { - continue; - } + if (CheckRole(ps.TargetPlayerId, CustomRoles.Scout) && Scout.HideVote.GetBool()) continue; - if (CheckRole(ps.TargetPlayerId, CustomRoles.Oracle) && Oracle.HideVote.GetBool()) - { - continue; - } + if (CheckRole(ps.TargetPlayerId, CustomRoles.Oracle) && Oracle.HideVote.GetBool()) continue; - if (ps.TargetPlayerId == ps.VotedFor && Options.MadmateSpawnMode.GetInt() == 2 && CustomRoles.Madmate.IsEnable() && MeetingStates.FirstMeeting) - { - continue; - } + if (ps.TargetPlayerId == ps.VotedFor && Options.MadmateSpawnMode.GetInt() == 2 && CustomRoles.Madmate.IsEnable() && MeetingStates.FirstMeeting) continue; AddVote(); - if (Main.PlayerStates[ps.TargetPlayerId].Role is Adventurer { IsEnable: true } av && av.ActiveWeapons.Contains(Adventurer.Weapon.Proxy)) - { - AddVote(); - } + if (Main.PlayerStates[ps.TargetPlayerId].Role is Adventurer { IsEnable: true } av && av.ActiveWeapons.Contains(Adventurer.Weapon.Proxy)) AddVote(); - if (CheckRole(ps.TargetPlayerId, CustomRoles.Mayor) && !Mayor.MayorHideVote.GetBool()) - { - Loop.Times(Mayor.MayorAdditionalVote.GetInt(), _ => AddVote()); - } + if (CheckRole(ps.TargetPlayerId, CustomRoles.Mayor) && !Mayor.MayorHideVote.GetBool()) Loop.Times(Mayor.MayorAdditionalVote.GetInt(), _ => AddVote()); - if (CheckRole(ps.TargetPlayerId, CustomRoles.Vindicator) && !Options.VindicatorHideVote.GetBool()) - { - Loop.Times(Options.VindicatorAdditionalVote.GetInt(), _ => AddVote()); - } + if (CheckRole(ps.TargetPlayerId, CustomRoles.Vindicator) && !Options.VindicatorHideVote.GetBool()) Loop.Times(Options.VindicatorAdditionalVote.GetInt(), _ => AddVote()); - if (CheckRole(ps.TargetPlayerId, CustomRoles.Knighted)) - { - AddVote(); - } + if (CheckRole(ps.TargetPlayerId, CustomRoles.Knighted)) AddVote(); if (CheckRole(ps.TargetPlayerId, CustomRoles.DualPersonality) && Options.DualVotes.GetBool()) { @@ -242,13 +188,13 @@ namespace EHR.Patches if (CheckRole(ps.TargetPlayerId, CustomRoles.TicketsStealer)) { - int count = (int)(Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == ps.TargetPlayerId) * Options.TicketsPerKill.GetFloat()); + var count = (int)(Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == ps.TargetPlayerId) * Options.TicketsPerKill.GetFloat()); Loop.Times(count, _ => AddVote()); } if (CheckRole(ps.TargetPlayerId, CustomRoles.Pickpocket)) { - int count = (int)(Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == ps.TargetPlayerId) * Pickpocket.VotesPerKill.GetFloat()); + var count = (int)(Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == ps.TargetPlayerId) * Pickpocket.VotesPerKill.GetFloat()); Loop.Times(count, _ => AddVote()); } @@ -278,19 +224,18 @@ namespace EHR.Patches Dictionary VotingData = __instance.CustomCalculateVotes(); Assumer.OnVotingEnd(VotingData); - byte exileId = byte.MaxValue; - int max = 0; + var exileId = byte.MaxValue; + var max = 0; voteLog.Info("===Decision to expel player processing begins==="); + foreach (KeyValuePair data in VotingData) { voteLog.Info($"{data.Key} ({Utils.GetVoteName(data.Key)}): {data.Value} votes"); + if (data.Value > max) { voteLog.Info($"{data.Key} has higher votes ({data.Value})"); - if (Dad.OnVotedOut(data.Key)) - { - continue; - } + if (Dad.OnVotedOut(data.Key)) continue; exileId = data.Key; max = data.Value; @@ -308,10 +253,12 @@ namespace EHR.Patches voteLog.Info($"Decided to eject: {exileId} ({Utils.GetVoteName(exileId)})"); - bool braked = false; + var braked = false; + if (tie) { - byte target = byte.MaxValue; + var target = byte.MaxValue; + foreach (KeyValuePair data in VotingData.Where(x => x.Key < 15 && x.Value == max)) { if (Main.BrakarVoteFor.Contains(data.Key)) @@ -346,10 +293,7 @@ namespace EHR.Patches break; case TieMode.All: byte[] exileIds = VotingData.Where(x => x.Key < 15 && x.Value == max).Select(kvp => kvp.Key).ToArray(); - foreach (byte playerId in exileIds) - { - Utils.GetPlayerById(playerId).SetRealKiller(null); - } + foreach (byte playerId in exileIds) Utils.GetPlayerById(playerId).SetRealKiller(null); TryAddAfterMeetingDeathPlayers(PlayerState.DeathReason.Vote, exileIds); exiledPlayer = null; @@ -360,10 +304,7 @@ namespace EHR.Patches break; } } - else if (!braked) - { - exiledPlayer = GameData.Instance.AllPlayers.ToArray().FirstOrDefault(info => !tie && info.PlayerId == exileId); - } + else if (!braked) exiledPlayer = GameData.Instance.AllPlayers.ToArray().FirstOrDefault(info => !tie && info.PlayerId == exileId); exiledPlayer?.Object.SetRealKiller(null); @@ -374,16 +315,14 @@ namespace EHR.Patches Main.LastVotedPlayerInfo = exiledPlayer; AntiBlackout.ExilePlayerId = exileId; + if (Main.LastVotedPlayerInfo != null) { AntiBlackout.ExilePlayerId = exileId; ConfirmEjections(Main.LastVotedPlayerInfo, braked); } - if (QuizMaster.On) - { - QuizMaster.Data.NumPlayersVotedLastMeeting = __instance.playerStates.Count(x => x.DidVote); - } + if (QuizMaster.On) QuizMaster.Data.NumPlayersVotedLastMeeting = __instance.playerStates.Count(x => x.DidVote); return false; } @@ -397,21 +336,12 @@ namespace EHR.Patches // Reference:https://github.com/music-discussion/TownOfHost-TheOtherRoles private static void ConfirmEjections(NetworkedPlayerInfo exiledPlayer, bool tiebreaker) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; - if (exiledPlayer == null) - { - return; - } + if (exiledPlayer == null) return; byte exileId = exiledPlayer.PlayerId; - if (exileId > 254) - { - return; - } + if (exileId > 254) return; string realName = exiledPlayer.Object.GetRealName(true); @@ -429,26 +359,17 @@ namespace EHR.Patches }).ToColoredString(); } - if (Options.ConfirmEgoistOnEject.GetBool() && player.Is(CustomRoles.Egoist)) - { - coloredRole = Utils.ColorString(Utils.GetRoleColor(CustomRoles.Egoist), GetRoleString("Temp.Blank") + coloredRole.RemoveHtmlTags()); - } + if (Options.ConfirmEgoistOnEject.GetBool() && player.Is(CustomRoles.Egoist)) coloredRole = Utils.ColorString(Utils.GetRoleColor(CustomRoles.Egoist), GetRoleString("Temp.Blank") + coloredRole.RemoveHtmlTags()); - if (Options.ConfirmLoversOnEject.GetBool() && Main.LoversPlayers.Exists(x => x.PlayerId == player.PlayerId)) - { - coloredRole = Utils.ColorString(Utils.GetRoleColor(CustomRoles.Lovers), GetRoleString("Temp.Blank") + coloredRole.RemoveHtmlTags()); - } + if (Options.ConfirmLoversOnEject.GetBool() && Main.LoversPlayers.Exists(x => x.PlayerId == player.PlayerId)) coloredRole = Utils.ColorString(Utils.GetRoleColor(CustomRoles.Lovers), GetRoleString("Temp.Blank") + coloredRole.RemoveHtmlTags()); - if (Options.RascalAppearAsMadmate.GetBool() && player.Is(CustomRoles.Rascal)) - { - coloredRole = Utils.ColorString(Utils.GetRoleColor(CustomRoles.Madmate), GetRoleString("Mad-") + coloredRole.RemoveHtmlTags()); - } + if (Options.RascalAppearAsMadmate.GetBool() && player.Is(CustomRoles.Rascal)) coloredRole = Utils.ColorString(Utils.GetRoleColor(CustomRoles.Madmate), GetRoleString("Mad-") + coloredRole.RemoveHtmlTags()); - string name = string.Empty; - int impnum = 0; - int neutralnum = 0; + var name = string.Empty; + var impnum = 0; + var neutralnum = 0; - bool DecidedWinner = false; + var DecidedWinner = false; if (CustomRoles.Bard.RoleExist()) { @@ -458,26 +379,17 @@ namespace EHR.Patches foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (pc == exiledPlayer.Object) - { - continue; - } + if (pc == exiledPlayer.Object) continue; if (pc.GetCustomRole().IsImpostor()) - { impnum++; - } else if (Options.MadmateCountMode.GetValue() == 1 && pc.IsMadmate()) - { impnum++; - } - else if (pc.IsNeutralKiller()) - { - neutralnum++; - } + else if (pc.IsNeutralKiller()) neutralnum++; } string coloredRealName = Utils.ColorString(Main.PlayerColors[player.PlayerId], realName); + switch (Options.CEMode.GetInt()) { case 0: @@ -485,29 +397,22 @@ namespace EHR.Patches break; case 1: if (player.IsImpostor() || player.Is(CustomRoles.Parasite) || player.Is(CustomRoles.Crewpostor) || player.Is(CustomRoles.Refugee) || player.Is(CustomRoles.Convict)) - { name = string.Format(GetString("BelongTo"), coloredRealName, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Impostor), GetString("TeamImpostor"))); - } else if (player.IsCrewmate()) - { name = string.Format(GetString("IsGood"), coloredRealName); - } - else if (player.GetCustomRole().IsNeutral() && !player.Is(CustomRoles.Parasite) && !player.Is(CustomRoles.Refugee) && !player.Is(CustomRoles.Crewpostor) && !player.Is(CustomRoles.Convict)) - { - name = string.Format(GetString("BelongTo"), coloredRealName, Utils.ColorString(new(255, 171, 27, byte.MaxValue), GetString("TeamNeutral"))); - } + else if (player.GetCustomRole().IsNeutral() && !player.Is(CustomRoles.Parasite) && !player.Is(CustomRoles.Refugee) && !player.Is(CustomRoles.Crewpostor) && !player.Is(CustomRoles.Convict)) name = string.Format(GetString("BelongTo"), coloredRealName, Utils.ColorString(new(255, 171, 27, byte.MaxValue), GetString("TeamNeutral"))); break; case 2: name = string.Format(GetString("PlayerIsRole"), coloredRealName, coloredRole); + if (Options.ShowTeamNextToRoleNameOnEject.GetBool()) { name += " ("; CustomTeamManager.CustomTeam team = CustomTeamManager.GetCustomTeam(player.PlayerId); + if (team != null) - { name += Utils.ColorString(team.RoleRevealScreenBackgroundColor == "*" || !ColorUtility.TryParseHtmlString(team.RoleRevealScreenBackgroundColor, out Color color) ? Color.yellow : color, team.RoleRevealScreenTitle == "*" ? team.TeamName : team.RoleRevealScreenTitle); - } else { name += player.GetTeam() switch @@ -542,35 +447,23 @@ namespace EHR.Patches if (!(!Options.InnocentCanWinByImp.GetBool() && crole.IsImpostor())) { if (DecidedWinner) - { name += string.Format(GetString("ExiledInnocentTargetAddBelow")); - } else - { name = string.Format(GetString("ExiledInnocentTargetInOneLine"), realName, coloredRole); - } DecidedWinner = true; } } - if (tiebreaker) - { - name += $" ({Utils.ColorString(Utils.GetRoleColor(CustomRoles.Brakar), GetString("Brakar"))})"; - } + if (tiebreaker) name += $" ({Utils.ColorString(Utils.GetRoleColor(CustomRoles.Brakar), GetString("Brakar"))})"; if (DecidedWinner) - { name += ""; - } else if (Options.ShowImpRemainOnEject.GetBool()) { name += "\n"; int actualNeutralnum = neutralnum; - if (!Options.ShowNKRemainOnEject.GetBool()) - { - neutralnum = 0; - } + if (!Options.ShowNKRemainOnEject.GetBool()) neutralnum = 0; switch (impnum, neutralnum) { @@ -588,14 +481,11 @@ namespace EHR.Patches 3 => $"3 {GetString("RemainingText.ImpPlural")} & ", _ => string.Empty }; + if (neutralnum == 1) - { name += $"1 {GetString("RemainingText.NKSingle")} {GetString("RemainingText.EjectionSuffix.NKSingle")}"; - } else - { name += $"{neutralnum} {GetString("RemainingText.NKPlural")} {GetString("RemainingText.EjectionSuffix.NKPlural")}"; - } break; case (> 0, 0): // Only imps remain @@ -606,16 +496,13 @@ namespace EHR.Patches 3 => GetString("ThreeImpRemain"), _ => string.Empty }; + break; case (0, > 0): // Only neutrals remain if (neutralnum == 1) - { name += GetString("OneNeutralRemain"); - } else - { name += string.Format(GetString("NeutralRemain"), neutralnum); - } break; } @@ -630,12 +517,14 @@ namespace EHR.Patches LateTask.New(() => { Main.DoBlockNameChange = true; + if (GameStates.IsInGame && player != null && !player.Data.Disconnected) { exiledPlayer.UpdateName(name, Utils.GetClientById(exiledPlayer.ClientId)); player.RpcSetName(name); } }, 2.5f, "Change Exiled Player Name"); + LateTask.New(() => { if (GameStates.IsInGame && player != null && !player.Data.Disconnected) @@ -664,40 +553,22 @@ namespace EHR.Patches { try { - if (Witch.PlayerIdList.Count > 0) - { - Witch.OnCheckForEndVoting(deathReason, playerIds); - } + if (Witch.PlayerIdList.Count > 0) Witch.OnCheckForEndVoting(deathReason, playerIds); - if (Virus.PlayerIdList.Count > 0) - { - Virus.OnCheckForEndVoting(deathReason, playerIds); - } + if (Virus.PlayerIdList.Count > 0) Virus.OnCheckForEndVoting(deathReason, playerIds); - if (deathReason == PlayerState.DeathReason.Vote) - { - Gaslighter.OnExile(playerIds); - } + if (deathReason == PlayerState.DeathReason.Vote) Gaslighter.OnExile(playerIds); - if (Wasp.On && deathReason == PlayerState.DeathReason.Vote) - { - Wasp.OnExile(playerIds); - } + if (Wasp.On && deathReason == PlayerState.DeathReason.Vote) Wasp.OnExile(playerIds); foreach (byte playerId in playerIds) { try { byte id = playerId; - if (CustomRoles.Lovers.IsEnable() && !Main.IsLoversDead && Main.LoversPlayers.Exists(lp => lp.PlayerId == id)) - { - FixedUpdatePatch.LoversSuicide(playerId, true, true); - } + if (CustomRoles.Lovers.IsEnable() && !Main.IsLoversDead && Main.LoversPlayers.Exists(lp => lp.PlayerId == id)) FixedUpdatePatch.LoversSuicide(playerId, true, true); - if (Main.PlayerStates.TryGetValue(id, out PlayerState state) && state.SubRoles.Contains(CustomRoles.Avanger)) - { - RevengeOnExile(playerId /*, deathReason*/); - } + if (Main.PlayerStates.TryGetValue(id, out PlayerState state) && state.SubRoles.Contains(CustomRoles.Avanger)) RevengeOnExile(playerId /*, deathReason*/); } catch (Exception e) { @@ -714,16 +585,10 @@ namespace EHR.Patches private static void RevengeOnExile(byte playerId /*, PlayerState.DeathReason deathReason*/) { PlayerControl player = Utils.GetPlayerById(playerId); - if (player == null) - { - return; - } + if (player == null) return; PlayerControl target = PickRevengeTarget(player /*, deathReason*/); - if (target == null) - { - return; - } + if (target == null) return; TryAddAfterMeetingDeathPlayers(PlayerState.DeathReason.Revenge, target.PlayerId); target.SetRealKiller(player); @@ -735,10 +600,7 @@ namespace EHR.Patches List TargetList = []; TargetList.AddRange(Main.AllAlivePlayerControls.Where(candidate => candidate != exiledplayer && !Main.AfterMeetingDeathPlayers.ContainsKey(candidate.PlayerId))); - if (TargetList.Count == 0) - { - return null; - } + if (TargetList.Count == 0) return null; PlayerControl target = TargetList.RandomElement(); return target; @@ -753,85 +615,47 @@ namespace EHR.Patches Dictionary dic = []; Main.BrakarVoteFor = []; Collector.CollectorVoteFor = []; + foreach (PlayerVoteArea ps in __instance.playerStates) { - if (ps == null) - { - continue; - } + if (ps == null) continue; if (ps.VotedFor is not 252 and not byte.MaxValue and not 254) { - int VoteNum = 1; + var VoteNum = 1; PlayerControl target = Utils.GetPlayerById(ps.VotedFor); + if (target != null) { - if (target.Is(CustomRoles.Zombie)) - { - VoteNum = 0; - } + if (target.Is(CustomRoles.Zombie)) VoteNum = 0; if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Brakar)) - { if (!Main.BrakarVoteFor.Contains(target.PlayerId)) - { Main.BrakarVoteFor.Add(target.PlayerId); - } - } Collector.CollectorVotes(target, ps); } - if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Mayor)) - { - VoteNum += Mayor.MayorAdditionalVote.GetInt(); - } + if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Mayor)) VoteNum += Mayor.MayorAdditionalVote.GetInt(); - if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Knighted)) - { - VoteNum += 1; - } + if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Knighted)) VoteNum += 1; - if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Glitch) && !Glitch.CanVote.GetBool()) - { - VoteNum = 0; - } + if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Glitch) && !Glitch.CanVote.GetBool()) VoteNum = 0; - if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Vindicator)) - { - VoteNum += Options.VindicatorAdditionalVote.GetInt(); - } + if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Vindicator)) VoteNum += Options.VindicatorAdditionalVote.GetInt(); - if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.DualPersonality) && Options.DualVotes.GetBool()) - { - VoteNum += VoteNum; - } + if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.DualPersonality) && Options.DualVotes.GetBool()) VoteNum += VoteNum; - if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.TicketsStealer)) - { - VoteNum += (int)(Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == ps.TargetPlayerId) * Options.TicketsPerKill.GetFloat()); - } + if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.TicketsStealer)) VoteNum += (int)(Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == ps.TargetPlayerId) * Options.TicketsPerKill.GetFloat()); - if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Pickpocket)) - { - VoteNum += (int)(Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == ps.TargetPlayerId) * Pickpocket.VotesPerKill.GetFloat()); - } + if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Pickpocket)) VoteNum += (int)(Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == ps.TargetPlayerId) * Pickpocket.VotesPerKill.GetFloat()); - if (Main.PlayerStates[ps.TargetPlayerId].Role is Adventurer { IsEnable: true } av && av.ActiveWeapons.Contains(Adventurer.Weapon.Proxy)) - { - VoteNum++; - } + if (Main.PlayerStates[ps.TargetPlayerId].Role is Adventurer { IsEnable: true } av && av.ActiveWeapons.Contains(Adventurer.Weapon.Proxy)) VoteNum++; - if (Main.PlayerStates[ps.TargetPlayerId].Role is Dad { IsEnable: true } dad && dad.UsingAbilities.Contains(Dad.Ability.GoForMilk)) - { - VoteNum = 0; - } + if (Main.PlayerStates[ps.TargetPlayerId].Role is Dad { IsEnable: true } dad && dad.UsingAbilities.Contains(Dad.Ability.GoForMilk)) VoteNum = 0; - if (ps.TargetPlayerId == ps.VotedFor && Options.MadmateSpawnMode.GetInt() == 2 && CustomRoles.Madmate.IsEnable() && MeetingStates.FirstMeeting) - { - VoteNum = 0; - } + if (ps.TargetPlayerId == ps.VotedFor && Options.MadmateSpawnMode.GetInt() == 2 && CustomRoles.Madmate.IsEnable() && MeetingStates.FirstMeeting) VoteNum = 0; dic[ps.VotedFor] = !dic.TryGetValue(ps.VotedFor, out int num) ? VoteNum : num + VoteNum; } @@ -846,10 +670,7 @@ namespace EHR.Patches { private static void NotifyRoleSkillOnMeetingStart() { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; CheckForEndVotingPatch.RunRoleCode = true; @@ -859,10 +680,7 @@ namespace EHR.Patches { foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (pc.IsModClient()) - { - continue; - } + if (pc.IsModClient()) continue; CustomRoles role = pc.GetCustomRole(); StringBuilder sb = new(); @@ -872,21 +690,16 @@ namespace EHR.Patches titleSb.Append($"{role.ToColoredString()} {Utils.GetRoleMode(role)}"); sb.Append(""); sb.Append(pc.GetRoleInfo(true).TrimStart()); - if (Options.CustomRoleSpawnChances.TryGetValue(role, out StringOptionItem opt)) - { - Utils.ShowChildrenSettings(opt, ref settings, disableColor: false); - } + if (Options.CustomRoleSpawnChances.TryGetValue(role, out StringOptionItem opt)) Utils.ShowChildrenSettings(opt, ref settings, disableColor: false); settings.Append(""); - if (role.PetActivatedAbility()) - { - sb.Append($"{GetString("SupportsPetMessage")}"); - } + if (role.PetActivatedAbility()) sb.Append($"{GetString("SupportsPetMessage")}"); string searchStr = GetString(role.ToString()); sb.Replace(searchStr, role.ToColoredString()); sb.Replace(searchStr.ToLower(), role.ToColoredString()); sb.Append(""); + foreach (CustomRoles subRole in Main.PlayerStates[pc.PlayerId].SubRoles) { sb.Append($"\n\n{subRole.ToColoredString()} {Utils.GetRoleMode(subRole)} {GetString($"{subRole}InfoLong")}"); @@ -895,36 +708,21 @@ namespace EHR.Patches sb.Replace(searchSubStr.ToLower(), subRole.ToColoredString()); } - if (settings.Length > 0) - { - AddMsg("\n", pc.PlayerId, settings.ToString()); - } + if (settings.Length > 0) AddMsg("\n", pc.PlayerId, settings.ToString()); AddMsg(sb.Append("").ToString(), pc.PlayerId, titleSb.ToString()); } } - if (msgToSend.Count > 0) - { - LateTask.New(() => { msgToSend.Do(x => Utils.SendMessage(x.Message, x.TargetID, x.Title)); }, 3f, "Skill Description First Meeting"); - } + if (msgToSend.Count > 0) LateTask.New(() => { msgToSend.Do(x => Utils.SendMessage(x.Message, x.TargetID, x.Title)); }, 3f, "Skill Description First Meeting"); - if (Options.MadmateSpawnMode.GetInt() == 2 && CustomRoles.Madmate.IsEnable() && MeetingStates.FirstMeeting) - { - AddMsg(string.Format(GetString("Message.MadmateSelfVoteModeNotify"), GetString("MadmateSpawnMode.SelfVote"))); - } + if (Options.MadmateSpawnMode.GetInt() == 2 && CustomRoles.Madmate.IsEnable() && MeetingStates.FirstMeeting) AddMsg(string.Format(GetString("Message.MadmateSelfVoteModeNotify"), GetString("MadmateSpawnMode.SelfVote"))); - if (CustomRoles.God.RoleExist() && God.NotifyGodAlive.GetBool()) - { - AddMsg(GetString("GodNoticeAlive"), 255, Utils.ColorString(Utils.GetRoleColor(CustomRoles.God), GetString("GodAliveTitle"))); - } + if (CustomRoles.God.RoleExist() && God.NotifyGodAlive.GetBool()) AddMsg(GetString("GodNoticeAlive"), 255, Utils.ColorString(Utils.GetRoleColor(CustomRoles.God), GetString("GodAliveTitle"))); if (MeetingStates.FirstMeeting && CustomRoles.Workaholic.RoleExist() && Workaholic.WorkaholicGiveAdviceAlive.GetBool() && !Workaholic.WorkaholicCannotWinAtDeath.GetBool() /* && !Options.GhostIgnoreTasks.GetBool()*/) { - foreach (PlayerControl pc in Main.AllAlivePlayerControls.Where(x => x.Is(CustomRoles.Workaholic)).ToArray()) - { - Workaholic.WorkaholicAlive.Add(pc.PlayerId); - } + foreach (PlayerControl pc in Main.AllAlivePlayerControls.Where(x => x.Is(CustomRoles.Workaholic)).ToArray()) Workaholic.WorkaholicAlive.Add(pc.PlayerId); List workaholicAliveList = []; workaholicAliveList.AddRange(Workaholic.WorkaholicAlive.Select(whId => Main.AllPlayerNames[whId])); @@ -936,10 +734,7 @@ namespace EHR.Patches // Bait Notify if (MeetingStates.FirstMeeting && CustomRoles.Bait.RoleExist() && Options.BaitNotification.GetBool()) { - foreach (PlayerControl pc in Main.AllAlivePlayerControls.Where(x => x.Is(CustomRoles.Bait)).ToArray()) - { - Main.BaitAlive.Add(pc.PlayerId); - } + foreach (PlayerControl pc in Main.AllAlivePlayerControls.Where(x => x.Is(CustomRoles.Bait)).ToArray()) Main.BaitAlive.Add(pc.PlayerId); List baitAliveList = []; baitAliveList.AddRange(Main.BaitAlive.Select(whId => Main.AllPlayerNames[whId])); @@ -948,25 +743,17 @@ namespace EHR.Patches AddMsg(string.Format(GetString("BaitAdviceAlive"), string.Join(separator, baitAliveList)), 255, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Bait), GetString("BaitAliveTitle"))); } - string MimicMsg = string.Empty; + var MimicMsg = string.Empty; + foreach (PlayerControl pc in Main.AllPlayerControls) { - if (pc.Is(CustomRoles.Mafia) && !pc.IsAlive()) - { - AddMsg(GetString("MafiaDeadMsg"), pc.PlayerId); - } + if (pc.Is(CustomRoles.Mafia) && !pc.IsAlive()) AddMsg(GetString("MafiaDeadMsg"), pc.PlayerId); foreach (byte csId in Main.CyberStarDead) { - if (!Options.ImpKnowCyberStarDead.GetBool() && pc.GetCustomRole().IsImpostor()) - { - continue; - } + if (!Options.ImpKnowCyberStarDead.GetBool() && pc.GetCustomRole().IsImpostor()) continue; - if (!Options.NeutralKnowCyberStarDead.GetBool() && pc.GetCustomRole().IsNeutral()) - { - continue; - } + if (!Options.NeutralKnowCyberStarDead.GetBool() && pc.GetCustomRole().IsNeutral()) continue; AddMsg(string.Format(GetString("CyberStarDead"), Main.AllPlayerNames[csId]), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.CyberStar), GetString("CyberStarNewsTitle"))); } @@ -974,23 +761,14 @@ namespace EHR.Patches if (pc != null && Silencer.ForSilencer.Contains(pc.PlayerId)) { string playername = pc.GetRealName(); - if (Doppelganger.DoppelVictim.TryGetValue(pc.PlayerId, out string value)) - { - playername = value; - } + if (Doppelganger.DoppelVictim.TryGetValue(pc.PlayerId, out string value)) playername = value; AddMsg(string.Format(GetString("SilencerDead"), playername, pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Silencer), GetString("SilencerKillTitle")))); } - if (Detective.DetectiveNotify.TryGetValue(pc.PlayerId, out string value1)) - { - AddMsg(value1, pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Detective), GetString("DetectiveNoticeTitle"))); - } + if (Detective.DetectiveNotify.TryGetValue(pc.PlayerId, out string value1)) AddMsg(value1, pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Detective), GetString("DetectiveNoticeTitle"))); - if (Main.SleuthMsgs.TryGetValue(pc.PlayerId, out string msg)) - { - AddMsg(msg, pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Sleuth), GetString("Sleuth"))); - } + if (Main.SleuthMsgs.TryGetValue(pc.PlayerId, out string msg)) AddMsg(msg, pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Sleuth), GetString("Sleuth"))); if (pc.Is(CustomRoles.Mimic) && !pc.IsAlive()) { @@ -998,30 +776,15 @@ namespace EHR.Patches Main.AllAlivePlayerControls.Where(x => x.GetRealKiller()?.PlayerId == pc1.PlayerId).Do(x => MimicMsg += $"\n{x.GetNameWithRole(true)}"); } - if (Mortician.MsgToSend.TryGetValue(pc.PlayerId, out string value2)) - { - AddMsg(value2, pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Mortician), GetString("MorticianCheckTitle"))); - } + if (Mortician.MsgToSend.TryGetValue(pc.PlayerId, out string value2)) AddMsg(value2, pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Mortician), GetString("MorticianCheckTitle"))); - if (Mediumshiper.ContactPlayer.ContainsValue(pc.PlayerId)) - { - AddMsg(string.Format(GetString("MediumshipNotifySelf"), Main.AllPlayerNames[Mediumshiper.ContactPlayer.FirstOrDefault(x => x.Value == pc.PlayerId).Key], pc.GetAbilityUseLimit()), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Mediumshiper), GetString("MediumshipTitle"))); - } + if (Mediumshiper.ContactPlayer.ContainsValue(pc.PlayerId)) AddMsg(string.Format(GetString("MediumshipNotifySelf"), Main.AllPlayerNames[Mediumshiper.ContactPlayer.FirstOrDefault(x => x.Value == pc.PlayerId).Key], pc.GetAbilityUseLimit()), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Mediumshiper), GetString("MediumshipTitle"))); - if (Mediumshiper.ContactPlayer.ContainsKey(pc.PlayerId) && (!Mediumshiper.OnlyReceiveMsgFromCrew.GetBool() || pc.IsCrewmate())) - { - AddMsg(string.Format(GetString("MediumshipNotifyTarget"), Main.AllPlayerNames[Mediumshiper.ContactPlayer[pc.PlayerId]]), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Mediumshiper), GetString("MediumshipTitle"))); - } + if (Mediumshiper.ContactPlayer.ContainsKey(pc.PlayerId) && (!Mediumshiper.OnlyReceiveMsgFromCrew.GetBool() || pc.IsCrewmate())) AddMsg(string.Format(GetString("MediumshipNotifyTarget"), Main.AllPlayerNames[Mediumshiper.ContactPlayer[pc.PlayerId]]), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Mediumshiper), GetString("MediumshipTitle"))); - if (Virus.VirusNotify.TryGetValue(pc.PlayerId, out string value3)) - { - AddMsg(value3, pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Virus), GetString("VirusNoticeTitle"))); - } + if (Virus.VirusNotify.TryGetValue(pc.PlayerId, out string value3)) AddMsg(value3, pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Virus), GetString("VirusNoticeTitle"))); - if (Enigma.MsgToSend.TryGetValue(pc.PlayerId, out string value4)) - { - AddMsg(value4, pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Enigma), Enigma.MsgToSendTitle[pc.PlayerId])); - } + if (Enigma.MsgToSend.TryGetValue(pc.PlayerId, out string value4)) AddMsg(value4, pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Enigma), Enigma.MsgToSendTitle[pc.PlayerId])); if (QuizMaster.On && QuizMaster.MessagesToSend.TryGetValue(pc.PlayerId, out string value5)) { @@ -1033,16 +796,10 @@ namespace EHR.Patches if (MimicMsg != string.Empty) { MimicMsg = GetString("MimicDeadMsg") + "\n" + MimicMsg; - foreach (PlayerControl ipc in Main.AllPlayerControls.Where(x => x.GetCustomRole().IsImpostorTeam()).ToArray()) - { - AddMsg(MimicMsg, ipc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Mimic), GetString("MimicMsgTitle"))); - } + foreach (PlayerControl ipc in Main.AllPlayerControls.Where(x => x.GetCustomRole().IsImpostorTeam()).ToArray()) AddMsg(MimicMsg, ipc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Mimic), GetString("MimicMsgTitle"))); } - if (msgToSend.Count > 0) - { - LateTask.New(() => msgToSend.Do(x => Utils.SendMessage(x.Message, x.TargetID, x.Title)), 6f, "Meeting Start Notify"); - } + if (msgToSend.Count > 0) LateTask.New(() => msgToSend.Do(x => Utils.SendMessage(x.Message, x.TargetID, x.Title)), 6f, "Meeting Start Notify"); Main.CyberStarDead.Clear(); Express.SpeedNormal.Clear(); @@ -1081,10 +838,7 @@ namespace EHR.Patches foreach (PlayerVoteArea pva in __instance.playerStates) { PlayerControl target = Utils.GetPlayerById(pva.TargetPlayerId); - if (target == null) - { - continue; - } + if (target == null) continue; bool shouldSeeTargetAddons = seer.PlayerId == target.PlayerId || new[] { seer, target }.All(x => x.Is(Team.Impostor)); (string, Color) RoleTextData = Utils.GetRoleText(seer.PlayerId, target.PlayerId, seeTargetBetrayalAddons: shouldSeeTargetAddons); @@ -1092,14 +846,12 @@ namespace EHR.Patches roleTextMeeting.transform.localPosition = new(0f, -0.18f, 0f); roleTextMeeting.fontSize = 1.4f; roleTextMeeting.text = RoleTextData.Item1; - if (Main.VisibleTasksCount) - { - roleTextMeeting.text += Utils.GetProgressText(target); - } + if (Main.VisibleTasksCount) roleTextMeeting.text += Utils.GetProgressText(target); roleTextMeeting.color = RoleTextData.Item2; roleTextMeeting.gameObject.name = "RoleTextMeeting"; roleTextMeeting.enableWordWrapping = false; + roleTextMeeting.enabled = target.AmOwner || (Main.VisibleTasksCount && seer.Data.IsDead && Options.GhostCanSeeOtherRoles.GetBool()) || @@ -1146,16 +898,13 @@ namespace EHR.Patches } string suffix = Main.PlayerStates[seer.PlayerId].Role.GetSuffix(seer, target, meeting: true); + if (suffix.Length > 0) { if (roleTextMeeting.enabled) - { roleTextMeeting.text += "\n"; - } else - { roleTextMeeting.text = string.Empty; - } roleTextMeeting.text += $"<#ffffff>{suffix}"; roleTextMeeting.enabled = true; @@ -1184,24 +933,15 @@ namespace EHR.Patches } TemplateManager.SendTemplate("OnMeeting", noErr: true); - if (MeetingStates.FirstMeeting) - { - TemplateManager.SendTemplate("OnFirstMeeting", noErr: true); - } + if (MeetingStates.FirstMeeting) TemplateManager.SendTemplate("OnFirstMeeting", noErr: true); - if (AmongUsClient.Instance.AmHost) - { - NotifyRoleSkillOnMeetingStart(); - } + if (AmongUsClient.Instance.AmHost) NotifyRoleSkillOnMeetingStart(); if (AmongUsClient.Instance.AmHost) { LateTask.New(() => { - foreach (PlayerControl pc in Main.AllPlayerControls) - { - pc.RpcSetNameEx(pc.GetRealName(true)); - } + foreach (PlayerControl pc in Main.AllPlayerControls) pc.RpcSetNameEx(pc.GetRealName(true)); ChatUpdatePatch.DoBlockChat = false; }, 3f, "SetName To Chat"); @@ -1209,16 +949,10 @@ namespace EHR.Patches foreach (PlayerVoteArea pva in __instance.playerStates) { - if (pva == null) - { - continue; - } + if (pva == null) continue; PlayerControl target = Utils.GetPlayerById(pva.TargetPlayerId); - if (target == null) - { - continue; - } + if (target == null) continue; if (seer.GetCustomRole().GetDYRole() is RoleTypes.Shapeshifter or RoleTypes.Phantom) { @@ -1233,34 +967,22 @@ namespace EHR.Patches CustomRoles seerRole = seer.GetCustomRole(); - if (seer.KnowDeathReason(target)) - { - sb.Append($"({Utils.ColorString(Utils.GetRoleColor(CustomRoles.Doctor), Utils.GetVitalText(target.PlayerId))})"); - } + if (seer.KnowDeathReason(target)) sb.Append($"({Utils.ColorString(Utils.GetRoleColor(CustomRoles.Doctor), Utils.GetVitalText(target.PlayerId))})"); switch (seer.GetCustomRoleTypes()) { case CustomRoleTypes.Impostor: - if (target.Is(CustomRoles.Snitch) && target.Is(CustomRoles.Madmate) && target.GetTaskState().IsTaskFinished) - { - sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Impostor), "★")); - } + if (target.Is(CustomRoles.Snitch) && target.Is(CustomRoles.Madmate) && target.GetTaskState().IsTaskFinished) sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Impostor), "★")); break; case CustomRoleTypes.Crewmate: - if (target.Is(CustomRoles.Marshall) && target.GetTaskState().IsTaskFinished) - { - sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Marshall), "★")); - } + if (target.Is(CustomRoles.Marshall) && target.GetTaskState().IsTaskFinished) sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Marshall), "★")); sb.Append(Marshall.GetWarningMark(seer, target)); break; } - if (seer.IsSnitchTarget()) - { - sb.Append(Snitch.GetWarningMark(seer, target)); - } + if (seer.IsSnitchTarget()) sb.Append(Snitch.GetWarningMark(seer, target)); switch (seerRole) { @@ -1268,10 +990,7 @@ namespace EHR.Patches sb.Append($"●"); break; case CustomRoles.Arsonist: - if (seer.IsDousedPlayer(target)) - { - sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Arsonist), "▲")); - } + if (seer.IsDousedPlayer(target)) sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Arsonist), "▲")); break; case CustomRoles.Executioner: @@ -1281,17 +1000,11 @@ namespace EHR.Patches sb.Append(EvilTracker.GetTargetMark(seer, target)); break; case CustomRoles.Revolutionist: - if (seer.IsDrawPlayer(target)) - { - sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Revolutionist), "●")); - } + if (seer.IsDrawPlayer(target)) sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Revolutionist), "●")); break; case CustomRoles.Psychic: - if (Psychic.IsRedForPsy(target, seer) && !seer.Data.IsDead) - { - pva.NameText.text = Utils.ColorString(Utils.GetRoleColor(CustomRoles.Impostor), pva.NameText.text); - } + if (Psychic.IsRedForPsy(target, seer) && !seer.Data.IsDead) pva.NameText.text = Utils.ColorString(Utils.GetRoleColor(CustomRoles.Impostor), pva.NameText.text); break; case CustomRoles.Gamer: @@ -1303,43 +1016,22 @@ namespace EHR.Patches break; } - if (Silencer.ForSilencer.Contains(target.PlayerId)) - { - sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Silencer), "╳")); - } + if (Silencer.ForSilencer.Contains(target.PlayerId)) sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Silencer), "╳")); - if (Main.LoversPlayers.Exists(x => x.PlayerId == target.PlayerId) && (Main.LoversPlayers.Exists(x => x.PlayerId == seer.PlayerId) || seer.Data.IsDead)) - { - sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Lovers), "♥")); - } + if (Main.LoversPlayers.Exists(x => x.PlayerId == target.PlayerId) && (Main.LoversPlayers.Exists(x => x.PlayerId == seer.PlayerId) || seer.Data.IsDead)) sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Lovers), "♥")); sb.Append(Witch.GetSpelledMark(target.PlayerId, true)); sb.Append(Wasp.GetStungMark(target.PlayerId)); - if (target.Is(CustomRoles.SuperStar) && Options.EveryOneKnowSuperStar.GetBool()) - { - sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.SuperStar), "★")); - } + if (target.Is(CustomRoles.SuperStar) && Options.EveryOneKnowSuperStar.GetBool()) sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.SuperStar), "★")); - if (BallLightning.IsGhost(target)) - { - sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.BallLightning), "■")); - } + if (BallLightning.IsGhost(target)) sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.BallLightning), "■")); - if (seer.PlayerId == target.PlayerId && (Medic.InProtect(seer.PlayerId) || Medic.TempMarkProtectedList.Contains(seer.PlayerId)) && Medic.WhoCanSeeProtect.GetInt() is 0 or 2) - { - sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Medic), " ●")); - } + if (seer.PlayerId == target.PlayerId && (Medic.InProtect(seer.PlayerId) || Medic.TempMarkProtectedList.Contains(seer.PlayerId)) && Medic.WhoCanSeeProtect.GetInt() is 0 or 2) sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Medic), " ●")); - if (seer.Is(CustomRoles.Medic) && (Medic.InProtect(target.PlayerId) || Medic.TempMarkProtectedList.Contains(target.PlayerId)) && Medic.WhoCanSeeProtect.GetInt() is 0 or 1) - { - sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Medic), " ●")); - } + if (seer.Is(CustomRoles.Medic) && (Medic.InProtect(target.PlayerId) || Medic.TempMarkProtectedList.Contains(target.PlayerId)) && Medic.WhoCanSeeProtect.GetInt() is 0 or 1) sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Medic), " ●")); - if (seer.Data.IsDead && Medic.InProtect(target.PlayerId) && !seer.Is(CustomRoles.Medic)) - { - sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Medic), " ●")); - } + if (seer.Data.IsDead && Medic.InProtect(target.PlayerId) && !seer.Is(CustomRoles.Medic)) sb.Append(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Medic), " ●")); sb.Append(Totocalcio.TargetMark(seer, target)); sb.Append(Romantic.TargetMark(seer, target)); @@ -1370,16 +1062,14 @@ namespace EHR.Patches try { // Meeting Skip with vote counting on keystroke (F6) - if (AmongUsClient.Instance.AmHost && Input.GetKeyDown(KeyCode.F6)) - { - __instance.CheckForEndVoting(); - } + if (AmongUsClient.Instance.AmHost && Input.GetKeyDown(KeyCode.F6)) __instance.CheckForEndVoting(); if (AmongUsClient.Instance.AmHost && Input.GetMouseButtonUp(1) && Input.GetKey(KeyCode.LeftControl)) { __instance.playerStates.DoIf(x => x.HighlightedFX.enabled, x => { PlayerControl player = Utils.GetPlayerById(x.TargetPlayerId); + if (player != null && !player.Data.IsDead) { Main.PlayerStates[player.PlayerId].deathReason = PlayerState.DeathReason.Execution; @@ -1392,21 +1082,17 @@ namespace EHR.Patches }); } - if (DestroyableSingleton.Instance.Chat.IsOpenOrOpening) - { - } + if (DestroyableSingleton.Instance.Chat.IsOpenOrOpening) { } if (!GameStates.IsVoting && __instance.lastSecond < 1) { - if (GameObject.Find("ShootButton") != null) - { - ClearShootButton(__instance, true); - } + if (GameObject.Find("ShootButton") != null) ClearShootButton(__instance, true); return; } BufferTime--; + if (BufferTime < 0 && __instance.discussionTimer > 0) { BufferTime = 10; @@ -1431,10 +1117,7 @@ namespace EHR.Patches { Logger.Fatal(ex.ToString(), "MeetingHudUpdatePatch.Postfix"); Logger.Warn("All Players and their info:", "Debug for Fatal Error"); - foreach (PlayerControl pc in Main.AllPlayerControls) - { - Logger.Info($" {(pc.IsAlive() ? "Alive" : $"Dead ({Main.PlayerStates[pc.PlayerId].deathReason})")}, {Utils.GetProgressText(pc)}, {Utils.GetVitalText(pc.PlayerId)}", $"{pc.GetNameWithRole()} / {pc.PlayerId}"); - } + foreach (PlayerControl pc in Main.AllPlayerControls) Logger.Info($" {(pc.IsAlive() ? "Alive" : $"Dead ({Main.PlayerStates[pc.PlayerId].deathReason})")}, {Utils.GetProgressText(pc)}, {Utils.GetVitalText(pc.PlayerId)}", $"{pc.GetNameWithRole()} / {pc.PlayerId}"); Logger.Warn("-----------------", "Debug for Fatal Error"); Logger.SendInGame("An error occured with this meeting. Please use /dump and send the log to the developer.\nSorry for the inconvenience."); @@ -1447,15 +1130,9 @@ namespace EHR.Patches { public static bool Prefix(PlayerVoteArea __instance, bool value) { - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; - if (!__instance.HighlightedFX) - { - return false; - } + if (!__instance.HighlightedFX) return false; __instance.HighlightedFX.enabled = value; return false; @@ -1469,6 +1146,7 @@ namespace EHR.Patches { MeetingStates.FirstMeeting = false; Logger.Info("------------End of meeting------------", "Phase"); + if (AmongUsClient.Instance.AmHost) { AntiBlackout.SetIsDead(); @@ -1488,18 +1166,13 @@ namespace EHR.Patches { PlayerVoteArea pva_src = null; PlayerVoteArea pva_target = null; - bool isSkip = false; + var isSkip = false; + foreach (PlayerVoteArea t in __instance.playerStates) { - if (t.TargetPlayerId == srcPlayerId) - { - pva_src = t; - } + if (t.TargetPlayerId == srcPlayerId) pva_src = t; - if (t.TargetPlayerId == suspectPlayerId) - { - pva_target = t; - } + if (t.TargetPlayerId == suspectPlayerId) pva_target = t; } if (pva_src == null) @@ -1516,6 +1189,7 @@ namespace EHR.Patches PlayerControl pc_src = Utils.GetPlayerById(srcPlayerId); PlayerControl pc_target = Utils.GetPlayerById(suspectPlayerId); + if (pc_src == null) { Logger.Error("Src PlayerControl is null", "MeetingHudCastVotePatch.Prefix"); @@ -1528,7 +1202,7 @@ namespace EHR.Patches isSkip = true; } - bool voteCanceled = false; + var voteCanceled = false; if (!Main.DontCancelVoteList.Contains(srcPlayerId) && !isSkip && pc_src.GetCustomRole().CancelsVote() && Main.PlayerStates[srcPlayerId].Role.OnVote(pc_src, pc_target)) { @@ -1543,10 +1217,7 @@ namespace EHR.Patches public static void Postfix([HarmonyArgument(0)] byte srcPlayerId) { - if (!ShouldCancelVoteList.TryGetValue(srcPlayerId, out (MeetingHud MeetingHud, PlayerVoteArea SourcePVA, PlayerControl SourcePC) info)) - { - return; - } + if (!ShouldCancelVoteList.TryGetValue(srcPlayerId, out (MeetingHud MeetingHud, PlayerVoteArea SourcePVA, PlayerControl SourcePC) info)) return; MeetingHud __instance = info.MeetingHud; PlayerVoteArea pva_src = info.SourcePVA; @@ -1556,9 +1227,7 @@ namespace EHR.Patches { pva_src.UnsetVote(); } - catch - { - } + catch { } __instance.RpcClearVote(pc_src.GetClientId()); diff --git a/Patches/NotificationPopperPatch.cs b/Patches/NotificationPopperPatch.cs index 5ab94c9bf..a4c4f4ad9 100644 --- a/Patches/NotificationPopperPatch.cs +++ b/Patches/NotificationPopperPatch.cs @@ -24,9 +24,11 @@ namespace EHR.Patches public static void AddSettingsChangeMessage(int index, OptionItem key, bool playSound = false) { SendRpc(0, index, playSound: playSound); + string str = key.Parent != null ? DestroyableSingleton.Instance.GetString(StringNames.LobbyChangeSettingNotification, "" + key.Parent.GetName() + ": " + key.GetName() + "", "" + key.GetString() + "") : DestroyableSingleton.Instance.GetString(StringNames.LobbyChangeSettingNotification, "" + key.GetName() + "", "" + key.GetString() + ""); + SettingsChangeMessageLogic(key, str, playSound); } @@ -40,9 +42,7 @@ namespace EHR.Patches private static void SettingsChangeMessageLogic(OptionItem key, string item, bool playSound) { if (Instance.lastMessageKey == key.Id && Instance.activeMessages.Count > 0) - { Instance.activeMessages[^1].UpdateMessage(item); // False error - } else { Instance.lastMessageKey = key.Id; @@ -53,18 +53,12 @@ namespace EHR.Patches Instance.AddMessageToQueue(newMessage); } - if (playSound) - { - SoundManager.Instance.PlaySoundImmediate(Instance.settingsChangeSound, false); - } + if (playSound) SoundManager.Instance.PlaySoundImmediate(Instance.settingsChangeSound, false); } private static void SendRpc(byte typeId, int index, CustomRoles customRole = CustomRoles.NotAssigned, bool playSound = true) { - if (Options.HideGameSettings.GetBool()) - { - return; - } + if (Options.HideGameSettings.GetBool()) return; Utils.SendRPC(CustomRPC.NotificationPopper, typeId, index, (int)customRole, playSound); } diff --git a/Patches/OnGameStartedPatch.cs b/Patches/OnGameStartedPatch.cs index ab23e012a..2e25504c3 100644 --- a/Patches/OnGameStartedPatch.cs +++ b/Patches/OnGameStartedPatch.cs @@ -32,10 +32,7 @@ namespace EHR { public static bool Prefix(AmongUsClient __instance) { - if (!GameStates.IsLocalGame) - { - return true; - } + if (!GameStates.IsLocalGame) return true; __instance.StartCoroutine(CoStartGame().WrapToIl2Cpp()); return false; @@ -43,37 +40,22 @@ namespace EHR IEnumerator CoStartGame() { AmongUsClient amongUsClient = __instance; - if (DestroyableSingleton.Instance.GameMenu.IsOpen) - { - DestroyableSingleton.Instance.GameMenu.Close(); - } + if (DestroyableSingleton.Instance.GameMenu.IsOpen) DestroyableSingleton.Instance.GameMenu.Close(); DestroyableSingleton.Instance.Init(); amongUsClient.logger.Info($"Received game start: {amongUsClient.AmHost}"); yield return null; - while (!DestroyableSingleton.InstanceExists) - { - yield return null; - } + while (!DestroyableSingleton.InstanceExists) yield return null; - while (PlayerControl.LocalPlayer == null) - { - yield return null; - } + while (PlayerControl.LocalPlayer == null) yield return null; PlayerControl.LocalPlayer.moveable = false; PlayerControl.LocalPlayer.MyPhysics.inputHandler.enabled = true; - PlayerCustomizationMenu objectOfType1 = Object.FindObjectOfType(); - if (objectOfType1 != null) - { - objectOfType1.Close(false); - } + var objectOfType1 = Object.FindObjectOfType(); + if (objectOfType1 != null) objectOfType1.Close(false); - GameSettingMenu objectOfType2 = Object.FindObjectOfType(); - if (objectOfType2 != null) - { - objectOfType2.Close(); - } + var objectOfType2 = Object.FindObjectOfType(); + if (objectOfType2 != null) objectOfType2.Close(); if (DestroyableSingleton.InstanceExists) { @@ -81,20 +63,12 @@ namespace EHR Object.Destroy(DestroyableSingleton.Instance.gameObject); } - if (DestroyableSingleton.InstanceExists) - { - Object.Destroy(DestroyableSingleton.Instance.gameObject); - } + if (DestroyableSingleton.InstanceExists) Object.Destroy(DestroyableSingleton.Instance.gameObject); - if (DestroyableSingleton.InstanceExists) - { - DestroyableSingleton.Instance.SetPlayingGame(); - } + if (DestroyableSingleton.InstanceExists) DestroyableSingleton.Instance.SetPlayingGame(); if (!string.IsNullOrEmpty(DataManager.Player.Store.ActiveCosmicube)) - { AmongUsClient.Instance.SetActivePodType(DestroyableSingleton.Instance.GetCubeDataByID(DataManager.Player.Store.ActiveCosmicube).podId); - } else { PlayerStorageManager.CloudPlayerPrefs playerPrefs = DestroyableSingleton.Instance.PlayerPrefs; @@ -108,22 +82,19 @@ namespace EHR yield return DestroyableSingleton.Instance.CoFadeFullScreen(Color.clear, Color.black, showLoader: true); ++StatsManager.Instance.BanPoints; StatsManager.Instance.LastGameStarted = DateTime.UtcNow; + if (amongUsClient.AmHost) - { yield return amongUsClient.CoStartGameHost(); - } else { yield return amongUsClient.CoStartGameClient(); - if (amongUsClient.AmHost) - { - yield return amongUsClient.CoStartGameHost(); - } + if (amongUsClient.AmHost) yield return amongUsClient.CoStartGameHost(); } - for (int index = 0; index < GameData.Instance.PlayerCount; ++index) + for (var index = 0; index < GameData.Instance.PlayerCount; ++index) { PlayerControl player = GameData.Instance.AllPlayers.ToArray()[index].Object; + if (player != null) { player.moveable = true; @@ -141,15 +112,14 @@ namespace EHR int map = Mathf.Clamp(GameOptionsManager.Instance.CurrentGameOptions.MapId, 0, Constants.MapNames.Length - 1); string gameName = GameCode.IntToGameName(AmongUsClient.Instance.GameId); DestroyableSingleton.Instance.Analytics.StartGame(PlayerControl.LocalPlayer.Data, GameData.Instance.PlayerCount, GameOptionsManager.Instance.CurrentGameOptions.NumImpostors, AmongUsClient.Instance.NetworkMode, (MapNames)map, GameOptionsManager.Instance.CurrentGameOptions.GameMode, gameName, DestroyableSingleton.Instance.CurrentRegion.Name, GameOptionsManager.Instance.CurrentGameOptions, GameData.Instance.AllPlayers); + try { DestroyableSingleton.Instance.StartGame(AmongUsClient.Instance.AmHost, GameData.Instance.PlayerCount, GameOptionsManager.Instance.CurrentGameOptions.NumImpostors, AmongUsClient.Instance.NetworkMode, StatsManager.Instance.GetStat(StringNames.StatsGamesImpostor), StatsManager.Instance.GetStat(StringNames.StatsGamesStarted), StatsManager.Instance.GetStat(StringNames.StatsCrewmateStreak)); NetworkedPlayerInfo.PlayerOutfit defaultOutfit = PlayerControl.LocalPlayer.Data.DefaultOutfit; DestroyableSingleton.Instance.StartGameCosmetics(defaultOutfit.ColorId, defaultOutfit.HatId, defaultOutfit.SkinId, defaultOutfit.PetId, defaultOutfit.VisorId, defaultOutfit.NamePlateId); } - catch - { - } + catch { } GameDebugCommands.AddCommands(); } @@ -160,9 +130,11 @@ namespace EHR SetUpRoleTextPatch.IsInIntro = true; Main.OverrideWelcomeMsg = string.Empty; + try { Main.NormalOptions.roleOptions.SetRoleRate(RoleTypes.GuardianAngel, 0, 0); + if (Options.DisableVanillaRoles.GetBool()) { Main.NormalOptions.roleOptions.SetRoleRate(RoleTypes.Scientist, 0, 0); @@ -173,10 +145,7 @@ namespace EHR Main.NormalOptions.roleOptions.SetRoleRate(RoleTypes.Tracker, 0, 0); } - if (Main.NormalOptions.MapId > 5) - { - Logger.SendInGame(GetString("UnsupportedMap")); - } + if (Main.NormalOptions.MapId > 5) Logger.SendInGame(GetString("UnsupportedMap")); Utils.GameStartTimeStamp = Utils.TimeStamp; @@ -295,6 +264,7 @@ namespace EHR if (AmongUsClient.Instance.AmHost) { string[] invalidColor = Main.AllPlayerControls.Where(p => p.Data.DefaultOutfit.ColorId < 0 || Palette.PlayerColors.Length <= p.Data.DefaultOutfit.ColorId).Select(p => $"{p.name}").ToArray(); + if (invalidColor.Length > 0) { string msg = GetString("Error.InvalidColor"); @@ -319,10 +289,7 @@ namespace EHR foreach (PlayerControl pc in Main.AllPlayerControls) { int colorId = pc.Data.DefaultOutfit.ColorId; - if (AmongUsClient.Instance.AmHost && Options.FormatNameMode.GetInt() == 1) - { - pc.RpcSetName(Palette.GetColorName(colorId)); - } + if (AmongUsClient.Instance.AmHost && Options.FormatNameMode.GetInt() == 1) pc.RpcSetName(Palette.GetColorName(colorId)); Main.PlayerStates[pc.PlayerId] = new(pc.PlayerId); Main.PlayerColors[pc.PlayerId] = Palette.PlayerColors[colorId]; @@ -340,6 +307,7 @@ namespace EHR } Main.VisibleTasksCount = true; + if (__instance.AmHost) { RPC.SyncCustomSettingsRPC(); @@ -442,10 +410,7 @@ namespace EHR private static System.Collections.IEnumerator StartGameHost() { - if (LobbyBehaviour.Instance) - { - LobbyBehaviour.Instance.Despawn(); - } + if (LobbyBehaviour.Instance) LobbyBehaviour.Instance.Despawn(); if (!ShipStatus.Instance) { @@ -457,24 +422,25 @@ namespace EHR AUClient.Spawn(ShipStatus.Instance); } - float timer = 0f; + var timer = 0f; + while (true) { - bool stopWaiting = true; + var stopWaiting = true; int maxTimer = GameOptionsManager.Instance.CurrentGameOptions.MapId is 5 or 4 ? 17 : 12; + lock (AUClient.allClients) { // For loop is necessary, or else when a client times out, a foreach loop will throw: // System.InvalidOperationException: Collection was modified; enumeration operation may not execute. - for (int i = 0; i < AUClient.allClients.Count; i++) + for (var i = 0; i < AUClient.allClients.Count; i++) { ClientData clientData = AUClient.allClients[i]; // False error + if (clientData.Id != AUClient.ClientId && !clientData.IsReady) { if (timer < maxTimer) - { stopWaiting = false; - } else { AUClient.SendLateRejection(clientData.Id, DisconnectReasons.ClientTimeout); @@ -486,10 +452,7 @@ namespace EHR } yield return null; - if (stopWaiting) - { - break; - } + if (stopWaiting) break; timer += Time.deltaTime; } @@ -501,10 +464,7 @@ namespace EHR private static System.Collections.IEnumerator AssignRoles() { - if (AmongUsClient.Instance.IsGameOver || GameStates.IsLobby || GameEndChecker.Ended) - { - yield break; - } + if (AmongUsClient.Instance.IsGameOver || GameStates.IsLobby || GameEndChecker.Ended) yield break; RpcSetRoleReplacer.Initialize(); @@ -513,6 +473,7 @@ namespace EHR CalculateVanillaRoleCount(); UpdateRoleTypeNums(); + foreach (KeyValuePair roleType in RoleTypeNums) { int roleNum = Options.DisableVanillaRoles.GetBool() ? 0 : RoleOpt.GetNumPerGame(roleType.Key); @@ -526,7 +487,7 @@ namespace EHR BasisChangingAddons.Clear(); - IRandom random = IRandom.Instance; + var random = IRandom.Instance; if (Options.CurrentGameMode == CustomGameMode.Standard) { @@ -546,14 +507,12 @@ namespace EHR HashSet bloodlustList = [], nimbleList = [], physicistList = [], finderList = [], noisyList = []; bool hasBanned = Main.NeverSpawnTogetherCombos.TryGetValue(OptionItem.CurrentPreset, out Dictionary> banned); + if (nimbleSpawn || physicistSpawn || finderSpawn || noisySpawn) { foreach (PlayerControl player in Main.AllPlayerControls) { - if (IsBasisChangingPlayer(player.PlayerId, CustomRoles.Bloodlust)) - { - continue; - } + if (IsBasisChangingPlayer(player.PlayerId, CustomRoles.Bloodlust)) continue; KeyValuePair kp = RoleResult.FirstOrDefault(x => x.Key == player.PlayerId); @@ -565,32 +524,17 @@ namespace EHR if (kp.Value.IsCrewmate()) { - if (!bloodlustBanned && !kp.Value.IsTaskBasedCrewmate()) - { - bloodlustList.Add(player.PlayerId); - } + if (!bloodlustBanned && !kp.Value.IsTaskBasedCrewmate()) bloodlustList.Add(player.PlayerId); - if (!nimbleBanned) - { - nimbleList.Add(player.PlayerId); - } + if (!nimbleBanned) nimbleList.Add(player.PlayerId); if (kp.Value.GetRoleTypes() == RoleTypes.Crewmate) { - if (!physicistBanned) - { - physicistList.Add(player.PlayerId); - } + if (!physicistBanned) physicistList.Add(player.PlayerId); - if (!finderBanned) - { - finderList.Add(player.PlayerId); - } + if (!finderBanned) finderList.Add(player.PlayerId); - if (!noisyBanned) - { - noisyList.Add(player.PlayerId); - } + if (!noisyBanned) noisyList.Add(player.PlayerId); } } } @@ -605,23 +549,18 @@ namespace EHR { CustomRoles.Noisy, (noisySpawn, noisyList) } }; - for (int i = 0; i < roleSpawnMapping.Count; i++) + for (var i = 0; i < roleSpawnMapping.Count; i++) { (CustomRoles addon, (bool SpawnFlag, HashSet RoleList) value) = roleSpawnMapping.ElementAt(i); - if (value.RoleList.Count == 0) - { - value.SpawnFlag = false; - } + if (value.RoleList.Count == 0) value.SpawnFlag = false; - if (Main.GM.Value) - { - value.RoleList.Remove(0); - } + if (Main.GM.Value) value.RoleList.Remove(0); if (Main.AlwaysSpawnTogetherCombos.TryGetValue(OptionItem.CurrentPreset, out Dictionary> combos) && combos.Values.Any(l => l.Contains(addon))) { HashSet roles = combos.Where(x => x.Value.Contains(addon)).Select(x => x.Key).ToHashSet(); HashSet players = RoleResult.Where(x => roles.Contains(x.Value) && x.Value.IsCrewmate() && (addon != CustomRoles.Bloodlust || x.Value.IsTasklessCrewmate()) && (addon == CustomRoles.Nimble || x.Value.GetRoleTypes() == RoleTypes.Crewmate) && !IsBasisChangingPlayer(x.Key, CustomRoles.Bloodlust)).Select(x => x.Key).ToHashSet(); + if (players.Count > 0) { value.RoleList = players; @@ -634,10 +573,7 @@ namespace EHR { value.SpawnFlag = true; HashSet newRoleList = Main.SetAddOns.Where(x => x.Value.Contains(addon)).Select(x => x.Key).ToHashSet(); - if (value.RoleList.Count != 1 || value.RoleList.First() != newRoleList.First()) - { - value.RoleList = newRoleList; - } + if (value.RoleList.Count != 1 || value.RoleList.First() != newRoleList.First()) value.RoleList = newRoleList; roleSpawnMapping[addon] = value; } @@ -648,12 +584,8 @@ namespace EHR if (spawnFlag) { foreach ((CustomRoles otherAddon, (bool otherSpawnFlag, _)) in roleSpawnMapping) - { if (otherAddon != addon && otherSpawnFlag && BasisChangingAddons.TryGetValue(otherAddon, out List otherList)) - { roleList.ExceptWith(otherList); - } - } BasisChangingAddons[addon] = roleList.Shuffle().Take(addon.GetCount()).ToList(); } @@ -678,43 +610,32 @@ namespace EHR foreach (PlayerControl pc in Main.AllPlayerControls) { - if (Main.PlayerStates[pc.PlayerId].MainRole != CustomRoles.NotAssigned) - { - continue; - } + if (Main.PlayerStates[pc.PlayerId].MainRole != CustomRoles.NotAssigned) continue; CustomRoles role = Enum.TryParse($"{pc.Data.Role.Role}EHR", out CustomRoles parsedRole) ? parsedRole : CustomRoles.NotAssigned; - if (role == CustomRoles.NotAssigned) - { - Logger.SendInGame(string.Format(GetString("Error.InvalidRoleAssignment"), pc?.Data?.PlayerName)); - } + if (role == CustomRoles.NotAssigned) Logger.SendInGame(string.Format(GetString("Error.InvalidRoleAssignment"), pc?.Data?.PlayerName)); Main.PlayerStates[pc.PlayerId].SetMainRole(role); } foreach (KeyValuePair kv in RoleResult) { - if (kv.Value.IsDesyncRole() || IsBasisChangingPlayer(kv.Key, CustomRoles.Bloodlust)) - { - continue; - } + if (kv.Value.IsDesyncRole() || IsBasisChangingPlayer(kv.Key, CustomRoles.Bloodlust)) continue; Main.PlayerStates[kv.Key].SetMainRole(kv.Value); } if (Options.CurrentGameMode != CustomGameMode.Standard) { - foreach (KeyValuePair pair in Main.PlayerStates) - { - ExtendedPlayerControl.RpcSetCustomRole(pair.Key, pair.Value.MainRole); - } + foreach (KeyValuePair pair in Main.PlayerStates) ExtendedPlayerControl.RpcSetCustomRole(pair.Key, pair.Value.MainRole); goto EndOfSelectRolePatch; } BasisChangingAddons.Do(x => x.Value.Do(y => Main.PlayerStates[y].SetSubRole(x.Key))); - bool overrideLovers = false; + var overrideLovers = false; + if (Main.SetAddOns.Count(x => x.Value.Contains(CustomRoles.Lovers)) == 2) { Main.LoversPlayers.Clear(); @@ -729,38 +650,24 @@ namespace EHR { foreach (CustomRoles role in item.Value) { - if (role is CustomRoles.Nimble or CustomRoles.Physicist or CustomRoles.Bloodlust or CustomRoles.Finder or CustomRoles.Noisy) - { - continue; - } + if (role is CustomRoles.Nimble or CustomRoles.Physicist or CustomRoles.Bloodlust or CustomRoles.Finder or CustomRoles.Noisy) continue; state.SetSubRole(role); - if (overrideLovers && role == CustomRoles.Lovers) - { - Main.LoversPlayers.Add(Utils.GetPlayerById(item.Key)); - } + if (overrideLovers && role == CustomRoles.Lovers) Main.LoversPlayers.Add(Utils.GetPlayerById(item.Key)); - if (role.IsGhostRole()) - { - GhostRolesManager.SpecificAssignGhostRole(item.Key, role, true); - } + if (role.IsGhostRole()) GhostRolesManager.SpecificAssignGhostRole(item.Key, role, true); } } } - if (!overrideLovers && CustomRoles.Lovers.IsEnable() && (CustomRoles.FFF.IsEnable() ? -1 : random.Next(1, 100)) <= Lovers.LoverSpawnChances.GetInt()) - { - AssignLoversRolesFromList(); - } + if (!overrideLovers && CustomRoles.Lovers.IsEnable() && (CustomRoles.FFF.IsEnable() ? -1 : random.Next(1, 100)) <= Lovers.LoverSpawnChances.GetInt()) AssignLoversRolesFromList(); // Add-on assignment PlayerControl[] aapc = Main.AllAlivePlayerControls.Shuffle(); - if (Main.GM.Value) - { - aapc = aapc.Without(PlayerControl.LocalPlayer).ToArray(); - } + if (Main.GM.Value) aapc = aapc.Without(PlayerControl.LocalPlayer).ToArray(); Dictionary addonNum = aapc.ToDictionary(x => x, _ => 0); + AddonRolesList .Except(BasisChangingAddons.Keys) .Where(x => x.IsEnable() && aapc.Any(p => CustomRolesHelper.CheckAddonConflict(x, p))) @@ -772,10 +679,8 @@ namespace EHR PlayerControl suitablePlayer = aapc .OrderBy(p => addonNum[p]) .FirstOrDefault(p => CustomRolesHelper.CheckAddonConflict(x, p)); - if (suitablePlayer != null) - { - addonNum[suitablePlayer]++; - } + + if (suitablePlayer != null) addonNum[suitablePlayer]++; return (Role: x, SuitablePlayer: suitablePlayer); }) @@ -784,20 +689,11 @@ namespace EHR foreach (PlayerState state in Main.PlayerStates.Values) { - if (Main.NeverSpawnTogetherCombos.TryGetValue(OptionItem.CurrentPreset, out Dictionary> neverList) && neverList.TryGetValue(state.MainRole, out List bannedAddonList)) - { - bannedAddonList.ForEach(x => state.RemoveSubRole(x)); - } + if (Main.NeverSpawnTogetherCombos.TryGetValue(OptionItem.CurrentPreset, out Dictionary> neverList) && neverList.TryGetValue(state.MainRole, out List bannedAddonList)) bannedAddonList.ForEach(x => state.RemoveSubRole(x)); - if (Main.AlwaysSpawnTogetherCombos.TryGetValue(OptionItem.CurrentPreset, out Dictionary> alwaysList) && alwaysList.TryGetValue(state.MainRole, out List addonList)) - { - addonList.ForEach(x => state.SetSubRole(x)); - } + if (Main.AlwaysSpawnTogetherCombos.TryGetValue(OptionItem.CurrentPreset, out Dictionary> alwaysList) && alwaysList.TryGetValue(state.MainRole, out List addonList)) addonList.ForEach(x => state.SetSubRole(x)); - if (!state.MainRole.IsImpostor()) - { - state.SubRoles.RemoveAll(x => x.IsImpOnlyAddon()); - } + if (!state.MainRole.IsImpostor()) state.SubRoles.RemoveAll(x => x.IsImpOnlyAddon()); } foreach (KeyValuePair pair in Main.PlayerStates) @@ -805,6 +701,7 @@ namespace EHR ExtendedPlayerControl.RpcSetCustomRole(pair.Key, pair.Value.MainRole); StringBuilder sb = new(); + foreach (CustomRoles subRole in pair.Value.SubRoles) { ExtendedPlayerControl.RpcSetCustomRole(pair.Key, subRole); @@ -822,10 +719,7 @@ namespace EHR { try { - if (pc.Data.Role.Role == RoleTypes.Shapeshifter) - { - Main.CheckShapeshift.Add(pc.PlayerId, false); - } + if (pc.Data.Role.Role == RoleTypes.Shapeshifter) Main.CheckShapeshift.Add(pc.PlayerId, false); if (pc.AmOwner && pc.GetCustomRole().GetDYRole() is RoleTypes.Shapeshifter or RoleTypes.Phantom) { @@ -861,10 +755,7 @@ namespace EHR LateTask.New(CustomTeamManager.InitializeCustomTeamPlayers, 7f, log: false); - if (overrideLovers) - { - Logger.Msg(Main.LoversPlayers.Join(x => x?.GetRealName()), "Lovers"); - } + if (overrideLovers) Logger.Msg(Main.LoversPlayers.Join(x => x?.GetRealName()), "Lovers"); EndOfSelectRolePatch: @@ -889,10 +780,7 @@ namespace EHR HudManager.Instance.SetHudActive(true); - foreach (PlayerControl pc in Main.AllPlayerControls) - { - pc.ResetKillCooldown(); - } + foreach (PlayerControl pc in Main.AllPlayerControls) pc.ResetKillCooldown(); foreach (KeyValuePair roleType in RoleTypeNums) @@ -950,10 +838,7 @@ namespace EHR ChatCommands.DraftRoles = []; }, 7f, log: false); - if ((MapNames)Main.NormalOptions.MapId == MapNames.Airship && AmongUsClient.Instance.AmHost && Main.GM.Value) - { - LateTask.New(() => PlayerControl.LocalPlayer.NetTransform.SnapTo(new(15.5f, 0.0f), (ushort)(PlayerControl.LocalPlayer.NetTransform.lastSequenceId + 8)), 15f, "GM Auto-TP Failsafe"); // TP to Main Hall - } + if ((MapNames)Main.NormalOptions.MapId == MapNames.Airship && AmongUsClient.Instance.AmHost && Main.GM.Value) LateTask.New(() => PlayerControl.LocalPlayer.NetTransform.SnapTo(new(15.5f, 0.0f), (ushort)(PlayerControl.LocalPlayer.NetTransform.lastSequenceId + 8)), 15f, "GM Auto-TP Failsafe"); // TP to Main Hall LateTask.New(() => Main.HasJustStarted = false, 12f, "HasJustStarted to false"); } @@ -986,10 +871,7 @@ namespace EHR private static void AssignDesyncRole(CustomRoles role, PlayerControl player, Dictionary senders, Dictionary<(byte, byte), (RoleTypes, CustomRoles)> rolesMap, RoleTypes BaseRole, RoleTypes hostBaseRole = RoleTypes.Crewmate) { - if (player == null) - { - return; - } + if (player == null) return; byte hostId = PlayerControl.LocalPlayer.PlayerId; bool isHost = player.PlayerId == hostId; @@ -1005,29 +887,20 @@ namespace EHR RoleTypes targetRoleType = othersRole; CustomRoles targetCustomRole = RoleResult.GetValueOrDefault(target.PlayerId, CustomRoles.CrewmateEHR); - if (targetCustomRole.GetVNRole() is CustomRoles.Noisemaker) - { - targetRoleType = RoleTypes.Noisemaker; - } + if (targetCustomRole.GetVNRole() is CustomRoles.Noisemaker) targetRoleType = RoleTypes.Noisemaker; rolesMap[(player.PlayerId, target.PlayerId)] = player.PlayerId != target.PlayerId ? (targetRoleType, targetCustomRole) : (selfRole, role); } // Set Desync role for others - foreach (PlayerControl seer in Main.AllPlayerControls.Where(x => player.PlayerId != x.PlayerId).ToArray()) - { - rolesMap[(seer.PlayerId, player.PlayerId)] = (othersRole, role); - } + foreach (PlayerControl seer in Main.AllPlayerControls.Where(x => player.PlayerId != x.PlayerId).ToArray()) rolesMap[(seer.PlayerId, player.PlayerId)] = (othersRole, role); RpcSetRoleReplacer.OverriddenSenderList.Add(senders[player.PlayerId]); // Set role for host, but not self // canOverride should be false for the host during assign - if (!isHost) - { - player.SetRole(othersRole, false); - } + if (!isHost) player.SetRole(othersRole, false); Logger.Info($"Registered Role: {player.Data?.PlayerName} => {role} : RoleType for self => {selfRole}, for others => {othersRole}", "AssignDesyncRoles"); } @@ -1038,28 +911,20 @@ namespace EHR { foreach (PlayerControl target in Main.AllPlayerControls) { - if (seer.PlayerId == target.PlayerId || target.PlayerId == PlayerControl.LocalPlayer.PlayerId) - { - continue; - } + if (seer.PlayerId == target.PlayerId || target.PlayerId == PlayerControl.LocalPlayer.PlayerId) continue; if (rolesMap.TryGetValue((seer.PlayerId, target.PlayerId), out (RoleTypes, CustomRoles) roleMap)) { try { int targetClientId = target.GetClientId(); - if (targetClientId == -1) - { - continue; - } + if (targetClientId == -1) continue; RoleTypes roleType = roleMap.Item1; CustomRpcSender sender = senders[seer.PlayerId]; sender.RpcSetRole(seer, roleType, targetClientId); } - catch - { - } + catch { } } } } @@ -1073,24 +938,16 @@ namespace EHR { SetRoleSelf(pc); } - catch - { - } + catch { } } } private static void SetRoleSelf(PlayerControl target) { - if (target == null) - { - return; - } + if (target == null) return; int targetClientId = target.GetClientId(); - if (targetClientId == -1) - { - return; - } + if (targetClientId == -1) return; RoleTypes roleType = RpcSetRoleReplacer.RoleMap.TryGetValue((target.PlayerId, target.PlayerId), out (RoleTypes RoleType, CustomRoles CustomRole) roleMap) ? roleMap.RoleType @@ -1121,12 +978,14 @@ namespace EHR MessageWriter stream = MessageWriter.Get(SendOption.Reliable); stream.StartMessage(5); stream.Write(AmongUsClient.Instance.GameId); + { stream.StartMessage(1); stream.WritePacked(playerInfo.NetId); playerInfo.Serialize(stream, false); stream.EndMessage(); } + stream.EndMessage(); AmongUsClient.Instance.SendOrDisconnect(stream); stream.Recycle(); @@ -1154,17 +1013,11 @@ namespace EHR List allPlayers = Main.AllPlayerControls.Where(pc => (!Main.NeverSpawnTogetherCombos.TryGetValue(OptionItem.CurrentPreset, out Dictionary> bannedCombos) || bannedCombos.All(x => !pc.Is(x.Key) || !x.Value.Contains(CustomRoles.Lovers))) && !pc.Is(CustomRoles.GM) && (!pc.HasSubRole() || pc.GetCustomSubRoles().Count < Options.NoLimitAddonsNumMax.GetInt()) && !pc.Is(CustomRoles.Dictator) && !pc.Is(CustomRoles.God) && !pc.Is(CustomRoles.FFF) && !pc.Is(CustomRoles.Bomber) && !pc.Is(CustomRoles.Nuker) && !pc.Is(CustomRoles.Provocateur) && !pc.Is(CustomRoles.Altruist) && (!pc.IsCrewmate() || Lovers.CrewCanBeInLove.GetBool()) && (!pc.GetCustomRole().IsNeutral() || Lovers.NeutralCanBeInLove.GetBool()) && (!pc.IsImpostor() || Lovers.ImpCanBeInLove.GetBool())).ToList(); const CustomRoles role = CustomRoles.Lovers; int count = Math.Clamp(RawCount, 0, allPlayers.Count); - if (RawCount == -1) - { - count = Math.Clamp(role.GetCount(), 0, allPlayers.Count); - } + if (RawCount == -1) count = Math.Clamp(role.GetCount(), 0, allPlayers.Count); - if (count <= 0) - { - return; - } + if (count <= 0) return; - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { PlayerControl player = allPlayers.RandomElement(); Main.LoversPlayers.Add(player); @@ -1215,10 +1068,7 @@ namespace EHR public static void AssignDesyncRoles() { // Assign desync roles - foreach ((byte playerId, CustomRoles role) in RoleResult.Where(x => x.Value.IsDesyncRole() || IsBasisChangingPlayer(x.Key, CustomRoles.Bloodlust)).ToArray()) - { - AssignDesyncRole(role, Utils.GetPlayerById(playerId), Senders, RoleMap, ForceImp(playerId) ? RoleTypes.Impostor : role.GetDYRole()); - } + foreach ((byte playerId, CustomRoles role) in RoleResult.Where(x => x.Value.IsDesyncRole() || IsBasisChangingPlayer(x.Key, CustomRoles.Bloodlust)).ToArray()) AssignDesyncRole(role, Utils.GetPlayerById(playerId), Senders, RoleMap, ForceImp(playerId) ? RoleTypes.Impostor : role.GetDYRole()); return; @@ -1238,24 +1088,15 @@ namespace EHR foreach ((byte playerId, CustomRoles role) in RoleResult) { PlayerControl player = Utils.GetPlayerById(playerId); - if (player == null || role.IsDesyncRole()) - { - continue; - } + if (player == null || role.IsDesyncRole()) continue; - if (Options.CurrentGameMode == CustomGameMode.Speedrun && SpeedrunManager.CanKill.Contains(playerId)) - { - continue; - } + if (Options.CurrentGameMode == CustomGameMode.Speedrun && SpeedrunManager.CanKill.Contains(playerId)) continue; RoleTypes roleType = role.GetRoleTypes(); if (BasisChangingAddons.FindFirst(x => x.Value.Contains(playerId), out KeyValuePair> kvp)) { - if (kvp.Key == CustomRoles.Bloodlust) - { - continue; - } + if (kvp.Key == CustomRoles.Bloodlust) continue; roleType = kvp.Key switch { @@ -1271,10 +1112,7 @@ namespace EHR foreach (PlayerControl target in Main.AllPlayerControls) { - if (RoleResult.TryGetValue(target.PlayerId, out CustomRoles targetRole) && targetRole.IsDesyncRole() && !target.IsHost()) - { - continue; - } + if (RoleResult.TryGetValue(target.PlayerId, out CustomRoles targetRole) && targetRole.IsDesyncRole() && !target.IsHost()) continue; RoleMap[(target.PlayerId, playerId)] = (roleType, role); } @@ -1294,36 +1132,21 @@ namespace EHR foreach ((byte targetId, CustomRpcSender sender) in Senders) { PlayerControl target = Utils.GetPlayerById(targetId); - if (OverriddenSenderList.Contains(sender)) - { - continue; - } + if (OverriddenSenderList.Contains(sender)) continue; - if (sender.CurrentState != CustomRpcSender.State.InRootMessage) - { - throw new InvalidOperationException("A CustomRpcSender had Invalid State."); - } + if (sender.CurrentState != CustomRpcSender.State.InRootMessage) throw new InvalidOperationException("A CustomRpcSender had Invalid State."); foreach ((byte seerId, RoleTypes roleType) in StoragedData) { - if (targetId == seerId || targetId == PlayerControl.LocalPlayer.PlayerId) - { - continue; - } + if (targetId == seerId || targetId == PlayerControl.LocalPlayer.PlayerId) continue; PlayerControl seer = Utils.GetPlayerById(seerId); - if (seer == null || target == null) - { - continue; - } + if (seer == null || target == null) continue; try { int targetClientId = target.GetClientId(); - if (targetClientId == -1) - { - continue; - } + if (targetClientId == -1) continue; // send rpc set role for other clients sender.AutoStartRpc(seer.NetId, (byte)RpcCalls.SetRole, targetClientId) @@ -1331,9 +1154,7 @@ namespace EHR .Write(true) // canOverride .EndRpc(); } - catch - { - } + catch { } } sender.EndMessage(); @@ -1362,10 +1183,7 @@ namespace EHR { LateTask.New(() => { - if (CoShowIntroPatch.IntroStarted) - { - return; - } + if (CoShowIntroPatch.IntroStarted) return; Logger.Warn("Starting intro manually", "StartGameHostPatch"); PlayerControl.AllPlayerControls.ForEach((Action)PlayerNameColor.Set); diff --git a/Patches/OutroPatch.cs b/Patches/OutroPatch.cs index e28db96d0..83da06ed1 100644 --- a/Patches/OutroPatch.cs +++ b/Patches/OutroPatch.cs @@ -41,6 +41,7 @@ namespace EHR if (Doppelganger.PlayerIdList.Count > 0 && Doppelganger.DoppelVictim.ContainsKey(id)) { PlayerControl dpc = Utils.GetPlayerById(id); + if (dpc != null) { dpc.RpcSetName(Doppelganger.DoppelVictim[id]); @@ -49,43 +50,29 @@ namespace EHR } SummaryText[id] = Utils.SummaryTexts(id, false); - if (state.SubRoles.Count == 0) - { - continue; - } + if (state.SubRoles.Count == 0) continue; Main.LastAddOns[id] = $"{id.ColoredPlayerName()}: {state.SubRoles.Join(x => x.ToColoredString())}"; } - if (Options.DumpLogAfterGameEnd.GetBool()) - { - Utils.DumpLog(false); - } + if (Options.DumpLogAfterGameEnd.GetBool()) Utils.DumpLog(false); StringBuilder sb = new(GetString("KillLog") + ":"); + foreach ((byte key, PlayerState value) in Main.PlayerStates.OrderBy(x => x.Value.RealKiller.TimeStamp.Ticks)) { DateTime date = value.RealKiller.TimeStamp; - if (date == DateTime.MinValue) - { - continue; - } + if (date == DateTime.MinValue) continue; byte killerId = value.GetRealKiller(); bool gmIsFM = Options.CurrentGameMode is CustomGameMode.FFA or CustomGameMode.MoveAndStop; bool gmIsFMHH = gmIsFM || Options.CurrentGameMode is CustomGameMode.HotPotato or CustomGameMode.HideAndSeek or CustomGameMode.Speedrun or CustomGameMode.CaptureTheFlag or CustomGameMode.NaturalDisasters or CustomGameMode.RoomRush; sb.Append($"\n{date:T} {Main.AllPlayerNames[key]} ({(gmIsFMHH ? string.Empty : Utils.GetDisplayRoleName(key, true))}{(gmIsFM ? string.Empty : Utils.GetSubRolesText(key, summary: true))}) [{Utils.GetVitalText(key)}]"); - if (killerId != byte.MaxValue && killerId != key) - { - sb.Append($"\n\t⇐ {Main.AllPlayerNames[killerId]} ({(gmIsFMHH ? string.Empty : Utils.GetDisplayRoleName(killerId, true))}{(gmIsFM ? string.Empty : Utils.GetSubRolesText(killerId, summary: true))})"); - } + if (killerId != byte.MaxValue && killerId != key) sb.Append($"\n\t⇐ {Main.AllPlayerNames[killerId]} ({(gmIsFMHH ? string.Empty : Utils.GetDisplayRoleName(killerId, true))}{(gmIsFM ? string.Empty : Utils.GetSubRolesText(killerId, summary: true))})"); } KillLog = sb.ToString(); - if (!KillLog.Contains('\n')) - { - KillLog = string.Empty; - } + if (!KillLog.Contains('\n')) KillLog = string.Empty; Main.NormalOptions.KillCooldown = Options.DefaultKillCooldown; @@ -93,19 +80,14 @@ namespace EHR HashSet winner = Main.AllPlayerControls.Where(pc => CustomWinnerHolder.WinnerIds.Contains(pc.PlayerId)).ToHashSet(); - foreach (CustomRoles team in CustomWinnerHolder.WinnerRoles) - { - winner.UnionWith(Main.AllPlayerControls.Where(p => p.Is(team) && !winner.Contains(p))); - } + foreach (CustomRoles team in CustomWinnerHolder.WinnerRoles) winner.UnionWith(Main.AllPlayerControls.Where(p => p.Is(team) && !winner.Contains(p))); Main.WinnerNameList = []; Main.WinnerList = []; + foreach (PlayerControl pc in winner) { - if (CustomWinnerHolder.WinnerTeam is not CustomWinner.Draw && pc.Is(CustomRoles.GM)) - { - continue; - } + if (CustomWinnerHolder.WinnerTeam is not CustomWinner.Draw && pc.Is(CustomRoles.GM)) continue; EndGameResult.CachedWinners.Add(new(pc.Data)); Main.WinnerList.Add(pc.PlayerId); @@ -123,10 +105,7 @@ namespace EHR Bloodmoon.OnMeetingStart(); AFKDetector.ExemptedPlayers.Clear(); - foreach (PlayerState state in Main.PlayerStates.Values) - { - state.Role.Init(); - } + foreach (PlayerState state in Main.PlayerStates.Values) state.Role.Init(); if (AmongUsClient.Instance.AmHost) { @@ -164,24 +143,19 @@ namespace EHR // ---------- Code from TOR (The Other Roles)! ---------- // https://github.com/TheOtherRolesAU/TheOtherRoles/blob/main/TheOtherRoles/Patches/EndGamePatch.cs - if (Options.CurrentGameMode is not CustomGameMode.Standard) - { - goto End; - } + if (Options.CurrentGameMode is not CustomGameMode.Standard) goto End; int num = Mathf.CeilToInt(7.5f); Il2CppArrayBase pbs = __instance?.transform.GetComponentsInChildren(); + if (pbs != null) - { foreach (PoolablePlayer pb in pbs) - { pb.ToggleName(false); - } - } List list = EndGameResult.CachedWinners.ToArray().ToList(); - for (int i = 0; i < list.Count; i++) + + for (var i = 0; i < list.Count; i++) { CachedPlayerData data = list[i]; int num2 = i % 2 == 0 ? -1 : 1; @@ -195,15 +169,14 @@ namespace EHR Vector3 vector = new(num7, num7, 1f); poolablePlayer.transform.localScale = vector; poolablePlayer.UpdateFromPlayerOutfit(data.Outfit, PlayerMaterial.MaskType.ComplexUI, data.IsDead, true); + if (data.IsDead) { poolablePlayer.cosmetics.currentBodySprite.BodySprite.sprite = poolablePlayer.cosmetics.currentBodySprite.GhostSprite; poolablePlayer.SetDeadFlipX(i % 2 == 0); } else - { poolablePlayer.SetFlipX(i % 2 == 0); - } bool lowered = i is 1 or 2 or 5 or 6 or 9 or 10 or 13 or 14; @@ -213,13 +186,10 @@ namespace EHR Vector3 defaultPos = poolablePlayer.cosmetics.nameText.transform.localPosition; - for (int j = 0; j < Main.WinnerList.Count; j++) + for (var j = 0; j < Main.WinnerList.Count; j++) { byte id = Main.WinnerList[j]; - if (Main.WinnerNameList[j].RemoveHtmlTags() != data.PlayerName.RemoveHtmlTags()) - { - continue; - } + if (Main.WinnerNameList[j].RemoveHtmlTags() != data.PlayerName.RemoveHtmlTags()) continue; CustomRoles role = Main.PlayerStates[id].MainRole; @@ -242,12 +212,12 @@ namespace EHR GameObject WinnerTextObject = Object.Instantiate(__instance.WinText.gameObject); WinnerTextObject.transform.position = new(__instance.WinText.transform.position.x, __instance.WinText.transform.position.y - 0.5f, __instance.WinText.transform.position.z); WinnerTextObject.transform.localScale = new(0.6f, 0.6f, 0.6f); - TextMeshPro WinnerText = WinnerTextObject.GetComponent(); + var WinnerText = WinnerTextObject.GetComponent(); WinnerText.fontSizeMin = 3f; WinnerText.text = string.Empty; - string CustomWinnerText = string.Empty; - string AdditionalWinnerText = string.Empty; + var CustomWinnerText = string.Empty; + var AdditionalWinnerText = string.Empty; string CustomWinnerColor = Utils.GetRoleColorCode(CustomRoles.Crewmate); switch (Options.CurrentGameMode) @@ -331,7 +301,8 @@ namespace EHR goto Skip; } - CustomRoles winnerRole = (CustomRoles)CustomWinnerHolder.WinnerTeam; + var winnerRole = (CustomRoles)CustomWinnerHolder.WinnerTeam; + if (winnerRole >= 0) { CustomWinnerText = GetWinnerRoleName(winnerRole); @@ -401,22 +372,16 @@ namespace EHR foreach (AdditionalWinners additionalWinners in CustomWinnerHolder.AdditionalWinnerTeams) { - CustomRoles addWinnerRole = (CustomRoles)additionalWinners; + var addWinnerRole = (CustomRoles)additionalWinners; Logger.Warn(additionalWinners.ToString(), "AdditionalWinner"); - if (addWinnerRole == CustomRoles.Sidekick) - { - continue; - } + if (addWinnerRole == CustomRoles.Sidekick) continue; AdditionalWinnerText += "\n" + Utils.ColorString(Utils.GetRoleColor(addWinnerRole), GetAdditionalWinnerRoleName(addWinnerRole)); } Skip: - if (CustomWinnerHolder.WinnerTeam is not CustomWinner.Draw and not CustomWinner.None and not CustomWinner.Error) - { - WinnerText.text = AdditionalWinnerText == string.Empty ? $"{CustomWinnerText}" : $"{CustomWinnerText}{AdditionalWinnerText}"; - } + if (CustomWinnerHolder.WinnerTeam is not CustomWinner.Draw and not CustomWinner.None and not CustomWinner.Error) WinnerText.text = AdditionalWinnerText == string.Empty ? $"{CustomWinnerText}" : $"{CustomWinnerText}{AdditionalWinnerText}"; EndOfText: @@ -435,12 +400,10 @@ namespace EHR StringBuilder sb = new($"{GetString("RoleSummaryText")}\n"); List cloneRoles = [.. Main.PlayerStates.Keys]; + foreach (byte id in Main.WinnerList) { - if (EndGamePatch.SummaryText[id].Contains("")) - { - continue; - } + if (EndGamePatch.SummaryText[id].Contains("")) continue; sb.Append('\n').Append(EndGamePatch.SummaryText[id]); cloneRoles.Remove(id); @@ -456,10 +419,7 @@ namespace EHR list.AddRange(cloneRoles.Select(id => (SoloKombatManager.GetRankOfScore(id), id))); list.Sort(); - foreach ((int, byte) id in list.Where(x => EndGamePatch.SummaryText.ContainsKey(x.Item2))) - { - sb.Append('\n').Append(EndGamePatch.SummaryText[id.Item2]); - } + foreach ((int, byte) id in list.Where(x => EndGamePatch.SummaryText.ContainsKey(x.Item2))) sb.Append('\n').Append(EndGamePatch.SummaryText[id.Item2]); break; } @@ -469,10 +429,7 @@ namespace EHR list.AddRange(cloneRoles.Select(id => (FFAManager.GetRankFromScore(id), id))); list.Sort(); - foreach ((int, byte) id in list.Where(x => EndGamePatch.SummaryText.ContainsKey(x.Item2))) - { - sb.Append('\n').Append(EndGamePatch.SummaryText[id.Item2]); - } + foreach ((int, byte) id in list.Where(x => EndGamePatch.SummaryText.ContainsKey(x.Item2))) sb.Append('\n').Append(EndGamePatch.SummaryText[id.Item2]); break; } @@ -482,60 +439,42 @@ namespace EHR list.AddRange(cloneRoles.Select(id => (MoveAndStopManager.GetRankOfScore(id), id))); list.Sort(); - foreach ((int, byte) id in list.Where(x => EndGamePatch.SummaryText.ContainsKey(x.Item2))) - { - sb.Append('\n').Append(EndGamePatch.SummaryText[id.Item2]); - } + foreach ((int, byte) id in list.Where(x => EndGamePatch.SummaryText.ContainsKey(x.Item2))) sb.Append('\n').Append(EndGamePatch.SummaryText[id.Item2]); break; } case CustomGameMode.HotPotato: { IOrderedEnumerable list = cloneRoles.OrderByDescending(HotPotatoManager.GetSurvivalTime); - foreach (byte id in list.Where(EndGamePatch.SummaryText.ContainsKey)) - { - sb.Append('\n').Append(EndGamePatch.SummaryText[id]); - } + foreach (byte id in list.Where(EndGamePatch.SummaryText.ContainsKey)) sb.Append('\n').Append(EndGamePatch.SummaryText[id]); break; } case CustomGameMode.Speedrun: { IOrderedEnumerable list = cloneRoles.OrderByDescending(id => Main.PlayerStates[id].TaskState.CompletedTasksCount); - foreach (byte id in list.Where(EndGamePatch.SummaryText.ContainsKey)) - { - sb.Append('\n').Append(EndGamePatch.SummaryText[id]); - } + foreach (byte id in list.Where(EndGamePatch.SummaryText.ContainsKey)) sb.Append('\n').Append(EndGamePatch.SummaryText[id]); break; } case CustomGameMode.CaptureTheFlag: { IOrderedEnumerable list = cloneRoles.OrderByDescending(CTFManager.GetFlagTime); - foreach (byte id in list.Where(EndGamePatch.SummaryText.ContainsKey)) - { - sb.Append('\n').Append(EndGamePatch.SummaryText[id]); - } + foreach (byte id in list.Where(EndGamePatch.SummaryText.ContainsKey)) sb.Append('\n').Append(EndGamePatch.SummaryText[id]); break; } case CustomGameMode.NaturalDisasters: { IOrderedEnumerable list = cloneRoles.OrderByDescending(NaturalDisasters.SurvivalTime); - foreach (byte id in list.Where(EndGamePatch.SummaryText.ContainsKey)) - { - sb.Append('\n').Append(EndGamePatch.SummaryText[id]); - } + foreach (byte id in list.Where(EndGamePatch.SummaryText.ContainsKey)) sb.Append('\n').Append(EndGamePatch.SummaryText[id]); break; } case CustomGameMode.RoomRush: { IOrderedEnumerable list = cloneRoles.OrderByDescending(RoomRush.GetSurvivalTime); - foreach (byte id in list.Where(EndGamePatch.SummaryText.ContainsKey)) - { - sb.Append('\n').Append(EndGamePatch.SummaryText[id]); - } + foreach (byte id in list.Where(EndGamePatch.SummaryText.ContainsKey)) sb.Append('\n').Append(EndGamePatch.SummaryText[id]); break; } @@ -543,10 +482,7 @@ namespace EHR { foreach (byte id in cloneRoles) { - if (EndGamePatch.SummaryText[id].Contains("")) - { - continue; - } + if (EndGamePatch.SummaryText[id].Contains("")) continue; sb.Append('\n').Append(EndGamePatch.SummaryText[id]); } @@ -557,13 +493,13 @@ namespace EHR sb.Append(""); - TextMeshPro RoleSummary = RoleSummaryObject.GetComponent(); + var RoleSummary = RoleSummaryObject.GetComponent(); RoleSummary.alignment = TextAlignmentOptions.TopLeft; RoleSummary.color = Color.white; RoleSummary.outlineWidth *= 1.2f; RoleSummary.fontSizeMin = RoleSummary.fontSizeMax = RoleSummary.fontSize = 1.25f; - RectTransform RoleSummaryRectTransform = RoleSummary.GetComponent(); + var RoleSummaryRectTransform = RoleSummary.GetComponent(); RoleSummaryRectTransform.anchoredPosition = new(Pos.x + 3.5f, Pos.y - 0.1f); RoleSummary.text = sb.ToString(); @@ -572,10 +508,7 @@ namespace EHR static string GetAdditionalWinnerRoleName(CustomRoles role) { string name = GetString($"AdditionalWinnerRoleText.{role}"); - if (name == string.Empty || name.StartsWith("*") || name.StartsWith("= Utils.TimeStamp) - { - return true; - } + if (LastProcess[__instance.PlayerId] + 1 >= Utils.TimeStamp) return true; ExternalRpcPetPatch.Prefix(__instance.MyPhysics, (byte)RpcCalls.Pet); @@ -63,15 +45,9 @@ namespace EHR.Patches public static void Postfix(PlayerControl __instance) { - if (!Options.UsePets.GetBool()) - { - return; - } + if (!Options.UsePets.GetBool()) return; - if (!(AmongUsClient.Instance.AmHost && AmongUsClient.Instance.AmClient)) - { - return; - } + if (!(AmongUsClient.Instance.AmHost && AmongUsClient.Instance.AmClient)) return; __instance.petting = false; } @@ -84,18 +60,12 @@ namespace EHR.Patches public static void Prefix(PlayerPhysics __instance, [HarmonyArgument(0)] byte callID) { - if (GameStates.IsLobby || !Options.UsePets.GetBool() || !AmongUsClient.Instance.AmHost || (RpcCalls)callID != RpcCalls.Pet) - { - return; - } + if (GameStates.IsLobby || !Options.UsePets.GetBool() || !AmongUsClient.Instance.AmHost || (RpcCalls)callID != RpcCalls.Pet) return; PlayerControl pc = __instance.myPlayer; PlayerPhysics physics = __instance; - if (pc == null || !pc.IsAlive()) - { - return; - } + if (pc == null || !pc.IsAlive()) return; if (!pc.inVent && !pc.inMovingPlat @@ -119,15 +89,9 @@ namespace EHR.Patches } } - if (!LastProcess.ContainsKey(pc.PlayerId)) - { - LastProcess.TryAdd(pc.PlayerId, Utils.TimeStamp - 2); - } + if (!LastProcess.ContainsKey(pc.PlayerId)) LastProcess.TryAdd(pc.PlayerId, Utils.TimeStamp - 2); - if (LastProcess[pc.PlayerId] + 1 >= Utils.TimeStamp) - { - return; - } + if (LastProcess[pc.PlayerId] + 1 >= Utils.TimeStamp) return; LastProcess[pc.PlayerId] = Utils.TimeStamp; @@ -151,9 +115,7 @@ namespace EHR.Patches !AmongUsClient.Instance.AmHost || GameStates.IsLobby ) - { return; - } if (Options.CurrentGameMode == CustomGameMode.CaptureTheFlag) { @@ -164,10 +126,7 @@ namespace EHR.Patches if (Mastermind.ManipulatedPlayers.ContainsKey(pc.PlayerId)) { PlayerControl killTarget = SelectKillButtonTarget(pc); - if (killTarget != null) - { - Mastermind.ForceKillForManipulatedPlayer(pc, killTarget); - } + if (killTarget != null) Mastermind.ForceKillForManipulatedPlayer(pc, killTarget); return; } @@ -181,58 +140,34 @@ namespace EHR.Patches if (pc.HasAbilityCD()) { if (!pc.IsHost()) - { pc.Notify(Translator.GetString("AbilityOnCooldown")); - } else - { Main.Instance.StartCoroutine(FlashCooldownTimer()); - } return; } - bool hasKillTarget = false; + var hasKillTarget = false; PlayerControl target = SelectKillButtonTarget(pc); - if (target != null) - { - hasKillTarget = true; - } + if (target != null) hasKillTarget = true; CustomRoles role = pc.GetCustomRole(); bool alwaysPetRole = role is CustomRoles.Necromancer or CustomRoles.Deathknight or CustomRoles.Refugee or CustomRoles.Sidekick; - if (!pc.CanUseKillButton() && !alwaysPetRole) - { - hasKillTarget = false; - } + if (!pc.CanUseKillButton() && !alwaysPetRole) hasKillTarget = false; if (role.UsesPetInsteadOfKill() && hasKillTarget && (pc.Data.RoleType != RoleTypes.Impostor || alwaysPetRole)) { - if (Options.CurrentGameMode != CustomGameMode.Speedrun) - { - pc.AddKCDAsAbilityCD(); - } + if (Options.CurrentGameMode != CustomGameMode.Speedrun) pc.AddKCDAsAbilityCD(); - if (Main.PlayerStates[pc.PlayerId].Role.OnCheckMurder(pc, target)) - { - pc.RpcCheckAndMurder(target); - } + if (Main.PlayerStates[pc.PlayerId].Role.OnCheckMurder(pc, target)) pc.RpcCheckAndMurder(target); - if (alwaysPetRole) - { - pc.SetKillCooldown(); - } + if (alwaysPetRole) pc.SetKillCooldown(); } else - { Main.PlayerStates[pc.PlayerId].Role.OnPet(pc); - } - if (pc.HasAbilityCD() || Main.PlayerStates[pc.PlayerId].Role is Sniper { IsAim: true }) - { - return; - } + if (pc.HasAbilityCD() || Main.PlayerStates[pc.PlayerId].Role is Sniper { IsAim: true }) return; pc.AddAbilityCD(); } @@ -255,8 +190,9 @@ namespace EHR.Patches private static IEnumerator FlashCooldownTimer() { - bool yellow = false; - for (int i = 0; i < 8; i++) + var yellow = false; + + for (var i = 0; i < 8; i++) { HudManagerPatch.CooldownTimerFlashColor = yellow ? Color.red : Color.yellow; yellow = !yellow; diff --git a/Patches/PetsPatch.cs b/Patches/PetsPatch.cs index 6b0ebbc91..4620a10cb 100644 --- a/Patches/PetsPatch.cs +++ b/Patches/PetsPatch.cs @@ -4,34 +4,24 @@ { public static void RpcRemovePet(PlayerControl pc) { - if (pc == null || !pc.Data.IsDead || pc.IsAlive()) - { - return; - } + if (pc == null || !pc.Data.IsDead || pc.IsAlive()) return; - if (!GameStates.IsInGame) - { - return; - } + if (!GameStates.IsInGame) return; - if (!Options.RemovePetsAtDeadPlayers.GetBool()) - { - return; - } + if (!Options.RemovePetsAtDeadPlayers.GetBool()) return; - if (pc.CurrentOutfit.PetId == "") - { - return; - } + if (pc.CurrentOutfit.PetId == "") return; - CustomRpcSender sender = CustomRpcSender.Create("Remove Pet From Dead Player"); + var sender = CustomRpcSender.Create("Remove Pet From Dead Player"); pc.SetPet(""); pc.Data.DefaultOutfit.PetSequenceId += 10; + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetPetStr) .Write("") .Write(pc.GetNextRpcSequenceId(RpcCalls.SetPetStr)) .EndRpc(); + sender.SendMessage(); } } diff --git a/Patches/PhantomRolePatch.cs b/Patches/PhantomRolePatch.cs index dfab52de9..f4587533d 100644 --- a/Patches/PhantomRolePatch.cs +++ b/Patches/PhantomRolePatch.cs @@ -55,32 +55,24 @@ namespace EHR.Patches [HarmonyPrefix] private static void CheckVanish_Prefix(PlayerControl __instance) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; PlayerControl phantom = __instance; Logger.Info($"Player: {phantom.GetRealName()}", "CheckVanish"); foreach (PlayerControl target in Main.AllPlayerControls) { - if (!target.IsAlive() || phantom == target || target.AmOwner || !target.HasDesyncRole()) - { - continue; - } + if (!target.IsAlive() || phantom == target || target.AmOwner || !target.HasDesyncRole()) continue; phantom.RpcSetRoleDesync(RoleTypes.Phantom, target.GetClientId()); phantom.RpcCheckVanishDesync(target); LateTask.New(() => { - if (GameStates.IsMeeting || phantom == null) - { - return; - } + if (GameStates.IsMeeting || phantom == null) return; string petId = phantom.Data.DefaultOutfit.PetId; + if (petId != "") { PetsList[phantom.PlayerId] = petId; @@ -98,25 +90,16 @@ namespace EHR.Patches [HarmonyPrefix] private static void CheckAppear_Prefix(PlayerControl __instance, bool shouldAnimate) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; PlayerControl phantom = __instance; Logger.Info($"Player: {phantom.GetRealName()} => shouldAnimate {shouldAnimate}", "CheckAppear"); - if (phantom.inVent) - { - phantom.MyPhysics.RpcBootFromVent(Main.LastEnteredVent[phantom.PlayerId].Id); - } + if (phantom.inVent) phantom.MyPhysics.RpcBootFromVent(Main.LastEnteredVent[phantom.PlayerId].Id); foreach (PlayerControl target in Main.AllPlayerControls) { - if (!target.IsAlive() || phantom == target || target.AmOwner || !target.HasDesyncRole()) - { - continue; - } + if (!target.IsAlive() || phantom == target || target.AmOwner || !target.HasDesyncRole()) continue; int clientId = target.GetClientId(); @@ -124,26 +107,17 @@ namespace EHR.Patches LateTask.New(() => { - if (target != null) - { - phantom.RpcCheckAppearDesync(shouldAnimate, target); - } + if (target != null) phantom.RpcCheckAppearDesync(shouldAnimate, target); }, 0.5f, $"Check Appear when vanish is over {target.PlayerId}"); LateTask.New(() => { - if (GameStates.IsMeeting || phantom == null) - { - return; - } + if (GameStates.IsMeeting || phantom == null) return; InvisibilityList.Remove(phantom); phantom.RpcSetRoleDesync(RoleTypes.Scientist, clientId); - if (PetsList.TryGetValue(phantom.PlayerId, out string petId)) - { - phantom.RpcSetPetDesync(petId, target); - } + if (PetsList.TryGetValue(phantom.PlayerId, out string petId)) phantom.RpcSetPetDesync(petId, target); }, 1.8f, $"Set Scientist when vanish is over {target.PlayerId}"); } } @@ -152,10 +126,7 @@ namespace EHR.Patches [HarmonyPrefix] private static void SetRoleInvisibility_Prefix(PlayerControl __instance, bool isActive, bool shouldAnimate, bool playFullAnimation) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; Logger.Info($"Player: {__instance.GetRealName()} => Is Active {isActive}, Animate:{shouldAnimate}, Full Animation:{playFullAnimation}", "SetRoleInvisibility"); } @@ -164,10 +135,7 @@ namespace EHR.Patches { try { - if (InvisibilityList.Count == 0 || !seer.IsAlive() || seer.Data.Role.Role is RoleTypes.Phantom || seer.AmOwner || !seer.HasDesyncRole()) - { - return; - } + if (InvisibilityList.Count == 0 || !seer.IsAlive() || seer.Data.Role.Role is RoleTypes.Phantom || seer.AmOwner || !seer.HasDesyncRole()) return; foreach (PlayerControl phantom in InvisibilityList) { @@ -194,52 +162,39 @@ namespace EHR.Patches private static IEnumerator CoRevertInvisible(PlayerControl phantom, PlayerControl seer, bool force) { // Set Scientist for meeting - if (!force) - { - yield return new WaitForSeconds(0.0001f); - } + if (!force) yield return new WaitForSeconds(0.0001f); - if (InValid(phantom, seer)) - { - yield break; - } + if (InValid(phantom, seer)) yield break; phantom?.RpcSetRoleDesync(RoleTypes.Scientist, seer.GetClientId()); // Return Phantom in meeting yield return new WaitForSeconds(1f); + { - if (InValid(phantom, seer)) - { - yield break; - } + if (InValid(phantom, seer)) yield break; phantom?.RpcSetRoleDesync(RoleTypes.Phantom, seer.GetClientId()); } + // Revert invis for phantom yield return new WaitForSeconds(1f); + { - if (InValid(phantom, seer)) - { - yield break; - } + if (InValid(phantom, seer)) yield break; phantom?.RpcStartAppearDesync(false, seer); } + // Set Scientist back yield return new WaitForSeconds(4f); + { - if (InValid(phantom, seer)) - { - yield break; - } + if (InValid(phantom, seer)) yield break; phantom?.RpcSetRoleDesync(RoleTypes.Scientist, seer.GetClientId()); - if (phantom != null && PetsList.TryGetValue(phantom.PlayerId, out string petId)) - { - phantom.RpcSetPetDesync(petId, seer); - } + if (phantom != null && PetsList.TryGetValue(phantom.PlayerId, out string petId)) phantom.RpcSetPetDesync(petId, seer); } } @@ -256,10 +211,7 @@ namespace EHR.Patches { public static bool Prefix(PhantomRole __instance) { - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; if (__instance.Player.AmOwner && !__instance.Player.Data.IsDead && __instance.Player.moveable && !Minigame.Instance && !__instance.IsCoolingDown && !__instance.fading) { diff --git a/Patches/PlayerControlPatch.cs b/Patches/PlayerControlPatch.cs index 0c1874a11..5327852ba 100644 --- a/Patches/PlayerControlPatch.cs +++ b/Patches/PlayerControlPatch.cs @@ -28,23 +28,16 @@ namespace EHR { public static bool Prefix(PlayerControl __instance, [HarmonyArgument(0)] PlayerControl target) { - if (!AmongUsClient.Instance.AmHost || target.Data.IsDead) - { - return false; - } + if (!AmongUsClient.Instance.AmHost || target.Data.IsDead) return false; Logger.Info($"CheckProtect: {__instance.GetNameWithRole().RemoveHtmlTags()} => {target.GetNameWithRole().RemoveHtmlTags()}", "CheckProtect"); if (__instance.Is(CustomRoles.EvilSpirit)) { if (target.Is(CustomRoles.Spiritcaller)) - { Spiritcaller.ProtectSpiritcaller(); - } else - { Spiritcaller.HauntPlayer(target); - } __instance.RpcResetAbilityCooldown(); return true; @@ -75,16 +68,10 @@ namespace EHR { public static bool Prefix(PlayerControl __instance, PlayerControl target, bool didSucceed) { - if (!AmongUsClient.Instance.AmHost) - { - Logger.Error("Client is calling RpcMurderPlayer, are you hacking?", "RpcMurderPlayerPatch.Prefix"); - } + if (!AmongUsClient.Instance.AmHost) Logger.Error("Client is calling RpcMurderPlayer, are you hacking?", "RpcMurderPlayerPatch.Prefix"); MurderResultFlags murderResultFlags = didSucceed ? MurderResultFlags.Succeeded : MurderResultFlags.FailedError; - if (AmongUsClient.Instance.AmClient) - { - __instance.MurderPlayer(target, murderResultFlags); - } + if (AmongUsClient.Instance.AmClient) __instance.MurderPlayer(target, murderResultFlags); MessageWriter messageWriter = AmongUsClient.Instance.StartRpcImmediately(__instance.NetId, (byte)RpcCalls.MurderPlayer, SendOption.Reliable); messageWriter.WriteNetObject(target); @@ -101,9 +88,7 @@ namespace EHR public static bool Prefix(PlayerControl __instance, [HarmonyArgument(0)] PlayerControl target) { if (AmongUsClient.Instance.AmHost) - { __instance.CheckMurder(target); - } else if (Options.CurrentGameMode != CustomGameMode.FFA) { MessageWriter messageWriter = AmongUsClient.Instance.StartRpcImmediately(__instance.NetId, (byte)RpcCalls.CheckMurder, SendOption.Reliable); @@ -130,25 +115,20 @@ namespace EHR public static void Update() { int n = HudManager.InstanceExists ? Math.Max(Main.AllPlayerControls.Length, 15) : 15; + for (byte i = 0; i < n; i++) { if (TimeSinceLastKill.ContainsKey(i)) { TimeSinceLastKill[i] += Time.deltaTime; - if (15f < TimeSinceLastKill[i]) - { - TimeSinceLastKill.Remove(i); - } + if (15f < TimeSinceLastKill[i]) TimeSinceLastKill.Remove(i); } } } public static bool Prefix(PlayerControl __instance, [HarmonyArgument(0)] PlayerControl target) { - if (!AmongUsClient.Instance.AmHost) - { - return false; - } + if (!AmongUsClient.Instance.AmHost) return false; PlayerControl killer = __instance; @@ -198,6 +178,7 @@ namespace EHR float divice = Options.CurrentGameMode != CustomGameMode.Standard ? 3000f : 2000f; float minTime = Mathf.Max(0.02f, AmongUsClient.Instance.Ping / divice * 6f); // The value of AmongUsClient.Instance.Ping is in milliseconds (ms), so ÷1000 + // No value is stored in TimeSinceLastKill || Stored time is greater than or equal to minTime => Allow kill // ↓ If not allowed if (TimeSinceLastKill.TryGetValue(killer.PlayerId, out float time) && time < minTime) @@ -207,21 +188,14 @@ namespace EHR } TimeSinceLastKill[killer.PlayerId] = 0f; + if (target.Is(CustomRoles.Diseased)) - { if (!Main.KilledDiseased.TryAdd(killer.PlayerId, 1)) - { Main.KilledDiseased[killer.PlayerId] += 1; - } - } if (target.Is(CustomRoles.Antidote)) - { if (!Main.KilledAntidote.TryAdd(killer.PlayerId, 1)) - { Main.KilledAntidote[killer.PlayerId] += 1; - } - } killer.ResetKillCooldown(); @@ -259,43 +233,22 @@ namespace EHR Deadlined.SetDone(killer); - if (ToiletMaster.OnAnyoneCheckMurderStart(killer, target)) - { - return false; - } + if (ToiletMaster.OnAnyoneCheckMurderStart(killer, target)) return false; - if (Dad.OnAnyoneCheckMurderStart(target)) - { - return false; - } + if (Dad.OnAnyoneCheckMurderStart(target)) return false; Simon.RemoveTarget(killer, Simon.Instruction.Kill); - if (Mastermind.ManipulatedPlayers.ContainsKey(killer.PlayerId)) - { - return Mastermind.ForceKillForManipulatedPlayer(killer, target); - } + if (Mastermind.ManipulatedPlayers.ContainsKey(killer.PlayerId)) return Mastermind.ForceKillForManipulatedPlayer(killer, target); - if (target.Is(CustomRoles.Spy) && !Spy.OnKillAttempt(killer, target)) - { - return false; - } + if (target.Is(CustomRoles.Spy) && !Spy.OnKillAttempt(killer, target)) return false; - if (Penguin.IsVictim(killer)) - { - return false; - } + if (Penguin.IsVictim(killer)) return false; Sniper.TryGetSniper(target.PlayerId, ref killer); - if (killer != __instance) - { - Logger.Info($"Real Killer: {killer.GetNameWithRole().RemoveHtmlTags()}", "CheckMurder"); - } + if (killer != __instance) Logger.Info($"Real Killer: {killer.GetNameWithRole().RemoveHtmlTags()}", "CheckMurder"); - if (Pelican.IsEaten(target.PlayerId)) - { - return false; - } + if (Pelican.IsEaten(target.PlayerId)) return false; if (killer.IsRoleBlocked()) { @@ -303,10 +256,7 @@ namespace EHR return false; } - if (Pursuer.OnClientMurder(killer)) - { - return false; - } + if (Pursuer.OnClientMurder(killer)) return false; if (killer.PlayerId != target.PlayerId) { @@ -317,14 +267,9 @@ namespace EHR case true when killer.GetCustomRole().GetDYRole() == RoleTypes.Impostor: if (killer.CheckDoubleTrigger(target, () => { - if (CheckMurder()) - { - killer.RpcCheckAndMurder(target); - } + if (CheckMurder()) killer.RpcCheckAndMurder(target); })) - { killer.RpcCheckAndMurder(target); - } return false; } @@ -335,14 +280,12 @@ namespace EHR } } - if (!killer.RpcCheckAndMurder(target, true)) - { - return false; - } + if (!killer.RpcCheckAndMurder(target, true)) return false; if (killer.Is(CustomRoles.Unlucky)) { - IRandom Ue = IRandom.Instance; + var Ue = IRandom.Instance; + if (Ue.Next(0, 100) < Options.UnluckyKillSuicideChance.GetInt()) { killer.Suicide(); @@ -350,10 +293,7 @@ namespace EHR } } - if (killer.Is(CustomRoles.Mare)) - { - killer.ResetKillCooldown(); - } + if (killer.Is(CustomRoles.Mare)) killer.ResetKillCooldown(); if (!DoubleTrigger.FirstTriggerTimer.ContainsKey(killer.PlayerId) && killer.Is(CustomRoles.Swift) && !target.Is(CustomRoles.Pestilence)) { @@ -383,15 +323,9 @@ namespace EHR public static bool RpcCheckAndMurder(PlayerControl killer, PlayerControl target, bool check = false) { - if (!AmongUsClient.Instance.AmHost) - { - return false; - } + if (!AmongUsClient.Instance.AmHost) return false; - if (target == null) - { - target = killer; - } + if (target == null) target = killer; if (CustomTeamManager.AreInSameCustomTeam(killer.PlayerId, target.PlayerId) && !CustomTeamManager.IsSettingEnabledForPlayerTeam(killer.PlayerId, CTAOption.KillEachOther)) { @@ -516,14 +450,12 @@ namespace EHR return false; } - if (Jackal.On && Jackal.ResetKillCooldownWhenSbGetKilled.GetBool() && !killer.Is(CustomRoles.Sidekick) && !target.Is(CustomRoles.Sidekick) && !killer.Is(CustomRoles.Jackal) && !target.Is(CustomRoles.Jackal) && !GameStates.IsMeeting) - { - Jackal.AfterPlayerDiedTask(killer); - } + if (Jackal.On && Jackal.ResetKillCooldownWhenSbGetKilled.GetBool() && !killer.Is(CustomRoles.Sidekick) && !target.Is(CustomRoles.Sidekick) && !killer.Is(CustomRoles.Jackal) && !target.Is(CustomRoles.Jackal) && !GameStates.IsMeeting) Jackal.AfterPlayerDiedTask(killer); if (target.Is(CustomRoles.Lucky)) { - IRandom rd = IRandom.Instance; + var rd = IRandom.Instance; + if (rd.Next(0, 100) < Options.LuckyProbability.GetInt()) { killer.SetKillCooldown(15f); @@ -608,15 +540,9 @@ namespace EHR return false; } - if (!check) - { - killer.Kill(target); - } + if (!check) killer.Kill(target); - if (killer.Is(CustomRoles.Doppelganger)) - { - Doppelganger.OnCheckMurderEnd(killer, target); - } + if (killer.Is(CustomRoles.Doppelganger)) Doppelganger.OnCheckMurderEnd(killer, target); return true; @@ -653,46 +579,26 @@ namespace EHR public static void Postfix(PlayerControl __instance, [HarmonyArgument(0)] PlayerControl target) { - if (__instance == null || target == null || __instance.PlayerId == 255 || target.PlayerId == 255) - { - return; - } + if (__instance == null || target == null || __instance.PlayerId == 255 || target.PlayerId == 255) return; - if (target.AmOwner) - { - RemoveDisableDevicesPatch.UpdateDisableDevices(); - } + if (target.AmOwner) RemoveDisableDevicesPatch.UpdateDisableDevices(); - if (!target.Data.IsDead || !AmongUsClient.Instance.AmHost) - { - return; - } + if (!target.Data.IsDead || !AmongUsClient.Instance.AmHost) return; - if (OverKiller.OverDeadPlayerList.Contains(target.PlayerId)) - { - return; - } + if (OverKiller.OverDeadPlayerList.Contains(target.PlayerId)) return; PlayerControl killer = __instance; // Alternative variable - if (target.PlayerId == Godfather.GodfatherTarget) - { - killer.RpcSetCustomRole(CustomRoles.Refugee); - } + if (target.PlayerId == Godfather.GodfatherTarget) killer.RpcSetCustomRole(CustomRoles.Refugee); PlagueDoctor.OnAnyMurder(); // Replacement process when the actual killer and killer are different - if (Sniper.TryGetSniper(target.PlayerId, ref killer)) - { - Main.PlayerStates[target.PlayerId].deathReason = PlayerState.DeathReason.Sniped; - } + if (Sniper.TryGetSniper(target.PlayerId, ref killer)) Main.PlayerStates[target.PlayerId].deathReason = PlayerState.DeathReason.Sniped; if (killer.Is(CustomRoles.Sniper)) { if (!Options.UsePets.GetBool()) - { killer.RpcResetAbilityCooldown(); - } else { int cd = Options.DefaultShapeshiftCooldown.GetInt(); @@ -701,10 +607,7 @@ namespace EHR } } - if (killer != __instance) - { - Logger.Info($"Real Killer = {killer.GetNameWithRole().RemoveHtmlTags()}", "MurderPlayer"); - } + if (killer != __instance) Logger.Info($"Real Killer = {killer.GetNameWithRole().RemoveHtmlTags()}", "MurderPlayer"); if (Main.PlayerStates[target.PlayerId].deathReason == PlayerState.DeathReason.etc) { @@ -722,15 +625,9 @@ namespace EHR Postman.CheckAndResetTargets(target, true); - if (target.Is(CustomRoles.Trapper) && killer != target) - { - killer.TrapperKilled(target); - } + if (target.Is(CustomRoles.Trapper) && killer != target) killer.TrapperKilled(target); - if (target.Is(CustomRoles.Stained)) - { - Stained.OnDeath(target, killer); - } + if (target.Is(CustomRoles.Stained)) Stained.OnDeath(target, killer); Witness.AllKillers[killer.PlayerId] = TimeStamp; @@ -739,17 +636,11 @@ namespace EHR switch (target.GetCustomRole()) { case CustomRoles.BallLightning: - if (killer != target) - { - BallLightning.MurderPlayer(killer, target); - } + if (killer != target) BallLightning.MurderPlayer(killer, target); break; case CustomRoles.Bane: - if (killer != target) - { - Bane.OnKilled(killer); - } + if (killer != target) Bane.OnKilled(killer); break; case CustomRoles.Markseeker: @@ -761,34 +652,19 @@ namespace EHR Chef.SpitOutFood(killer); - if (Options.CurrentGameMode == CustomGameMode.Speedrun) - { - SpeedrunManager.ResetTimer(killer); - } + if (Options.CurrentGameMode == CustomGameMode.Speedrun) SpeedrunManager.ResetTimer(killer); - if (killer.Is(CustomRoles.TicketsStealer) && killer.PlayerId != target.PlayerId) - { - killer.Notify(string.Format(GetString("TicketsStealerGetTicket"), ((Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == killer.PlayerId) + 1) * Options.TicketsPerKill.GetFloat()).ToString("0.0#####"))); - } + if (killer.Is(CustomRoles.TicketsStealer) && killer.PlayerId != target.PlayerId) killer.Notify(string.Format(GetString("TicketsStealerGetTicket"), ((Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == killer.PlayerId) + 1) * Options.TicketsPerKill.GetFloat()).ToString("0.0#####"))); - if (killer.Is(CustomRoles.Pickpocket) && killer.PlayerId != target.PlayerId) - { - killer.Notify(string.Format(GetString("PickpocketGetVote"), ((Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == killer.PlayerId) + 1) * Pickpocket.VotesPerKill.GetFloat()).ToString("0.0#####"))); - } + if (killer.Is(CustomRoles.Pickpocket) && killer.PlayerId != target.PlayerId) killer.Notify(string.Format(GetString("PickpocketGetVote"), ((Main.AllPlayerControls.Count(x => x.GetRealKiller()?.PlayerId == killer.PlayerId) + 1) * Pickpocket.VotesPerKill.GetFloat()).ToString("0.0#####"))); - if (killer.Is(CustomRoles.Deadlined)) - { - Deadlined.SetDone(killer); - } + if (killer.Is(CustomRoles.Deadlined)) Deadlined.SetDone(killer); if (target.Is(CustomRoles.Avanger)) { PlayerControl[] pcList = Main.AllAlivePlayerControls.Where(x => x.PlayerId != target.PlayerId).ToArray(); PlayerControl rp = pcList.RandomElement(); - if (!rp.Is(CustomRoles.Pestilence)) - { - rp.Suicide(PlayerState.DeathReason.Revenge, target); - } + if (!rp.Is(CustomRoles.Pestilence)) rp.Suicide(PlayerState.DeathReason.Revenge, target); } if (target.Is(CustomRoles.Bait) && !killer.Is(CustomRoles.Minimalism) && (killer.PlayerId != target.PlayerId || target.GetRealKiller()?.GetCustomRole() is CustomRoles.Swooper or CustomRoles.Wraith || !killer.Is(CustomRoles.Oblivious) || !Options.ObliviousBaitImmune.GetBool())) @@ -796,34 +672,25 @@ namespace EHR killer.RPCPlayCustomSound("Congrats"); target.RPCPlayCustomSound("Congrats"); float delay; + if (Options.BaitDelayMax.GetFloat() < Options.BaitDelayMin.GetFloat()) - { delay = 0f; - } else - { delay = IRandom.Instance.Next((int)Options.BaitDelayMin.GetFloat(), (int)Options.BaitDelayMax.GetFloat() + 1); - } delay = Math.Max(delay, 0.15f); - if (delay > 0.15f && Options.BaitDelayNotify.GetBool()) - { - killer.Notify(ColorString(GetRoleColor(CustomRoles.Bait), string.Format(GetString("KillBaitNotify"), (int)delay)), delay); - } + if (delay > 0.15f && Options.BaitDelayNotify.GetBool()) killer.Notify(ColorString(GetRoleColor(CustomRoles.Bait), string.Format(GetString("KillBaitNotify"), (int)delay)), delay); Logger.Info($"{killer.GetNameWithRole().RemoveHtmlTags()} 击杀诱饵 => {target.GetNameWithRole().RemoveHtmlTags()}", "MurderPlayer"); + LateTask.New(() => { if (GameStates.IsInTask) { if (!Options.ReportBaitAtAllCost.GetBool()) - { killer.CmdReportDeadBody(target.Data); - } else - { killer.NoCheckStartMeeting(target.Data, true); - } } }, delay, "Bait Self Report"); } @@ -874,15 +741,9 @@ namespace EHR { public static bool ProcessShapeshift(PlayerControl shapeshifter, PlayerControl target) { - if (!Main.ProcessShapeshifts) - { - return true; - } + if (!Main.ProcessShapeshifts) return true; - if (shapeshifter == null || target == null) - { - return true; - } + if (shapeshifter == null || target == null) return true; Logger.Info($"{shapeshifter.GetNameWithRole()} => {target.GetNameWithRole()}", "Shapeshift"); @@ -890,10 +751,7 @@ namespace EHR if (AmongUsClient.Instance.AmHost && shapeshifting) { - if (!Rhapsode.CheckAbilityUse(shapeshifter)) - { - return false; - } + if (!Rhapsode.CheckAbilityUse(shapeshifter)) return false; if (shapeshifter.Is(CustomRoles.Trainee) && MeetingStates.FirstMeeting) { @@ -905,22 +763,13 @@ namespace EHR Main.CheckShapeshift[shapeshifter.PlayerId] = shapeshifting; Main.ShapeshiftTarget[shapeshifter.PlayerId] = target.PlayerId; - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; - if (!shapeshifting) - { - Camouflage.RpcSetSkin(shapeshifter); - } + if (!shapeshifting) Camouflage.RpcSetSkin(shapeshifter); - bool isSSneeded = true; + var isSSneeded = true; - if (!Pelican.IsEaten(shapeshifter.PlayerId) && !GameStates.IsVoting) - { - isSSneeded = Main.PlayerStates[shapeshifter.PlayerId].Role.OnShapeshift(shapeshifter, target, shapeshifting); - } + if (!Pelican.IsEaten(shapeshifter.PlayerId) && !GameStates.IsVoting) isSSneeded = Main.PlayerStates[shapeshifter.PlayerId].Role.OnShapeshift(shapeshifter, target, shapeshifting); if (shapeshifter.Is(CustomRoles.Hangman) && shapeshifter.GetAbilityUseLimit() < 1 && shapeshifting) { @@ -929,10 +778,7 @@ namespace EHR } bool ctf = Options.CurrentGameMode == CustomGameMode.CaptureTheFlag; - if (ctf) - { - CTFManager.TryPickUpFlag(shapeshifter); - } + if (ctf) CTFManager.TryPickUpFlag(shapeshifter); CustomRoles role = shapeshifter.GetCustomRole(); @@ -960,15 +806,9 @@ namespace EHR isSSneeded &= !doSSwithoutAnim; // Forced rewriting in case the name cannot be corrected due to the timing of canceling the transformation being off. - if (!shapeshifting && !shapeshifter.Is(CustomRoles.Glitch) && isSSneeded) - { - LateTask.New(() => NotifyRoles(NoCache: true), 1.2f, "ShapeShiftNotify"); - } + if (!shapeshifting && !shapeshifter.Is(CustomRoles.Glitch) && isSSneeded) LateTask.New(() => NotifyRoles(NoCache: true), 1.2f, "ShapeShiftNotify"); - if (!(shapeshifting && doSSwithoutAnim) && !isSSneeded && !Swapster.FirstSwapTarget.ContainsKey(shapeshifter.PlayerId)) - { - LateTask.New(shapeshifter.RpcResetAbilityCooldown, 0.01f, log: false); - } + if (!(shapeshifting && doSSwithoutAnim) && !isSSneeded && !Swapster.FirstSwapTarget.ContainsKey(shapeshifter.PlayerId)) LateTask.New(shapeshifter.RpcResetAbilityCooldown, 0.01f, log: false); if (!isSSneeded) { @@ -995,19 +835,13 @@ namespace EHR // Tasks that should run when someone performs a shapeshift (with the egg animation) should be here. public static void Prefix(PlayerControl __instance, [HarmonyArgument(0)] PlayerControl target) { - if (!Main.ProcessShapeshifts || !GameStates.IsInTask || __instance == null || target == null) - { - return; - } + if (!Main.ProcessShapeshifts || !GameStates.IsInTask || __instance == null || target == null) return; bool shapeshifting = __instance.PlayerId != target.PlayerId; foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (pc.Is(CustomRoles.Shiftguard)) - { - pc.Notify(shapeshifting ? GetString("ShiftguardNotifySS") : GetString("ShiftguardNotifyUnshift")); - } + if (pc.Is(CustomRoles.Shiftguard)) pc.Notify(shapeshifting ? GetString("ShiftguardNotifySS") : GetString("ShiftguardNotifyUnshift")); switch (Main.PlayerStates[pc.PlayerId].Role) { @@ -1039,25 +873,13 @@ namespace EHR public static bool Prefix(PlayerControl __instance, [HarmonyArgument(0)] NetworkedPlayerInfo target) { - if (GameStates.IsMeeting) - { - return false; - } + if (GameStates.IsMeeting) return false; - if (Options.DisableMeeting.GetBool()) - { - return false; - } + if (Options.DisableMeeting.GetBool()) return false; - if (Options.CurrentGameMode != CustomGameMode.Standard) - { - return false; - } + if (Options.CurrentGameMode != CustomGameMode.Standard) return false; - if (Options.DisableReportWhenCC.GetBool() && (Camouflager.IsActive || (IsActive(SystemTypes.Comms) && Options.CommsCamouflage.GetBool()))) - { - return false; - } + if (Options.DisableReportWhenCC.GetBool() && (Camouflager.IsActive || (IsActive(SystemTypes.Comms) && Options.CommsCamouflage.GetBool()))) return false; if (!CanReport[__instance.PlayerId]) { @@ -1068,23 +890,14 @@ namespace EHR Logger.Info($"{__instance.GetNameWithRole().RemoveHtmlTags()} => {target?.Object?.GetNameWithRole() ?? "null"}", "ReportDeadBody"); - foreach (KeyValuePair kvp in Main.PlayerStates) - { - kvp.Value.LastRoom = GetPlayerById(kvp.Key).GetPlainShipRoom(); - } + foreach (KeyValuePair kvp in Main.PlayerStates) kvp.Value.LastRoom = GetPlayerById(kvp.Key).GetPlainShipRoom(); - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; try { // If the caller is dead, this process will cancel the meeting, so stop here. - if (__instance.Data.IsDead) - { - return false; - } + if (__instance.Data.IsDead) return false; //============================================= // Next, check whether this meeting is allowed @@ -1093,32 +906,17 @@ namespace EHR PlayerControl killer = target?.Object?.GetRealKiller(); CustomRoles? killerRole = killer?.GetCustomRole(); - if (((IsActive(SystemTypes.Comms) && Options.CommsCamouflage.GetBool() && (Main.NormalOptions.MapId != 5 || !Options.CommsCamouflageDisableOnFungle.GetBool())) || Camouflager.IsActive) && Options.DisableReportWhenCC.GetBool()) - { - return false; - } + if (((IsActive(SystemTypes.Comms) && Options.CommsCamouflage.GetBool() && (Main.NormalOptions.MapId != 5 || !Options.CommsCamouflageDisableOnFungle.GetBool())) || Camouflager.IsActive) && Options.DisableReportWhenCC.GetBool()) return false; - if (Main.PlayerStates.Values.Any(x => x.Role is Tremor { IsDoom: true })) - { - return false; - } + if (Main.PlayerStates.Values.Any(x => x.Role is Tremor { IsDoom: true })) return false; if (target == null) { - if (__instance.Is(CustomRoles.Jester) && !Jester.JesterCanUseButton.GetBool()) - { - return false; - } + if (__instance.Is(CustomRoles.Jester) && !Jester.JesterCanUseButton.GetBool()) return false; - if (__instance.Is(CustomRoles.NiceSwapper) && !NiceSwapper.CanStartMeeting.GetBool()) - { - return false; - } + if (__instance.Is(CustomRoles.NiceSwapper) && !NiceSwapper.CanStartMeeting.GetBool()) return false; - if (__instance.Is(CustomRoles.Adrenaline) && !Adrenaline.CanCallMeeting(__instance)) - { - return false; - } + if (__instance.Is(CustomRoles.Adrenaline) && !Adrenaline.CanCallMeeting(__instance)) return false; if (SoulHunter.IsSoulHunterTarget(__instance.PlayerId)) { @@ -1131,55 +929,35 @@ namespace EHR { if (Bloodhound.UnreportablePlayers.Contains(target.PlayerId) || Vulture.UnreportablePlayers.Contains(target.PlayerId)) - { return false; - } - if (!Librarian.OnAnyoneReport(__instance)) - { - return false; - } + if (!Librarian.OnAnyoneReport(__instance)) return false; - if (!Hypnotist.OnAnyoneReport()) - { - return false; - } + if (!Hypnotist.OnAnyoneReport()) return false; - if (!Altruist.OnAnyoneCheckReportDeadBody(__instance, target)) - { - return false; - } + if (!Altruist.OnAnyoneCheckReportDeadBody(__instance, target)) return false; - if (!BoobyTrap.OnAnyoneCheckReportDeadBody(__instance, target)) - { - return false; - } + if (!BoobyTrap.OnAnyoneCheckReportDeadBody(__instance, target)) return false; - if (!Main.PlayerStates[__instance.PlayerId].Role.CheckReportDeadBody(__instance, target, killer)) - { - return false; - } + if (!Main.PlayerStates[__instance.PlayerId].Role.CheckReportDeadBody(__instance, target, killer)) return false; if (Main.PlayerStates[target.PlayerId].deathReason == PlayerState.DeathReason.Gambled || killerRole == CustomRoles.Scavenger || Cleaner.CleanerBodies.Contains(target.PlayerId)) - { return false; - } PlayerControl tpc = GetPlayerById(target.PlayerId); if (__instance.Is(CustomRoles.Oblivious)) { if (!tpc.Is(CustomRoles.Bait) || Options.ObliviousBaitImmune.GetBool()) /* && (target?.Object != null)*/ - { return false; - } } if (__instance.Is(CustomRoles.Unlucky) && (target.Object == null || !target.Object.Is(CustomRoles.Bait))) { - IRandom Ue = IRandom.Instance; + var Ue = IRandom.Instance; + if (Ue.Next(0, 100) < Options.UnluckyReportSuicideChance.GetInt()) { __instance.Suicide(); @@ -1187,15 +965,13 @@ namespace EHR } } - if (tpc.Is(CustomRoles.Unreportable)) - { - return false; - } + if (tpc.Is(CustomRoles.Unreportable)) return false; } if (Options.SyncButtonMode.GetBool() && target == null) { Logger.Info("Max buttons:" + Options.SyncedButtonCount.GetInt() + ", used:" + Options.UsedButtonCount, "ReportDeadBody"); + if (Options.SyncedButtonCount.GetFloat() <= Options.UsedButtonCount) { Logger.Info("The ship has no more emergency meetings left", "ReportDeadBody"); @@ -1203,10 +979,7 @@ namespace EHR } Options.UsedButtonCount++; - if (Math.Abs(Options.SyncedButtonCount.GetFloat() - Options.UsedButtonCount) < 0.5f) - { - Logger.Info("This was the last allowed emergency meeting", "ReportDeadBody"); - } + if (Math.Abs(Options.SyncedButtonCount.GetFloat() - Options.UsedButtonCount) < 0.5f) Logger.Info("This was the last allowed emergency meeting", "ReportDeadBody"); } AfterReportTasks(__instance, target); @@ -1253,12 +1026,11 @@ namespace EHR else { PlayerControl tpc = target.Object; + if (tpc != null && !tpc.IsAlive()) { if (player.Is(CustomRoles.Detective) && player.PlayerId != target.PlayerId) - { Detective.OnReportDeadBody(player, target.Object); - } else if (player.Is(CustomRoles.Sleuth) && player.PlayerId != target.PlayerId) { string msg = string.Format(GetString("SleuthMsg"), tpc.GetRealName(), tpc.GetDisplayRoleName()); @@ -1266,28 +1038,19 @@ namespace EHR } } - if (Virus.InfectedBodies.Contains(target.PlayerId)) - { - Virus.OnKilledBodyReport(player); - } + if (Virus.InfectedBodies.Contains(target.PlayerId)) Virus.OnKilledBodyReport(player); if (QuizMaster.On) { QuizMaster.Data.LastReporterName = player.GetRealName(); QuizMaster.Data.LastReportedPlayer = (Palette.GetColorName(target.DefaultOutfit.ColorId), target.Object); - if (MeetingStates.FirstMeeting) - { - QuizMaster.Data.FirstReportedBodyPlayerName = target.Object.GetRealName(); - } + if (MeetingStates.FirstMeeting) QuizMaster.Data.FirstReportedBodyPlayerName = target.Object.GetRealName(); } } if (QuizMaster.On) { - if (MeetingStates.FirstMeeting) - { - QuizMaster.Data.NumPlayersDeadFirstRound = Main.AllPlayerControls.Count(x => x.Data.IsDead && !x.Is(CustomRoles.GM)); - } + if (MeetingStates.FirstMeeting) QuizMaster.Data.NumPlayersDeadFirstRound = Main.AllPlayerControls.Count(x => x.Data.IsDead && !x.Is(CustomRoles.GM)); QuizMaster.Data.NumMeetings++; } @@ -1295,6 +1058,7 @@ namespace EHR if (Main.LoversPlayers.Exists(x => x.IsAlive()) && Main.IsLoversDead && Lovers.LoverDieConsequence.GetValue() == 1) { PlayerControl aliveLover = Main.LoversPlayers.First(x => x.IsAlive()); + switch (Lovers.LoverSuicideTime.GetValue()) { case 1: @@ -1329,41 +1093,25 @@ namespace EHR Vulture.Clear(); foreach (PlayerState state in Main.PlayerStates.Values) - { if (state.Role.IsEnable) - { state.Role.OnReportDeadBody(); - } - } Main.AbilityCD.Clear(); SendRPC(CustomRPC.SyncAbilityCD, 2); - if (player.Is(CustomRoles.Damocles)) - { - Damocles.OnReport(player.PlayerId); - } + if (player.Is(CustomRoles.Damocles)) Damocles.OnReport(player.PlayerId); Damocles.OnMeetingStart(); - if (player.Is(CustomRoles.Stressed)) - { - Stressed.OnReport(player); - } + if (player.Is(CustomRoles.Stressed)) Stressed.OnReport(player); Stressed.OnMeetingStart(); foreach (PlayerControl pc in Main.AllPlayerControls) { - if (Main.CheckShapeshift.ContainsKey(pc.PlayerId) && !Doppelganger.DoppelVictim.ContainsKey(pc.PlayerId)) - { - Camouflage.RpcSetSkin(pc, RevertToDefault: true); - } + if (Main.CheckShapeshift.ContainsKey(pc.PlayerId) && !Doppelganger.DoppelVictim.ContainsKey(pc.PlayerId)) Camouflage.RpcSetSkin(pc, RevertToDefault: true); - if (Main.CurrentMap == MapNames.Fungle && (pc.IsMushroomMixupActive() || IsActive(SystemTypes.MushroomMixupSabotage))) - { - pc.FixMixedUpOutfit(); - } + if (Main.CurrentMap == MapNames.Fungle && (pc.IsMushroomMixupActive() || IsActive(SystemTypes.MushroomMixupSabotage))) pc.FixMixedUpOutfit(); PhantomRolePatch.OnReportDeadBody(pc, force); } @@ -1376,13 +1124,11 @@ namespace EHR LateTask.New(SyncAllSettings, 3f, "SyncAllSettings on meeting start"); Main.ProcessShapeshifts = false; + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { CustomRoles role = pc.GetCustomRole(); - if (role.AlwaysUsesUnshift() || (role.SimpleAbilityTrigger() && Options.UseUnshiftTrigger.GetBool() && (!pc.IsNeutralKiller() || Options.UseUnshiftTriggerForNKs.GetBool()))) - { - pc.RpcShapeshift(pc, false); - } + if (role.AlwaysUsesUnshift() || (role.SimpleAbilityTrigger() && Options.UseUnshiftTrigger.GetBool() && (!pc.IsNeutralKiller() || Options.UseUnshiftTriggerForNKs.GetBool()))) pc.RpcShapeshift(pc, false); } } } @@ -1401,22 +1147,14 @@ namespace EHR public static void Postfix(PlayerControl __instance) { - if (__instance == null || __instance.PlayerId == 255) - { - return; - } + if (__instance == null || __instance.PlayerId == 255) return; - if (AmongUsClient.Instance.AmHost && __instance.AmOwner) - { - CustomNetObject.FixedUpdate(); - } + if (AmongUsClient.Instance.AmHost && __instance.AmOwner) CustomNetObject.FixedUpdate(); - if (AmongUsClient.Instance.AmHost && __instance.IsAlive()) - { - VentilationSystemDeterioratePatch.CheckVentInteraction(__instance); - } + if (AmongUsClient.Instance.AmHost && __instance.IsAlive()) VentilationSystemDeterioratePatch.CheckVentInteraction(__instance); byte id = __instance.PlayerId; + if (AmongUsClient.Instance.AmHost && GameStates.IsInTask && ReportDeadBodyPatch.CanReport[id] && ReportDeadBodyPatch.WaitReport[id].Count > 0) { if (id.IsPlayerRoleBlocked()) @@ -1451,10 +1189,7 @@ namespace EHR break; } } - else if (!Main.HasJustStarted && GameStates.IsInTask && !ExileController.Instance && GhostRolesManager.ShouldHaveGhostRole(__instance)) - { - GhostRolesManager.AssignGhostRole(__instance); - } + else if (!Main.HasJustStarted && GameStates.IsInTask && !ExileController.Instance && GhostRolesManager.ShouldHaveGhostRole(__instance)) GhostRolesManager.AssignGhostRole(__instance); } if (GameStates.InGame && Options.DontUpdateDeadPlayers.GetBool() && !__instance.IsAlive() && !__instance.GetCustomRole().NeedsUpdateAfterDeath() && Options.CurrentGameMode != CustomGameMode.RoomRush) @@ -1462,10 +1197,7 @@ namespace EHR int buffer = Options.DeepLowLoad.GetBool() ? 30 : 10; DeadBufferTime.TryAdd(id, buffer); DeadBufferTime[id]--; - if (DeadBufferTime[id] > 0) - { - return; - } + if (DeadBufferTime[id] > 0) return; DeadBufferTime[id] = buffer; } @@ -1483,6 +1215,7 @@ namespace EHR catch (Exception ex) { long now = TimeStamp; + if (LastErrorTS != now) { Logger.Error($"Error for {__instance.GetNameWithRole()}:", "FixedUpdatePatch"); @@ -1501,17 +1234,14 @@ namespace EHR byte lpId = PlayerControl.LocalPlayer.PlayerId; bool localPlayer = playerId == lpId; // Updates that are independent of the player are only executed for the local player. - bool lowLoad = false; + var lowLoad = false; + if (Options.LowLoadMode.GetBool()) { if (BufferTime[playerId] > 0) - { lowLoad = true; - } else - { BufferTime[playerId] = Options.DeepLowLoad.GetBool() ? 30 : 10; - } } if (localPlayer) @@ -1532,20 +1262,15 @@ namespace EHR AFKDetector.OnFixedUpdate(player); } - if (RPCHandlerPatch.ReportDeadBodyRPCs.Remove(playerId)) - { - Logger.Info($"Cleared ReportDeadBodyRPC Count for {player.GetRealName().RemoveHtmlTags()}", "FixedUpdatePatch"); - } + if (RPCHandlerPatch.ReportDeadBodyRPCs.Remove(playerId)) Logger.Info($"Cleared ReportDeadBodyRPC Count for {player.GetRealName().RemoveHtmlTags()}", "FixedUpdatePatch"); } bool inTask = GameStates.IsInTask; bool alive = player.IsAlive(); + if (AmongUsClient.Instance.AmHost) { - if (GameStates.IsLobby && ((ModUpdater.HasUpdate && ModUpdater.ForceUpdate) || ModUpdater.IsBroken || !Main.AllowPublicRoom) && AmongUsClient.Instance.IsGamePublic) - { - AmongUsClient.Instance.ChangeGamePublic(false); - } + if (GameStates.IsLobby && ((ModUpdater.HasUpdate && ModUpdater.ForceUpdate) || ModUpdater.IsBroken || !Main.AllowPublicRoom) && AmongUsClient.Instance.IsGamePublic) AmongUsClient.Instance.ChangeGamePublic(false); // Kick low level people if (!lowLoad && GameStates.IsLobby && !player.AmOwner && Options.KickLowLevelPlayer.GetInt() != 0 && ( @@ -1554,16 +1279,15 @@ namespace EHR )) { LevelKickBufferTime--; + if (LevelKickBufferTime <= 0) { LevelKickBufferTime = 20; + if (player.GetClient().ProductUserId != "") { string hashedPuid = player.GetClient().GetHashedPuid(); - if (!BanManager.TempBanWhiteList.Contains(hashedPuid)) - { - BanManager.TempBanWhiteList.Add(hashedPuid); - } + if (!BanManager.TempBanWhiteList.Contains(hashedPuid)) BanManager.TempBanWhiteList.Add(hashedPuid); } if (!Main.AllPlayerControls.All(x => x.Data.PlayerLevel <= 1) && !LobbyPatch.IsGlitchedRoomCode()) @@ -1584,62 +1308,37 @@ namespace EHR player.MarkDirtySettings(); } - if (!Main.KillTimers.TryAdd(playerId, 10f) && ((!player.inVent && !player.MyPhysics.Animations.IsPlayingEnterVentAnimation()) || player.Is(CustomRoles.Haste)) && Main.KillTimers[playerId] > 0) - { - Main.KillTimers[playerId] -= Time.fixedDeltaTime; - } + if (!Main.KillTimers.TryAdd(playerId, 10f) && ((!player.inVent && !player.MyPhysics.Animations.IsPlayingEnterVentAnimation()) || player.Is(CustomRoles.Haste)) && Main.KillTimers[playerId] > 0) Main.KillTimers[playerId] -= Time.fixedDeltaTime; if (localPlayer) - { if (QuizMaster.On && inTask && !lowLoad && QuizMaster.AllSabotages.Any(IsActive)) - { QuizMaster.Data.LastSabotage = QuizMaster.AllSabotages.FirstOrDefault(IsActive); - } - } - if (!lowLoad && player.IsModClient() && player.Is(CustomRoles.Haste)) - { - player.ForceKillTimerContinue = true; - } + if (!lowLoad && player.IsModClient() && player.Is(CustomRoles.Haste)) player.ForceKillTimerContinue = true; - if (DoubleTrigger.FirstTriggerTimer.Count > 0) - { - DoubleTrigger.OnFixedUpdate(player); - } + if (DoubleTrigger.FirstTriggerTimer.Count > 0) DoubleTrigger.OnFixedUpdate(player); - if (Main.PlayerStates.TryGetValue(playerId, out PlayerState s) && s.Role.IsEnable) - { - s.Role.OnFixedUpdate(player); - } + if (Main.PlayerStates.TryGetValue(playerId, out PlayerState s) && s.Role.IsEnable) s.Role.OnFixedUpdate(player); if (inTask && player.Is(CustomRoles.PlagueBearer) && PlagueBearer.IsPlaguedAll(player)) { player.RpcSetCustomRole(CustomRoles.Pestilence); player.Notify(GetString("PlagueBearerToPestilence")); player.RpcGuardAndKill(player); - if (!PlagueBearer.PestilenceList.Contains(playerId)) - { - PlagueBearer.PestilenceList.Add(playerId); - } + if (!PlagueBearer.PestilenceList.Contains(playerId)) PlagueBearer.PestilenceList.Add(playerId); player.ResetKillCooldown(); PlagueBearer.PlayerIdList.Remove(playerId); } bool checkPos = inTask && player != null && alive && !Pelican.IsEaten(playerId); - if (checkPos) - { - Asthmatic.OnCheckPlayerPosition(player); - } + if (checkPos) Asthmatic.OnCheckPlayerPosition(player); foreach (PlayerState state in Main.PlayerStates.Values) { if (state.Role.IsEnable) { - if (checkPos) - { - state.Role.OnCheckPlayerPosition(player); - } + if (checkPos) state.Role.OnCheckPlayerPosition(player); state.Role.OnGlobalFixedUpdate(player, lowLoad); } @@ -1648,88 +1347,47 @@ namespace EHR if (Main.PlayerStates.TryGetValue(playerId, out PlayerState playerState) && inTask && alive) { List subRoles = playerState.SubRoles; - if (subRoles.Contains(CustomRoles.Dynamo)) - { - Dynamo.OnFixedUpdate(player); - } + if (subRoles.Contains(CustomRoles.Dynamo)) Dynamo.OnFixedUpdate(player); - if (subRoles.Contains(CustomRoles.Spurt)) - { - Spurt.OnFixedUpdate(player); - } + if (subRoles.Contains(CustomRoles.Spurt)) Spurt.OnFixedUpdate(player); if (!lowLoad) { - if (subRoles.Contains(CustomRoles.Damocles)) - { - Damocles.Update(player); - } + if (subRoles.Contains(CustomRoles.Damocles)) Damocles.Update(player); - if (subRoles.Contains(CustomRoles.Stressed)) - { - Stressed.Update(player); - } + if (subRoles.Contains(CustomRoles.Stressed)) Stressed.Update(player); - if (subRoles.Contains(CustomRoles.Asthmatic)) - { - Asthmatic.OnFixedUpdate(); - } + if (subRoles.Contains(CustomRoles.Asthmatic)) Asthmatic.OnFixedUpdate(); - if (subRoles.Contains(CustomRoles.Disco)) - { - Disco.OnFixedUpdate(player); - } + if (subRoles.Contains(CustomRoles.Disco)) Disco.OnFixedUpdate(player); - if (subRoles.Contains(CustomRoles.Clumsy)) - { - Clumsy.OnFixedUpdate(player); - } + if (subRoles.Contains(CustomRoles.Clumsy)) Clumsy.OnFixedUpdate(player); - if (subRoles.Contains(CustomRoles.Sonar)) - { - Sonar.OnFixedUpdate(player); - } + if (subRoles.Contains(CustomRoles.Sonar)) Sonar.OnFixedUpdate(player); - if (subRoles.Contains(CustomRoles.Sleep)) - { - Sleep.CheckGlowNearby(player); - } + if (subRoles.Contains(CustomRoles.Sleep)) Sleep.CheckGlowNearby(player); - if (subRoles.Contains(CustomRoles.Introvert)) - { - Introvert.OnFixedUpdate(player); - } + if (subRoles.Contains(CustomRoles.Introvert)) Introvert.OnFixedUpdate(player); - if (subRoles.Contains(CustomRoles.Allergic)) - { - Allergic.OnFixedUpdate(player); - } + if (subRoles.Contains(CustomRoles.Allergic)) Allergic.OnFixedUpdate(player); } } long now = TimeStamp; + if (!lowLoad && Options.UsePets.GetBool() && inTask && (!LastUpdate.TryGetValue(playerId, out long lastPetNotify) || lastPetNotify < now)) { if (Main.AbilityCD.TryGetValue(playerId, out (long StartTimeStamp, int TotalCooldown) timer)) { - if (timer.StartTimeStamp + timer.TotalCooldown < now || !alive) - { - player.RemoveAbilityCD(); - } + if (timer.StartTimeStamp + timer.TotalCooldown < now || !alive) player.RemoveAbilityCD(); - if (!player.IsModClient() && timer.TotalCooldown - (now - timer.StartTimeStamp) <= 60) - { - NotifyRoles(SpecifySeer: player, SpecifyTarget: player); - } + if (!player.IsModClient() && timer.TotalCooldown - (now - timer.StartTimeStamp) <= 60) NotifyRoles(SpecifySeer: player, SpecifyTarget: player); LastUpdate[playerId] = now; } } - if (!lowLoad) - { - Randomizer.OnFixedUpdateForPlayers(player); - } + if (!lowLoad) Randomizer.OnFixedUpdateForPlayers(player); RoleBlockManager.OnFixedUpdate(player); } @@ -1748,36 +1406,20 @@ namespace EHR AddExtraAbilityUsesOnFinishedTasks(player); } - if (inTask && alive && Options.LadderDeath.GetBool()) - { - FallFromLadder.FixedUpdate(player); - } + if (inTask && alive && Options.LadderDeath.GetBool()) FallFromLadder.FixedUpdate(player); - if (localPlayer && GameStates.IsInGame) - { - LoversSuicide(); - } + if (localPlayer && GameStates.IsInGame) LoversSuicide(); - if (inTask && localPlayer && Options.DisableDevices.GetBool()) - { - DisableDevice.FixedUpdate(); - } + if (inTask && localPlayer && Options.DisableDevices.GetBool()) DisableDevice.FixedUpdate(); if (localPlayer && GameStates.IsInGame && Main.RefixCooldownDelay <= 0) { foreach (PlayerControl pc in Main.AllPlayerControls) - { if (pc.Is(CustomRoles.Vampire) || pc.Is(CustomRoles.Warlock) || pc.Is(CustomRoles.Assassin) || pc.Is(CustomRoles.Undertaker) || pc.Is(CustomRoles.Poisoner)) - { Main.AllPlayerKillCooldown[pc.PlayerId] = Options.DefaultKillCooldown * 2; - } - } } - if (!Main.DoBlockNameChange && AmongUsClient.Instance.AmHost) - { - ApplySuffix(__instance); - } + if (!Main.DoBlockNameChange && AmongUsClient.Instance.AmHost) ApplySuffix(__instance); } if (__instance.AmOwner && inTask && ((Main.ChangedRole && localPlayer && AmongUsClient.Instance.AmHost) || (!__instance.Is(CustomRoleTypes.Impostor) && __instance.CanUseKillButton() && !__instance.Data.IsDead))) @@ -1788,7 +1430,7 @@ namespace EHR } Transform RoleTextTransform = __instance.cosmetics.nameText.transform.Find("RoleText"); - TextMeshPro RoleText = RoleTextTransform.GetComponent(); + var RoleText = RoleTextTransform.GetComponent(); if (RoleText != null && __instance != null && !lowLoad) { @@ -1797,22 +1439,14 @@ namespace EHR if (Main.PlayerVersion.TryGetValue(playerId, out PlayerVersion ver)) { if (Main.ForkId != ver.forkId) - { __instance.cosmetics.nameText.text = $"{ver.forkId}\n{__instance?.name}"; - } else if (Main.Version.CompareTo(ver.version) == 0) - { __instance.cosmetics.nameText.text = ver.tag == $"{ThisAssembly.Git.Commit}({ThisAssembly.Git.Branch})" ? $"{__instance.name}" : $"{ver.tag}\n{__instance?.name}"; - } else - { __instance.cosmetics.nameText.text = $"v{ver.version}\n{__instance?.name}"; - } } else - { __instance.cosmetics.nameText.text = Main.ShowPlayerInfoInLobby.Value && !__instance.AmOwner ? $"<#888888>{__instance.GetClient().PlatformData.Platform} | {__instance.FriendCode} | {__instance.GetClient().GetHashedPuid()}\n{__instance?.Data?.PlayerName}" : __instance?.Data?.PlayerName; - } } if (GameStates.IsInGame) @@ -1831,10 +1465,7 @@ namespace EHR RoleText.text = RoleTextData.Item1; RoleText.color = RoleTextData.Item2; - if (Options.CurrentGameMode is not CustomGameMode.Standard and not CustomGameMode.HideAndSeek) - { - RoleText.text = string.Empty; - } + if (Options.CurrentGameMode is not CustomGameMode.Standard and not CustomGameMode.HideAndSeek) RoleText.text = string.Empty; RoleText.enabled = IsRoleTextEnabled(__instance); @@ -1847,13 +1478,10 @@ namespace EHR if (!AmongUsClient.Instance.IsGameStarted && AmongUsClient.Instance.NetworkMode != NetworkModes.FreePlay) { RoleText.enabled = false; - if (!__instance.AmOwner) - { - __instance.cosmetics.nameText.text = __instance?.Data?.PlayerName; - } + if (!__instance.AmOwner) __instance.cosmetics.nameText.text = __instance?.Data?.PlayerName; } - bool isProgressTextLong = false; + var isProgressTextLong = false; string progressText = GetProgressText(__instance); if (progressText.RemoveHtmlTags().Length > 25 && Main.VisibleTasksCount) @@ -1862,10 +1490,7 @@ namespace EHR progressText = $"\n{progressText}"; } - if (Main.VisibleTasksCount) - { - RoleText.text += progressText; - } + if (Main.VisibleTasksCount) RoleText.text += progressText; PlayerControl seer = PlayerControl.LocalPlayer; PlayerControl target = __instance; @@ -1887,18 +1512,10 @@ namespace EHR if (target.AmOwner && inTask) { if (target.Is(CustomRoles.Arsonist) && target.IsDouseDone()) - { RealName = ColorString(GetRoleColor(CustomRoles.Arsonist), GetString("EnterVentToWin")); - } - else if (target.Is(CustomRoles.Revolutionist) && target.IsDrawDone()) - { - RealName = ColorString(GetRoleColor(CustomRoles.Revolutionist), string.Format(GetString("EnterVentWinCountDown"), Revolutionist.RevolutionistCountdown.GetValueOrDefault(seer.PlayerId, 10))); - } + else if (target.Is(CustomRoles.Revolutionist) && target.IsDrawDone()) RealName = ColorString(GetRoleColor(CustomRoles.Revolutionist), string.Format(GetString("EnterVentWinCountDown"), Revolutionist.RevolutionistCountdown.GetValueOrDefault(seer.PlayerId, 10))); - if (Pelican.IsEaten(seer.PlayerId)) - { - RealName = ColorString(GetRoleColor(CustomRoles.Pelican), GetString("EatenByPelican")); - } + if (Pelican.IsEaten(seer.PlayerId)) RealName = ColorString(GetRoleColor(CustomRoles.Pelican), GetString("EatenByPelican")); switch (Options.CurrentGameMode) { @@ -1907,34 +1524,21 @@ namespace EHR break; } - if (Deathpact.IsInActiveDeathpact(seer)) - { - RealName = Deathpact.GetDeathpactString(seer); - } + if (Deathpact.IsInActiveDeathpact(seer)) RealName = Deathpact.GetDeathpactString(seer); - if (NameNotifyManager.GetNameNotify(target, out string name) && name.Length > 0) - { - RealName = name; - } + if (NameNotifyManager.GetNameNotify(target, out string name) && name.Length > 0) RealName = name; } // Name Color Manager RealName = RealName.ApplyNameColorData(seer, target, false); if (Marshall.CanSeeMarshall(seer)) - { if (target.Is(CustomRoles.Marshall) && target.GetTaskState().IsTaskFinished) - { Mark.Append(ColorString(GetRoleColor(CustomRoles.Marshall), "★")); - } - } Main.PlayerStates.Values.Do(x => Suffix.Append(x.Role.GetSuffix(seer, target, meeting: GameStates.IsMeeting))); - if (self) - { - Suffix.Append(CustomTeamManager.GetSuffix(seer)); - } + if (self) Suffix.Append(CustomTeamManager.GetSuffix(seer)); Suffix.Append(AFKDetector.GetSuffix(seer, target)); @@ -1957,10 +1561,7 @@ namespace EHR switch (seer.GetCustomRole()) { case CustomRoles.Lookout: - if (seer.IsAlive() && target.IsAlive()) - { - Mark.Append(ColorString(GetRoleColor(CustomRoles.Lookout), " " + target.PlayerId) + " "); - } + if (seer.IsAlive() && target.IsAlive()) Mark.Append(ColorString(GetRoleColor(CustomRoles.Lookout), " " + target.PlayerId) + " "); break; case CustomRoles.PlagueBearer when PlagueBearer.IsPlagued(seer.PlayerId, target.PlayerId): @@ -1968,59 +1569,40 @@ namespace EHR break; case CustomRoles.Arsonist: if (seer.IsDousedPlayer(target)) - { Mark.Append($"▲"); - } else if ( Arsonist.CurrentDousingTarget != byte.MaxValue && Arsonist.CurrentDousingTarget == target.PlayerId ) - { Mark.Append($"△"); - } break; case CustomRoles.Revolutionist: if (seer.IsDrawPlayer(target)) - { Mark.Append($"●"); - } else if ( Revolutionist.CurrentDrawTarget != byte.MaxValue && Revolutionist.CurrentDrawTarget == target.PlayerId ) - { Mark.Append($"○"); - } break; case CustomRoles.Farseer: if (Revolutionist.CurrentDrawTarget != byte.MaxValue && Revolutionist.CurrentDrawTarget == target.PlayerId) - { Mark.Append($"○"); - } break; case CustomRoles.Analyst: - if ((Main.PlayerStates[seer.PlayerId].Role as Analyst).CurrentTarget.ID == target.PlayerId) - { - Mark.Append($"○"); - } + if ((Main.PlayerStates[seer.PlayerId].Role as Analyst).CurrentTarget.ID == target.PlayerId) Mark.Append($"○"); break; case CustomRoles.Samurai: - if ((Main.PlayerStates[seer.PlayerId].Role as Samurai).Target.Id == target.PlayerId) - { - Mark.Append($"○"); - } + if ((Main.PlayerStates[seer.PlayerId].Role as Samurai).Target.Id == target.PlayerId) Mark.Append($"○"); break; case CustomRoles.Puppeteer: - if (Puppeteer.PuppeteerList.ContainsValue(seer.PlayerId) && Puppeteer.PuppeteerList.ContainsKey(target.PlayerId)) - { - Mark.Append($"◆"); - } + if (Puppeteer.PuppeteerList.ContainsValue(seer.PlayerId) && Puppeteer.PuppeteerList.ContainsKey(target.PlayerId)) Mark.Append($"◆"); break; case CustomRoles.EvilTracker: @@ -2031,27 +1613,16 @@ namespace EHR break; case CustomRoles.AntiAdminer when inTask: (Main.PlayerStates[seer.PlayerId].Role as AntiAdminer).OnFixedUpdate(seer); + if (target.AmOwner) { - if (AntiAdminer.IsAdminWatch) - { - Suffix.Append(GetString("AntiAdminerAD")); - } + if (AntiAdminer.IsAdminWatch) Suffix.Append(GetString("AntiAdminerAD")); - if (AntiAdminer.IsVitalWatch) - { - Suffix.Append(GetString("AntiAdminerVI")); - } + if (AntiAdminer.IsVitalWatch) Suffix.Append(GetString("AntiAdminerVI")); - if (AntiAdminer.IsDoorLogWatch) - { - Suffix.Append(GetString("AntiAdminerDL")); - } + if (AntiAdminer.IsDoorLogWatch) Suffix.Append(GetString("AntiAdminerDL")); - if (AntiAdminer.IsCameraWatch) - { - Suffix.Append(GetString("AntiAdminerCA")); - } + if (AntiAdminer.IsCameraWatch) Suffix.Append(GetString("AntiAdminerCA")); } break; @@ -2068,20 +1639,11 @@ namespace EHR Mark.Append(Lawyer.LawyerMark(seer, target)); Mark.Append(Marshall.GetWarningMark(seer, target)); - if (Randomizer.IsShielded(target)) - { - Mark.Append(ColorString(GetRoleColor(CustomRoles.Randomizer), "✚")); - } + if (Randomizer.IsShielded(target)) Mark.Append(ColorString(GetRoleColor(CustomRoles.Randomizer), "✚")); - if (target.AmOwner) - { - Mark.Append(Sniper.GetShotNotify(target.PlayerId)); - } + if (target.AmOwner) Mark.Append(Sniper.GetShotNotify(target.PlayerId)); - if (BallLightning.IsGhost(target)) - { - Mark.Append(ColorString(GetRoleColor(CustomRoles.BallLightning), "■")); - } + if (BallLightning.IsGhost(target)) Mark.Append(ColorString(GetRoleColor(CustomRoles.BallLightning), "■")); Mark.Append(Medic.GetMark(seer, target)); Mark.Append(Gaslighter.GetMark(seer, target)); @@ -2090,46 +1652,26 @@ namespace EHR Mark.Append(Deathpact.GetDeathpactMark(seer, target)); Main.LoversPlayers.ToArray().DoIf(x => x == null, x => Main.LoversPlayers.Remove(x)); - if (!Main.HasJustStarted) - { - Main.LoversPlayers.DoIf(x => !x.Is(CustomRoles.Lovers), x => x.RpcSetCustomRole(CustomRoles.Lovers)); - } + if (!Main.HasJustStarted) Main.LoversPlayers.DoIf(x => !x.Is(CustomRoles.Lovers), x => x.RpcSetCustomRole(CustomRoles.Lovers)); if (Main.LoversPlayers.Exists(x => x.PlayerId == target.PlayerId)) { if (Main.LoversPlayers.Exists(x => x.PlayerId == seer.PlayerId)) - { Mark.Append($" ♥"); - } - else if (!seer.IsAlive()) - { - Mark.Append($" ♥"); - } + else if (!seer.IsAlive()) Mark.Append($" ♥"); } if (self) { Suffix.Append(Bloodmoon.GetSuffix(seer)); Suffix.Append(Haunter.GetSuffix(seer)); - if (seer.Is(CustomRoles.Asthmatic)) - { - Suffix.Append(Asthmatic.GetSuffixText(seer.PlayerId)); - } + if (seer.Is(CustomRoles.Asthmatic)) Suffix.Append(Asthmatic.GetSuffixText(seer.PlayerId)); - if (seer.Is(CustomRoles.Sonar)) - { - Suffix.Append(Sonar.GetSuffix(seer, GameStates.IsMeeting)); - } + if (seer.Is(CustomRoles.Sonar)) Suffix.Append(Sonar.GetSuffix(seer, GameStates.IsMeeting)); - if (seer.Is(CustomRoles.Deadlined)) - { - Suffix.Append(Deadlined.GetSuffix(seer)); - } + if (seer.Is(CustomRoles.Deadlined)) Suffix.Append(Deadlined.GetSuffix(seer)); - if (seer.Is(CustomRoles.Allergic)) - { - Suffix.Append(Allergic.GetSelfSuffix(seer)); - } + if (seer.Is(CustomRoles.Allergic)) Suffix.Append(Allergic.GetSelfSuffix(seer)); } switch (Options.CurrentGameMode) @@ -2154,47 +1696,32 @@ namespace EHR break; } - if (Options.CurrentGameMode == CustomGameMode.SoloKombat) - { - Suffix.Append(SoloKombatManager.GetDisplayHealth(target)); - } + if (Options.CurrentGameMode == CustomGameMode.SoloKombat) Suffix.Append(SoloKombatManager.GetDisplayHealth(target)); - if (MeetingStates.FirstMeeting && Main.ShieldPlayer == target.FriendCode && !string.IsNullOrEmpty(target.FriendCode) && !self && Options.CurrentGameMode is CustomGameMode.Standard or CustomGameMode.SoloKombat or CustomGameMode.FFA) - { - Suffix.Append(GetString("DiedR1Warning")); - } + if (MeetingStates.FirstMeeting && Main.ShieldPlayer == target.FriendCode && !string.IsNullOrEmpty(target.FriendCode) && !self && Options.CurrentGameMode is CustomGameMode.Standard or CustomGameMode.SoloKombat or CustomGameMode.FFA) Suffix.Append(GetString("DiedR1Warning")); // Devourer - if (Devourer.HideNameOfConsumedPlayer.GetBool() && Devourer.PlayerIdList.Any(x => Main.PlayerStates[x].Role is Devourer { IsEnable: true } dv && dv.PlayerSkinsCosumed.Contains(seer.PlayerId))) - { - RealName = GetString("DevouredName"); - } + if (Devourer.HideNameOfConsumedPlayer.GetBool() && Devourer.PlayerIdList.Any(x => Main.PlayerStates[x].Role is Devourer { IsEnable: true } dv && dv.PlayerSkinsCosumed.Contains(seer.PlayerId))) RealName = GetString("DevouredName"); // Camouflage - if ((IsActive(SystemTypes.Comms) && Options.CommsCamouflage.GetBool() && (Main.NormalOptions.MapId != 5 || !Options.CommsCamouflageDisableOnFungle.GetBool())) || Camouflager.IsActive) - { - RealName = $"{RealName} "; - } + if ((IsActive(SystemTypes.Comms) && Options.CommsCamouflage.GetBool() && (Main.NormalOptions.MapId != 5 || !Options.CommsCamouflageDisableOnFungle.GetBool())) || Camouflager.IsActive) RealName = $"{RealName} "; string DeathReason = seer.Data.IsDead && seer.KnowDeathReason(target) ? $"\n『{ColorString(GetRoleColor(CustomRoles.Doctor), GetVitalText(target.PlayerId))}』" : string.Empty; string currentText = target.cosmetics.nameText.text; - string changeTo = $"{RealName}{DeathReason}{Mark}\r\n{Suffix}"; + var changeTo = $"{RealName}{DeathReason}{Mark}\r\n{Suffix}"; bool needUpdate = currentText != changeTo; if (needUpdate) { target.cosmetics.nameText.text = changeTo; - float offset = 0.2f; + var offset = 0.2f; if (NameNotifyManager.GetNameNotify(seer, out string notify) && notify.Contains('\n')) { int count = notify.Count(x => x == '\n'); - for (int i = 0; i < count; i++) - { - offset += 0.15f; - } + for (var i = 0; i < count; i++) offset += 0.15f; } if (Suffix.ToString() != string.Empty) @@ -2204,20 +1731,11 @@ namespace EHR offset += 0.15f; } - if (!seer.IsAlive()) - { - offset += 0.1f; - } + if (!seer.IsAlive()) offset += 0.1f; - if (isProgressTextLong) - { - offset += 0.3f; - } + if (isProgressTextLong) offset += 0.3f; - if (Options.CurrentGameMode == CustomGameMode.MoveAndStop) - { - offset += 0.2f; - } + if (Options.CurrentGameMode == CustomGameMode.MoveAndStop) offset += 0.2f; RoleText.transform.SetLocalY(offset); } @@ -2232,10 +1750,7 @@ namespace EHR public static void AddExtraAbilityUsesOnFinishedTasks(PlayerControl player) { - if (Main.HasJustStarted || !player.IsAlive()) - { - return; - } + if (Main.HasJustStarted || !player.IsAlive()) return; if (Main.PlayerStates[player.PlayerId].Role is SabotageMaster sm) { @@ -2248,10 +1763,7 @@ namespace EHR if (Math.Abs(add - float.MaxValue) > 0.5f && add > 0) { - if (player.Is(CustomRoles.Bloodlust)) - { - add *= 5; - } + if (player.Is(CustomRoles.Bloodlust)) add *= 5; player.RpcIncreaseAbilityUseLimitBy(add); } @@ -2260,10 +1772,7 @@ namespace EHR public static void LoversSuicide(byte deathId = 0x7f, bool exile = false, bool force = false, bool guess = false) { - if (Lovers.LoverDieConsequence.GetValue() == 0 || Main.IsLoversDead || (!Main.LoversPlayers.Exists(player => player.Data.IsDead && player.PlayerId == deathId) && !force)) - { - return; - } + if (Lovers.LoverDieConsequence.GetValue() == 0 || Main.IsLoversDead || (!Main.LoversPlayers.Exists(player => player.Data.IsDead && player.PlayerId == deathId) && !force)) return; Main.IsLoversDead = true; PlayerControl partnerPlayer = Main.LoversPlayers.First(player => player.PlayerId != deathId && !player.Data.IsDead); @@ -2275,19 +1784,12 @@ namespace EHR return; } - if (Lovers.LoverSuicideTime.GetValue() != 0 && !exile && !guess) - { - return; - } + if (Lovers.LoverSuicideTime.GetValue() != 0 && !exile && !guess) return; if (exile) - { CheckForEndVotingPatch.TryAddAfterMeetingDeathPlayers(PlayerState.DeathReason.FollowingSuicide, partnerPlayer.PlayerId); - } else - { partnerPlayer.Suicide(PlayerState.DeathReason.FollowingSuicide); - } } } @@ -2323,34 +1825,19 @@ namespace EHR { Logger.Info($" {pc.GetNameWithRole()}, Vent ID: {__instance.Id} ({__instance.name})", "ExitVent"); - if (pc.PlayerId == PlayerControl.LocalPlayer.PlayerId) - { - LateTask.New(() => HudManager.Instance.SetHudActive(pc, pc.Data.Role, true), 0.6f, log: false); - } + if (pc.PlayerId == PlayerControl.LocalPlayer.PlayerId) LateTask.New(() => HudManager.Instance.SetHudActive(pc, pc.Data.Role, true), 0.6f, log: false); - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; - if (Main.KillTimers.ContainsKey(pc.PlayerId)) - { - Main.KillTimers[pc.PlayerId] += 0.5f; - } + if (Main.KillTimers.ContainsKey(pc.PlayerId)) Main.KillTimers[pc.PlayerId] += 0.5f; Drainer.OnAnyoneExitVent(pc); Main.PlayerStates[pc.PlayerId].Role.OnExitVent(pc, __instance); - if (Options.WhackAMole.GetBool()) - { - LateTask.New(() => pc.TPToRandomVent(), 0.5f, "Whack-A-Mole TP"); - } + if (Options.WhackAMole.GetBool()) LateTask.New(() => pc.TPToRandomVent(), 0.5f, "Whack-A-Mole TP"); - if (!pc.IsModClient() && pc.Is(CustomRoles.Haste)) - { - pc.SetKillCooldown(Math.Max(Main.KillTimers[pc.PlayerId], 0.1f)); - } + if (!pc.IsModClient() && pc.Is(CustomRoles.Haste)) pc.SetKillCooldown(Math.Max(Main.KillTimers[pc.PlayerId], 0.1f)); } } @@ -2374,36 +1861,24 @@ namespace EHR switch (pc.GetCustomRole()) { case CustomRoles.Mayor when !Options.UsePets.GetBool() && Mayor.MayorUsedButtonCount.TryGetValue(pc.PlayerId, out int count2) && count2 < Mayor.MayorNumOfUseButton.GetInt(): - if (AmongUsClient.Instance.AmHost) - { - pc.MyPhysics?.RpcBootFromVent(__instance.Id); - } + if (AmongUsClient.Instance.AmHost) pc.MyPhysics?.RpcBootFromVent(__instance.Id); pc.ReportDeadBody(null); break; } - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; Main.LastEnteredVent[pc.PlayerId] = __instance; Main.LastEnteredVentLocation[pc.PlayerId] = pc.Pos(); if (pc.Is(CustomRoles.Unlucky)) { - IRandom Ue = IRandom.Instance; - if (Ue.Next(0, 100) < Options.UnluckyVentSuicideChance.GetInt()) - { - pc.Suicide(); - } + var Ue = IRandom.Instance; + if (Ue.Next(0, 100) < Options.UnluckyVentSuicideChance.GetInt()) pc.Suicide(); } - if (pc.Is(CustomRoles.Damocles)) - { - Damocles.OnEnterVent(pc.PlayerId, __instance.Id); - } + if (pc.Is(CustomRoles.Damocles)) Damocles.OnEnterVent(pc.PlayerId, __instance.Id); Chef.SpitOutFood(pc); @@ -2416,17 +1891,11 @@ namespace EHR { public static bool Prefix(PlayerPhysics __instance, [HarmonyArgument(0)] int id) { - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; Logger.Info($" {__instance.myPlayer.GetNameWithRole()}, Vent ID: {id}", "CoEnterVent"); - if (Main.KillTimers.ContainsKey(__instance.myPlayer.PlayerId)) - { - Main.KillTimers[__instance.myPlayer.PlayerId] += 0.5f; - } + if (Main.KillTimers.ContainsKey(__instance.myPlayer.PlayerId)) Main.KillTimers[__instance.myPlayer.PlayerId] += 0.5f; CheckInvalidMovementPatch.ExemptedPlayers.Add(__instance.myPlayer.PlayerId); @@ -2438,6 +1907,7 @@ namespace EHR __instance.myPlayer?.Notify(GetString("FFA-NoVentingBecauseTwoPlayers"), 7f); __instance.RpcBootFromVent(id); }, 0.5f, "FFA-NoVentingWhenTwoPlayersAlive"); + return true; case CustomGameMode.FFA when FFAManager.FFADisableVentingWhenKcdIsUp.GetBool() && Main.KillTimers[__instance.myPlayer.PlayerId] <= 0: LateTask.New(() => @@ -2445,6 +1915,7 @@ namespace EHR __instance.myPlayer?.Notify(GetString("FFA-NoVentingBecauseKCDIsUP"), 7f); __instance.RpcBootFromVent(id); }, 0.5f, "FFA-NoVentingWhenKCDIsUP"); + return true; case CustomGameMode.MoveAndStop: case CustomGameMode.HotPotato: @@ -2467,6 +1938,7 @@ namespace EHR __instance.myPlayer?.Notify(BlockedAction.Vent.GetBlockNotify()); __instance.RpcBootFromVent(id); }, 0.5f, "RoleBlockedBootFromVent"); + return true; } @@ -2489,12 +1961,14 @@ namespace EHR __instance.myPlayer?.Notify(GetString("SoulHunterTargetNotifyNoVent")); __instance.RpcBootFromVent(id); }, 0.5f, "SoulHunterTargetBootFromVent"); + return true; } if (Ventguard.BlockedVents.Contains(id)) { PlayerControl pc = __instance.myPlayer; + if (!Ventguard.VentguardBlockDoesNotAffectCrew.GetBool() || !pc.IsCrewmate()) { LateTask.New(() => @@ -2504,26 +1978,16 @@ namespace EHR }, 0.5f, "VentguardBlockedVentBootFromVent"); if (Ventguard.VentguardNotifyOnBlockedVentUse.GetBool()) - { foreach (PlayerControl ventguard in Main.AllAlivePlayerControls.Where(x => x.Is(CustomRoles.Ventguard)).ToArray()) - { ventguard.Notify(GetString("VentguardNotify")); - } - } return true; } } - if (__instance.myPlayer.Is(CustomRoles.Circumvent)) - { - Circumvent.OnCoEnterVent(__instance, id); - } + if (__instance.myPlayer.Is(CustomRoles.Circumvent)) Circumvent.OnCoEnterVent(__instance, id); - if (!__instance.myPlayer.CanUseVent() && Options.CurrentGameMode is CustomGameMode.Standard or CustomGameMode.HideAndSeek && !__instance.myPlayer.Is(CustomRoles.Nimble) && !__instance.myPlayer.Is(CustomRoles.Bloodlust)) - { - LateTask.New(() => __instance.RpcBootFromVent(id), 0.5f, "CannotUseVentBootFromVent"); - } + if (!__instance.myPlayer.CanUseVent() && Options.CurrentGameMode is CustomGameMode.Standard or CustomGameMode.HideAndSeek && !__instance.myPlayer.Is(CustomRoles.Nimble) && !__instance.myPlayer.Is(CustomRoles.Bloodlust)) LateTask.New(() => __instance.RpcBootFromVent(id), 0.5f, "CannotUseVentBootFromVent"); if (((__instance.myPlayer.Data.Role.Role != RoleTypes.Engineer && !__instance.myPlayer.CanUseImpostorVentButton()) || (__instance.myPlayer.Is(CustomRoles.Mayor) && Mayor.MayorUsedButtonCount.TryGetValue(__instance.myPlayer.PlayerId, out int count) && count >= Mayor.MayorNumOfUseButton.GetInt()) || @@ -2535,9 +1999,7 @@ namespace EHR LateTask.New(() => __instance.RpcBootFromVent(id), 0.5f, "CannotUseVentBootFromVent2"); return true; } - catch - { - } + catch { } return true; } @@ -2553,10 +2015,7 @@ namespace EHR { public static void Postfix(PlayerControl pc /*, uint taskId*/) { - if (GameStates.IsMeeting) - { - return; - } + if (GameStates.IsMeeting) return; Logger.Info($"TaskComplete: {pc.GetNameWithRole().RemoveHtmlTags()}", "CompleteTask"); Main.PlayerStates[pc.PlayerId].UpdateTask(pc); @@ -2569,49 +2028,32 @@ namespace EHR { public static bool Prefix(PlayerControl __instance) { - if (GameStates.IsMeeting) - { - return false; - } + if (GameStates.IsMeeting) return false; return !Workhorse.OnCompleteTask(__instance) && Capitalism.AddTaskForPlayer(__instance); // Cancel task win } public static void Postfix(PlayerControl __instance, [HarmonyArgument(0)] uint idx) { - if (GameStates.IsMeeting) - { - return; - } + if (GameStates.IsMeeting) return; - PlayerTask task = __instance.myTasks[(Index)Convert.ToInt32(idx)] as PlayerTask; - if (__instance != null && __instance.IsAlive()) - { - Benefactor.OnTaskComplete(__instance, task); - } + var task = __instance.myTasks[(Index)Convert.ToInt32(idx)] as PlayerTask; + if (__instance != null && __instance.IsAlive()) Benefactor.OnTaskComplete(__instance, task); - if (__instance == null) - { - return; - } + if (__instance == null) return; Snitch.OnCompleteTask(__instance); bool isTaskFinish = __instance.GetTaskState().IsTaskFinished; + if (isTaskFinish && __instance.Is(CustomRoles.Snitch) && __instance.Is(CustomRoles.Madmate)) { - foreach (PlayerControl impostor in Main.AllAlivePlayerControls.Where(pc => pc.Is(CustomRoleTypes.Impostor)).ToArray()) - { - NameColorManager.Add(impostor.PlayerId, __instance.PlayerId, "#ff1919"); - } + foreach (PlayerControl impostor in Main.AllAlivePlayerControls.Where(pc => pc.Is(CustomRoleTypes.Impostor)).ToArray()) NameColorManager.Add(impostor.PlayerId, __instance.PlayerId, "#ff1919"); NotifyRoles(SpecifySeer: __instance, ForceLoop: true); } - if (Options.CurrentGameMode == CustomGameMode.HideAndSeek && HnSManager.PlayerRoles[__instance.PlayerId].Interface.Team == Team.Crewmate && __instance.IsAlive()) - { - Hider.OnSpecificTaskComplete(__instance, task); - } + if (Options.CurrentGameMode == CustomGameMode.HideAndSeek && HnSManager.PlayerRoles[__instance.PlayerId].Interface.Team == Team.Crewmate && __instance.IsAlive()) Hider.OnSpecificTaskComplete(__instance, task); } } @@ -2620,10 +2062,7 @@ namespace EHR { public static void Postfix(PlayerControl __instance) { - if (AmongUsClient.Instance.AmHost) - { - PetsPatch.RpcRemovePet(__instance); - } + if (AmongUsClient.Instance.AmHost) PetsPatch.RpcRemovePet(__instance); } } @@ -2649,30 +2088,15 @@ namespace EHR if (AmongUsClient.Instance.AmHost) { - if (Options.DisableZiplineFromTop.GetBool() && fromTop) - { - return false; - } + if (Options.DisableZiplineFromTop.GetBool() && fromTop) return false; - if (Options.DisableZiplineFromUnder.GetBool() && !fromTop) - { - return false; - } + if (Options.DisableZiplineFromUnder.GetBool() && !fromTop) return false; - if (__instance.IsImpostor() && Options.DisableZiplineForImps.GetBool()) - { - return false; - } + if (__instance.IsImpostor() && Options.DisableZiplineForImps.GetBool()) return false; - if (__instance.GetCustomRole().IsNeutral() && Options.DisableZiplineForNeutrals.GetBool()) - { - return false; - } + if (__instance.GetCustomRole().IsNeutral() && Options.DisableZiplineForNeutrals.GetBool()) return false; - if (__instance.IsCrewmate() && Options.DisableZiplineForCrew.GetBool()) - { - return false; - } + if (__instance.IsCrewmate() && Options.DisableZiplineForCrew.GetBool()) return false; } return true; @@ -2705,53 +2129,36 @@ namespace EHR canOverrideRole = true; // Skip after first assign - if (StartGameHostPatch.RpcSetRoleReplacer.BlockSetRole) - { - return true; - } + if (StartGameHostPatch.RpcSetRoleReplacer.BlockSetRole) return true; string targetName = __instance.GetNameWithRole(); Logger.Info($"{targetName} => {roleType}", "PlayerControl.RpcSetRole"); - if (!ShipStatus.Instance.enabled) - { - return true; - } + if (!ShipStatus.Instance.enabled) return true; if (roleType is RoleTypes.CrewmateGhost or RoleTypes.ImpostorGhost) { bool targetIsKiller = __instance.Is(CustomRoleTypes.Impostor) || Main.ResetCamPlayerList.Contains(__instance.PlayerId); Dictionary ghostRoles = new(); + foreach (PlayerControl seer in Main.AllPlayerControls) { bool self = seer.PlayerId == __instance.PlayerId; bool seerIsKiller = seer.Is(CustomRoleTypes.Impostor) || Main.ResetCamPlayerList.Contains(seer.PlayerId); if (__instance.HasGhostRole()) - { ghostRoles[seer] = RoleTypes.GuardianAngel; - } else if ((self && targetIsKiller) || (!seerIsKiller && __instance.Is(CustomRoleTypes.Impostor))) - { ghostRoles[seer] = RoleTypes.ImpostorGhost; - } else - { ghostRoles[seer] = RoleTypes.CrewmateGhost; - } } if (__instance.HasGhostRole()) - { roleType = RoleTypes.GuardianAngel; - } else if (ghostRoles.All(kvp => kvp.Value == RoleTypes.CrewmateGhost)) - { roleType = RoleTypes.CrewmateGhost; - } else if (ghostRoles.All(kvp => kvp.Value == RoleTypes.ImpostorGhost)) - { roleType = RoleTypes.ImpostorGhost; - } else { foreach ((PlayerControl seer, RoleTypes role) in ghostRoles) @@ -2787,10 +2194,8 @@ namespace EHR RoleTypes.Tracker => CustomRoles.TrackerEHR, _ => CustomRoles.NotAssigned }; - if (moddedRole != CustomRoles.NotAssigned) - { - Main.PlayerStates[__instance.PlayerId].SetMainRole(moddedRole); - } + + if (moddedRole != CustomRoles.NotAssigned) Main.PlayerStates[__instance.PlayerId].SetMainRole(moddedRole); } } } @@ -2841,10 +2246,7 @@ namespace EHR { Logger.Info($" {__instance.GetNameWithRole()}", "CheckVanish"); bool allow = Main.PlayerStates[__instance.PlayerId].Role.OnVanish(__instance); - if (!allow) - { - LateTask.New(__instance.RpcResetAbilityCooldown, 0.2f, log: false); - } + if (!allow) LateTask.New(__instance.RpcResetAbilityCooldown, 0.2f, log: false); return true; } @@ -2873,17 +2275,12 @@ namespace EHR { public static void Postfix(PlayerControl __instance) { - if (!__instance.IsAlive()) - { - return; - } + if (!__instance.IsAlive()) return; if (PlayerControl.LocalPlayer.Data.Role.IsImpostor && // Has Impostor role behavior !PlayerControl.LocalPlayer.Is(Team.Impostor) && // Not an actual Impostor PlayerControl.LocalPlayer.GetCustomRole().GetDYRole() is RoleTypes.Impostor or RoleTypes.Shapeshifter or RoleTypes.Phantom) // Has Desynced Impostor role - { __instance.cosmetics.ToggleNameVisible(false); - } } } @@ -2892,10 +2289,7 @@ namespace EHR { public static void Postfix(PlayerControl __instance) { - if (!__instance.IsAlive()) - { - return; - } + if (!__instance.IsAlive()) return; __instance.cosmetics.ToggleNameVisible(true); } diff --git a/Patches/PlayerJoinAndLeftPatch.cs b/Patches/PlayerJoinAndLeftPatch.cs index b3f6fec39..075548bf8 100644 --- a/Patches/PlayerJoinAndLeftPatch.cs +++ b/Patches/PlayerJoinAndLeftPatch.cs @@ -20,10 +20,7 @@ namespace EHR { public static void Postfix(AmongUsClient __instance) { - while (!Options.IsLoaded) - { - Task.Delay(1); - } + while (!Options.IsLoaded) Task.Delay(1); Logger.Info($"{__instance.GameId} joined lobby", "OnGameJoined"); @@ -44,16 +41,10 @@ namespace EHR Main.AllPlayerNames = []; Main.AllClientRealNames = []; - if (Main.NormalOptions?.KillCooldown == 0f) - { - Main.NormalOptions.KillCooldown = Main.LastKillCooldown.Value; - } + if (Main.NormalOptions?.KillCooldown == 0f) Main.NormalOptions.KillCooldown = Main.LastKillCooldown.Value; AURoleOptions.SetOpt(Main.NormalOptions?.Cast()); - if (AURoleOptions.ShapeshifterCooldown == 0f) - { - AURoleOptions.ShapeshifterCooldown = Main.LastShapeshifterCooldown.Value; - } + if (AURoleOptions.ShapeshifterCooldown == 0f) AURoleOptions.ShapeshifterCooldown = Main.LastShapeshifterCooldown.Value; LateTask.New(() => { @@ -94,14 +85,11 @@ namespace EHR { private static bool IsDisconnected(this ClientData client) { - AmongUsClient __instance = AmongUsClient.Instance; + var __instance = AmongUsClient.Instance; + foreach (ClientData clientData in __instance.allClients) - { if (clientData.Id == client.Id) - { return true; - } - } return false; } @@ -131,17 +119,12 @@ namespace EHR } } } - catch - { - } + catch { } }, 3f, "green bean kick late task", false); if (AmongUsClient.Instance.AmHost && client.FriendCode == "" && Options.KickPlayerFriendCodeNotExist.GetBool() && !GameStates.IsLocalGame) { - if (!BanManager.TempBanWhiteList.Contains(client.GetHashedPuid())) - { - BanManager.TempBanWhiteList.Add(client.GetHashedPuid()); - } + if (!BanManager.TempBanWhiteList.Contains(client.GetHashedPuid())) BanManager.TempBanWhiteList.Add(client.GetHashedPuid()); AmongUsClient.Instance.KickPlayer(client.Id, true); Logger.SendInGame(string.Format(GetString("Message.KickedByNoFriendCode"), client.PlayerName)); @@ -186,17 +169,11 @@ namespace EHR { try { - if (data != null && data.Character != null) - { - StartGameHostPatch.DataDisconnected[data.Character.PlayerId] = true; - } + if (data != null && data.Character != null) StartGameHostPatch.DataDisconnected[data.Character.PlayerId] = true; if (GameStates.IsInGame) { - if (Options.CurrentGameMode == CustomGameMode.HideAndSeek) - { - HnSManager.PlayerRoles.Remove(data.Character.PlayerId); - } + if (Options.CurrentGameMode == CustomGameMode.HideAndSeek) HnSManager.PlayerRoles.Remove(data.Character.PlayerId); if (data.Character.Is(CustomRoles.Lovers) && !data.Character.Data.IsDead) { @@ -219,34 +196,19 @@ namespace EHR break; } - if (Executioner.Target.ContainsValue(data.Character.PlayerId)) - { - Executioner.ChangeRoleByTarget(data.Character); - } + if (Executioner.Target.ContainsValue(data.Character.PlayerId)) Executioner.ChangeRoleByTarget(data.Character); - if (Lawyer.Target.ContainsValue(data.Character.PlayerId)) - { - Lawyer.ChangeRoleByTarget(data.Character); - } + if (Lawyer.Target.ContainsValue(data.Character.PlayerId)) Lawyer.ChangeRoleByTarget(data.Character); - if (Spiritualist.SpiritualistTarget == data.Character.PlayerId) - { - Spiritualist.RemoveTarget(); - } + if (Spiritualist.SpiritualistTarget == data.Character.PlayerId) Spiritualist.RemoveTarget(); Postman.CheckAndResetTargets(data.Character); GhostRolesManager.AssignedGhostRoles.Remove(data.Character.PlayerId); PlayerState state = Main.PlayerStates[data.Character.PlayerId]; - if (state.deathReason == PlayerState.DeathReason.etc) - { - state.deathReason = PlayerState.DeathReason.Disconnected; - } + if (state.deathReason == PlayerState.DeathReason.etc) state.deathReason = PlayerState.DeathReason.Disconnected; - if (!state.IsDead) - { - state.SetDead(); - } + if (!state.IsDead) state.SetDead(); Utils.AfterPlayerDeathTasks(data.Character, GameStates.IsMeeting, true); @@ -315,6 +277,7 @@ namespace EHR if (data != null && data.Character != null) { uint netid = data.Character.NetId; + LateTask.New(() => { if (GameStates.IsOnlineGame) @@ -330,9 +293,7 @@ namespace EHR Utils.CountAlivePlayers(true); } - catch (NullReferenceException) - { - } + catch (NullReferenceException) { } catch (Exception ex) { Logger.Error(ex.ToString(), "OnPlayerLeftPatch.Postfix"); @@ -350,10 +311,7 @@ namespace EHR { public static void Postfix([HarmonyArgument(1)] int ownerId, [HarmonyArgument(2)] SpawnFlags flags) { - if (!AmongUsClient.Instance.AmHost || flags != SpawnFlags.IsClientCharacter) - { - return; - } + if (!AmongUsClient.Instance.AmHost || flags != SpawnFlags.IsClientCharacter) return; ClientData client = Utils.GetClientById(ownerId); @@ -361,9 +319,7 @@ namespace EHR if (client == null || client.Character == null // client is null || client.ColorId < 0 || Palette.PlayerColors.Length <= client.ColorId) // invalid client color - { Logger.Warn("client is null or client have invalid color", "TrySyncAndSendMessage"); - } else { LateTask.New(() => { OptionItem.SyncAllOptions(client.Id); }, 3f, "Sync All Options For New Player"); @@ -371,21 +327,14 @@ namespace EHR LateTask.New(() => { if (Main.OverrideWelcomeMsg != "") - { Utils.SendMessage(Main.OverrideWelcomeMsg, client.Character.PlayerId); - } else - { TemplateManager.SendTemplate("welcome", client.Character.PlayerId, true); - } }, 3f, "Welcome Message"); LateTask.New(() => { - if (client.Character == null) - { - return; - } + if (client.Character == null) return; MessageWriter sender = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.RequestRetryVersionCheck, SendOption.Reliable, client.Character.OwnerId); AmongUsClient.Instance.FinishRpcImmediately(sender); @@ -417,10 +366,7 @@ namespace EHR } } - if (client != null && client.Character != null) - { - Main.GuessNumber[client.Character.PlayerId] = [-1, 7]; - } + if (client != null && client.Character != null) Main.GuessNumber[client.Character.PlayerId] = [-1, 7]; if (Main.OverrideWelcomeMsg == string.Empty && Main.PlayerStates.Count > 0 && client != null && Main.ClientIdList.Contains(client.Id)) { @@ -492,44 +438,24 @@ namespace EHR { public static void Postfix(PlayerControl __instance, ref string playerName) { - if (!AmongUsClient.Instance.AmHost || !GameStates.IsLobby) - { - return; - } + if (!AmongUsClient.Instance.AmHost || !GameStates.IsLobby) return; - if (BanManager.CheckDenyNamePlayer(__instance, playerName)) - { - return; - } + if (BanManager.CheckDenyNamePlayer(__instance, playerName)) return; - if (Main.AllClientRealNames.TryAdd(__instance.OwnerId, playerName)) - { - RPC.SyncAllClientRealNames(); - } + if (Main.AllClientRealNames.TryAdd(__instance.OwnerId, playerName)) RPC.SyncAllClientRealNames(); string name = playerName; if (Options.FormatNameMode.GetInt() == 2 && __instance.Data.ClientId != AmongUsClient.Instance.ClientId) - { name = Main.Get_TName_Snacks; - } else { name = name.RemoveHtmlTags().Replace(@"\", string.Empty).Replace("/", string.Empty).Replace("\n", string.Empty).Replace("\r", string.Empty).Replace("<", string.Empty).Replace(">", string.Empty); - if (name.Length > 10) - { - name = name[..10]; - } + if (name.Length > 10) name = name[..10]; - if (Options.DisableEmojiName.GetBool()) - { - name = Regex.Replace(name, @"\p{Cs}", string.Empty); - } + if (Options.DisableEmojiName.GetBool()) name = Regex.Replace(name, @"\p{Cs}", string.Empty); - if (Regex.Replace(Regex.Replace(name, @"\s", string.Empty), @"[\x01-\x1F,\x7F]", string.Empty).Length < 1) - { - name = Main.Get_TName_Snacks; - } + if (Regex.Replace(Regex.Replace(name, @"\s", string.Empty), @"[\x01-\x1F,\x7F]", string.Empty).Length < 1) name = Main.Get_TName_Snacks; } Main.AllPlayerNames[__instance.PlayerId] = name; @@ -560,16 +486,10 @@ namespace EHR public static void Postfix() { - if (GameStates.IsLocalGame || !Options.KickNotJoinedPlayersRegularly.GetBool() || Main.AllPlayerControls.Length < 7) - { - return; - } + if (GameStates.IsLocalGame || !Options.KickNotJoinedPlayersRegularly.GetBool() || Main.AllPlayerControls.Length < 7) return; Timer += Time.fixedDeltaTime; - if (Timer < 25f) - { - return; - } + if (Timer < 25f) return; Timer = 0f; @@ -582,16 +502,10 @@ namespace EHR { public static void Postfix(PlayerControl __instance, byte bodyColor) { - if (Main.IntroDestroyed || __instance == null) - { - return; - } + if (Main.IntroDestroyed || __instance == null) return; Logger.Info($"{__instance.GetRealName()}'s color is {Palette.GetColorName(bodyColor)}", "RpcSetColor"); - if (bodyColor == 255) - { - return; - } + if (bodyColor == 255) return; Main.PlayerColors[__instance.PlayerId] = Palette.PlayerColors[bodyColor]; } diff --git a/Patches/RandomSpawnPatch.cs b/Patches/RandomSpawnPatch.cs index 24e0cfe55..9b7ae82c9 100644 --- a/Patches/RandomSpawnPatch.cs +++ b/Patches/RandomSpawnPatch.cs @@ -28,28 +28,26 @@ namespace EHR public static bool Prefix(CustomNetworkTransform __instance, [HarmonyArgument(0)] byte callId, [HarmonyArgument(1)] MessageReader reader) { - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; - if (!__instance.isActiveAndEnabled) - { - return false; - } + if (!__instance.isActiveAndEnabled) return false; if ((RpcCalls)callId == RpcCalls.SnapTo && (MapNames)Main.NormalOptions.MapId == MapNames.Airship) { PlayerControl player = __instance.myPlayer; + if (!HasSpawned.Contains(player.PlayerId)) { Vector2 position; + { MessageReader newReader = MessageReader.Get(reader); position = NetHelpers.ReadVector2(newReader); newReader.Recycle(); } + Logger.Info($"SnapTo: {player.GetRealName()}, ({position.x}, {position.y})", "RandomSpawn"); + if (IsAirshipVanillaSpawnPosition(position)) { AirshipSpawn(player); @@ -67,16 +65,10 @@ namespace EHR float decupleYFloat = position.y * 10f; int decupleXInt = Mathf.RoundToInt(decupleXFloat); - if (Mathf.Abs(decupleXInt - decupleXFloat) >= 0.09f) - { - return false; - } + if (Mathf.Abs(decupleXInt - decupleXFloat) >= 0.09f) return false; int decupleYInt = Mathf.RoundToInt(decupleYFloat); - if (Mathf.Abs(decupleYInt - decupleYFloat) >= 0.09f) - { - return false; - } + if (Mathf.Abs(decupleYInt - decupleYFloat) >= 0.09f) return false; (int decupleXInt, int decupleYInt) decuplePosition = (decupleXInt, decupleYInt); return DecupleVanillaSpawnPositions.Contains(decuplePosition); @@ -85,23 +77,15 @@ namespace EHR private static void AirshipSpawn(PlayerControl player) { Logger.Info($"Spawn: {player.GetRealName()}", "RandomSpawn"); + if (AmongUsClient.Instance.AmHost) { - if (player.Is(CustomRoles.Penguin)) - { - Penguin.OnSpawnAirship(); - } + if (player.Is(CustomRoles.Penguin)) Penguin.OnSpawnAirship(); player.RpcResetAbilityCooldown(); - if (Options.FixFirstKillCooldown.GetBool() && !MeetingStates.MeetingCalled) - { - player.SetKillCooldown(Main.AllPlayerKillCooldown[player.PlayerId]); - } + if (Options.FixFirstKillCooldown.GetBool() && !MeetingStates.MeetingCalled) player.SetKillCooldown(Main.AllPlayerKillCooldown[player.PlayerId]); - if (Options.RandomSpawn.GetBool() || player.Is(CustomRoles.GM)) - { - new AirshipSpawnMap().RandomTeleport(player); - } + if (Options.RandomSpawn.GetBool() || player.Is(CustomRoles.GM)) new AirshipSpawnMap().RandomTeleport(player); } HasSpawned.Add(player.PlayerId); diff --git a/Patches/RecomputeTaskPatch.cs b/Patches/RecomputeTaskPatch.cs index 4ee83ae4c..3fb2a35e8 100644 --- a/Patches/RecomputeTaskPatch.cs +++ b/Patches/RecomputeTaskPatch.cs @@ -12,21 +12,16 @@ namespace EHR foreach (NetworkedPlayerInfo p in __instance.AllPlayers) { - if (p == null) - { - continue; - } + if (p == null) continue; bool hasTasks = Utils.HasTasks(p) && Main.PlayerStates[p.PlayerId].TaskState.AllTasksCount > 0; + if (hasTasks) { foreach (NetworkedPlayerInfo.TaskInfo task in p.Tasks) { __instance.TotalTasks++; - if (task.Complete) - { - __instance.CompletedTasks++; - } + if (task.Complete) __instance.CompletedTasks++; } } } diff --git a/Patches/RegionMenuPatch.cs b/Patches/RegionMenuPatch.cs index 8bc66fdd4..23daa73c7 100644 --- a/Patches/RegionMenuPatch.cs +++ b/Patches/RegionMenuPatch.cs @@ -15,7 +15,7 @@ namespace EHR.Patches public static void AdjustButtonPositions_Postfix(RegionMenu __instance) { const int maxColumns = 4; - int buttonsPerColumn = 6; + var buttonsPerColumn = 6; const float buttonSpacing = 0.6f; const float buttonSpacingSide = 2.25f; @@ -34,7 +34,7 @@ namespace EHR.Patches Vector3 startPosition = new(-totalWidth / 2, totalHeight / 2, 0f); - for (int i = 0; i < buttons.Count; i++) + for (var i = 0; i < buttons.Count; i++) { int col = i / buttonsPerColumn; int row = i % buttonsPerColumn; diff --git a/Patches/SabotageSystemPatch.cs b/Patches/SabotageSystemPatch.cs index 2c7dcf16b..665bceb66 100644 --- a/Patches/SabotageSystemPatch.cs +++ b/Patches/SabotageSystemPatch.cs @@ -16,23 +16,14 @@ namespace EHR public static void Prefix(ReactorSystemType __instance) { - if (!Options.SabotageTimeControl.GetBool()) - { - return; - } + if (!Options.SabotageTimeControl.GetBool()) return; - if ((MapNames)Main.NormalOptions.MapId is MapNames.Airship) - { - return; - } + if ((MapNames)Main.NormalOptions.MapId is MapNames.Airship) return; // When the sabotage ends if (!__instance.IsActive || !SetDurationForReactorSabotage) { - if (!SetDurationForReactorSabotage && !__instance.IsActive) - { - SetDurationForReactorSabotage = true; - } + if (!SetDurationForReactorSabotage && !__instance.IsActive) SetDurationForReactorSabotage = true; return; } @@ -68,23 +59,14 @@ namespace EHR public static void Prefix(HeliSabotageSystem __instance) { - if (!Options.SabotageTimeControl.GetBool()) - { - return; - } + if (!Options.SabotageTimeControl.GetBool()) return; - if ((MapNames)Main.NormalOptions.MapId is not MapNames.Airship) - { - return; - } + if ((MapNames)Main.NormalOptions.MapId is not MapNames.Airship) return; // When the sabotage ends if (!__instance.IsActive || ShipStatus.Instance == null || !SetDurationForReactorSabotage) { - if (!SetDurationForReactorSabotage && !__instance.IsActive) - { - SetDurationForReactorSabotage = true; - } + if (!SetDurationForReactorSabotage && !__instance.IsActive) SetDurationForReactorSabotage = true; return; } @@ -104,23 +86,14 @@ namespace EHR public static void Prefix(LifeSuppSystemType __instance) { - if (!Options.SabotageTimeControl.GetBool()) - { - return; - } + if (!Options.SabotageTimeControl.GetBool()) return; - if ((MapNames)Main.NormalOptions.MapId is MapNames.Polus or MapNames.Airship or MapNames.Fungle) - { - return; - } + if ((MapNames)Main.NormalOptions.MapId is MapNames.Polus or MapNames.Airship or MapNames.Fungle) return; // When the sabotage ends if (!__instance.IsActive || !SetDurationForO2Sabotage) { - if (!SetDurationForO2Sabotage && !__instance.IsActive) - { - SetDurationForO2Sabotage = true; - } + if (!SetDurationForO2Sabotage && !__instance.IsActive) SetDurationForO2Sabotage = true; return; } @@ -154,6 +127,7 @@ namespace EHR { // Need for hiding player names if player is desync Impostor Utils.NotifyRoles(SpecifySeer: pc, ForceLoop: true, MushroomMixup: true); + if (!pc.Is(Team.Impostor) && pc.HasDesyncRole()) { // Need for hiding player names if player is desync Impostor @@ -172,28 +146,16 @@ namespace EHR { __state = __instance.IsActive; - if (Options.UsePets.GetBool()) - { - __instance.petEmptyChance = 0; - } + if (Options.UsePets.GetBool()) __instance.petEmptyChance = 0; - if (!Options.SabotageTimeControl.GetBool()) - { - return; - } + if (!Options.SabotageTimeControl.GetBool()) return; - if ((MapNames)Main.NormalOptions.MapId is not MapNames.Fungle) - { - return; - } + if ((MapNames)Main.NormalOptions.MapId is not MapNames.Fungle) return; // When the sabotage ends if (!__instance.IsActive || !SetDurationMushroomMixupSabotage) { - if (!SetDurationMushroomMixupSabotage && !__instance.IsActive) - { - SetDurationMushroomMixupSabotage = true; - } + if (!SetDurationMushroomMixupSabotage && !__instance.IsActive) SetDurationMushroomMixupSabotage = true; return; } @@ -224,12 +186,8 @@ namespace EHR }, 1.2f, "Reset Ability Cooldown Arter Mushroom Mixup"); foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { if (!pc.Is(CustomRoleTypes.Impostor) && pc.HasDesyncRole()) - { Utils.NotifyRoles(SpecifySeer: pc, ForceLoop: true, MushroomMixup: true); - } - } } } } @@ -241,47 +199,30 @@ namespace EHR private static bool Prefix(SwitchSystem __instance, [HarmonyArgument(0)] PlayerControl player, [HarmonyArgument(1)] MessageReader msgReader) { byte amount; + { MessageReader newReader = MessageReader.Get(msgReader); amount = newReader.ReadByte(); newReader.Recycle(); } - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; // No matter if the blackout sabotage is sounded (beware of misdirection as it flies under the host's name) - if (amount.HasBit(SwitchSystem.DamageSystem)) - { - return true; - } + if (amount.HasBit(SwitchSystem.DamageSystem)) return true; // Cancel if player can't fix a specific outage on Airship if (Main.CurrentMap == MapNames.Airship) { Vector2 pos = player.Pos(); - if (Options.DisableAirshipViewingDeckLightsPanel.GetBool() && Vector2.Distance(pos, new(-12.93f, -11.28f)) <= 2f) - { - return false; - } + if (Options.DisableAirshipViewingDeckLightsPanel.GetBool() && Vector2.Distance(pos, new(-12.93f, -11.28f)) <= 2f) return false; - if (Options.DisableAirshipGapRoomLightsPanel.GetBool() && Vector2.Distance(pos, new(13.92f, 6.43f)) <= 2f) - { - return false; - } + if (Options.DisableAirshipGapRoomLightsPanel.GetBool() && Vector2.Distance(pos, new(13.92f, 6.43f)) <= 2f) return false; - if (Options.DisableAirshipCargoLightsPanel.GetBool() && Vector2.Distance(pos, new(30.56f, 2.12f)) <= 2f) - { - return false; - } + if (Options.DisableAirshipCargoLightsPanel.GetBool() && Vector2.Distance(pos, new(30.56f, 2.12f)) <= 2f) return false; } - if (player.Is(CustomRoles.Fool)) - { - return false; - } + if (player.Is(CustomRoles.Fool)) return false; if (Options.BlockDisturbancesToSwitches.GetBool()) { @@ -290,15 +231,12 @@ namespace EHR // Far left switch - (amount: 0) 00001 // Far right switch - (amount: 4) 10000 // ref: SwitchSystem.RepairDamage, SwitchMinigame.FixedUpdate - byte switchedKnob = (byte)(0b_00001 << amount); + var switchedKnob = (byte)(0b_00001 << amount); // ExpectedSwitches: Up and down state of switches when all are on // ActualSwitches: Actual up/down state of switch // if Expected and Actual are the same for the operated knob, the knob is already fixed - if ((__instance.ActualSwitches & switchedKnob) == (__instance.ExpectedSwitches & switchedKnob)) - { - return false; - } + if ((__instance.ActualSwitches & switchedKnob) == (__instance.ExpectedSwitches & switchedKnob)) return false; } return true; @@ -313,10 +251,7 @@ namespace EHR public static void Postfix() { long now = Utils.TimeStamp; - if (LastUpdate >= now) - { - return; - } + if (LastUpdate >= now) return; LastUpdate = now; @@ -325,12 +260,8 @@ namespace EHR if (GameStates.IsInTask) { foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { if (pc.GetCustomRole().NeedUpdateOnLights() || pc.Is(CustomRoles.Mare) || pc.Is(CustomRoles.Torch) || pc.Is(CustomRoles.Sleep) || Beacon.IsAffectedPlayer(pc.PlayerId)) - { Utils.NotifyRoles(SpecifyTarget: pc, ForceLoop: true); - } - } } Logger.Info("Lights sabotage called", "ElectricTask"); @@ -345,10 +276,7 @@ namespace EHR public static void Postfix() { long now = Utils.TimeStamp; - if (LastUpdate >= now) - { - return; - } + if (LastUpdate >= now) return; LastUpdate = now; @@ -357,12 +285,8 @@ namespace EHR if (GameStates.IsInTask) { foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { if (pc.GetCustomRole().NeedUpdateOnLights() || pc.Is(CustomRoles.Mare) || pc.Is(CustomRoles.Torch) || pc.Is(CustomRoles.Sleep) || Beacon.IsAffectedPlayer(pc.PlayerId)) - { Utils.NotifyRoles(SpecifyTarget: pc, ForceLoop: true); - } - } } Logger.Info("Lights sabotage fixed", "ElectricTask"); @@ -385,15 +309,9 @@ namespace EHR public static bool Prefix([HarmonyArgument(0)] PlayerControl player) { - if (Options.DisableSabotage.GetBool() || Options.CurrentGameMode != CustomGameMode.Standard) - { - return false; - } + if (Options.DisableSabotage.GetBool() || Options.CurrentGameMode != CustomGameMode.Standard) return false; - if (SecurityGuard.BlockSabo.Count > 0) - { - return false; - } + if (SecurityGuard.BlockSabo.Count > 0) return false; if (player.IsRoleBlocked()) { @@ -401,15 +319,9 @@ namespace EHR return false; } - if (player.Is(Team.Impostor) && !player.IsAlive() && Options.DeadImpCantSabotage.GetBool()) - { - return false; - } + if (player.Is(Team.Impostor) && !player.IsAlive() && Options.DeadImpCantSabotage.GetBool()) return false; - if (!player.Is(Team.Impostor) && !player.IsAlive()) - { - return false; - } + if (!player.Is(Team.Impostor) && !player.IsAlive()) return false; bool allow = player.GetCustomRole() switch { @@ -420,10 +332,8 @@ namespace EHR CustomRoles.Refugee when player.IsAlive() => true, _ => Main.PlayerStates[player.PlayerId].Role.CanUseSabotage(player) && Main.PlayerStates[player.PlayerId].Role.OnSabotage(player) }; - if (allow && QuizMaster.On) - { - QuizMaster.Data.NumSabotages++; - } + + if (allow && QuizMaster.On) QuizMaster.Data.NumSabotages++; return allow; } @@ -431,10 +341,7 @@ namespace EHR public static void Postfix(SabotageSystemType __instance) { - if (!IsCooldownModificationEnabled || !AmongUsClient.Instance.AmHost) - { - return; - } + if (!IsCooldownModificationEnabled || !AmongUsClient.Instance.AmHost) return; __instance.Timer = ModifiedCooldownSec; __instance.IsDirty = true; @@ -447,6 +354,7 @@ namespace EHR public static bool Prefix([HarmonyArgument(1)] MessageReader msgReader) { byte amount; + { MessageReader newReader = MessageReader.Get(msgReader); amount = newReader.ReadByte(); diff --git a/Patches/ServerVersionPatch.cs b/Patches/ServerVersionPatch.cs index 784b0ea64..53b971837 100644 --- a/Patches/ServerVersionPatch.cs +++ b/Patches/ServerVersionPatch.cs @@ -7,10 +7,7 @@ namespace EHR.Patches { public static void Postfix(ref int __result) { - if (GameStates.IsLocalGame) - { - Logger.Info($"IsLocalGame: {__result}", "VersionServer"); - } + if (GameStates.IsLocalGame) Logger.Info($"IsLocalGame: {__result}", "VersionServer"); if (GameStates.IsOnlineGame) { diff --git a/Patches/ShipStatusPatch.cs b/Patches/ShipStatusPatch.cs index 882d94387..b42afd8d4 100644 --- a/Patches/ShipStatusPatch.cs +++ b/Patches/ShipStatusPatch.cs @@ -20,15 +20,10 @@ namespace EHR { public static void Postfix( /*ShipStatus __instance*/) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; if (Main.IsFixedCooldown && Main.RefixCooldownDelay >= 0) - { Main.RefixCooldownDelay -= Time.fixedDeltaTime; - } else if (!float.IsNaN(Main.RefixCooldownDelay)) { Utils.MarkEveryoneDirtySettingsV4(); @@ -45,12 +40,10 @@ namespace EHR { try { - if (systemType is SystemTypes.Ventilation or SystemTypes.Security or SystemTypes.Decontamination or SystemTypes.Decontamination2 or SystemTypes.Decontamination3 or SystemTypes.MedBay) - { - return true; - } + if (systemType is SystemTypes.Ventilation or SystemTypes.Security or SystemTypes.Decontamination or SystemTypes.Decontamination2 or SystemTypes.Decontamination3 or SystemTypes.MedBay) return true; byte amount = MessageReader.Get(reader).ReadByte(); + if (EAC.CheckInvalidSabotage(systemType, player, amount)) { Logger.Info("EAC patched Sabotage RPC", "MessageReaderUpdateSystemPatch"); @@ -59,9 +52,7 @@ namespace EHR return RepairSystemPatch.Prefix(systemType, player, amount); } - catch - { - } + catch { } return true; } @@ -70,16 +61,11 @@ namespace EHR { try { - if (systemType is SystemTypes.Ventilation or SystemTypes.Security or SystemTypes.Decontamination or SystemTypes.Decontamination2 or SystemTypes.Decontamination3 or SystemTypes.MedBay) - { - return; - } + if (systemType is SystemTypes.Ventilation or SystemTypes.Security or SystemTypes.Decontamination or SystemTypes.Decontamination2 or SystemTypes.Decontamination3 or SystemTypes.MedBay) return; RepairSystemPatch.Postfix(systemType, player); } - catch - { - } + catch { } } } @@ -92,25 +78,13 @@ namespace EHR [HarmonyArgument(2)] byte amount) { Logger.Msg($"SystemType: {systemType}, PlayerName: {player.GetNameWithRole().RemoveHtmlTags()}, amount: {amount}", "RepairSystem"); - if (RepairSender.Enabled && AmongUsClient.Instance.NetworkMode != NetworkModes.OnlineGame) - { - Logger.SendInGame($"SystemType: {systemType}, PlayerName: {player.GetNameWithRole().RemoveHtmlTags()}, amount: {amount}"); - } + if (RepairSender.Enabled && AmongUsClient.Instance.NetworkMode != NetworkModes.OnlineGame) Logger.SendInGame($"SystemType: {systemType}, PlayerName: {player.GetNameWithRole().RemoveHtmlTags()}, amount: {amount}"); - if (!AmongUsClient.Instance.AmHost) - { - return true; // Execute the following only on the host - } + if (!AmongUsClient.Instance.AmHost) return true; // Execute the following only on the host - if ((Options.CurrentGameMode != CustomGameMode.Standard || Options.DisableSabotage.GetBool()) && systemType == SystemTypes.Sabotage) - { - return false; - } + if ((Options.CurrentGameMode != CustomGameMode.Standard || Options.DisableSabotage.GetBool()) && systemType == SystemTypes.Sabotage) return false; - if (player.Is(CustomRoles.Fool) && systemType is SystemTypes.Comms or SystemTypes.Electrical) - { - return false; - } + if (player.Is(CustomRoles.Fool) && systemType is SystemTypes.Comms or SystemTypes.Electrical) return false; switch (player.GetCustomRole()) { @@ -131,7 +105,8 @@ namespace EHR switch (systemType) { case SystemTypes.Doors when player.Is(CustomRoles.Unlucky) && player.IsAlive(): - IRandom Ue = IRandom.Instance; + var Ue = IRandom.Instance; + if (Ue.Next(0, 100) < Options.UnluckySabotageSuicideChance.GetInt()) { player.Suicide(); @@ -140,26 +115,19 @@ namespace EHR break; case SystemTypes.Electrical when amount <= 4 && Main.NormalOptions.MapId == 4: - if (Options.DisableAirshipViewingDeckLightsPanel.GetBool() && Vector2.Distance(player.transform.position, new(-12.93f, -11.28f)) <= 2f) - { - return false; - } + if (Options.DisableAirshipViewingDeckLightsPanel.GetBool() && Vector2.Distance(player.transform.position, new(-12.93f, -11.28f)) <= 2f) return false; - if (Options.DisableAirshipGapRoomLightsPanel.GetBool() && Vector2.Distance(player.transform.position, new(13.92f, 6.43f)) <= 2f) - { - return false; - } + if (Options.DisableAirshipGapRoomLightsPanel.GetBool() && Vector2.Distance(player.transform.position, new(13.92f, 6.43f)) <= 2f) return false; - if (Options.DisableAirshipCargoLightsPanel.GetBool() && Vector2.Distance(player.transform.position, new(30.56f, 2.12f)) <= 2f) - { - return false; - } + if (Options.DisableAirshipCargoLightsPanel.GetBool() && Vector2.Distance(player.transform.position, new(30.56f, 2.12f)) <= 2f) return false; goto Next; case SystemTypes.Electrical when amount <= 4: Next: + { - SwitchSystem SwitchSystem = ShipStatus.Instance?.Systems?[SystemTypes.Electrical]?.Cast(); + var SwitchSystem = ShipStatus.Instance?.Systems?[SystemTypes.Electrical]?.Cast(); + if (SwitchSystem is { IsActive: true }) { switch (Main.PlayerStates[player.PlayerId].Role) @@ -174,10 +142,7 @@ namespace EHR case Alchemist { FixNextSabo: true } am: { Logger.Info($"{player.GetNameWithRole().RemoveHtmlTags()} instant-fix-lights", "Alchemist"); - if (amount.HasBit(SwitchSystem.DamageSystem)) - { - break; - } + if (amount.HasBit(SwitchSystem.DamageSystem)) break; SwitchSystem.ActualSwitches = (byte)(SwitchSystem.ExpectedSwitches ^ (1 << amount)); am.FixNextSabo = false; @@ -187,10 +152,7 @@ namespace EHR case Adventurer av: { Logger.Info($"{player.GetNameWithRole().RemoveHtmlTags()} instant-fix-lights", "Adventurer"); - if (amount.HasBit(SwitchSystem.DamageSystem)) - { - break; - } + if (amount.HasBit(SwitchSystem.DamageSystem)) break; SwitchSystem.ActualSwitches = (byte)(SwitchSystem.ExpectedSwitches ^ (1 << amount)); av.OnLightsFix(); @@ -206,29 +168,17 @@ namespace EHR } } - if (player.Is(CustomRoles.Damocles) && Damocles.CountRepairSabotage) - { - Damocles.OnRepairSabotage(player.PlayerId); - } + if (player.Is(CustomRoles.Damocles) && Damocles.CountRepairSabotage) Damocles.OnRepairSabotage(player.PlayerId); - if (player.Is(CustomRoles.Stressed) && Stressed.CountRepairSabotage) - { - Stressed.OnRepairSabotage(player); - } + if (player.Is(CustomRoles.Stressed) && Stressed.CountRepairSabotage) Stressed.OnRepairSabotage(player); } break; } case SystemTypes.Sabotage when AmongUsClient.Instance.NetworkMode != NetworkModes.FreePlay: - if (Options.CurrentGameMode != CustomGameMode.Standard) - { - return false; - } + if (Options.CurrentGameMode != CustomGameMode.Standard) return false; - if (SecurityGuard.BlockSabo.Count > 0) - { - return false; - } + if (SecurityGuard.BlockSabo.Count > 0) return false; if (player.IsRoleBlocked()) { @@ -236,15 +186,9 @@ namespace EHR return false; } - if (player.Is(Team.Impostor) && !player.IsAlive() && Options.DeadImpCantSabotage.GetBool()) - { - return false; - } + if (player.Is(Team.Impostor) && !player.IsAlive() && Options.DeadImpCantSabotage.GetBool()) return false; - if (!player.Is(Team.Impostor) && !player.IsAlive()) - { - return false; - } + if (!player.Is(Team.Impostor) && !player.IsAlive()) return false; return player.GetCustomRole() switch { @@ -263,10 +207,8 @@ namespace EHR MapNames.Airship => Options.DisableAirshipCamera.GetBool(), _ => false }; - if (camerasDisabled) - { - player.Notify(Translator.GetString("CamerasDisabledNotify"), 15f); - } + + if (camerasDisabled) player.Notify(Translator.GetString("CamerasDisabledNotify"), 15f); return !camerasDisabled; } @@ -279,10 +221,7 @@ namespace EHR switch (systemType) { case SystemTypes.Comms: - if (!Camouflage.CheckCamouflage()) - { - Utils.NotifyRoles(); - } + if (!Camouflage.CheckCamouflage()) Utils.NotifyRoles(); goto case SystemTypes.Electrical; case SystemTypes.Reactor: @@ -291,20 +230,11 @@ namespace EHR case SystemTypes.HeliSabotage: case SystemTypes.Electrical: { - if (player.Is(CustomRoles.Damocles) && Damocles.CountRepairSabotage) - { - Damocles.OnRepairSabotage(player.PlayerId); - } + if (player.Is(CustomRoles.Damocles) && Damocles.CountRepairSabotage) Damocles.OnRepairSabotage(player.PlayerId); - if (player.Is(CustomRoles.Stressed) && Stressed.CountRepairSabotage) - { - Stressed.OnRepairSabotage(player); - } + if (player.Is(CustomRoles.Stressed) && Stressed.CountRepairSabotage) Stressed.OnRepairSabotage(player); - if (Main.PlayerStates[player.PlayerId].Role is Rogue rg) - { - rg.OnFixSabotage(); - } + if (Main.PlayerStates[player.PlayerId].Role is Rogue rg) rg.OnFixSabotage(); break; } @@ -314,25 +244,16 @@ namespace EHR public static void CheckAndOpenDoorsRange(ShipStatus __instance, int amount, int min, int max) { List Ids = new(); - for (int i = min; i <= max; i++) - { - Ids.Add(i); - } + for (int i = min; i <= max; i++) Ids.Add(i); CheckAndOpenDoors(__instance, amount, [.. Ids]); } private static void CheckAndOpenDoors(ShipStatus __instance, int amount, params int[] DoorIds) { - if (!DoorIds.Contains(amount)) - { - return; - } + if (!DoorIds.Contains(amount)) return; - foreach (int id in DoorIds) - { - __instance.RpcUpdateSystem(SystemTypes.Doors, (byte)id); - } + foreach (int id in DoorIds) __instance.RpcUpdateSystem(SystemTypes.Doors, (byte)id); } } @@ -343,15 +264,9 @@ namespace EHR { bool allow = !Options.DisableSabotage.GetBool() && Options.CurrentGameMode is not CustomGameMode.SoloKombat and not CustomGameMode.FFA and not CustomGameMode.MoveAndStop and not CustomGameMode.HotPotato and not CustomGameMode.Speedrun and not CustomGameMode.CaptureTheFlag and not CustomGameMode.NaturalDisasters and not CustomGameMode.RoomRush; - if (SecurityGuard.BlockSabo.Count > 0) - { - allow = false; - } + if (SecurityGuard.BlockSabo.Count > 0) allow = false; - if (Options.DisableCloseDoor.GetBool()) - { - allow = false; - } + if (Options.DisableCloseDoor.GetBool()) allow = false; Logger.Info($"({room}) => {(allow ? "Allowed" : "Blocked")}", "DoorClose"); return allow; @@ -369,10 +284,7 @@ namespace EHR if (Options.AllowConsole.GetBool()) { - if (!ConsoleManager.ConsoleActive && ConsoleManager.ConsoleEnabled) - { - ConsoleManager.CreateConsole(); - } + if (!ConsoleManager.ConsoleActive && ConsoleManager.ConsoleEnabled) ConsoleManager.CreateConsole(); } else { @@ -441,10 +353,7 @@ namespace EHR { if (RolesIsAssigned && !Main.IntroDestroyed) { - foreach (PlayerControl player in Main.AllPlayerControls) - { - Main.PlayerStates[player.PlayerId].InitTask(player); - } + foreach (PlayerControl player in Main.AllPlayerControls) Main.PlayerStates[player.PlayerId].InitTask(player); GameData.Instance.RecomputeTaskCounts(); TaskState.InitialTotalTasks = GameData.Instance.TotalTasks; @@ -463,16 +372,10 @@ namespace EHR // it's better to manually teleport them public static bool Prefix(ShipStatus __instance, PlayerControl player, int numPlayers, bool initialSpawn) { - if (!AmongUsClient.Instance.AmHost || initialSpawn || !player.IsAlive()) - { - return true; - } + if (!AmongUsClient.Instance.AmHost || initialSpawn || !player.IsAlive()) return true; // Lazy doesn't teleport to the meeting table - if (player.Is(CustomRoles.Lazy)) - { - return false; - } + if (player.Is(CustomRoles.Lazy)) return false; Vector2 direction = Vector2.up.Rotate((player.PlayerId - 1) * (360f / numPlayers)); Vector2 position = __instance.MeetingSpawnCenter + (direction * __instance.SpawnRadius) + new Vector2(0.0f, 0.3636f); @@ -491,16 +394,10 @@ namespace EHR [HarmonyArgument(1)] int numPlayers, [HarmonyArgument(2)] bool initialSpawn) { - if (!AmongUsClient.Instance.AmHost || initialSpawn || !player.IsAlive()) - { - return true; - } + if (!AmongUsClient.Instance.AmHost || initialSpawn || !player.IsAlive()) return true; // Lazy doesn't teleport to the meeting table - if (player.Is(CustomRoles.Lazy)) - { - return false; - } + if (player.Is(CustomRoles.Lazy)) return false; int num1 = Mathf.FloorToInt(numPlayers / 2f); int num2 = player.PlayerId % 15; @@ -521,15 +418,9 @@ namespace EHR { public static bool Prefix(VentilationSystem __instance, [HarmonyArgument(0)] byte playerId, [HarmonyArgument(1)] VentilationSystem.Operation op, [HarmonyArgument(2)] byte ventId, [HarmonyArgument(3)] SequenceBuffer seqBuffer) { - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; - if (Utils.GetPlayerById(playerId) == null) - { - return true; - } + if (Utils.GetPlayerById(playerId) == null) return true; switch (op) { @@ -552,18 +443,12 @@ namespace EHR { public static void Prefix(ShipStatus __instance, [HarmonyArgument(1)] bool initialState) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; - if (initialState) - { - return; - } + if (initialState) return; bool cancel = Main.AllPlayerControls.Any(VentilationSystemDeterioratePatch.BlockVentInteraction); - VentilationSystem ventilationSystem = __instance.Systems[SystemTypes.Ventilation].Cast(); + var ventilationSystem = __instance.Systems[SystemTypes.Ventilation].Cast(); if (cancel && ventilationSystem is { IsDirty: true }) { @@ -583,34 +468,22 @@ namespace EHR public static void Postfix(VentilationSystem __instance) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; - if (!GameStates.InGame) - { - return; - } + if (!GameStates.InGame) return; foreach (PlayerControl pc in Main.AllPlayerControls) { if (BlockVentInteraction(pc)) { - int players = 0; + var players = 0; + foreach (NetworkedPlayerInfo playerInfo in GameData.Instance.AllPlayers) - { if (playerInfo != null && !playerInfo.Disconnected) - { ++players; - } - } int closestVentId = pc.GetClosestVent().Id; - if (closestVentId == LastClosestVent[pc.PlayerId] && players >= 3) - { - continue; - } + if (closestVentId == LastClosestVent[pc.PlayerId] && players >= 3) continue; LastClosestVent[pc.PlayerId] = closestVentId; MessageWriter writer = MessageWriter.Get(); @@ -622,17 +495,15 @@ namespace EHR writer.StartMessage((byte)SystemTypes.Ventilation); int vents = ShipStatus.Instance.AllVents.Count(vent => !pc.CanUseVent(vent.Id)); List AllPlayers = []; + foreach (NetworkedPlayerInfo playerInfo in GameData.Instance.AllPlayers) - { if (playerInfo != null && !playerInfo.Disconnected) - { AllPlayers.Add(playerInfo); - } - } int maxVents = Math.Min(vents, AllPlayers.Count); - int blockedVents = 0; + var blockedVents = 0; writer.WritePacked(maxVents); + foreach (Vent vent in pc.GetVentsFromClosest()) { if (!pc.CanUseVent(vent.Id)) @@ -642,13 +513,11 @@ namespace EHR ++blockedVents; } - if (blockedVents >= maxVents) - { - break; - } + if (blockedVents >= maxVents) break; } writer.WritePacked(__instance.PlayersInsideVents.Count); + foreach (Il2CppSystem.Collections.Generic.KeyValuePair keyValuePair2 in __instance.PlayersInsideVents) { writer.Write(keyValuePair2.Key); @@ -673,15 +542,9 @@ namespace EHR { foreach (PlayerControl pc in Main.AllPlayerControls) { - if (pc.AmOwner) - { - continue; - } + if (pc.AmOwner) continue; - if (player != null && pc != player) - { - continue; - } + if (player != null && pc != player) continue; if (BlockVentInteraction(pc)) { @@ -694,17 +557,15 @@ namespace EHR writer.StartMessage((byte)SystemTypes.Ventilation); int vents = ShipStatus.Instance.AllVents.Count(vent => !pc.CanUseVent(vent.Id)); List AllPlayers = []; + foreach (NetworkedPlayerInfo playerInfo in GameData.Instance.AllPlayers) - { if (playerInfo != null && !playerInfo.Disconnected) - { AllPlayers.Add(playerInfo); - } - } int maxVents = Math.Min(vents, AllPlayers.Count); - int blockedVents = 0; + var blockedVents = 0; writer.WritePacked(maxVents); + foreach (Vent vent in pc.GetVentsFromClosest()) { if (!pc.CanUseVent(vent.Id)) @@ -714,13 +575,11 @@ namespace EHR ++blockedVents; } - if (blockedVents >= maxVents) - { - break; - } + if (blockedVents >= maxVents) break; } writer.WritePacked(__instance.PlayersInsideVents.Count); + foreach (Il2CppSystem.Collections.Generic.KeyValuePair keyValuePair2 in __instance.PlayersInsideVents) { writer.Write(keyValuePair2.Key); @@ -754,10 +613,7 @@ namespace EHR public static void CheckVentInteraction(PlayerControl pc) { - if (!GameStates.IsInTask || ExileController.Instance || !ShipStatus.Instance) - { - return; - } + if (!GameStates.IsInTask || ExileController.Instance || !ShipStatus.Instance) return; const int bufferTimeWait = 10; @@ -777,6 +633,7 @@ namespace EHR int closestVent = pc.GetClosestVent().Id; + if (!LastClosestVentForUpdate.TryGetValue(pc.PlayerId, out int lastClosestVent)) { LastClosestVentForUpdate[pc.PlayerId] = closestVent; @@ -805,10 +662,7 @@ namespace EHR // Patch block use vent for host becouse host always skips RpcSerializeVent public static bool Prefix([HarmonyArgument(0)] int id, ref bool __result) { - if (!AmongUsClient.Instance.AmHost) - { - return true; - } + if (!AmongUsClient.Instance.AmHost) return true; if (!PlayerControl.LocalPlayer.CanUseVent(id)) { diff --git a/Patches/TaskAdderPatch.cs b/Patches/TaskAdderPatch.cs index 89091992a..99928dee0 100644 --- a/Patches/TaskAdderPatch.cs +++ b/Patches/TaskAdderPatch.cs @@ -18,6 +18,7 @@ namespace EHR __instance.RootFolderPrefab, __instance.transform ); + rolesFolder.gameObject.SetActive(false); rolesFolder.FolderName = Main.ModName; CustomRolesFolder = rolesFolder; @@ -28,21 +29,25 @@ namespace EHR public static void Postfix(TaskAdderGame __instance, [HarmonyArgument(0)] TaskFolder taskFolder) { Logger.Info("Opened " + taskFolder.FolderName, "TaskFolder"); - float xCursor = 0f; - float yCursor = 0f; - float maxHeight = 0f; + var xCursor = 0f; + var yCursor = 0f; + var maxHeight = 0f; + if (CustomRolesFolder != null && CustomRolesFolder.FolderName == taskFolder.FolderName) { CustomRoles[] list = Enum.GetValues(); + foreach (CustomRoles cRoleID in list) { TaskAddButton button = Object.Instantiate(__instance.RoleButton); button.Text.text = Utils.GetRoleName(cRoleID); __instance.AddFileAsChild(CustomRolesFolder, button, ref xCursor, ref yCursor, ref maxHeight); - RoleBehaviour roleBehaviour = new RoleBehaviour + + var roleBehaviour = new RoleBehaviour { Role = (RoleTypes)cRoleID + 1000 }; + button.Role = roleBehaviour; Color roleColor = Utils.GetRoleColor(cRoleID); @@ -69,9 +74,7 @@ namespace EHR __instance.Overlay.enabled = PlayerCustomRole == FileCustomRole; } } - catch - { - } + catch { } return true; } @@ -92,9 +95,7 @@ namespace EHR return false; } } - catch - { - } + catch { } return true; } diff --git a/Patches/TaskAssignPatch.cs b/Patches/TaskAssignPatch.cs index 7c7fcf112..b8b8da2ed 100644 --- a/Patches/TaskAssignPatch.cs +++ b/Patches/TaskAssignPatch.cs @@ -18,10 +18,7 @@ namespace EHR public static void Prefix( /*ShipStatus __instance,*/ [HarmonyArgument(4)] Il2CppSystem.Collections.Generic.List unusedTasks) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; if (DisableTasksSettings.Count == 0) { @@ -103,19 +100,13 @@ namespace EHR }; } - if (!Options.DisableShortTasks.GetBool() && !Options.DisableCommonTasks.GetBool() && !Options.DisableLongTasks.GetBool() && !Options.DisableOtherTasks.GetBool()) - { - return; - } + if (!Options.DisableShortTasks.GetBool() && !Options.DisableCommonTasks.GetBool() && !Options.DisableLongTasks.GetBool() && !Options.DisableOtherTasks.GetBool()) return; List disabledTasks = []; + foreach (NormalPlayerTask task in unusedTasks) - { if (DisableTasksSettings.TryGetValue(task.TaskType, out OptionItem setting) && setting.GetBool()) - { disabledTasks.Add(task); - } - } foreach (NormalPlayerTask task in disabledTasks) { @@ -140,15 +131,12 @@ namespace EHR } PlayerControl pc = __instance.Object; - if (pc == null) - { - return; - } + if (pc == null) return; CustomRoles role = GhostRolesManager.AssignedGhostRoles.TryGetValue(pc.PlayerId, out (CustomRoles Role, IGhostRole Instance) gr) && gr.Instance is Specter or Haunter ? gr.Role : pc.GetCustomRole(); // Default number of tasks - bool hasCommonTasks = true; + var hasCommonTasks = true; int NumLongTasks = Main.NormalOptions.NumLongTasks; int NumShortTasks = Main.NormalOptions.NumShortTasks; @@ -159,10 +147,7 @@ namespace EHR NumLongTasks = data.NumLongTasks.GetInt(); // Number of long tasks to allocate NumShortTasks = data.NumShortTasks.GetInt(); // Number of short tasks to allocate // Longs and shorts are constantly reallocated. - if (role is CustomRoles.Specter or CustomRoles.Haunter) - { - Main.PlayerStates[pc.PlayerId].TaskState.AllTasksCount = NumLongTasks + NumShortTasks; - } + if (role is CustomRoles.Specter or CustomRoles.Haunter) Main.PlayerStates[pc.PlayerId].TaskState.AllTasksCount = NumLongTasks + NumShortTasks; } if (pc.Is(CustomRoles.Busy)) @@ -188,10 +173,7 @@ namespace EHR } // Workhorse task assignment - if (pc.Is(CustomRoles.Workhorse)) - { - (hasCommonTasks, NumLongTasks, NumShortTasks) = Workhorse.TaskData; - } + if (pc.Is(CustomRoles.Workhorse)) (hasCommonTasks, NumLongTasks, NumShortTasks) = Workhorse.TaskData; // Capitalism is going to harm people~ if (Capitalism.CapitalismAssignTask.ContainsKey(pc.PlayerId)) @@ -200,10 +182,7 @@ namespace EHR Capitalism.CapitalismAssignTask.Remove(pc.PlayerId); } - if (taskTypeIds.Length == 0) - { - hasCommonTasks = false; // Set common to 0 when redistributing tasks - } + if (taskTypeIds.Length == 0) hasCommonTasks = false; // Set common to 0 when redistributing tasks switch (hasCommonTasks) { @@ -217,46 +196,34 @@ namespace EHR // List containing IDs of assignable tasks // Clone of the second argument of the original RpcSetTasks Il2CppSystem.Collections.Generic.List TasksList = new(); - foreach (byte num in taskTypeIds) - { - TasksList.Add(num); - } + foreach (byte num in taskTypeIds) TasksList.Add(num); // Reference: ShipStatus.Begin // Processing to delete unnecessary assigned tasks // If the setting is to assign common tasks, delete all other than common tasks // Empty the list if no common tasks are assigned int defaultCommonTasksNum = Main.RealOptionsData.GetInt(Int32OptionNames.NumCommonTasks); + if (hasCommonTasks) - { TasksList.RemoveRange(defaultCommonTasksNum, TasksList.Count - defaultCommonTasksNum); - } else - { TasksList.Clear(); - } // HashSet where assigned tasks will be placed // Prevent multiple assignments of the same task Il2CppSystem.Collections.Generic.HashSet usedTaskTypes = new(); - int start2 = 0; - int start3 = 0; + var start2 = 0; + var start3 = 0; // List of assignable long tasks Il2CppSystem.Collections.Generic.List LongTasks = new(); - foreach (NormalPlayerTask task in ShipStatus.Instance.LongTasks) - { - LongTasks.Add(task); - } + foreach (NormalPlayerTask task in ShipStatus.Instance.LongTasks) LongTasks.Add(task); Shuffle(LongTasks); // List of assignable short tasks Il2CppSystem.Collections.Generic.List ShortTasks = new(); - foreach (NormalPlayerTask task in ShipStatus.Instance.ShortTasks) - { - ShortTasks.Add(task); - } + foreach (NormalPlayerTask task in ShipStatus.Instance.ShortTasks) ShortTasks.Add(task); Shuffle(ShortTasks); @@ -268,6 +235,7 @@ namespace EHR usedTaskTypes, LongTasks ); + ShipStatus.Instance.AddTasksFromList( ref start3, NumShortTasks, @@ -278,15 +246,12 @@ namespace EHR // Convert list of tasks to array (Il2CppStructArray) taskTypeIds = new(TasksList.Count); - for (int i = 0; i < TasksList.Count; i++) - { - taskTypeIds[i] = TasksList[i]; - } + for (var i = 0; i < TasksList.Count; i++) taskTypeIds[i] = TasksList[i]; } private static void Shuffle(Il2CppSystem.Collections.Generic.List list) { - for (int i = 0; i < list.Count - 1; i++) + for (var i = 0; i < list.Count - 1; i++) { T obj = list[i]; int rand = Random.Range(i, list.Count); diff --git a/Patches/TextBoxPatch.cs b/Patches/TextBoxPatch.cs index 7af015362..38af11f2f 100644 --- a/Patches/TextBoxPatch.cs +++ b/Patches/TextBoxPatch.cs @@ -19,18 +19,17 @@ namespace EHR.Patches { try { - bool flag = false; - char ch = ' '; + var flag = false; + var ch = ' '; __instance.AdjustCaretPosition(input.Length - __instance.text.Length); __instance.tempTxt.Clear(); foreach (char c in input) { char upperInvariant = c; + if (ch == ' ' && upperInvariant == ' ') - { __instance.AdjustCaretPosition(-1); - } else { switch (upperInvariant) @@ -45,10 +44,7 @@ namespace EHR.Patches break; } - if (__instance.ForceUppercase) - { - upperInvariant = char.ToUpperInvariant(upperInvariant); - } + if (__instance.ForceUppercase) upperInvariant = char.ToUpperInvariant(upperInvariant); if (upperInvariant is not '\r' and not '\n' and not '\b') { @@ -66,6 +62,7 @@ namespace EHR.Patches } input = __instance.tempTxt.ToString(); + if (!input.Equals(__instance.text) || !inputCompo.Equals(__instance.compoText)) { __instance.text = input; @@ -76,26 +73,17 @@ namespace EHR.Patches if (__instance.Hidden) { str = ""; - for (int index = 0; index < __instance.text.Length; ++index) - { - str += "*"; - } + for (var index = 0; index < __instance.text.Length; ++index) str += "*"; } __instance.outputText.text = str + compoText; __instance.outputText.ForceMeshUpdate(true, true); - if (__instance.keyboard != null) - { - __instance.keyboard.text = __instance.text; - } + if (__instance.keyboard != null) __instance.keyboard.text = __instance.text; __instance.OnChange.Invoke(); } - if (flag) - { - __instance.OnEnter.Invoke(); - } + if (flag) __instance.OnEnter.Invoke(); __instance.SetPipePosition(); } @@ -118,6 +106,7 @@ namespace EHR.Patches } string input = __instance.outputText.text.Trim().Replace("\b", ""); + if (!input.StartsWith('/') || input.Length < 2) { Destroy(); @@ -128,22 +117,17 @@ namespace EHR.Patches Command command = null; double highestMatchRate = 0; string inputCheck = input.Split(' ')[0]; - bool exactMatch = false; + var exactMatch = false; bool english = TranslationController.Instance.currentLanguage.languageID == SupportedLangs.English; + foreach (Command cmd in ChatCommands.AllCommands) { foreach (string form in cmd.CommandForms) { - if (english && !form.All(char.IsAscii)) - { - continue; - } + if (english && !form.All(char.IsAscii)) continue; string check = "/" + form; - if (check.Length < inputCheck.Length) - { - continue; - } + if (check.Length < inputCheck.Length) continue; if (check == inputCheck) { @@ -153,25 +137,20 @@ namespace EHR.Patches break; } - int matchNum = 0; - for (int i = 0; i < inputCheck.Length; i++) + var matchNum = 0; + + for (var i = 0; i < inputCheck.Length; i++) { - if (i >= check.Length) - { - break; - } + if (i >= check.Length) break; if (inputCheck[i].Equals(check[i])) - { matchNum++; - } else - { break; - } } double matchRate = (double)matchNum / inputCheck.Length; + if (matchRate > highestMatchRate) { highestMatchRate = matchRate; @@ -179,10 +158,7 @@ namespace EHR.Patches } } - if (exactMatch) - { - break; - } + if (exactMatch) break; } if (command == null || highestMatchRate < 1) @@ -222,35 +198,28 @@ namespace EHR.Patches string inputForm = input.TrimStart('/'); string text = "/" + (exactMatch ? inputForm : command.CommandForms.Where(x => x.All(char.IsAscii) && x.StartsWith(inputForm)).MaxBy(x => x.Length)); - string info = $"{command.Description}"; + var info = $"{command.Description}"; if (exactMatch && command.Arguments.Length > 0) { bool poll = command.CommandForms.Contains("poll"); bool say = command.CommandForms.Contains("say"); int spaces = poll ? input.SkipWhile(x => x != '?').Count(x => x == ' ') + 1 : input.Count(x => x == ' '); - if (say) - { - spaces = Math.Min(spaces, 1); - } + if (say) spaces = Math.Min(spaces, 1); - string preText = $"{text} {command.Arguments}"; - if (!poll) - { - text += " " + command.Arguments.Split(' ').Skip(spaces).Join(delimiter: " "); - } + var preText = $"{text} {command.Arguments}"; + if (!poll) text += " " + command.Arguments.Split(' ').Skip(spaces).Join(delimiter: " "); string[] args = preText.Split(' ')[1..]; - for (int i = 0; i < args.Length; i++) + + for (var i = 0; i < args.Length; i++) { - if (command.ArgsDescriptions.Length <= i) - { - break; - } + if (command.ArgsDescriptions.Length <= i) break; int skip = poll ? input.TakeWhile(x => x != '?').Count(x => x == ' ') - 1 : 0; string arg = poll ? i == 0 ? args[..++skip].Join(delimiter: " ") : args[spaces - 1 < i ? skip + i + spaces : skip + i] : args[spaces > i ? i : i + spaces]; bool current = spaces - 1 == i, invalid = IsInvalidArg(), valid = IsValidArg(); + info += "\n" + (invalid, current, valid) switch { (true, true, false) => "<#ffa500>\u27a1 ", @@ -260,11 +229,9 @@ namespace EHR.Patches (false, true, false) => "<#ffff44>\u27a1 ", _ => " " }; + info += $" - {arg}{GetExtraArgInfo()}: {command.ArgsDescriptions[i]}"; - if (current || invalid || valid) - { - info += ""; - } + if (current || invalid || valid) info += ""; continue; @@ -325,24 +292,15 @@ namespace EHR.Patches void Destroy() { - if (PlaceHolderText != null) - { - PlaceHolderText.enabled = false; - } + if (PlaceHolderText != null) PlaceHolderText.enabled = false; - if (CommandInfoText != null) - { - CommandInfoText.enabled = false; - } + if (CommandInfoText != null) CommandInfoText.enabled = false; } } public static void OnTabPress(ChatController __instance) { - if (PlaceHolderText == null || PlaceHolderText.text == "") - { - return; - } + if (PlaceHolderText == null || PlaceHolderText.text == "") return; __instance.freeChatField.textArea.SetText(PlaceHolderText.text); __instance.freeChatField.textArea.compoText = ""; @@ -356,9 +314,7 @@ namespace EHR.Patches PlaceHolderText?.gameObject.SetActive(open); CommandInfoText?.gameObject.SetActive(open); } - catch - { - } + catch { } } } diff --git a/Patches/UsablesPatch.cs b/Patches/UsablesPatch.cs index 86d8acd93..5e30feb7e 100644 --- a/Patches/UsablesPatch.cs +++ b/Patches/UsablesPatch.cs @@ -11,25 +11,16 @@ namespace EHR { canUse = couldUse = false; // Even if you return this with false, usable items other than tasks will remain usable (buttons, etc.) - if (Main.GM.Value && AmongUsClient.Instance.AmHost && GameStates.InGame) - { - return false; - } + if (Main.GM.Value && AmongUsClient.Instance.AmHost && GameStates.InGame) return false; PlayerControl lp = PlayerControl.LocalPlayer; return __instance.AllowImpostor || (Utils.HasTasks(lp.Data, false) && (!lp.Is(CustomRoles.Wizard) || HasTasksAsWizard())); bool HasTasksAsWizard() { - if (lp.GetTaskState().IsTaskFinished) - { - return false; - } + if (lp.GetTaskState().IsTaskFinished) return false; - if (!lp.IsAlive()) - { - return true; - } + if (!lp.IsAlive()) return true; return lp.GetAbilityUseLimit() < 1f; } @@ -41,10 +32,7 @@ namespace EHR { public static void Postfix(EmergencyMinigame __instance) { - if (Options.DisableMeeting.GetBool() || Options.CurrentGameMode != CustomGameMode.Standard) - { - __instance.Close(); - } + if (Options.DisableMeeting.GetBool() || Options.CurrentGameMode != CustomGameMode.Standard) __instance.Close(); } } @@ -67,17 +55,14 @@ namespace EHR canUse = couldUse; // Not available if custom roles are not available - if (!canUse) - { - return false; - } + if (!canUse) return false; // Mod's own processing up to this point // Replace vanilla processing from here - IUsable usableVent = __instance.Cast(); + var usableVent = __instance.Cast(); // Distance between vent and player - float actualDistance = float.MaxValue; + var actualDistance = float.MaxValue; couldUse = // true for classic and for vanilla HnS @@ -91,15 +76,13 @@ namespace EHR // Check vent cleaning if (ShipStatus.Instance.Systems.TryGetValue(SystemTypes.Ventilation, out ISystemType systemType)) { - VentilationSystem ventilationSystem = systemType.TryCast(); + var ventilationSystem = systemType.TryCast(); // If someone is cleaning a vent, you can't get into that vent - if (ventilationSystem != null && ventilationSystem.IsVentCurrentlyBeingCleaned(__instance.Id)) - { - couldUse = false; - } + if (ventilationSystem != null && ventilationSystem.IsVentCurrentlyBeingCleaned(__instance.Id)) couldUse = false; } canUse = couldUse; + if (canUse) { Vector3 center = playerControl.Collider.bounds.center; @@ -118,10 +101,7 @@ namespace EHR { public static bool Prefix(ref bool __result) { - if (RunLoginPatch.ClickCount < 20) - { - return true; - } + if (RunLoginPatch.ClickCount < 20) return true; // __result = true; // return false; } diff --git a/Roles/AddOns/Common/Allergic.cs b/Roles/AddOns/Common/Allergic.cs index 6d9fedcf1..db05e3c0c 100644 --- a/Roles/AddOns/Common/Allergic.cs +++ b/Roles/AddOns/Common/Allergic.cs @@ -17,9 +17,11 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { Options.SetupAdtRoleOptions(645941, CustomRoles.Allergic, canSetNum: true, teamSpawnOptions: true); + Time = new IntegerOptionItem(645948, "Allergic.Time", new(0, 60, 1), 15, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Allergic]) .SetValueFormat(OptionFormat.Seconds); + Range = new FloatOptionItem(645949, "Allergic.Range", new(0.1f, 10f, 0.1f), 1.5f, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Allergic]) .SetValueFormat(OptionFormat.Multiplier); @@ -33,6 +35,7 @@ namespace EHR.AddOns.Common LateTask.New(() => { PlayerControl[] aapc = Main.AllAlivePlayerControls; + foreach (PlayerControl pc in aapc) { if (pc.Is(CustomRoles.Allergic)) @@ -46,17 +49,12 @@ namespace EHR.AddOns.Common public static void OnFixedUpdate(PlayerControl pc) { - if (Main.HasJustStarted || ExileController.Instance) - { - return; - } + if (Main.HasJustStarted || ExileController.Instance) return; - if (!AllergicPlayers.TryGetValue(pc.PlayerId, out byte targetId)) - { - return; - } + if (!AllergicPlayers.TryGetValue(pc.PlayerId, out byte targetId)) return; PlayerControl target = targetId.GetPlayer(); + if (target == null || !target.IsAlive() || Vector2.Distance(pc.Pos(), target.Pos()) > Range.GetFloat()) { if (AllergyMaxTS.Remove(pc.PlayerId)) @@ -83,9 +81,7 @@ namespace EHR.AddOns.Common pc.Suicide(PlayerState.DeathReason.Allergy); } else - { Utils.NotifyRoles(SpecifyTarget: pc, SpecifySeer: pc); - } } public static void ReceiveRPC(MessageReader reader) @@ -103,10 +99,7 @@ namespace EHR.AddOns.Common public static string GetSelfSuffix(PlayerControl seer) { - if (!seer.IsAlive() || !AllergyMaxTS.TryGetValue(seer.PlayerId, out long endTS)) - { - return string.Empty; - } + if (!seer.IsAlive() || !AllergyMaxTS.TryGetValue(seer.PlayerId, out long endTS)) return string.Empty; return string.Format(Translator.GetString("Allergic.Suffix"), Math.Ceiling(endTS / (float)Utils.TimeStamp * 100)); } diff --git a/Roles/AddOns/Common/Antidote.cs b/Roles/AddOns/Common/Antidote.cs index b03b17b71..e1dd1c72b 100644 --- a/Roles/AddOns/Common/Antidote.cs +++ b/Roles/AddOns/Common/Antidote.cs @@ -10,9 +10,11 @@ namespace EHR.AddOns.Common { const int id = 648500; SetupAdtRoleOptions(id, CustomRoles.Antidote, canSetNum: true, teamSpawnOptions: true); + AntidoteCDOpt = new FloatOptionItem(id + 8, "AntidoteCDOpt", new(0f, 180f, 1f), 5f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Antidote]) .SetValueFormat(OptionFormat.Seconds); + AntidoteCDReset = new BooleanOptionItem(id + 7, "AntidoteCDReset", true, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Antidote]); } diff --git a/Roles/AddOns/Common/Asthmatic.cs b/Roles/AddOns/Common/Asthmatic.cs index 48f2360bd..df47ee4a5 100644 --- a/Roles/AddOns/Common/Asthmatic.cs +++ b/Roles/AddOns/Common/Asthmatic.cs @@ -21,15 +21,19 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(15419, CustomRoles.Asthmatic, canSetNum: true, teamSpawnOptions: true); + AsthmaticMinRedTime = new IntegerOptionItem(15426, "AsthmaticMinRedTime", new(1, 90, 1), 5, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Asthmatic]) .SetValueFormat(OptionFormat.Seconds); + AsthmaticMaxRedTime = new IntegerOptionItem(15427, "AsthmaticMaxRedTime", new(1, 90, 1), 15, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Asthmatic]) .SetValueFormat(OptionFormat.Seconds); + AsthmaticMinGreenTime = new IntegerOptionItem(15428, "AsthmaticMinGreenTime", new(1, 90, 1), 5, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Asthmatic]) .SetValueFormat(OptionFormat.Seconds); + AsthmaticMaxGreenTime = new IntegerOptionItem(15429, "AsthmaticMaxGreenTime", new(1, 90, 1), 30, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Asthmatic]) .SetValueFormat(OptionFormat.Seconds); @@ -61,15 +65,12 @@ namespace EHR.AddOns.Common { LateTask.New(() => { - IRandom r = IRandom.Instance; + var r = IRandom.Instance; long now = Utils.TimeStamp; + foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { if (pc.Is(CustomRoles.Asthmatic)) - { Timers[pc.PlayerId] = new(30, r.Next(MinRedTime, MaxRedTime), now, '●', false, moveAndStop: false); - } - } }, 8f, "Add Asthmatic Timers"); } @@ -78,6 +79,7 @@ namespace EHR.AddOns.Common foreach (KeyValuePair kvp in Timers.ToArray()) { PlayerState state = Main.PlayerStates[kvp.Key]; + if (state.IsDead || !state.SubRoles.Contains(CustomRoles.Asthmatic)) { state.RemoveSubRole(CustomRoles.Asthmatic); @@ -93,10 +95,7 @@ namespace EHR.AddOns.Common public static void OnCheckPlayerPosition(PlayerControl pc) { - if (!pc.Is(CustomRoles.Asthmatic) || ExileController.Instance || !RunChecks || !Timers.TryGetValue(pc.PlayerId, out Counter counter)) - { - return; - } + if (!pc.Is(CustomRoles.Asthmatic) || ExileController.Instance || !RunChecks || !Timers.TryGetValue(pc.PlayerId, out Counter counter)) return; Vector2 currentPosition = pc.transform.position; @@ -137,10 +136,7 @@ namespace EHR.AddOns.Common string suffix = GetSuffixText(pc.PlayerId); - if (!pc.IsModClient() && (!LastSuffix.TryGetValue(pc.PlayerId, out string beforeSuffix) || beforeSuffix != suffix)) - { - Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - } + if (!pc.IsModClient() && (!LastSuffix.TryGetValue(pc.PlayerId, out string beforeSuffix) || beforeSuffix != suffix)) Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); LastSuffix[pc.PlayerId] = suffix; } diff --git a/Roles/AddOns/Common/Bait.cs b/Roles/AddOns/Common/Bait.cs index 3aa81470e..d1fc212c4 100644 --- a/Roles/AddOns/Common/Bait.cs +++ b/Roles/AddOns/Common/Bait.cs @@ -9,16 +9,21 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(13700, CustomRoles.Bait, canSetNum: true, teamSpawnOptions: true); + BaitDelayMin = new FloatOptionItem(13713, "BaitDelayMin", new(0f, 90f, 1f), 0f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Bait]) .SetValueFormat(OptionFormat.Seconds); + BaitDelayMax = new FloatOptionItem(13714, "BaitDelayMax", new(0f, 90f, 1f), 0f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Bait]) .SetValueFormat(OptionFormat.Seconds); + BaitDelayNotify = new BooleanOptionItem(13715, "BaitDelayNotify", true, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Bait]); + BaitNotification = new BooleanOptionItem(13716, "BaitNotification", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Bait]); + ReportBaitAtAllCost = new BooleanOptionItem(13717, "ReportBaitAtAllCost", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Bait]); } diff --git a/Roles/AddOns/Common/Bewilder.cs b/Roles/AddOns/Common/Bewilder.cs index a48691d31..eb6e6f487 100644 --- a/Roles/AddOns/Common/Bewilder.cs +++ b/Roles/AddOns/Common/Bewilder.cs @@ -9,6 +9,7 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(15200, CustomRoles.Bewilder, canSetNum: true, teamSpawnOptions: true); + BewilderVision = new FloatOptionItem(15210, "BewilderVision", new(0f, 5f, 0.05f), 0.6f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Bewilder]) .SetValueFormat(OptionFormat.Multiplier); diff --git a/Roles/AddOns/Common/Busy.cs b/Roles/AddOns/Common/Busy.cs index 9cd5e2501..6356285ee 100644 --- a/Roles/AddOns/Common/Busy.cs +++ b/Roles/AddOns/Common/Busy.cs @@ -9,8 +9,10 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(15290, CustomRoles.Busy, canSetNum: true, teamSpawnOptions: true); + BusyLongTasks = new IntegerOptionItem(15298, "BusyLongTasks", new(0, 90, 1), 1, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Busy]); + BusyShortTasks = new IntegerOptionItem(15297, "BusyShortTasks", new(0, 90, 1), 1, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Busy]); } diff --git a/Roles/AddOns/Common/Clumsy.cs b/Roles/AddOns/Common/Clumsy.cs index e51f9ec6f..779fcab8d 100644 --- a/Roles/AddOns/Common/Clumsy.cs +++ b/Roles/AddOns/Common/Clumsy.cs @@ -17,6 +17,7 @@ float speed = Main.AllPlayerSpeed[pc.PlayerId]; Main.AllPlayerSpeed[pc.PlayerId] = Main.MinSpeed; pc.MarkDirtySettings(); + LateTask.New(() => { Main.AllPlayerSpeed[pc.PlayerId] = speed; diff --git a/Roles/AddOns/Common/Deadlined.cs b/Roles/AddOns/Common/Deadlined.cs index 0590c73f5..e22007b1e 100644 --- a/Roles/AddOns/Common/Deadlined.cs +++ b/Roles/AddOns/Common/Deadlined.cs @@ -12,6 +12,7 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { Options.SetupAdtRoleOptions(649292, CustomRoles.Deadlined, canSetNum: true, teamSpawnOptions: true); + InactiveTime = new IntegerOptionItem(649299, "Deadlined.InactiveTime", new(0, 60, 1), 15, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Deadlined]) .SetValueFormat(OptionFormat.Seconds); @@ -31,52 +32,32 @@ namespace EHR.AddOns.Common foreach (PlayerControl pc in Main.AllPlayerControls) { TaskState ts = pc.GetTaskState(); - if (pc.Is(CustomRoles.Deadlined) && (!pc.IsAlive() || ts.IsTaskFinished || (!ts.HasTasks && !pc.CanUseKillButton()))) - { - Main.PlayerStates[pc.PlayerId].RemoveSubRole(CustomRoles.Deadlined); - } + if (pc.Is(CustomRoles.Deadlined) && (!pc.IsAlive() || ts.IsTaskFinished || (!ts.HasTasks && !pc.CanUseKillButton()))) Main.PlayerStates[pc.PlayerId].RemoveSubRole(CustomRoles.Deadlined); } } public static void OnMeetingStart() { - if (MeetingStates.FirstMeeting) - { - return; - } + if (MeetingStates.FirstMeeting) return; - if (MeetingEndTS + InactiveTime.GetInt() > Utils.TimeStamp) - { - return; - } + if (MeetingEndTS + InactiveTime.GetInt() > Utils.TimeStamp) return; foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (!pc.Is(CustomRoles.Deadlined)) - { - continue; - } + if (!pc.Is(CustomRoles.Deadlined)) continue; - if (!DidTask.Contains(pc.PlayerId)) - { - pc.Suicide(); - } + if (!DidTask.Contains(pc.PlayerId)) pc.Suicide(); } } public static string GetSuffix(PlayerControl seer, bool hud = false) { - if (!seer.Is(CustomRoles.Deadlined) || (seer.IsModClient() && !hud)) - { - return string.Empty; - } + if (!seer.Is(CustomRoles.Deadlined) || (seer.IsModClient() && !hud)) return string.Empty; - if (DidTask.Contains(seer.PlayerId) || MeetingStates.FirstMeeting) - { - return "<#00ff00>\u2713"; - } + if (DidTask.Contains(seer.PlayerId) || MeetingStates.FirstMeeting) return "<#00ff00>\u2713"; long now = Utils.TimeStamp; + return MeetingEndTS + InactiveTime.GetInt() <= now ? Translator.GetString("Deadlined.MustDoTask") : string.Format(Translator.GetString("Deadlined.SafeTime"), InactiveTime.GetInt() - (now - MeetingEndTS)); diff --git a/Roles/AddOns/Common/Disco.cs b/Roles/AddOns/Common/Disco.cs index 1235259f0..fa45263ab 100644 --- a/Roles/AddOns/Common/Disco.cs +++ b/Roles/AddOns/Common/Disco.cs @@ -12,6 +12,7 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(15430, CustomRoles.Disco, canSetNum: true, teamSpawnOptions: true); + DiscoChangeInterval = new IntegerOptionItem(15437, "DiscoChangeInterval", new(1, 90, 1), 5, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Disco]) .SetValueFormat(OptionFormat.Seconds); @@ -29,27 +30,23 @@ namespace EHR.AddOns.Common } catch { - CustomRpcSender sender = CustomRpcSender.Create($"Disco.ChangeColor({pc.Data.PlayerName})"); + var sender = CustomRpcSender.Create($"Disco.ChangeColor({pc.Data.PlayerName})"); + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetColor) .Write(pc.Data.NetId) .Write((byte)colorId) .EndRpc(); + sender.SendMessage(); } } public static void OnFixedUpdate(PlayerControl pc) { - if (!pc.Is(CustomRoles.Disco) || !GameStates.IsInTask || pc.IsShifted() || Camouflager.IsActive || (Utils.IsActive(SystemTypes.Comms) && CommsCamouflage.GetBool()) || pc.inVent || pc.MyPhysics.Animations.IsPlayingEnterVentAnimation() || pc.walkingToVent || pc.onLadder || pc.MyPhysics.Animations.IsPlayingAnyLadderAnimation() || pc.inMovingPlat) - { - return; - } + if (!pc.Is(CustomRoles.Disco) || !GameStates.IsInTask || pc.IsShifted() || Camouflager.IsActive || (Utils.IsActive(SystemTypes.Comms) && CommsCamouflage.GetBool()) || pc.inVent || pc.MyPhysics.Animations.IsPlayingEnterVentAnimation() || pc.walkingToVent || pc.onLadder || pc.MyPhysics.Animations.IsPlayingAnyLadderAnimation() || pc.inMovingPlat) return; long now = Utils.TimeStamp; - if (LastChange.TryGetValue(pc.PlayerId, out long change) && change + DiscoChangeInterval.GetInt() > now) - { - return; - } + if (LastChange.TryGetValue(pc.PlayerId, out long change) && change + DiscoChangeInterval.GetInt() > now) return; ChangeColor(pc); LastChange[pc.PlayerId] = now; diff --git a/Roles/AddOns/Common/Diseased.cs b/Roles/AddOns/Common/Diseased.cs index ceab6a1b2..459bd93ce 100644 --- a/Roles/AddOns/Common/Diseased.cs +++ b/Roles/AddOns/Common/Diseased.cs @@ -10,9 +10,11 @@ namespace EHR.AddOns.Common { const int id = 648600; SetupAdtRoleOptions(id, CustomRoles.Diseased, canSetNum: true, teamSpawnOptions: true); + DiseasedCDOpt = new FloatOptionItem(id + 8, "DiseasedCDOpt", new(0f, 180f, 1f), 25f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Diseased]) .SetValueFormat(OptionFormat.Seconds); + DiseasedCDReset = new BooleanOptionItem(id + 7, "DiseasedCDReset", true, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Diseased]); } diff --git a/Roles/AddOns/Common/DoubleShot.cs b/Roles/AddOns/Common/DoubleShot.cs index d87eaea43..77c4a4e0c 100644 --- a/Roles/AddOns/Common/DoubleShot.cs +++ b/Roles/AddOns/Common/DoubleShot.cs @@ -15,6 +15,7 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(13900, CustomRoles.DoubleShot, canSetNum: true, teamSpawnOptions: true); + MaxTries = new IntegerOptionItem(13907, "DoubleShot.MaxTries", new(1, 30, 1), 1, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.DoubleShot]) .SetValueFormat(OptionFormat.Times); @@ -27,10 +28,7 @@ namespace EHR.AddOns.Common public static bool CheckGuess(PlayerControl guesser, bool isUI) { - if (!guesser.Is(CustomRoles.DoubleShot)) - { - return false; - } + if (!guesser.Is(CustomRoles.DoubleShot)) return false; if (!Tries.TryGetValue(guesser.PlayerId, out int tries)) { @@ -54,13 +52,9 @@ namespace EHR.AddOns.Common Logger.Msg($"{guesser.PlayerId} : {tries}", "GuesserDoubleShotTries"); if (!isUI) - { Utils.SendMessage(Translator.GetString("GuessDoubleShot"), guesser.PlayerId); - } else - { guesser.ShowPopUp(Translator.GetString("GuessDoubleShot")); - } } } } diff --git a/Roles/AddOns/Common/DualPersonality.cs b/Roles/AddOns/Common/DualPersonality.cs index ecb4747b6..1dfd08a50 100644 --- a/Roles/AddOns/Common/DualPersonality.cs +++ b/Roles/AddOns/Common/DualPersonality.cs @@ -9,6 +9,7 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(14700, CustomRoles.DualPersonality, canSetNum: true, teamSpawnOptions: true); + DualVotes = new BooleanOptionItem(14712, "DualVotes", true, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.DualPersonality]); } diff --git a/Roles/AddOns/Common/Dynamo.cs b/Roles/AddOns/Common/Dynamo.cs index 0f8678914..8977c4201 100644 --- a/Roles/AddOns/Common/Dynamo.cs +++ b/Roles/AddOns/Common/Dynamo.cs @@ -20,12 +20,15 @@ namespace EHR.AddOns.Common { const int id = 19390; Options.SetupAdtRoleOptions(id, CustomRoles.Dynamo, canSetNum: true, teamSpawnOptions: true); + IncreaseSpeedBy = new FloatOptionItem(id + 9, "Dynamo.IncreaseSpeedBy", new(0.1f, 1f, 0.1f), 0.1f, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Dynamo]) .SetValueFormat(OptionFormat.Multiplier); + IncreaseSpeedFrequency = new FloatOptionItem(id + 7, "Dynamo.IncreaseSpeedFrequency", new(0.5f, 30f, 0.5f), 5f, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Dynamo]) .SetValueFormat(OptionFormat.Seconds); + MaxSpeed = new FloatOptionItem(id + 8, "Dynamo.MaxSpeed", new(0.1f, 3f, 0.1f), 3f, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Dynamo]) .SetValueFormat(OptionFormat.Multiplier); @@ -54,6 +57,7 @@ namespace EHR.AddOns.Common { float speed = Main.AllPlayerSpeed[pc.PlayerId]; float defaultSpeed = StartingSpeed[pc.PlayerId]; + if (Math.Abs(speed - defaultSpeed) > 0.1f) { Main.AllPlayerSpeed[pc.PlayerId] = defaultSpeed; @@ -64,19 +68,13 @@ namespace EHR.AddOns.Common } SpeedIncreaseTimer[pc.PlayerId] += Time.fixedDeltaTime; - if (SpeedIncreaseTimer[pc.PlayerId] < IncreaseSpeedFrequency.GetFloat()) - { - return; - } + if (SpeedIncreaseTimer[pc.PlayerId] < IncreaseSpeedFrequency.GetFloat()) return; SpeedIncreaseTimer[pc.PlayerId] = 0f; Main.AllPlayerSpeed[pc.PlayerId] += IncreaseSpeedBy.GetFloat(); float maxSpeed = MaxSpeed.GetFloat(); - if (Main.AllPlayerSpeed[pc.PlayerId] > maxSpeed) - { - Main.AllPlayerSpeed[pc.PlayerId] = maxSpeed; - } + if (Main.AllPlayerSpeed[pc.PlayerId] > maxSpeed) Main.AllPlayerSpeed[pc.PlayerId] = maxSpeed; pc.MarkDirtySettings(); } diff --git a/Roles/AddOns/Common/Flash.cs b/Roles/AddOns/Common/Flash.cs index 2a68d3e72..94b8f3dc6 100644 --- a/Roles/AddOns/Common/Flash.cs +++ b/Roles/AddOns/Common/Flash.cs @@ -7,6 +7,7 @@ public void SetupCustomOption() { Options.SetupAdtRoleOptions(18700, CustomRoles.Flashman, canSetNum: true, tab: TabGroup.Addons, teamSpawnOptions: true); + Options.FlashmanSpeed = new FloatOptionItem(18707, "FlashmanSpeed", new(0.25f, 3f, 0.05f), 2.5f, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Flashman]) .SetValueFormat(OptionFormat.Multiplier); diff --git a/Roles/AddOns/Common/Giant.cs b/Roles/AddOns/Common/Giant.cs index a0830e7f0..34b535764 100644 --- a/Roles/AddOns/Common/Giant.cs +++ b/Roles/AddOns/Common/Giant.cs @@ -7,6 +7,7 @@ public void SetupCustomOption() { Options.SetupAdtRoleOptions(18750, CustomRoles.Giant, canSetNum: true, tab: TabGroup.Addons, teamSpawnOptions: true); + Options.GiantSpeed = new FloatOptionItem(18757, "GiantSpeed", new(0.25f, 3f, 0.05f), 0.75f, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Giant]) .SetValueFormat(OptionFormat.Multiplier); diff --git a/Roles/AddOns/Common/Guesser.cs b/Roles/AddOns/Common/Guesser.cs index 2bea363a3..cc3f2aa56 100644 --- a/Roles/AddOns/Common/Guesser.cs +++ b/Roles/AddOns/Common/Guesser.cs @@ -12,8 +12,10 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(19100, CustomRoles.Guesser, canSetNum: true, tab: TabGroup.Addons, teamSpawnOptions: true); + GCanGuessAdt = new BooleanOptionItem(19110, "GCanGuessAdt", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Guesser]); + GTryHideMsg = new BooleanOptionItem(19111, "GuesserTryHideMsg", true, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Guesser]) .SetColor(Color.green); diff --git a/Roles/AddOns/Common/Introvert.cs b/Roles/AddOns/Common/Introvert.cs index 360381354..e685dbea3 100644 --- a/Roles/AddOns/Common/Introvert.cs +++ b/Roles/AddOns/Common/Introvert.cs @@ -16,9 +16,11 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { Options.SetupAdtRoleOptions(645741, CustomRoles.Introvert, canSetNum: true, teamSpawnOptions: true); + Radius = new FloatOptionItem(645748, "Introvert.Radius", new(0.1f, 10f, 0.1f), 2f, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Introvert]) .SetValueFormat(OptionFormat.Multiplier); + Time = new IntegerOptionItem(645749, "Introvert.Time", new(0, 30, 1), 8, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Introvert]) .SetValueFormat(OptionFormat.Seconds); @@ -26,10 +28,7 @@ namespace EHR.AddOns.Common public static void OnFixedUpdate(PlayerControl pc) { - if (Main.HasJustStarted || ExileController.Instance) - { - return; - } + if (Main.HasJustStarted || ExileController.Instance) return; Vector2 pos = pc.Pos(); float radius = Radius.GetFloat(); @@ -49,6 +48,7 @@ namespace EHR.AddOns.Common if (!TeleportAwayDelays.TryGetValue(pc.PlayerId, out long endTS)) { int time = Time.GetInt(); + if (time == 0) { pc.TPToRandomVent(); @@ -93,10 +93,7 @@ namespace EHR.AddOns.Common public static string GetSelfSuffix(PlayerControl seer) { - if (!seer.IsAlive() || !TeleportAwayDelays.TryGetValue(seer.PlayerId, out long endTS)) - { - return string.Empty; - } + if (!seer.IsAlive() || !TeleportAwayDelays.TryGetValue(seer.PlayerId, out long endTS)) return string.Empty; return string.Format(Translator.GetString("Introvert.Suffix"), endTS - Utils.TimeStamp); } diff --git a/Roles/AddOns/Common/Lovers.cs b/Roles/AddOns/Common/Lovers.cs index 19fcd7415..7ad5af44d 100644 --- a/Roles/AddOns/Common/Lovers.cs +++ b/Roles/AddOns/Common/Lovers.cs @@ -61,15 +61,16 @@ namespace EHR.AddOns.Common const int id = 16200; const CustomGameMode customGameMode = CustomGameMode.Standard; - StringOptionItem spawnOption = new StringOptionItem(id, role.ToString(), RatesZeroOne, 0, TabGroup.Addons) + var spawnOption = new StringOptionItem(id, role.ToString(), RatesZeroOne, 0, TabGroup.Addons) .SetColor(Utils.GetRoleColor(role)) .SetHeader(true) .SetGameMode(customGameMode) as StringOptionItem; - IntegerOptionItem rateOption = new IntegerOptionItem(id + 2, "LoverSpawnChances", new(0, 100, 5), 50, TabGroup.Addons) + var rateOption = new IntegerOptionItem(id + 2, "LoverSpawnChances", new(0, 100, 5), 50, TabGroup.Addons) .SetParent(spawnOption) .SetValueFormat(OptionFormat.Percent) .SetGameMode(customGameMode) as IntegerOptionItem; + LoverSpawnChances = rateOption; LoverDieConsequence = new StringOptionItem(id + 3, "LoverDieConsequence", Consequences, 0, TabGroup.Addons) diff --git a/Roles/AddOns/Common/Loyal.cs b/Roles/AddOns/Common/Loyal.cs index 061dabaa6..2511e29bc 100644 --- a/Roles/AddOns/Common/Loyal.cs +++ b/Roles/AddOns/Common/Loyal.cs @@ -9,8 +9,10 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(15500, CustomRoles.Loyal, canSetNum: true); + ImpCanBeLoyal = new BooleanOptionItem(15510, "ImpCanBeLoyal", true, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Loyal]); + CrewCanBeLoyal = new BooleanOptionItem(15511, "CrewCanBeLoyal", true, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Loyal]); } diff --git a/Roles/AddOns/Common/Lucky.cs b/Roles/AddOns/Common/Lucky.cs index 8ce62d034..63de109f4 100644 --- a/Roles/AddOns/Common/Lucky.cs +++ b/Roles/AddOns/Common/Lucky.cs @@ -9,6 +9,7 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(14300, CustomRoles.Lucky, canSetNum: true, teamSpawnOptions: true); + LuckyProbability = new IntegerOptionItem(14310, "LuckyProbability", new(0, 100, 5), 50, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Lucky]) .SetValueFormat(OptionFormat.Percent); diff --git a/Roles/AddOns/Common/Oblivious.cs b/Roles/AddOns/Common/Oblivious.cs index 348f1d830..59b917d55 100644 --- a/Roles/AddOns/Common/Oblivious.cs +++ b/Roles/AddOns/Common/Oblivious.cs @@ -9,6 +9,7 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(15400, CustomRoles.Oblivious, canSetNum: true, teamSpawnOptions: true); + ObliviousBaitImmune = new BooleanOptionItem(15413, "ObliviousBaitImmune", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Oblivious]); } diff --git a/Roles/AddOns/Common/Onbound.cs b/Roles/AddOns/Common/Onbound.cs index 45852a9e0..f7485aa15 100644 --- a/Roles/AddOns/Common/Onbound.cs +++ b/Roles/AddOns/Common/Onbound.cs @@ -8,6 +8,7 @@ public void SetupCustomOption() { Options.SetupAdtRoleOptions(14500, CustomRoles.Onbound, canSetNum: true, teamSpawnOptions: true); + GuesserSuicides = new BooleanOptionItem(14507, "GuesserSuicides", true, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Onbound]) .SetGameMode(CustomGameMode.Standard); diff --git a/Roles/AddOns/Common/Rascal.cs b/Roles/AddOns/Common/Rascal.cs index 24d4ed843..0ed705e66 100644 --- a/Roles/AddOns/Common/Rascal.cs +++ b/Roles/AddOns/Common/Rascal.cs @@ -9,6 +9,7 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(15600, CustomRoles.Rascal, canSetNum: true, tab: TabGroup.Addons, teamSpawnOptions: true); + RascalAppearAsMadmate = new BooleanOptionItem(15610, "RascalAppearAsMadmate", true, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Rascal]); } diff --git a/Roles/AddOns/Common/Sleep.cs b/Roles/AddOns/Common/Sleep.cs index c88f901ab..5793d91a6 100644 --- a/Roles/AddOns/Common/Sleep.cs +++ b/Roles/AddOns/Common/Sleep.cs @@ -13,12 +13,10 @@ namespace EHR.AddOns.Common public static void CheckGlowNearby(PlayerControl pc) { - if (!pc.IsAlive() || !GameStates.IsInTask) - { - return; - } + if (!pc.IsAlive() || !GameStates.IsInTask) return; Vector2 pos = pc.Pos(); + if (Main.AllAlivePlayerControls.Any(x => x.Is(CustomRoles.Glow) && Vector2.Distance(x.Pos(), pos) <= 1.5f)) { Main.PlayerStates[pc.PlayerId].RemoveSubRole(CustomRoles.Sleep); diff --git a/Roles/AddOns/Common/Sonar.cs b/Roles/AddOns/Common/Sonar.cs index 744957b56..fdf67bfc9 100644 --- a/Roles/AddOns/Common/Sonar.cs +++ b/Roles/AddOns/Common/Sonar.cs @@ -15,22 +15,17 @@ namespace EHR.AddOns.Common public static string GetSuffix(PlayerControl seer, bool meeting) { - if (meeting || !seer.Is(CustomRoles.Sonar) || !Target.TryGetValue(seer.PlayerId, out byte targetId)) - { - return string.Empty; - } + if (meeting || !seer.Is(CustomRoles.Sonar) || !Target.TryGetValue(seer.PlayerId, out byte targetId)) return string.Empty; return TargetArrow.GetArrows(seer, targetId); } public static void OnFixedUpdate(PlayerControl seer) { - if (!seer.Is(CustomRoles.Sonar) || !GameStates.IsInTask || seer.inVent || Main.AllAlivePlayerControls.Length == 1) - { - return; - } + if (!seer.Is(CustomRoles.Sonar) || !GameStates.IsInTask || seer.inVent || Main.AllAlivePlayerControls.Length == 1) return; PlayerControl closest = Main.AllAlivePlayerControls.Where(x => x.PlayerId != seer.PlayerId).MinBy(x => Vector2.Distance(seer.Pos(), x.Pos())); + if (Target.TryGetValue(seer.PlayerId, out byte targetId)) { if (targetId != closest.PlayerId) diff --git a/Roles/AddOns/Common/Spurt.cs b/Roles/AddOns/Common/Spurt.cs index f282dcfc5..1199cc32a 100644 --- a/Roles/AddOns/Common/Spurt.cs +++ b/Roles/AddOns/Common/Spurt.cs @@ -22,15 +22,19 @@ namespace EHR.AddOns.Common { const int id = 648950; SetupAdtRoleOptions(id, CustomRoles.Spurt, canSetNum: true, teamSpawnOptions: true); + MinSpeed = new FloatOptionItem(id + 10, "SpurtMinSpeed", new(0f, 3f, 0.25f), 0.75f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Spurt]) .SetValueFormat(OptionFormat.Multiplier); + MaxSpeed = new FloatOptionItem(id + 7, "SpurtMaxSpeed", new(1.5f, 3f, 0.25f), 3f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Spurt]) .SetValueFormat(OptionFormat.Multiplier); + Modulator = new FloatOptionItem(id + 8, "SpurtModule", new(0.25f, 3f, 0.25f), 1.25f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Spurt]) .SetValueFormat(OptionFormat.Multiplier); + DisplaysCharge = new BooleanOptionItem(id + 9, "EnableSpurtCharge", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Spurt]); } @@ -60,20 +64,14 @@ namespace EHR.AddOns.Common float minSpeed = MinSpeed.GetFloat(); float maxSpeed = MaxSpeed.GetFloat(); - if (Mathf.Approximately(minSpeed, maxSpeed)) - { - return 100; - } + if (Mathf.Approximately(minSpeed, maxSpeed)) return 100; return (int)((Main.AllPlayerSpeed[player.PlayerId] - minSpeed) / (maxSpeed - minSpeed) * 100); } public static string GetSuffix(PlayerControl player, bool isforhud = false) { - if (!player.Is(CustomRoles.Spurt) || !DisplaysCharge.GetBool() || GameStates.IsMeeting) - { - return string.Empty; - } + if (!player.Is(CustomRoles.Spurt) || !DisplaysCharge.GetBool() || GameStates.IsMeeting) return string.Empty; int fontsize = isforhud ? 100 : 55; @@ -91,10 +89,12 @@ namespace EHR.AddOns.Common float Decreaseby = Mathf.Clamp(modulator / 20 * 0.5f, 0.01f, 0.3f); int charge = DetermineCharge(player); + if (DisplaysCharge.GetBool() && !player.IsModClient() && LastNum[player.PlayerId] != charge) { LastNum[player.PlayerId] = charge; long now = Utils.TimeStamp; + if (now != LastUpdate[player.PlayerId]) { Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); diff --git a/Roles/AddOns/Common/Stained.cs b/Roles/AddOns/Common/Stained.cs index 8d60287c3..fb45b1e29 100644 --- a/Roles/AddOns/Common/Stained.cs +++ b/Roles/AddOns/Common/Stained.cs @@ -14,10 +14,7 @@ namespace EHR.AddOns.Common public static void OnDeath(PlayerControl pc, PlayerControl killer) { - if (killer == null || pc == null || pc.PlayerId == killer.PlayerId || !killer.IsAlive() || !GameStates.IsInTask) - { - return; - } + if (killer == null || pc == null || pc.PlayerId == killer.PlayerId || !killer.IsAlive() || !GameStates.IsInTask) return; VioletNameList.Add(killer.PlayerId); Utils.NotifyRoles(SpecifyTarget: killer); diff --git a/Roles/AddOns/Common/Sunglasses.cs b/Roles/AddOns/Common/Sunglasses.cs index e74b57c81..d8015c791 100644 --- a/Roles/AddOns/Common/Sunglasses.cs +++ b/Roles/AddOns/Common/Sunglasses.cs @@ -9,6 +9,7 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(15450, CustomRoles.Sunglasses, canSetNum: true, teamSpawnOptions: true); + SunglassesVision = new FloatOptionItem(15460, "SunglassesVision", new(0f, 5f, 0.05f), 0.75f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Sunglasses]) .SetValueFormat(OptionFormat.Multiplier); diff --git a/Roles/AddOns/Common/Torch.cs b/Roles/AddOns/Common/Torch.cs index d402590f6..ea224b473 100644 --- a/Roles/AddOns/Common/Torch.cs +++ b/Roles/AddOns/Common/Torch.cs @@ -9,9 +9,11 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(14200, CustomRoles.Torch, canSetNum: true, teamSpawnOptions: true); + TorchVision = new FloatOptionItem(14210, "TorchVision", new(0.5f, 5f, 0.25f), 1.25f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Torch]) .SetValueFormat(OptionFormat.Multiplier); + TorchAffectedByLights = new BooleanOptionItem(14220, "TorchAffectedByLights", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Torch]); } diff --git a/Roles/AddOns/Common/Trapper.cs b/Roles/AddOns/Common/Trapper.cs index a2d81627a..512e13b80 100644 --- a/Roles/AddOns/Common/Trapper.cs +++ b/Roles/AddOns/Common/Trapper.cs @@ -9,6 +9,7 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(13800, CustomRoles.Trapper, canSetNum: true, teamSpawnOptions: true); + TrapperBlockMoveTime = new FloatOptionItem(13813, "TrapperBlockMoveTime", new(0f, 180f, 1f), 5f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Trapper]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/AddOns/Common/Truant.cs b/Roles/AddOns/Common/Truant.cs index decb0f64f..5f6c443e7 100644 --- a/Roles/AddOns/Common/Truant.cs +++ b/Roles/AddOns/Common/Truant.cs @@ -9,6 +9,7 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(15438, CustomRoles.Truant, canSetNum: true, teamSpawnOptions: true); + TruantWaitingTime = new IntegerOptionItem(15445, "TruantWaitingTime", new(1, 90, 1), 3, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Truant]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/AddOns/Common/Unlucky.cs b/Roles/AddOns/Common/Unlucky.cs index c7c498974..ee1c934ff 100644 --- a/Roles/AddOns/Common/Unlucky.cs +++ b/Roles/AddOns/Common/Unlucky.cs @@ -9,18 +9,23 @@ namespace EHR.AddOns.Common public void SetupCustomOption() { SetupAdtRoleOptions(14350, CustomRoles.Unlucky, canSetNum: true, teamSpawnOptions: true); + UnluckyKillSuicideChance = new IntegerOptionItem(14364, "UnluckyKillSuicideChance", new(0, 100, 1), 2, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Unlucky]) .SetValueFormat(OptionFormat.Percent); + UnluckyTaskSuicideChance = new IntegerOptionItem(14365, "UnluckyTaskSuicideChance", new(0, 100, 1), 5, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Unlucky]) .SetValueFormat(OptionFormat.Percent); + UnluckyVentSuicideChance = new IntegerOptionItem(14366, "UnluckyVentSuicideChance", new(0, 100, 1), 3, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Unlucky]) .SetValueFormat(OptionFormat.Percent); + UnluckyReportSuicideChance = new IntegerOptionItem(14367, "UnluckyReportSuicideChance", new(0, 100, 1), 1, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Unlucky]) .SetValueFormat(OptionFormat.Percent); + UnluckySabotageSuicideChance = new IntegerOptionItem(14368, "UnluckySabotageSuicideChance", new(0, 100, 1), 4, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Unlucky]) .SetValueFormat(OptionFormat.Percent); diff --git a/Roles/AddOns/Crewmate/Bloodlust.cs b/Roles/AddOns/Crewmate/Bloodlust.cs index 7650d8007..944810e7b 100644 --- a/Roles/AddOns/Crewmate/Bloodlust.cs +++ b/Roles/AddOns/Crewmate/Bloodlust.cs @@ -13,11 +13,14 @@ namespace EHR.AddOns.Crewmate public void SetupCustomOption() { SetupAdtRoleOptions(Id, CustomRoles.Bloodlust); + KCD = new FloatOptionItem(Id + 6, "KillCooldown", new(0f, 60f, 2.5f), 30f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Bloodlust]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 4, "CanVent", true, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Bloodlust]); + HasImpVision = new BooleanOptionItem(Id + 5, "ImpostorVision", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Bloodlust]); } diff --git a/Roles/AddOns/Crewmate/Finder.cs b/Roles/AddOns/Crewmate/Finder.cs index 8daf4b62c..95b7fcaeb 100644 --- a/Roles/AddOns/Crewmate/Finder.cs +++ b/Roles/AddOns/Crewmate/Finder.cs @@ -10,12 +10,15 @@ public void SetupCustomOption() { Options.SetupAdtRoleOptions(15660, CustomRoles.Finder, canSetNum: true); + FinderCD = new FloatOptionItem(15668, "TrackerCooldown", new(0f, 180f, 1f), 25f, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Finder]) .SetValueFormat(OptionFormat.Seconds); + FinderDuration = new FloatOptionItem(15666, "TrackerDuration", new(0f, 180f, 1f), 10f, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Finder]) .SetValueFormat(OptionFormat.Seconds); + FinderDelay = new FloatOptionItem(15667, "TrackerDelay", new(0f, 180f, 1f), 5f, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Finder]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/AddOns/Crewmate/Lazy.cs b/Roles/AddOns/Crewmate/Lazy.cs index 4d3f601bb..974a82f77 100644 --- a/Roles/AddOns/Crewmate/Lazy.cs +++ b/Roles/AddOns/Crewmate/Lazy.cs @@ -9,8 +9,10 @@ namespace EHR.AddOns.Crewmate public void SetupCustomOption() { SetupAdtRoleOptions(14100, CustomRoles.Lazy, canSetNum: true); + TasklessCrewCanBeLazy = new BooleanOptionItem(14110, "TasklessCrewCanBeLazy", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Lazy]); + TaskBasedCrewCanBeLazy = new BooleanOptionItem(14120, "TaskBasedCrewCanBeLazy", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Lazy]); } diff --git a/Roles/AddOns/Crewmate/Nimble.cs b/Roles/AddOns/Crewmate/Nimble.cs index 2f421b96f..670158eb2 100644 --- a/Roles/AddOns/Crewmate/Nimble.cs +++ b/Roles/AddOns/Crewmate/Nimble.cs @@ -11,9 +11,11 @@ namespace EHR.AddOns.Crewmate public void SetupCustomOption() { SetupAdtRoleOptions(15640, CustomRoles.Nimble, canSetNum: true); + NimbleCD = new FloatOptionItem(15647, "VentCooldown", new(0, 180, 1), 30, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Nimble]) .SetValueFormat(OptionFormat.Seconds); + NimbleInVentTime = new FloatOptionItem(15646, "MaxInVentTime", new(0, 180, 1), 15, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Nimble]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/AddOns/Crewmate/Noisy.cs b/Roles/AddOns/Crewmate/Noisy.cs index e6caf2188..aa8a202cc 100644 --- a/Roles/AddOns/Crewmate/Noisy.cs +++ b/Roles/AddOns/Crewmate/Noisy.cs @@ -9,8 +9,10 @@ public void SetupCustomOption() { Options.SetupAdtRoleOptions(15670, CustomRoles.Noisy, canSetNum: true); + NoisyImpostorAlert = new BooleanOptionItem(15677, "NoisemakerImpostorAlert", true, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Noisy]); + NoisyAlertDuration = new FloatOptionItem(15676, "NoisemakerAlertDuration", new(0f, 180f, 1f), 10f, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Noisy]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/AddOns/Crewmate/Physicist.cs b/Roles/AddOns/Crewmate/Physicist.cs index f59b5b09c..c5d4d94a4 100644 --- a/Roles/AddOns/Crewmate/Physicist.cs +++ b/Roles/AddOns/Crewmate/Physicist.cs @@ -11,9 +11,11 @@ namespace EHR.AddOns.Crewmate public void SetupCustomOption() { SetupAdtRoleOptions(15650, CustomRoles.Physicist, canSetNum: true); + PhysicistCD = new FloatOptionItem(15657, "VitalsCooldown", new(0, 180, 1), 20, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Physicist]) .SetValueFormat(OptionFormat.Seconds); + PhysicistViewDuration = new FloatOptionItem(15656, "VitalsDuration", new(0, 180, 1), 5, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Physicist]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/AddOns/Crewmate/Stressed.cs b/Roles/AddOns/Crewmate/Stressed.cs index 30ec1dca2..5a5242b68 100644 --- a/Roles/AddOns/Crewmate/Stressed.cs +++ b/Roles/AddOns/Crewmate/Stressed.cs @@ -40,27 +40,35 @@ namespace EHR.AddOns.Crewmate public void SetupCustomOption() { SetupAdtRoleOptions(Id, CustomRoles.Stressed, canSetNum: true); + StressedExtraTimeAfterTaskComplete = new IntegerOptionItem(Id + 11, "StressedExtraTimeAfterTask", new(0, 60, 1), 30, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Stressed]) .SetValueFormat(OptionFormat.Seconds); + StressedExtraTimeAfterMeeting = new IntegerOptionItem(Id + 4, "DamoclesExtraTimeAfterMeeting", new(0, 60, 1), 15, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Stressed]) .SetValueFormat(OptionFormat.Seconds); + StressedExtraTimeAfterImpostorDeath = new IntegerOptionItem(Id + 5, "StressedExtraTimeAfterImpostorDeath", new(0, 60, 1), 10, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Stressed]) .SetValueFormat(OptionFormat.Seconds); + StressedExtraTimeAfterImpostorEjected = new IntegerOptionItem(Id + 6, "StressedExtraTimeAfterImpostorEjected", new(0, 60, 1), 25, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Stressed]) .SetValueFormat(OptionFormat.Seconds); + StressedExtraTimeAfterFixingSabotage = new IntegerOptionItem(Id + 7, "StressedExtraTimeAfterFixingSabotage", new(0, 60, 1), 20, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Stressed]) .SetValueFormat(OptionFormat.Seconds); + StressedExtraTimeAfterReporting = new IntegerOptionItem(Id + 8, "StressedExtraTimeAfterReporting", new(0, 60, 1), 10, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Stressed]) .SetValueFormat(OptionFormat.Seconds); + StressedTimePenaltyAfterCrewmateEjected = new IntegerOptionItem(Id + 9, "StressedTimePenaltyAfterCrewmateEjected", new(0, 60, 1), 15, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Stressed]) .SetValueFormat(OptionFormat.Seconds); + StressedStartingTime = new IntegerOptionItem(Id + 10, "DamoclesStartingTime", new(0, 60, 1), 30, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Stressed]) .SetValueFormat(OptionFormat.Seconds); @@ -110,14 +118,12 @@ namespace EHR.AddOns.Crewmate public static void Update(PlayerControl pc) { long now = Utils.TimeStamp; - if (pc == null || !LastUpdates.TryGetValue(pc.PlayerId, out long x) || x >= now || !Timers.ContainsKey(pc.PlayerId) || !IsEnable || !GameStates.IsInTask || !pc.Is(CustomRoles.Stressed)) - { - return; - } + if (pc == null || !LastUpdates.TryGetValue(pc.PlayerId, out long x) || x >= now || !Timers.ContainsKey(pc.PlayerId) || !IsEnable || !GameStates.IsInTask || !pc.Is(CustomRoles.Stressed)) return; LastUpdates[pc.PlayerId] = now; TaskState ts = pc.GetTaskState(); + if (ts.IsTaskFinished || !ts.HasTasks || !pc.IsAlive()) { Main.PlayerStates[pc.PlayerId].RemoveSubRole(CustomRoles.Stressed); @@ -134,23 +140,14 @@ namespace EHR.AddOns.Crewmate pc.Suicide(); } - if (pc.IsNonHostModClient()) - { - SendRPC(pc.PlayerId, Timers[pc.PlayerId], LastUpdates[pc.PlayerId]); - } + if (pc.IsNonHostModClient()) SendRPC(pc.PlayerId, Timers[pc.PlayerId], LastUpdates[pc.PlayerId]); - if (!pc.IsModClient()) - { - Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - } + if (!pc.IsModClient()) Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); } public static void SendRPC(byte id, int time, long lastUpdate) { - if (!Utils.DoRPC || !IsEnable) - { - return; - } + if (!Utils.DoRPC || !IsEnable) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncStressedTimer, SendOption.Reliable); writer.Write(id); @@ -161,10 +158,7 @@ namespace EHR.AddOns.Crewmate public static void ReceiveRPC(MessageReader reader) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; byte id = reader.ReadByte(); int time = reader.ReadInt32(); @@ -176,21 +170,14 @@ namespace EHR.AddOns.Crewmate private static void LogTimer(byte id = byte.MaxValue, [CallerMemberName] string action = "") { if (Timers.TryGetValue(id, out int time)) - { Logger.Info($"{action} - Timer: {time} for {id.ColoredPlayerName()}", "Stressed"); - } else - { Timers.Do(x => Logger.Info($"{action} - Timer: {x.Value} for {x.Key.ColoredPlayerName()}", "Stressed")); - } } public static void OnTaskComplete(PlayerControl pc) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; Timers[pc.PlayerId] += TimeAfterTaskComplete; LogTimer(pc.PlayerId); @@ -198,20 +185,14 @@ namespace EHR.AddOns.Crewmate public static void AfterMeetingTasks() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; CountRepairSabotage = true; } public static void OnNonCrewmateDead() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; AdjustTime(TimeAfterImpDead); LogTimer(); @@ -219,10 +200,7 @@ namespace EHR.AddOns.Crewmate public static void OnNonCrewmateEjected() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; AdjustTime(TimeAfterImpEject); LogTimer(); @@ -230,10 +208,7 @@ namespace EHR.AddOns.Crewmate public static void OnCrewmateEjected() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; AdjustTime(TimeMinusAfterCrewEject); LogTimer(); @@ -241,10 +216,7 @@ namespace EHR.AddOns.Crewmate public static void OnRepairSabotage(PlayerControl pc) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; Timers[pc.PlayerId] += TimeAfterSaboFix; LogTimer(pc.PlayerId); @@ -252,10 +224,7 @@ namespace EHR.AddOns.Crewmate public static void OnReport(PlayerControl pc) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; Timers[pc.PlayerId] += TimeAfterReport; LogTimer(pc.PlayerId); @@ -263,10 +232,7 @@ namespace EHR.AddOns.Crewmate public static void OnMeetingStart() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; AdjustTime(TimeAfterMeeting + 9); LogTimer(); @@ -279,10 +245,7 @@ namespace EHR.AddOns.Crewmate private static void AdjustTime(int change) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; Timers.AdjustAllValues(x => x + change); } diff --git a/Roles/AddOns/Crewmate/Workhorse.cs b/Roles/AddOns/Crewmate/Workhorse.cs index 4240cb4aa..41b273e22 100644 --- a/Roles/AddOns/Crewmate/Workhorse.cs +++ b/Roles/AddOns/Crewmate/Workhorse.cs @@ -25,17 +25,22 @@ namespace EHR.AddOns.Crewmate public void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.Addons, CustomRoles.Workhorse, zeroOne: true); + SpawnChance = new IntegerOptionItem(Id + 13, "WorkhorseSpawnChance", new(0, 100, 5), 65, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Workhorse]) .SetValueFormat(OptionFormat.Percent); + OptionAssignOnlyToCrewmate = new BooleanOptionItem(Id + 10, "AssignOnlyToCrewmate", true, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Workhorse]); + OptionNumLongTasks = new IntegerOptionItem(Id + 11, "WorkhorseNumLongTasks", new(0, 5, 1), 1, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Workhorse]) .SetValueFormat(OptionFormat.Pieces); + OptionNumShortTasks = new IntegerOptionItem(Id + 12, "WorkhorseNumShortTasks", new(0, 5, 1), 1, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Workhorse]) .SetValueFormat(OptionFormat.Pieces); + OptionSnitchCanBeWorkhorse = new BooleanOptionItem(Id + 14, "SnitchCanBeWorkhorse", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Workhorse]); } @@ -61,62 +66,32 @@ namespace EHR.AddOns.Crewmate private static bool IsAssignTarget(PlayerControl pc) { - if (!pc.IsAlive() || IsThisRole(pc.PlayerId)) - { - return false; - } + if (!pc.IsAlive() || IsThisRole(pc.PlayerId)) return false; - if (pc.Is(CustomRoles.Needy) || pc.Is(CustomRoles.Lazy) || pc.Is(CustomRoles.Bloodlust)) - { - return false; - } + if (pc.Is(CustomRoles.Needy) || pc.Is(CustomRoles.Lazy) || pc.Is(CustomRoles.Bloodlust)) return false; - if (pc.GetCustomRole().GetVNRole(true) is CustomRoles.Impostor or CustomRoles.Shapeshifter) - { - return false; - } + if (pc.GetCustomRole().GetVNRole(true) is CustomRoles.Impostor or CustomRoles.Shapeshifter) return false; TaskState taskState = pc.GetTaskState(); - if (taskState.CompletedTasksCount + 1 < taskState.AllTasksCount) - { - return false; - } + if (taskState.CompletedTasksCount + 1 < taskState.AllTasksCount) return false; bool canBeTarget = Utils.HasTasks(pc.Data) && !OverrideTasksData.AllData.ContainsKey(pc.GetCustomRole()); - if (AssignOnlyToCrewmate) - { - return canBeTarget && pc.Is(CustomRoleTypes.Crewmate); - } + if (AssignOnlyToCrewmate) return canBeTarget && pc.Is(CustomRoleTypes.Crewmate); return canBeTarget; } public static bool OnCompleteTask(PlayerControl pc) { - if (!CustomRoles.Workhorse.IsEnable() || PlayerIdList.Count >= CustomRoles.Workhorse.GetCount()) - { - return false; - } + if (!CustomRoles.Workhorse.IsEnable() || PlayerIdList.Count >= CustomRoles.Workhorse.GetCount()) return false; - if (CurrentGameMode != CustomGameMode.Standard) - { - return false; - } + if (CurrentGameMode != CustomGameMode.Standard) return false; - if (pc.Is(CustomRoles.Snitch) && !OptionSnitchCanBeWorkhorse.GetBool()) - { - return false; - } + if (pc.Is(CustomRoles.Snitch) && !OptionSnitchCanBeWorkhorse.GetBool()) return false; - if (!IsAssignTarget(pc)) - { - return false; - } + if (!IsAssignTarget(pc)) return false; - if (IRandom.Instance.Next(100) >= SpawnChance.GetInt()) - { - return false; - } + if (IRandom.Instance.Next(100) >= SpawnChance.GetInt()) return false; pc.RpcSetCustomRole(CustomRoles.Workhorse); TaskState taskState = pc.GetTaskState(); diff --git a/Roles/AddOns/GhostRoles/Bloodmoon.cs b/Roles/AddOns/GhostRoles/Bloodmoon.cs index 9813e2ffe..bcdb691f0 100644 --- a/Roles/AddOns/GhostRoles/Bloodmoon.cs +++ b/Roles/AddOns/GhostRoles/Bloodmoon.cs @@ -24,10 +24,7 @@ namespace EHR.AddOns.GhostRoles public void OnProtect(PlayerControl pc, PlayerControl target) { - if (!pc.RpcCheckAndMurder(target, true)) - { - return; - } + if (!pc.RpcCheckAndMurder(target, true)) return; ScheduledDeaths.TryAdd(target.PlayerId, Utils.TimeStamp); } @@ -35,41 +32,36 @@ namespace EHR.AddOns.GhostRoles public void SetupCustomOption() { Options.SetupRoleOptions(649400, TabGroup.OtherRoles, CustomRoles.Bloodmoon); + CD = new IntegerOptionItem(649402, "AbilityCooldown", new(0, 60, 1), 60, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Bloodmoon]) .SetValueFormat(OptionFormat.Seconds); + Duration = new IntegerOptionItem(649403, "Bloodmoon.Duration", new(0, 60, 1), 15, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Bloodmoon]) .SetValueFormat(OptionFormat.Seconds); + Speed = new FloatOptionItem(649404, "Bloodmoon.Speed", new(0.05f, 5f, 0.05f), 1f, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Bloodmoon]) .SetValueFormat(OptionFormat.Multiplier); + DieOnMeetingCall = new BooleanOptionItem(649405, "Bloodmoon.DieOnMeetingCall", true, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Bloodmoon]); } public static void Update(PlayerControl pc, Bloodmoon instance) { - if (!GameStates.IsInTask || ExileController.Instance) - { - return; - } + if (!GameStates.IsInTask || ExileController.Instance) return; long now = Utils.TimeStamp; - if (now == instance.LastUpdate) - { - return; - } + if (now == instance.LastUpdate) return; instance.LastUpdate = now; foreach (KeyValuePair death in ScheduledDeaths) { PlayerControl player = Utils.GetPlayerById(death.Key); - if (player == null || !player.IsAlive()) - { - continue; - } + if (player == null || !player.IsAlive()) continue; if (now - death.Value < Duration.GetInt()) { @@ -77,10 +69,7 @@ namespace EHR.AddOns.GhostRoles continue; } - if (pc.RpcCheckAndMurder(player, true)) - { - player.Suicide(realKiller: pc); - } + if (pc.RpcCheckAndMurder(player, true)) player.Suicide(realKiller: pc); } } @@ -91,10 +80,7 @@ namespace EHR.AddOns.GhostRoles foreach (byte id in ScheduledDeaths.Keys) { PlayerControl pc = Utils.GetPlayerById(id); - if (pc == null || !pc.IsAlive()) - { - continue; - } + if (pc == null || !pc.IsAlive()) continue; pc.Suicide(); } @@ -105,10 +91,7 @@ namespace EHR.AddOns.GhostRoles public static string GetSuffix(PlayerControl seer) { - if (!ScheduledDeaths.TryGetValue(seer.PlayerId, out long ts)) - { - return string.Empty; - } + if (!ScheduledDeaths.TryGetValue(seer.PlayerId, out long ts)) return string.Empty; long timeLeft = Duration.GetInt() - (Utils.TimeStamp - ts) + 1; (string TextColor, string TimeColor) colors = GetColors(); diff --git a/Roles/AddOns/GhostRoles/GA.cs b/Roles/AddOns/GhostRoles/GA.cs index cbbdad39d..45ed0067e 100644 --- a/Roles/AddOns/GhostRoles/GA.cs +++ b/Roles/AddOns/GhostRoles/GA.cs @@ -14,10 +14,7 @@ namespace EHR.AddOns.GhostRoles public void OnProtect(PlayerControl pc, PlayerControl target) { - if (ProtectionList.Add(target.PlayerId)) - { - LateTask.New(() => ProtectionList.Remove(target.PlayerId), ProtectDuration.GetFloat()); - } + if (ProtectionList.Add(target.PlayerId)) LateTask.New(() => ProtectionList.Remove(target.PlayerId), ProtectDuration.GetFloat()); } public void OnAssign(PlayerControl pc) @@ -28,9 +25,11 @@ namespace EHR.AddOns.GhostRoles public void SetupCustomOption() { Options.SetupRoleOptions(649600, TabGroup.OtherRoles, CustomRoles.GA); + ProtectDuration = new IntegerOptionItem(649602, "BKProtectDuration", new(1, 90, 1), 5, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.GA]) .SetValueFormat(OptionFormat.Seconds); + CD = new IntegerOptionItem(649603, "AbilityCooldown", new(0, 60, 1), 30, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.GA]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/AddOns/GhostRoles/Haunter.cs b/Roles/AddOns/GhostRoles/Haunter.cs index 4935a1b59..b58ae2f88 100644 --- a/Roles/AddOns/GhostRoles/Haunter.cs +++ b/Roles/AddOns/GhostRoles/Haunter.cs @@ -29,20 +29,16 @@ namespace EHR.AddOns.GhostRoles public Team Team => Team.Crewmate | Team.Neutral; public int Cooldown => 900; - public void OnProtect(PlayerControl pc, PlayerControl target) - { - } + public void OnProtect(PlayerControl pc, PlayerControl target) { } public void OnAssign(PlayerControl pc) { HaunterId = pc.PlayerId; + LateTask.New(() => { TaskState taskState = pc.GetTaskState(); - if (taskState == null) - { - return; - } + if (taskState == null) return; taskState.HasTasks = true; taskState.CompletedTasksCount = 0; @@ -58,27 +54,31 @@ namespace EHR.AddOns.GhostRoles public void SetupCustomOption() { Options.SetupRoleOptions(649300, TabGroup.OtherRoles, CustomRoles.Haunter); + TasksBeforeBeingKnown = new IntegerOptionItem(649302, "Haunter.TasksBeforeBeingKnown", new(1, 10, 1), 1, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Haunter]); + RevealNeutralKillers = new BooleanOptionItem(649303, "Haunter.RevealNeutralKillers", true, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Haunter]); + RevealMadmates = new BooleanOptionItem(649304, "Haunter.RevealMadmates", true, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Haunter]); + NumberOfReveals = new IntegerOptionItem(649305, "Haunter.NumberOfReveals", new(1, 10, 1), 1, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Haunter]); + CanWinWithCrewmates = new StringOptionItem(649306, "Haunter.CanWinWithCrewmates", WinWithCrewOpts, 1, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Haunter]); + Options.OverrideTasksData.Create(649307, TabGroup.OtherRoles, CustomRoles.Haunter); } public void OnOneTaskLeft(PlayerControl pc) { - if (WarnedImps.Count > 0) - { - return; - } + if (WarnedImps.Count > 0) return; WarnedImps = []; + IEnumerable filtered = Main.AllAlivePlayerControls.Where(x => { return x.GetTeam() switch @@ -89,6 +89,7 @@ namespace EHR.AddOns.GhostRoles _ => false }; }); + foreach (PlayerControl imp in filtered) { TargetArrow.Add(imp.PlayerId, pc.PlayerId); @@ -101,14 +102,12 @@ namespace EHR.AddOns.GhostRoles public void OnFinishedTasks(PlayerControl pc) { - if (WarnedImps.Count == 0) - { - return; - } + if (WarnedImps.Count == 0) return; List targets = []; int numOfReveals = NumberOfReveals.GetInt(); - for (int i = 0; i < numOfReveals; i++) + + for (var i = 0; i < numOfReveals; i++) { int index = IRandom.Instance.Next(WarnedImps.Count); byte target = WarnedImps[index]; @@ -127,10 +126,7 @@ namespace EHR.AddOns.GhostRoles public void Update(PlayerControl pc) { - if (WarnedImps.Count == 0 || WarnTimeStamp == Utils.TimeStamp) - { - return; - } + if (WarnedImps.Count == 0 || WarnTimeStamp == Utils.TimeStamp) return; if (WarnedImps.Any(imp => TargetArrow.GetArrows(Utils.GetPlayerById(imp), pc.PlayerId) == "・")) { @@ -151,15 +147,9 @@ namespace EHR.AddOns.GhostRoles { foreach ((CustomRoles Role, IGhostRole Instance) role in GhostRolesManager.AssignedGhostRoles.Values) { - if (role.Instance is not Haunter haunter) - { - continue; - } + if (role.Instance is not Haunter haunter) continue; - if (!haunter.WarnedImps.Contains(seer.PlayerId)) - { - continue; - } + if (!haunter.WarnedImps.Contains(seer.PlayerId)) continue; return TargetArrow.GetArrows(seer, haunter.HaunterId); } diff --git a/Roles/AddOns/GhostRoles/Minion.cs b/Roles/AddOns/GhostRoles/Minion.cs index bf8f3ddfe..947035fd9 100644 --- a/Roles/AddOns/GhostRoles/Minion.cs +++ b/Roles/AddOns/GhostRoles/Minion.cs @@ -14,32 +14,26 @@ namespace EHR.AddOns.GhostRoles public void OnProtect(PlayerControl pc, PlayerControl target) { - if (!BlindPlayers.Add(target.PlayerId)) - { - return; - } + if (!BlindPlayers.Add(target.PlayerId)) return; target.MarkDirtySettings(); LateTask.New(() => { - if (BlindPlayers.Remove(target.PlayerId)) - { - target.MarkDirtySettings(); - } + if (BlindPlayers.Remove(target.PlayerId)) target.MarkDirtySettings(); }, BlindDuration.GetFloat(), "Remove Minion Blindness"); } - public void OnAssign(PlayerControl pc) - { - } + public void OnAssign(PlayerControl pc) { } public void SetupCustomOption() { Options.SetupRoleOptions(649000, TabGroup.OtherRoles, CustomRoles.Minion); + BlindDuration = new IntegerOptionItem(649002, "MinionBlindDuration", new(1, 90, 1), 5, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Minion]) .SetValueFormat(OptionFormat.Seconds); + CD = new IntegerOptionItem(649003, "AbilityCooldown", new(0, 60, 1), 30, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Minion]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/AddOns/GhostRoles/Specter.cs b/Roles/AddOns/GhostRoles/Specter.cs index f80e7acc7..bd3704309 100644 --- a/Roles/AddOns/GhostRoles/Specter.cs +++ b/Roles/AddOns/GhostRoles/Specter.cs @@ -14,13 +14,11 @@ namespace EHR.AddOns.GhostRoles public void OnAssign(PlayerControl pc) { IsWon = false; + LateTask.New(() => { TaskState taskState = pc.GetTaskState(); - if (taskState == null) - { - return; - } + if (taskState == null) return; taskState.HasTasks = true; taskState.CompletedTasksCount = 0; @@ -33,15 +31,15 @@ namespace EHR.AddOns.GhostRoles }, 1f, "Specter Assign"); } - public void OnProtect(PlayerControl pc, PlayerControl target) - { - } + public void OnProtect(PlayerControl pc, PlayerControl target) { } public void SetupCustomOption() { Options.SetupRoleOptions(649100, TabGroup.OtherRoles, CustomRoles.Specter); + SnatchWin = new BooleanOptionItem(649102, "SnatchWin", false, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Specter]); + Options.OverrideTasksData.Create(649103, TabGroup.OtherRoles, CustomRoles.Specter); } diff --git a/Roles/AddOns/GhostRoles/Warden.cs b/Roles/AddOns/GhostRoles/Warden.cs index fb05d987c..9426eab42 100644 --- a/Roles/AddOns/GhostRoles/Warden.cs +++ b/Roles/AddOns/GhostRoles/Warden.cs @@ -17,43 +17,36 @@ namespace EHR.AddOns.GhostRoles public void OnProtect(PlayerControl pc, PlayerControl target) { - if (SpeedList.ContainsKey(target.PlayerId)) - { - return; - } + if (SpeedList.ContainsKey(target.PlayerId)) return; float speed = Main.AllPlayerSpeed[target.PlayerId]; float targetSpeed = speed + ExtraSpeed.GetFloat(); - if (Math.Abs(speed - targetSpeed) < 0.1f || speed > targetSpeed) - { - return; - } + if (Math.Abs(speed - targetSpeed) < 0.1f || speed > targetSpeed) return; Main.AllPlayerSpeed[target.PlayerId] += ExtraSpeed.GetFloat(); target.MarkDirtySettings(); - if (NotifyTarget.GetBool()) - { - target.Notify(Translator.GetString("WardenNotify")); - } + if (NotifyTarget.GetBool()) target.Notify(Translator.GetString("WardenNotify")); SpeedList[target.PlayerId] = (Utils.TimeStamp, speed); } - public void OnAssign(PlayerControl pc) - { - } + public void OnAssign(PlayerControl pc) { } public void SetupCustomOption() { Options.SetupRoleOptions(649200, TabGroup.OtherRoles, CustomRoles.Warden); + ExtraSpeedDuration = new IntegerOptionItem(649202, "ExpressSpeedDur", new(1, 90, 1), 5, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Warden]) .SetValueFormat(OptionFormat.Seconds); + ExtraSpeed = new FloatOptionItem(649203, "WardenAdditionalSpeed", new(0f, 3f, 0.05f), 0.25f, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Warden]) .SetValueFormat(OptionFormat.Multiplier); + NotifyTarget = new BooleanOptionItem(649204, "WardenNotifyTarget", true, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Warden]); + CD = new IntegerOptionItem(649205, "AbilityCooldown", new(0, 60, 1), 30, TabGroup.OtherRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Warden]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/AddOns/Impostor/Circumvent.cs b/Roles/AddOns/Impostor/Circumvent.cs index 9b6ccc9d9..6ef1f4117 100644 --- a/Roles/AddOns/Impostor/Circumvent.cs +++ b/Roles/AddOns/Impostor/Circumvent.cs @@ -22,8 +22,10 @@ namespace EHR.AddOns.Impostor { const int id = 14680; Options.SetupAdtRoleOptions(id, CustomRoles.Circumvent, canSetNum: true); + VentPreventionMode = new StringOptionItem(id + 5, "VentPreventionMode", VentPreventionModes, 1, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Circumvent]); + Limit = new IntegerOptionItem(id + 4, "VentLimit", new(1, 90, 1), 8, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Circumvent]); } @@ -35,20 +37,13 @@ namespace EHR.AddOns.Impostor public static void Add() { - if (VentPreventionMode.GetValue() == 0) - { - return; - } + if (VentPreventionMode.GetValue() == 0) return; LateTask.New(() => { foreach (KeyValuePair state in Main.PlayerStates) - { if (state.Value.SubRoles.Contains(CustomRoles.Circumvent)) - { Limits[state.Key] = Limit.GetInt(); - } - } }, 3f, "Add Circumvents"); } @@ -69,22 +64,17 @@ namespace EHR.AddOns.Impostor public static void AfterMeetingTasks() { - if (VentPreventionMode.GetValue() != 2) - { - return; - } + if (VentPreventionMode.GetValue() != 2) return; Limits.SetAllValues(Limit.GetInt()); } public static string GetProgressText(byte playerId) { - if (!Limits.TryGetValue(playerId, out int limit)) - { - return string.Empty; - } + if (!Limits.TryGetValue(playerId, out int limit)) return string.Empty; int mode = VentPreventionMode.GetValue(); + string color = limit switch { > 11 => "#00ff00", @@ -105,10 +95,7 @@ namespace EHR.AddOns.Impostor public static bool CanUseImpostorVentButton(PlayerControl pc) { - if (!pc.Is(CustomRoles.Circumvent)) - { - return true; - } + if (!pc.Is(CustomRoles.Circumvent)) return true; return pc.inVent || (!Limits.TryGetValue(pc.PlayerId, out int limit) && VentPreventionMode.GetValue() != 0) || limit > 0; } diff --git a/Roles/AddOns/Impostor/Damocles.cs b/Roles/AddOns/Impostor/Damocles.cs index ee1887a0a..8eb1250a9 100644 --- a/Roles/AddOns/Impostor/Damocles.cs +++ b/Roles/AddOns/Impostor/Damocles.cs @@ -30,12 +30,15 @@ namespace EHR.AddOns.Impostor public void SetupCustomOption() { SetupAdtRoleOptions(Id, CustomRoles.Damocles, canSetNum: true); + DamoclesExtraTimeAfterKill = new IntegerOptionItem(Id + 6, "DamoclesExtraTimeAfterKill", new(0, 60, 1), 30, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Damocles]) .SetValueFormat(OptionFormat.Seconds); + DamoclesExtraTimeAfterMeeting = new IntegerOptionItem(Id + 4, "DamoclesExtraTimeAfterMeeting", new(0, 60, 1), 30, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Damocles]) .SetValueFormat(OptionFormat.Seconds); + DamoclesStartingTime = new IntegerOptionItem(Id + 5, "DamoclesStartingTime", new(0, 60, 1), 30, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Damocles]) .SetValueFormat(OptionFormat.Seconds); @@ -57,10 +60,7 @@ namespace EHR.AddOns.Impostor { byte id = pc.PlayerId; long now = Utils.TimeStamp; - if ((LastUpdate.TryGetValue(id, out long ts) && ts >= now) || !GameStates.IsInTask || pc == null) - { - return; - } + if ((LastUpdate.TryGetValue(id, out long ts) && ts >= now) || !GameStates.IsInTask || pc == null) return; if (!pc.IsAlive()) { @@ -69,10 +69,7 @@ namespace EHR.AddOns.Impostor } LastUpdate[id] = now; - if (!Timer.ContainsKey(id)) - { - Timer[id] = StartingTime + 8; - } + if (!Timer.ContainsKey(id)) Timer[id] = StartingTime + 8; Timer[id]--; @@ -82,36 +79,24 @@ namespace EHR.AddOns.Impostor pc.Suicide(); } - if (pc.IsNonHostModClient()) - { - SendRPC(id); - } + if (pc.IsNonHostModClient()) SendRPC(id); - if (!pc.IsModClient()) - { - Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - } + if (!pc.IsModClient()) Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); } public static void SendRPC(byte playerId) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncDamoclesTimer, SendOption.Reliable); writer.Write(playerId); writer.Write(Timer[playerId]); writer.Write(LastUpdate[playerId].ToString()); writer.Write(PreviouslyEnteredVents[playerId].Count); + if (PreviouslyEnteredVents[playerId].Count > 0) - { foreach (int vent in PreviouslyEnteredVents[playerId].ToArray()) - { writer.Write(vent); - } - } AmongUsClient.Instance.FinishRpcImmediately(writer); } @@ -122,13 +107,10 @@ namespace EHR.AddOns.Impostor Timer[playerId] = reader.ReadInt32(); LastUpdate[playerId] = long.Parse(reader.ReadString()); int elements = reader.ReadInt32(); + if (elements > 0) - { - for (int i = 0; i < elements; i++) - { + for (var i = 0; i < elements; i++) PreviouslyEnteredVents[playerId].Add(reader.ReadInt32()); - } - } } public static void OnMurder(byte id) @@ -143,15 +125,9 @@ namespace EHR.AddOns.Impostor public static void OnEnterVent(byte id, int ventId) { - if (!PreviouslyEnteredVents.ContainsKey(id)) - { - PreviouslyEnteredVents[id] = []; - } + if (!PreviouslyEnteredVents.ContainsKey(id)) PreviouslyEnteredVents[id] = []; - if (PreviouslyEnteredVents[id].Contains(ventId)) - { - return; - } + if (PreviouslyEnteredVents[id].Contains(ventId)) return; PreviouslyEnteredVents[id].Add(ventId); Timer[id] += 10; diff --git a/Roles/AddOns/Impostor/DeadlyQuota.cs b/Roles/AddOns/Impostor/DeadlyQuota.cs index 93f167bc9..95ff67245 100644 --- a/Roles/AddOns/Impostor/DeadlyQuota.cs +++ b/Roles/AddOns/Impostor/DeadlyQuota.cs @@ -7,6 +7,7 @@ public void SetupCustomOption() { Options.SetupAdtRoleOptions(14650, CustomRoles.DeadlyQuota, canSetNum: true); + Options.DQNumOfKillsNeeded = new IntegerOptionItem(14660, "DQNumOfKillsNeeded", new(1, 14, 1), 3, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.DeadlyQuota]); } diff --git a/Roles/AddOns/Impostor/Egoist.cs b/Roles/AddOns/Impostor/Egoist.cs index a80cb1602..3c2c59e3a 100644 --- a/Roles/AddOns/Impostor/Egoist.cs +++ b/Roles/AddOns/Impostor/Egoist.cs @@ -7,6 +7,7 @@ public void SetupCustomOption() { Options.SetupAdtRoleOptions(18900, CustomRoles.Egoist, canSetNum: true, tab: TabGroup.Addons); + Options.ImpEgoistVisibalToAllies = new BooleanOptionItem(18912, "ImpEgoistVisibalToAllies", true, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Egoist]); } diff --git a/Roles/AddOns/Impostor/LastImpostor.cs b/Roles/AddOns/Impostor/LastImpostor.cs index 508fac214..015288b08 100644 --- a/Roles/AddOns/Impostor/LastImpostor.cs +++ b/Roles/AddOns/Impostor/LastImpostor.cs @@ -11,6 +11,7 @@ namespace EHR.AddOns.Impostor public void SetupCustomOption() { Options.SetupSingleRoleOptions(Id, TabGroup.Addons, CustomRoles.LastImpostor); + Reduction = new FloatOptionItem(Id + 15, "SansReduceKillCooldown", new(5f, 95f, 5f), 20f, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.LastImpostor]) .SetValueFormat(OptionFormat.Percent); @@ -28,15 +29,9 @@ namespace EHR.AddOns.Impostor public static void SetKillCooldown() { - if (CurrentId == byte.MaxValue) - { - return; - } + if (CurrentId == byte.MaxValue) return; - if (!Main.AllPlayerKillCooldown.TryGetValue(CurrentId, out float cd)) - { - return; - } + if (!Main.AllPlayerKillCooldown.TryGetValue(CurrentId, out float cd)) return; float minus = cd * (Reduction.GetFloat() / 100f); Main.AllPlayerKillCooldown[CurrentId] -= minus; @@ -50,15 +45,9 @@ namespace EHR.AddOns.Impostor public static void SetSubRole() { - if (CurrentId != byte.MaxValue || !AmongUsClient.Instance.AmHost) - { - return; - } + if (CurrentId != byte.MaxValue || !AmongUsClient.Instance.AmHost) return; - if (Options.CurrentGameMode != CustomGameMode.Standard || !CustomRoles.LastImpostor.IsEnable() || Main.AliveImpostorCount != 1) - { - return; - } + if (Options.CurrentGameMode != CustomGameMode.Standard || !CustomRoles.LastImpostor.IsEnable() || Main.AliveImpostorCount != 1) return; foreach (PlayerControl pc in Main.AllAlivePlayerControls) { @@ -69,12 +58,11 @@ namespace EHR.AddOns.Impostor SetKillCooldown(); pc.SyncSettings(); Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); + if (Main.KillTimers.TryGetValue(pc.PlayerId, out float timer) && Main.AllPlayerKillCooldown.TryGetValue(pc.PlayerId, out float cd) && timer > cd) - { pc.SetKillCooldown(); - } break; } diff --git a/Roles/AddOns/Impostor/Madmate.cs b/Roles/AddOns/Impostor/Madmate.cs index 7680dce2c..78f6e8c37 100644 --- a/Roles/AddOns/Impostor/Madmate.cs +++ b/Roles/AddOns/Impostor/Madmate.cs @@ -9,27 +9,38 @@ namespace EHR.AddOns.Impostor public void SetupCustomOption() { SetupAdtRoleOptions(15800, CustomRoles.Madmate, canSetNum: true, canSetChance: false, allowZeroCount: true); + MadmateSpawnMode = new StringOptionItem(15810, "MadmateSpawnMode", MadmateSpawnModeStrings, 0, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Madmate]); + MadmateCountMode = new StringOptionItem(15811, "MadmateCountMode", MadmateCountModeStrings, 0, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Madmate]); + SheriffCanBeMadmate = new BooleanOptionItem(15812, "SheriffCanBeMadmate", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Madmate]); + MayorCanBeMadmate = new BooleanOptionItem(15813, "MayorCanBeMadmate", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Madmate]); + NGuesserCanBeMadmate = new BooleanOptionItem(15814, "NGuesserCanBeMadmate", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Madmate]); + MarshallCanBeMadmate = new BooleanOptionItem(15815, "MarshallCanBeMadmate", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Madmate]); + FarseerCanBeMadmate = new BooleanOptionItem(15816, "FarseerCanBeMadmate", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Madmate]); + PresidentCanBeMadmate = new BooleanOptionItem(15817, "PresidentCanBeMadmate", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Madmate]); + SnitchCanBeMadmate = new BooleanOptionItem(15818, "SnitchCanBeMadmate", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Madmate]); + MadSnitchTasks = new IntegerOptionItem(15819, "MadSnitchTasks", new(0, 90, 1), 3, TabGroup.Addons) .SetParent(SnitchCanBeMadmate) .SetValueFormat(OptionFormat.Pieces); + JudgeCanBeMadmate = new BooleanOptionItem(15820, "JudgeCanBeMadmate", false, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Madmate]); } diff --git a/Roles/AddOns/Impostor/Mare.cs b/Roles/AddOns/Impostor/Mare.cs index 52e5a116f..7b035b1e1 100644 --- a/Roles/AddOns/Impostor/Mare.cs +++ b/Roles/AddOns/Impostor/Mare.cs @@ -9,14 +9,18 @@ namespace EHR.AddOns.Impostor public void SetupCustomOption() { SetupAdtRoleOptions(1600, CustomRoles.Mare, canSetNum: true, tab: TabGroup.Addons); + MareKillCD = new FloatOptionItem(1609, "KillCooldown", new(0f, 60f, 1f), 15f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Mare]) .SetValueFormat(OptionFormat.Seconds); + MareKillCDNormally = new FloatOptionItem(1606, "KillCooldownNormally", new(0f, 90f, 1f), 40f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Mare]) .SetValueFormat(OptionFormat.Seconds); + MareHasIncreasedSpeed = new BooleanOptionItem(1607, "MareHasIncreasedSpeed", true, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Mare]); + MareSpeedDuringLightsOut = new FloatOptionItem(1608, "MareSpeedDuringLightsOut", new(0.5f, 3f, 0.05f), 1.75f, TabGroup.Addons) .SetParent(CustomRoleSpawnChances[CustomRoles.Mare]) .SetValueFormat(OptionFormat.Multiplier); diff --git a/Roles/AddOns/Impostor/Mimic.cs b/Roles/AddOns/Impostor/Mimic.cs index 9f4622038..da6b24f69 100644 --- a/Roles/AddOns/Impostor/Mimic.cs +++ b/Roles/AddOns/Impostor/Mimic.cs @@ -7,6 +7,7 @@ public void SetupCustomOption() { Options.SetupAdtRoleOptions(16000, CustomRoles.Mimic, canSetNum: true, tab: TabGroup.Addons); + Options.MimicCanSeeDeadRoles = new BooleanOptionItem(16010, "MimicCanSeeDeadRoles", true, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Mimic]); } diff --git a/Roles/AddOns/Impostor/TicketsStealer.cs b/Roles/AddOns/Impostor/TicketsStealer.cs index 6afd6a0ba..b7a3bd452 100644 --- a/Roles/AddOns/Impostor/TicketsStealer.cs +++ b/Roles/AddOns/Impostor/TicketsStealer.cs @@ -7,6 +7,7 @@ public void SetupCustomOption() { Options.SetupAdtRoleOptions(16100, CustomRoles.TicketsStealer, canSetNum: true, tab: TabGroup.Addons); + Options.TicketsPerKill = new FloatOptionItem(16110, "TicketsPerKill", new(0.1f, 90f, 0.1f), 0.5f, TabGroup.Addons) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.TicketsStealer]); } diff --git a/Roles/Crewmate/Addict.cs b/Roles/Crewmate/Addict.cs index b444602cf..3e204a451 100644 --- a/Roles/Crewmate/Addict.cs +++ b/Roles/Crewmate/Addict.cs @@ -30,14 +30,19 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Addict); + VentCooldown = new FloatOptionItem(Id + 11, "VentCooldown", new(5f, 70f, 1f), 40f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Addict]) .SetValueFormat(OptionFormat.Seconds); + TimeLimit = new FloatOptionItem(Id + 12, "SerialKillerLimit", new(5f, 75f, 1f), 45f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Addict]) .SetValueFormat(OptionFormat.Seconds); + ImmortalTimeAfterVent = new FloatOptionItem(Id + 13, "AddictInvulnerbilityTimeAfterVent", new(0f, 30f, 1f), 10f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Addict]) .SetValueFormat(OptionFormat.Seconds); + SpeedWhileImmortal = new FloatOptionItem(Id + 14, "AddictSpeedWhileInvulnerble", new(0.25f, 5f, 0.25f), 1.75f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Addict]) .SetValueFormat(OptionFormat.Multiplier); + FreezeTimeAfterImmortal = new FloatOptionItem(Id + 15, "AddictFreezeTimeAfterInvulnerbility", new(0f, 10f, 1f), 3f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Addict]) .SetValueFormat(OptionFormat.Seconds); } @@ -80,10 +85,7 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl player) { - if (!GameStates.IsInTask || !IsEnable || Math.Abs(SuicideTimer - -10f) < 0.5f || !player.IsAlive()) - { - return; - } + if (!GameStates.IsInTask || !IsEnable || Math.Abs(SuicideTimer - -10f) < 0.5f || !player.IsAlive()) return; if (SuicideTimer >= TimeLimit.GetFloat()) { @@ -91,17 +93,13 @@ namespace EHR.Crewmate SuicideTimer = -10f; } else if (Mathf.Approximately(SuicideTimer + 8, TimeLimit.GetFloat())) - { player.Notify(Translator.GetString("AddictWarning"), 8f); - } else { SuicideTimer += Time.fixedDeltaTime; if (IsImmortal(player)) - { ImmortalTimer += Time.fixedDeltaTime; - } else if (Math.Abs(ImmortalTimer - 420f) > 0.5f && FreezeTimeAfterImmortal.GetFloat() > 0) { AddictGetDown(player); @@ -118,10 +116,7 @@ namespace EHR.Crewmate public override void OnEnterVent(PlayerControl pc, Vent vent) { - if (!pc.Is(CustomRoles.Addict)) - { - return; - } + if (!pc.Is(CustomRoles.Addict)) return; SuicideTimer = 0f; ImmortalTimer = 0f; @@ -135,6 +130,7 @@ namespace EHR.Crewmate Main.AllPlayerSpeed[addict.PlayerId] = Main.MinSpeed; ReportDeadBodyPatch.CanReport[addict.PlayerId] = false; addict.MarkDirtySettings(); + LateTask.New(() => { Main.AllPlayerSpeed[addict.PlayerId] = DefaultSpeed; diff --git a/Roles/Crewmate/Adrenaline.cs b/Roles/Crewmate/Adrenaline.cs index 6b24e8d9a..27b222550 100644 --- a/Roles/Crewmate/Adrenaline.cs +++ b/Roles/Crewmate/Adrenaline.cs @@ -21,18 +21,23 @@ namespace EHR.Crewmate public override void SetupCustomOption() { - int id = 648300; + var id = 648300; Options.SetupRoleOptions(id++, TabGroup.CrewmateRoles, CustomRoles.Adrenaline); + Time = new IntegerOptionItem(++id, "Adrenaline.Time", new(1, 120, 1), 15, TabGroup.CrewmateRoles) .SetValueFormat(OptionFormat.Seconds) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Adrenaline]); + MaxSurvives = new IntegerOptionItem(++id, "Adrenaline.MaxSurvives", new(1, 5, 1), 1, TabGroup.CrewmateRoles) .SetValueFormat(OptionFormat.Times) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Adrenaline]); + MinTasksRequired = new IntegerOptionItem(++id, "Adrenaline.MinTasksRequired", new(1, 5, 1), 1, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Adrenaline]); + CanCallMeetingDuringTimer = new BooleanOptionItem(++id, "Adrenaline.CanCallMeetingDuringTimer", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Adrenaline]); + SpeedIncreaseDuringTimer = new FloatOptionItem(++id, "Adrenaline.SpeedDuringTimer", new(0f, 3f, 0.05f), 0.5f, TabGroup.CrewmateRoles) .SetValueFormat(OptionFormat.Multiplier) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Adrenaline]); @@ -55,10 +60,7 @@ namespace EHR.Crewmate public override bool OnCheckMurderAsTarget(PlayerControl killer, PlayerControl target) { - if (!base.OnCheckMurderAsTarget(killer, target) || target.GetAbilityUseLimit() < 1 || target.GetTaskState().CompletedTasksCount < MinTasksRequired.GetInt()) - { - return true; - } + if (!base.OnCheckMurderAsTarget(killer, target) || target.GetAbilityUseLimit() < 1 || target.GetTaskState().CompletedTasksCount < MinTasksRequired.GetInt()) return true; target.RpcRemoveAbilityUse(); Timer = Time.GetInt(); @@ -70,10 +72,7 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (Timer == 0 || !pc.IsAlive()) - { - return; - } + if (Timer == 0 || !pc.IsAlive()) return; if (GameStates.IsMeeting) { @@ -84,10 +83,7 @@ namespace EHR.Crewmate } long now = Utils.TimeStamp; - if (now == LastUpdate) - { - return; - } + if (now == LastUpdate) return; LastUpdate = now; @@ -115,10 +111,7 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != AdrenalineId || meeting || (seer.IsModClient() && !hud) || Timer == 0) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != AdrenalineId || meeting || (seer.IsModClient() && !hud) || Timer == 0) return string.Empty; return string.Format(Translator.GetString("Adrenaline.Suffix"), Timer); } diff --git a/Roles/Crewmate/Adventurer.cs b/Roles/Crewmate/Adventurer.cs index fc8b806a9..4a08def68 100644 --- a/Roles/Crewmate/Adventurer.cs +++ b/Roles/Crewmate/Adventurer.cs @@ -98,10 +98,7 @@ namespace EHR.Crewmate .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Adventurer]) .SetValueFormat(OptionFormat.Seconds); - foreach (Weapon weapon in Enum.GetValues()) - { - WeaponEnabledSettings[weapon] = CreateWeaponEnabledSetting(11333 + (int)weapon, weapon); - } + foreach (Weapon weapon in Enum.GetValues()) WeaponEnabledSettings[weapon] = CreateWeaponEnabledSetting(11333 + (int)weapon, weapon); } public override void Add(byte playerId) @@ -121,10 +118,7 @@ namespace EHR.Crewmate LastGroupingResourceTimeStamp = Utils.TimeStamp + 20; ResourceLocations = []; - foreach (Resource resource in Enum.GetValues()) - { - ResourceCounts[resource] = 0; - } + foreach (Resource resource in Enum.GetValues()) ResourceCounts[resource] = 0; } public override void Init() @@ -159,6 +153,7 @@ namespace EHR.Crewmate Weapon weapon = SelectedWeaponToCraft == Weapon.RNG ? EnabledWeapons.RandomElement() : SelectedWeaponToCraft; ActiveWeapons.Add(weapon); pc.Notify(string.Format(Translator.GetString("AdventurerWeaponCrafted"), Translator.GetString($"AdventurerGun.{weapon}"))); + foreach ((Resource resource, int count) in Ingredients[weapon]) { ResourceCounts[resource] -= count; @@ -182,6 +177,7 @@ namespace EHR.Crewmate break; case false when ActiveWeapons.Count > 0: PlayerControl target = ExternalRpcPetPatch.SelectKillButtonTarget(pc); + switch (ActiveWeapons[0]) { case Weapon.Gun when target != null: @@ -195,10 +191,7 @@ namespace EHR.Crewmate case Weapon.Portal: IEnumerable e = Main.AllAlivePlayerControls.Where(x => x.PlayerId != pc.PlayerId && !x.inVent && !x.inMovingPlat && !x.onLadder); PlayerControl[] filtered = e as PlayerControl[] ?? e.ToArray(); - if (filtered.Length == 0) - { - return; - } + if (filtered.Length == 0) return; PlayerControl other = filtered.RandomElement(); Vector2 pos = other.Pos(); @@ -213,7 +206,8 @@ namespace EHR.Crewmate case Weapon.Wrench: if (Utils.IsActive(SystemTypes.Electrical)) { - SwitchSystem SwitchSystem = ShipStatus.Instance?.Systems?[SystemTypes.Electrical]?.TryCast(); + var SwitchSystem = ShipStatus.Instance?.Systems?[SystemTypes.Electrical]?.TryCast(); + if (SwitchSystem != null) { SwitchSystem.ActualSwitches = 0; @@ -268,10 +262,7 @@ namespace EHR.Crewmate public override void OnGlobalFixedUpdate(PlayerControl pc, bool lowLoad) { - if (lowLoad) - { - return; - } + if (lowLoad) return; long now = Utils.TimeStamp; @@ -317,10 +308,7 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (Count++ < 10) - { - return; - } + if (Count++ < 10) return; Count = 0; @@ -376,7 +364,8 @@ namespace EHR.Crewmate public static bool OnAnyoneCheckMurder(PlayerControl target) { - bool any = false; + var any = false; + foreach (PlayerState s in Main.PlayerStates.Values) { if (s.Role is Adventurer { IsEnable: true } av && av.ShieldedPlayers.Contains(target.PlayerId)) @@ -392,10 +381,7 @@ namespace EHR.Crewmate public override bool KnowRole(PlayerControl seer, PlayerControl target) { - if (base.KnowRole(seer, target)) - { - return true; - } + if (base.KnowRole(seer, target)) return true; return RevealedPlayers.Contains(target.PlayerId); } @@ -421,15 +407,9 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.IsModClient() && !hud) - { - return string.Empty; - } + if (seer.IsModClient() && !hud) return string.Empty; - if (seer.PlayerId != target.PlayerId || seer.PlayerId != AdventurerPC.PlayerId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != AdventurerPC.PlayerId) return string.Empty; IEnumerable resources = from resource in Enum.GetValues() @@ -437,14 +417,12 @@ namespace EHR.Crewmate select $"{Utils.ColorString(displayData.Color, $"{displayData.Icon}")}{ResourceCounts[resource]}"; string finalText = string.Join(' ', resources); - if (meeting) - { - return finalText; - } + if (meeting) return finalText; finalText += $"\n{LocateArrow.GetArrows(seer)}\n"; finalText += ""; + finalText += InCraftingMode ? string.Format( Translator.GetString("AdventurerIngredientsDisplay"), @@ -453,6 +431,7 @@ namespace EHR.Crewmate .Select(x => $"{Utils.ColorString(ResourceDisplayData[x.Resource].Color, $"{ResourceDisplayData[x.Resource].Icon}")}" + $"{Utils.ColorString(x.Count > ResourceCounts[x.Resource] ? Color.red : Color.white, $"{x.Count}")}"))) : Translator.GetString("AdventurerVentToEnterCrafting"); + finalText += ""; return finalText; diff --git a/Roles/Crewmate/Aid.cs b/Roles/Crewmate/Aid.cs index 3f82ad2e4..ec85ee175 100644 --- a/Roles/Crewmate/Aid.cs +++ b/Roles/Crewmate/Aid.cs @@ -25,17 +25,22 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Aid); + AidCD = new FloatOptionItem(Id + 10, "AidCD", new(0f, 60f, 1f), 15f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Aid]) .SetValueFormat(OptionFormat.Seconds); + AidDur = new FloatOptionItem(Id + 11, "AidDur", new(0f, 60f, 1f), 10f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Aid]) .SetValueFormat(OptionFormat.Seconds); + TargetKnowsShield = new BooleanOptionItem(Id + 14, "AidTargetKnowsAboutShield", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Aid]); + UseLimitOpt = new IntegerOptionItem(Id + 12, "AbilityUseLimit", new(1, 20, 1), 5, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Aid]) .SetValueFormat(OptionFormat.Times); + UsePet = Options.CreatePetUseSetting(Id + 13, CustomRoles.Aid); } @@ -75,15 +80,9 @@ namespace EHR.Crewmate public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null) - { - return false; - } + if (killer == null) return false; - if (target == null) - { - return false; - } + if (target == null) return false; TargetId = target.PlayerId; Utils.NotifyRoles(SpecifySeer: killer, SpecifyTarget: target); @@ -92,12 +91,9 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (pc == null || !pc.Is(CustomRoles.Aid) || ShieldedPlayers.Count == 0) - { - return; - } + if (pc == null || !pc.Is(CustomRoles.Aid) || ShieldedPlayers.Count == 0) return; - bool change = false; + var change = false; foreach (KeyValuePair x in ShieldedPlayers.ToArray()) { @@ -109,15 +105,13 @@ namespace EHR.Crewmate } } - if (change && GameStates.IsInTask) - { - Utils.NotifyRoles(SpecifySeer: pc); - } + if (change && GameStates.IsInTask) Utils.NotifyRoles(SpecifySeer: pc); } public override void OnCoEnterVent(PlayerPhysics physics, int ventId) { PlayerControl pc = physics.myPlayer; + if (pc.GetAbilityUseLimit() >= 1 && TargetId != byte.MaxValue) { pc.RpcRemoveAbilityUse(); @@ -152,10 +146,7 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud)) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud)) return string.Empty; if (TargetKnowsShield.GetBool() && ShieldedPlayers.TryGetValue(seer.PlayerId, out long ts)) { diff --git a/Roles/Crewmate/Alchemist.cs b/Roles/Crewmate/Alchemist.cs index 77ed817d2..11e1ff8f1 100644 --- a/Roles/Crewmate/Alchemist.cs +++ b/Roles/Crewmate/Alchemist.cs @@ -43,22 +43,31 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Alchemist); + VentCooldown = new FloatOptionItem(Id + 11, "AlchemistAbilityCooldown", new(0f, 70f, 1f), 15f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Alchemist]) .SetValueFormat(OptionFormat.Seconds); + ShieldDuration = new FloatOptionItem(Id + 12, "AlchemistShieldDur", new(5f, 70f, 1f), 20f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Alchemist]) .SetValueFormat(OptionFormat.Seconds); + InvisDuration = new FloatOptionItem(Id + 13, "AlchemistInvisDur", new(5f, 70f, 1f), 20f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Alchemist]) .SetValueFormat(OptionFormat.Seconds); + Speed = new FloatOptionItem(Id + 14, "AlchemistSpeed", new(0.1f, 5f, 0.1f), 1.5f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Alchemist]) .SetValueFormat(OptionFormat.Multiplier); + SpeedDuration = new FloatOptionItem(Id + 15, "AlchemistSpeedDur", new(5f, 70f, 1f), 20f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Alchemist]) .SetValueFormat(OptionFormat.Seconds); + Vision = new FloatOptionItem(Id + 16, "AlchemistVision", new(0f, 1f, 0.05f), 0.85f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Alchemist]) .SetValueFormat(OptionFormat.Multiplier); + VisionOnLightsOut = new FloatOptionItem(Id + 17, "AlchemistVisionOnLightsOut", new(0f, 1f, 0.05f), 0.4f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Alchemist]) .SetValueFormat(OptionFormat.Multiplier); + VisionDuration = new FloatOptionItem(Id + 18, "AlchemistVisionDur", new(5f, 70f, 1f), 20f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Alchemist]) .SetValueFormat(OptionFormat.Seconds); + OverrideTasksData.Create(Id + 20, TabGroup.CrewmateRoles, CustomRoles.Alchemist); } @@ -88,10 +97,7 @@ namespace EHR.Crewmate private void SendRPCData() { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetAlchemistPotion, SendOption.Reliable); writer.Write(AlchemistId); @@ -106,10 +112,7 @@ namespace EHR.Crewmate public static void ReceiveRPCData(MessageReader reader) { byte id = reader.ReadByte(); - if (Main.PlayerStates[id].Role is not Alchemist am) - { - return; - } + if (Main.PlayerStates[id].Role is not Alchemist am) return; am.IsProtected = reader.ReadBoolean(); am.PotionID = reader.ReadByte(); @@ -162,27 +165,23 @@ namespace EHR.Crewmate public static void DrinkPotion(PlayerControl player, int ventId, bool isPet = false) { - if (Main.PlayerStates[player.PlayerId].Role is not Alchemist am) - { - return; - } + if (Main.PlayerStates[player.PlayerId].Role is not Alchemist am) return; switch (am.PotionID) { case 1: // Shield am.IsProtected = true; player.Notify(GetString("AlchemistShielded"), ShieldDuration.GetInt()); + LateTask.New(() => { am.IsProtected = false; player.Notify(GetString("AlchemistShieldOut")); }, ShieldDuration.GetInt(), "Alchemist Shield"); + break; case 2: // Suicide - if (!isPet) - { - player.MyPhysics.RpcBootFromVent(ventId); - } + if (!isPet) player.MyPhysics.RpcBootFromVent(ventId); LateTask.New(() => { player.Suicide(PlayerState.DeathReason.Poison); }, !isPet ? 1f : 0.1f, "Alchemist Suicide"); break; @@ -196,18 +195,21 @@ namespace EHR.Crewmate tar1.TP(tar2); tar1.RPCPlayCustomSound("Teleport"); }, !isPet ? 2f : 0.1f, "AlchemistTPToRandomPlayer"); + break; case 4: // Increased speed player.Notify(GetString("AlchemistHasSpeed")); player.MarkDirtySettings(); float tmpSpeed = Main.AllPlayerSpeed[player.PlayerId]; Main.AllPlayerSpeed[player.PlayerId] = Speed.GetFloat(); + LateTask.New(() => { Main.AllPlayerSpeed[player.PlayerId] = Main.AllPlayerSpeed[player.PlayerId] - Speed.GetFloat() + tmpSpeed; player.MarkDirtySettings(); player.Notify(GetString("AlchemistSpeedOut")); }, SpeedDuration.GetInt(), "Alchemist Speed"); + break; case 5: // Quick fix next sabo // Done when making the potion @@ -219,18 +221,17 @@ namespace EHR.Crewmate am.VisionPotionActive = true; player.MarkDirtySettings(); player.Notify(GetString("AlchemistHasVision"), VisionDuration.GetFloat()); + LateTask.New(() => { am.VisionPotionActive = false; player.MarkDirtySettings(); player.Notify(GetString("AlchemistVisionOut")); }, VisionDuration.GetFloat(), "Alchemist Vision"); + break; case 10 when !player.Is(CustomRoles.Nimble): - if (!isPet) - { - player.MyPhysics.RpcBootFromVent(ventId); - } + if (!isPet) player.MyPhysics.RpcBootFromVent(ventId); player.Notify(GetString("AlchemistNoPotion")); break; @@ -243,10 +244,7 @@ namespace EHR.Crewmate private void SendRPC() { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetAlchemistTimer, SendOption.Reliable); writer.Write(AlchemistId); @@ -257,20 +255,14 @@ namespace EHR.Crewmate public static void ReceiveRPC(MessageReader reader) { byte id = reader.ReadByte(); - if (Main.PlayerStates[id].Role is not Alchemist am) - { - return; - } + if (Main.PlayerStates[id].Role is not Alchemist am) return; am.InvisTime = long.Parse(reader.ReadString()); } public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = VentCooldown.GetFloat(); AURoleOptions.EngineerInVentMaxTime = 1f; @@ -278,17 +270,11 @@ namespace EHR.Crewmate public override void OnCoEnterVent(PlayerPhysics instance, int ventId) { - if (PotionID != 6) - { - return; - } + if (PotionID != 6) return; PotionID = 10; PlayerControl pc = instance.myPlayer; - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; LateTask.New(() => { @@ -306,18 +292,16 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl player) { - if (!GameStates.IsInTask || !IsEnable) - { - return; - } + if (!GameStates.IsInTask || !IsEnable) return; long now = Utils.TimeStamp; if (lastFixedTime != now && InvisTime != -10) { lastFixedTime = now; - bool refresh = false; + var refresh = false; long remainTime = InvisTime + (long)InvisDuration.GetFloat() - now; + switch (remainTime) { case < 0: @@ -332,21 +316,16 @@ namespace EHR.Crewmate break; } - if (refresh) - { - SendRPC(); - } + if (refresh) SendRPC(); } } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (!hud || seer == null || seer.PlayerId != target.PlayerId || !GameStates.IsInTask || seer.PlayerId != AlchemistId) - { - return string.Empty; - } + if (!hud || seer == null || seer.PlayerId != target.PlayerId || !GameStates.IsInTask || seer.PlayerId != AlchemistId) return string.Empty; + + var str = new StringBuilder(); - StringBuilder str = new StringBuilder(); if (IsInvis) { long remainTime = InvisTime + (long)InvisDuration.GetFloat() - Utils.TimeStamp; @@ -354,7 +333,8 @@ namespace EHR.Crewmate } else { - string preText = $"{GetString("PotionInStore")}:"; + var preText = $"{GetString("PotionInStore")}:"; + switch (PotionID) { case 1: // Shield @@ -383,10 +363,7 @@ namespace EHR.Crewmate break; } - if (FixNextSabo) - { - str.Append($"\n{GetString("QuickFixPotionWaitForUse")}"); - } + if (FixNextSabo) str.Append($"\n{GetString("QuickFixPotionWaitForUse")}"); } return str.ToString(); @@ -394,12 +371,10 @@ namespace EHR.Crewmate public override string GetProgressText(byte playerId, bool comms) { - if (Utils.GetPlayerById(playerId) == null || !GameStates.IsInTask || Utils.GetPlayerById(playerId).IsModClient()) - { - return string.Empty; - } + if (Utils.GetPlayerById(playerId) == null || !GameStates.IsInTask || Utils.GetPlayerById(playerId).IsModClient()) return string.Empty; + + var str = new StringBuilder(); - StringBuilder str = new StringBuilder(); switch (PotionID) { case 1: // Shield @@ -425,20 +400,14 @@ namespace EHR.Crewmate break; } - if (FixNextSabo) - { - str.Append($" ({GetString("QuickFix")})"); - } + if (FixNextSabo) str.Append($" ({GetString("QuickFix")})"); return str.ToString(); } public static void RepairSystem(PlayerControl pc, SystemTypes systemType, byte amount) { - if (Main.PlayerStates[pc.PlayerId].Role is not Alchemist { IsEnable: true } am) - { - return; - } + if (Main.PlayerStates[pc.PlayerId].Role is not Alchemist { IsEnable: true } am) return; am.FixNextSabo = false; @@ -487,13 +456,9 @@ namespace EHR.Crewmate public override void SetButtonTexts(HudManager hud, byte id) { if (UsePets.GetBool()) - { hud.PetButton?.OverrideText(GetString("AlchemistVentButtonText")); - } else - { hud.AbilityButton?.OverrideText(GetString("AlchemistVentButtonText")); - } } } } \ No newline at end of file diff --git a/Roles/Crewmate/Altruist.cs b/Roles/Crewmate/Altruist.cs index f0863b325..457d6e0fc 100644 --- a/Roles/Crewmate/Altruist.cs +++ b/Roles/Crewmate/Altruist.cs @@ -64,20 +64,14 @@ namespace EHR.Crewmate public static bool OnAnyoneCheckReportDeadBody(PlayerControl reporter, NetworkedPlayerInfo target) { - if (ReviveTargetCanReportTheirOwnBody.GetBool()) - { - return true; - } + if (ReviveTargetCanReportTheirOwnBody.GetBool()) return true; return !RevivedPlayers.Contains(reporter.PlayerId) || target.PlayerId != reporter.PlayerId; } public override bool CheckReportDeadBody(PlayerControl reporter, NetworkedPlayerInfo target, PlayerControl killer) { - if (!RevivingMode || target.Disconnected) - { - return true; - } + if (!RevivingMode || target.Disconnected) return true; PlayerState state = Main.PlayerStates[reporter.PlayerId]; state.deathReason = PlayerState.DeathReason.Sacrifice; @@ -96,10 +90,7 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (pc.IsAlive() || !GameStates.IsInTask || ReviveStartTS == 0 || ReviveTarget == byte.MaxValue) - { - return; - } + if (pc.IsAlive() || !GameStates.IsInTask || ReviveStartTS == 0 || ReviveTarget == byte.MaxValue) return; if (Utils.TimeStamp - ReviveStartTS < ReviveTime.GetInt()) { @@ -115,12 +106,10 @@ namespace EHR.Crewmate RevivedPlayers.Add(ReviveTarget); PlayerControl killer = rtg?.GetRealKiller(); + if (killer != null && ReviveTargetsKillerGetsAlert.GetBool()) { - if (ReviveTargetsKillerGetsArrow.GetBool()) - { - TargetArrow.Add(killer.PlayerId, ReviveTarget); - } + if (ReviveTargetsKillerGetsArrow.GetBool()) TargetArrow.Add(killer.PlayerId, ReviveTarget); killer.KillFlash(); killer.Notify(string.Format(Translator.GetString("AltruistKillerAlert"), ReviveTarget.ColoredPlayerName()), 10f); @@ -133,14 +122,12 @@ namespace EHR.Crewmate public override void OnGlobalFixedUpdate(PlayerControl pc, bool lowLoad) { - if (lowLoad || !ReviveTargetsKillerGetsArrow.GetBool() || GameStates.IsMeeting || ExileController.Instance) - { - return; - } + if (lowLoad || !ReviveTargetsKillerGetsArrow.GetBool() || GameStates.IsMeeting || ExileController.Instance) return; if (RevivedPlayers.FindFirst(x => x.GetPlayer()?.GetRealKiller()?.PlayerId == pc.PlayerId, out byte revived)) { PlayerControl revivedPlayer = revived.GetPlayer(); + if (revivedPlayer == null || !revivedPlayer.IsAlive()) { TargetArrow.Remove(pc.PlayerId, revived); @@ -169,15 +156,9 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != AlturistId || meeting || hud) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != AlturistId || meeting || hud) return string.Empty; - if (ReviveStartTS != 0) - { - return string.Format(Translator.GetString("AltruistSuffixRevive"), ReviveTime.GetInt() - (Utils.TimeStamp - ReviveStartTS)); - } + if (ReviveStartTS != 0) return string.Format(Translator.GetString("AltruistSuffixRevive"), ReviveTime.GetInt() - (Utils.TimeStamp - ReviveStartTS)); return string.Format(Translator.GetString("AltruistSuffix"), Translator.GetString(RevivingMode ? "AltruistReviveMode" : "AltruistReportMode")); } diff --git a/Roles/Crewmate/Analyst.cs b/Roles/Crewmate/Analyst.cs index 365fb1242..9eda9c61f 100644 --- a/Roles/Crewmate/Analyst.cs +++ b/Roles/Crewmate/Analyst.cs @@ -29,23 +29,32 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Analyst); + UseLimitOpt = new IntegerOptionItem(Id + 10, "AbilityUseLimit", new(0, 30, 1), 3, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Analyst]) .SetValueFormat(OptionFormat.Times); + CD = new FloatOptionItem(Id + 11, "AnalyzeCD", new(0f, 60f, 2.5f), 15f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Analyst]) .SetValueFormat(OptionFormat.Seconds); + CD.ReplacementDictionary = ReplacementDict; + Duration = new IntegerOptionItem(Id + 12, "AnalyzeDur", new(1, 30, 1), 5, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Analyst]) .SetValueFormat(OptionFormat.Seconds); + Duration.ReplacementDictionary = ReplacementDict; + SeeKillCount = new BooleanOptionItem(Id + 13, "AnalyzerSeeKillCount", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Analyst]); + SeeVentCount = new BooleanOptionItem(Id + 14, "AnalyzerSeeVentCount", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Analyst]); + SeeRoleBasis = new BooleanOptionItem(Id + 15, "AnalyzerSeeRoleBasis", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Analyst]); + UsePet = CreatePetUseSetting(Id + 16, CustomRoles.Analyst); } @@ -110,38 +119,20 @@ namespace EHR.Crewmate public static void OnAnyoneEnterVent(PlayerControl pc) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; - if (!VentCount.TryAdd(pc.PlayerId, 1)) - { - VentCount[pc.PlayerId]++; - } + if (!VentCount.TryAdd(pc.PlayerId, 1)) VentCount[pc.PlayerId]++; } public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!IsEnable) - { - return false; - } + if (!IsEnable) return false; - if (killer == null || target == null) - { - return false; - } + if (killer == null || target == null) return false; - if (killer.GetAbilityUseLimit() <= 0) - { - return false; - } + if (killer.GetAbilityUseLimit() <= 0) return false; - if (CurrentTarget.ID != byte.MaxValue) - { - return false; - } + if (CurrentTarget.ID != byte.MaxValue) return false; CurrentTarget = (target.PlayerId, Utils.TimeStamp); killer.SetKillCooldown(Duration.GetFloat()); @@ -152,26 +143,14 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - if (pc == null) - { - return; - } + if (pc == null) return; - if (CurrentTarget.ID == byte.MaxValue) - { - return; - } + if (CurrentTarget.ID == byte.MaxValue) return; PlayerControl target = Utils.GetPlayerById(CurrentTarget.ID); - if (target == null) - { - return; - } + if (target == null) return; if (Vector2.Distance(target.Pos(), pc.Pos()) > (pc.Is(CustomRoles.Reach) ? 2.5f : 1.5f)) { @@ -191,10 +170,7 @@ namespace EHR.Crewmate public override void OnReportDeadBody() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; CurrentTarget.ID = byte.MaxValue; } diff --git a/Roles/Crewmate/Autocrat.cs b/Roles/Crewmate/Autocrat.cs index d0e898905..2ef01a3c4 100644 --- a/Roles/Crewmate/Autocrat.cs +++ b/Roles/Crewmate/Autocrat.cs @@ -24,10 +24,7 @@ namespace EHR.Crewmate public override void OnTaskComplete(PlayerControl pc, int completedTaskCount, int totalTaskCount) { - if (!pc.IsAlive()) - { - return; - } + if (!pc.IsAlive()) return; Main.AllAlivePlayerControls.OrderBy(x => Vector2.Distance(x.Pos(), pc.Pos())).FirstOrDefault(x => x.PlayerId != pc.PlayerId)?.TP(pc); } diff --git a/Roles/Crewmate/Bane.cs b/Roles/Crewmate/Bane.cs index 949d07ee1..7f340df26 100644 --- a/Roles/Crewmate/Bane.cs +++ b/Roles/Crewmate/Bane.cs @@ -22,10 +22,7 @@ public static void OnKilled(PlayerControl killer) { - if (killer == null || killer.Is(CustomRoles.Bloodlust)) - { - return; - } + if (killer == null || killer.Is(CustomRoles.Bloodlust)) return; CustomRoles erasedRole = killer.IsImpostor() ? CustomRoles.ImpostorEHR : killer.IsCrewmate() ? CustomRoles.CrewmateEHR : CustomRoles.Amnesiac; killer.RpcSetCustomRole(erasedRole); diff --git a/Roles/Crewmate/Beacon.cs b/Roles/Crewmate/Beacon.cs index 9dad1aa90..d2b3888a4 100644 --- a/Roles/Crewmate/Beacon.cs +++ b/Roles/Crewmate/Beacon.cs @@ -20,9 +20,11 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Beacon); + VisionIncrease = new FloatOptionItem(Id + 2, "BeaconVisionIncrease", new(0.05f, 1.25f, 0.05f), 0.5f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Beacon]) .SetValueFormat(OptionFormat.Multiplier); + Radius = new FloatOptionItem(Id + 3, "PerceiverRadius", new(0.1f, 5f, 0.1f), 1.5f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Beacon]) .SetValueFormat(OptionFormat.Multiplier); @@ -49,16 +51,10 @@ namespace EHR.Crewmate public override void OnCheckPlayerPosition(PlayerControl pc) { - if (!GameStates.IsInTask || pc == null) - { - return; - } + if (!GameStates.IsInTask || pc == null) return; long now = Utils.TimeStamp; - if (LastChange.TryGetValue(pc.PlayerId, out long ts) && ts == now) - { - return; - } + if (LastChange.TryGetValue(pc.PlayerId, out long ts) && ts == now) return; Vector2 pos = pc.Pos(); float radius = Radius.GetFloat(); @@ -70,10 +66,7 @@ namespace EHR.Crewmate case true when !beaconNearby: { AffectedPlayers.Remove(pc.PlayerId); - if (Utils.IsActive(SystemTypes.Electrical)) - { - pc.MarkDirtySettings(); - } + if (Utils.IsActive(SystemTypes.Electrical)) pc.MarkDirtySettings(); LastChange[pc.PlayerId] = now; break; @@ -81,10 +74,7 @@ namespace EHR.Crewmate case false when beaconNearby: { AffectedPlayers.Add(pc.PlayerId); - if (Utils.IsActive(SystemTypes.Electrical)) - { - pc.MarkDirtySettings(); - } + if (Utils.IsActive(SystemTypes.Electrical)) pc.MarkDirtySettings(); LastChange[pc.PlayerId] = now; break; diff --git a/Roles/Crewmate/Benefactor.cs b/Roles/Crewmate/Benefactor.cs index 659fe2267..d536bd5a0 100644 --- a/Roles/Crewmate/Benefactor.cs +++ b/Roles/Crewmate/Benefactor.cs @@ -25,12 +25,15 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Benefactor); + TaskMarkPerRoundOpt = new IntegerOptionItem(Id + 10, "TaskMarkPerRound", new(1, 14, 1), 3, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Benefactor]) .SetValueFormat(OptionFormat.Votes); + ShieldDuration = new IntegerOptionItem(Id + 11, "AidDur", new(1, 30, 1), 10, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Benefactor]) .SetValueFormat(OptionFormat.Seconds); + Options.OverrideTasksData.Create(Id + 12, TabGroup.CrewmateRoles, CustomRoles.Benefactor); } @@ -51,10 +54,7 @@ namespace EHR.Crewmate private static void SendRPC(byte benefactorId, int taskIndex = -1, bool isShield = false, bool clearAll = false, bool shieldExpire = false, byte shieldedId = byte.MaxValue) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncBenefactorMarkedTask, SendOption.Reliable); writer.Write(benefactorId); @@ -63,10 +63,7 @@ namespace EHR.Crewmate writer.Write(clearAll); writer.Write(shieldExpire); writer.Write(shieldedId); - if (!isShield) - { - writer.Write(TaskMarkPerRound[benefactorId]); - } + if (!isShield) writer.Write(TaskMarkPerRound[benefactorId]); AmongUsClient.Instance.FinishRpcImmediately(writer); } @@ -74,65 +71,43 @@ namespace EHR.Crewmate public static void ReceiveRPC(MessageReader reader) { byte benefactorID = reader.ReadByte(); - if (Main.PlayerStates[benefactorID].Role is not Benefactor { IsEnable: true }) - { - return; - } + if (Main.PlayerStates[benefactorID].Role is not Benefactor { IsEnable: true }) return; int taskInd = reader.ReadInt32(); bool IsShield = reader.ReadBoolean(); bool clearAll = reader.ReadBoolean(); bool shieldExpire = reader.ReadBoolean(); byte shieldedId = reader.ReadByte(); + if (!IsShield) { int uses = reader.ReadInt32(); TaskMarkPerRound[benefactorID] = uses; + if (!clearAll && !shieldExpire) { - if (!TaskIndex.ContainsKey(benefactorID)) - { - TaskIndex[benefactorID] = []; - } + if (!TaskIndex.ContainsKey(benefactorID)) TaskIndex[benefactorID] = []; TaskIndex[benefactorID].Add(taskInd); } } else { - if (TaskIndex.ContainsKey(benefactorID)) - { - TaskIndex[benefactorID].Remove(taskInd); - } + if (TaskIndex.ContainsKey(benefactorID)) TaskIndex[benefactorID].Remove(taskInd); } - if (clearAll && TaskIndex.ContainsKey(benefactorID)) - { - TaskIndex[benefactorID].Clear(); - } + if (clearAll && TaskIndex.ContainsKey(benefactorID)) TaskIndex[benefactorID].Clear(); - if (IsShield) - { - ShieldedPlayers.TryAdd(shieldedId, Utils.TimeStamp); - } + if (IsShield) ShieldedPlayers.TryAdd(shieldedId, Utils.TimeStamp); - if (shieldExpire) - { - ShieldedPlayers.Remove(shieldedId); - } + if (shieldExpire) ShieldedPlayers.Remove(shieldedId); - if (clearAll && ShieldedPlayers.Count > 0) - { - ShieldedPlayers.Clear(); - } + if (clearAll && ShieldedPlayers.Count > 0) ShieldedPlayers.Clear(); } public override string GetProgressText(byte playerId, bool comms) { - if (!IsEnable) - { - return string.Empty; - } + if (!IsEnable) return string.Empty; TaskMarkPerRound.TryAdd(playerId, 0); int markedTasks = TaskMarkPerRound[playerId]; @@ -142,19 +117,14 @@ namespace EHR.Crewmate public override void AfterMeetingTasks() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; ShieldedPlayers.Clear(); + foreach (byte playerId in TaskMarkPerRound.Keys.ToArray()) { TaskMarkPerRound[playerId] = 0; - if (TaskIndex.ContainsKey(playerId)) - { - TaskIndex[playerId].Clear(); - } + if (TaskIndex.ContainsKey(playerId)) TaskIndex[playerId].Clear(); SendRPC(playerId, clearAll: true); } @@ -162,10 +132,7 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; foreach (KeyValuePair x in ShieldedPlayers.Where(x => x.Value + ShieldDuration.GetInt() < Utils.TimeStamp)) { @@ -176,15 +143,14 @@ namespace EHR.Crewmate public static void OnTaskComplete(PlayerControl player, PlayerTask task) // Special case for Benefactor { - if (player == null) - { - return; - } + if (player == null) return; byte playerId = player.PlayerId; + if (player.Is(CustomRoles.Benefactor)) { TaskMarkPerRound.TryAdd(playerId, 0); + if (TaskMarkPerRound[playerId] >= MaxTasksMarkedPerRound) { TaskMarkPerRound[playerId] = MaxTasksMarkedPerRound; @@ -193,10 +159,7 @@ namespace EHR.Crewmate } TaskMarkPerRound[playerId]++; - if (!TaskIndex.ContainsKey(playerId)) - { - TaskIndex[playerId] = []; - } + if (!TaskIndex.ContainsKey(playerId)) TaskIndex[playerId] = []; TaskIndex[playerId].Add(task.Index); SendRPC(playerId, task.Index); @@ -209,10 +172,7 @@ namespace EHR.Crewmate if (TaskIndex[benefactorId].Contains(task.Index)) { PlayerControl benefactorPC = Utils.GetPlayerById(benefactorId); - if (benefactorPC == null) - { - continue; - } + if (benefactorPC == null) continue; player.Notify(GetString("BenefactorTargetGotShieldNotify")); TaskIndex[benefactorId].Remove(task.Index); diff --git a/Roles/Crewmate/Bloodhound.cs b/Roles/Crewmate/Bloodhound.cs index 9710b6f0f..328694c00 100644 --- a/Roles/Crewmate/Bloodhound.cs +++ b/Roles/Crewmate/Bloodhound.cs @@ -29,18 +29,24 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Bloodhound); + ArrowsPointingToDeadBody = new BooleanOptionItem(Id + 10, "BloodhoundArrowsPointingToDeadBody", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bloodhound]); + LeaveDeadBodyUnreportable = new BooleanOptionItem(Id + 11, "BloodhoundLeaveDeadBodyUnreportable", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bloodhound]); + NotifyKiller = new BooleanOptionItem(Id + 14, "BloodhoundNotifyKiller", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bloodhound]); + UseLimitOpt = new IntegerOptionItem(Id + 12, "AbilityUseLimit", new(0, 20, 1), 1, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bloodhound]) .SetValueFormat(OptionFormat.Times); + BloodhoundAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 13, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bloodhound]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 15, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bloodhound]) .SetValueFormat(OptionFormat.Times); @@ -80,18 +86,12 @@ namespace EHR.Crewmate public static void OnPlayerDead(PlayerControl target) { - if (!ArrowsPointingToDeadBody.GetBool()) - { - return; - } + if (!ArrowsPointingToDeadBody.GetBool()) return; foreach (byte id in PlayerIdList) { PlayerControl player = Utils.GetPlayerById(id); - if (player == null || !player.IsAlive()) - { - continue; - } + if (player == null || !player.IsAlive()) continue; Vector2 pos = target.Pos(); LocateArrow.Add(id, pos); @@ -102,10 +102,7 @@ namespace EHR.Crewmate { if (killer != null) { - if (BloodhoundTargets.Contains(killer.PlayerId)) - { - return false; - } + if (BloodhoundTargets.Contains(killer.PlayerId)) return false; Vector2 pos = target.Object.Pos(); LocateArrow.Remove(pc.PlayerId, pos); @@ -118,45 +115,26 @@ namespace EHR.Crewmate pc.Notify(GetString("BloodhoundTrackRecorded")); pc.RpcRemoveAbilityUse(); - if (LeaveDeadBodyUnreportable.GetBool()) - { - UnreportablePlayers.Add(target.PlayerId); - } + if (LeaveDeadBodyUnreportable.GetBool()) UnreportablePlayers.Add(target.PlayerId); - if (NotifyKiller.GetBool()) - { - killer.Notify(GetString("BloodhoundKillerNotify")); - } + if (NotifyKiller.GetBool()) killer.Notify(GetString("BloodhoundKillerNotify")); } else - { pc.Notify(GetString("OutOfAbilityUsesDoMoreTasks")); - } } else - { pc.Notify(GetString("BloodhoundNoTrack")); - } return false; } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (target != null && seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (target != null && seer.PlayerId != target.PlayerId) return string.Empty; - if (GameStates.IsMeeting || seer.PlayerId != BloodhoundId || hud) - { - return string.Empty; - } + if (GameStates.IsMeeting || seer.PlayerId != BloodhoundId || hud) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is not Bloodhound bh) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not Bloodhound bh) return string.Empty; return bh.BloodhoundTargets.Count > 0 ? bh.BloodhoundTargets.Select(targetId => TargetArrow.GetArrows(seer, targetId)).Aggregate(string.Empty, (current, arrow) => current + Utils.ColorString(seer.GetRoleColor(), arrow)) : Utils.ColorString(Color.white, LocateArrow.GetArrows(seer)); } diff --git a/Roles/Crewmate/Bodyguard.cs b/Roles/Crewmate/Bodyguard.cs index 06fe50eec..277d1a035 100644 --- a/Roles/Crewmate/Bodyguard.cs +++ b/Roles/Crewmate/Bodyguard.cs @@ -26,34 +26,27 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(8400, TabGroup.CrewmateRoles, CustomRoles.Bodyguard); + BodyguardProtectRadius = new FloatOptionItem(8410, "BodyguardProtectRadius", new(0.5f, 5f, 0.5f), 1.5f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bodyguard]) .SetValueFormat(OptionFormat.Multiplier); + BodyguardKillsKiller = new BooleanOptionItem(8411, "BodyguardKillsKiller", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bodyguard]); } public static bool OnAnyoneCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.IsCrewmate()) - { - return true; - } + if (killer.IsCrewmate()) return true; if (killer.PlayerId != target.PlayerId) { foreach (Bodyguard bodyguard in Instances) { - if (bodyguard.BodyguardPC.PlayerId == target.PlayerId) - { - continue; - } + if (bodyguard.BodyguardPC.PlayerId == target.PlayerId) continue; float dis = Vector2.Distance(bodyguard.BodyguardPC.Pos(), target.Pos()); - if (dis > BodyguardProtectRadius.GetFloat()) - { - return true; - } + if (dis > BodyguardProtectRadius.GetFloat()) return true; if (bodyguard.BodyguardPC.IsMadmate() && killer.Is(Team.Impostor)) { @@ -62,13 +55,9 @@ namespace EHR.Crewmate } if (BodyguardKillsKiller.GetBool() && bodyguard.BodyguardPC.RpcCheckAndMurder(killer, true)) - { bodyguard.BodyguardPC.Kill(killer); - } else - { killer.SetKillCooldown(); - } bodyguard.BodyguardPC.Suicide(PlayerState.DeathReason.Sacrifice, killer); Logger.Info($"{bodyguard.BodyguardPC.GetRealName()} stood up and died for {killer.GetRealName()}", "Bodyguard"); diff --git a/Roles/Crewmate/CameraMan.cs b/Roles/Crewmate/CameraMan.cs index c25ed65d8..0b6e057f7 100644 --- a/Roles/Crewmate/CameraMan.cs +++ b/Roles/Crewmate/CameraMan.cs @@ -26,17 +26,22 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.CameraMan); + VentCooldown = new FloatOptionItem(Id + 10, "VentCooldown", new(0f, 70f, 1f), 15f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.CameraMan]) .SetValueFormat(OptionFormat.Seconds); + UseLimitOpt = new IntegerOptionItem(Id + 11, "AbilityUseLimit", new(0, 20, 1), 1, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.CameraMan]) .SetValueFormat(OptionFormat.Times); + TPBackWhenMoveAway = new BooleanOptionItem(Id + 14, "TPBackWhenMoveAway", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.CameraMan]); + CameraManAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 12, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 1f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.CameraMan]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 13, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.CameraMan]) .SetValueFormat(OptionFormat.Times); @@ -45,6 +50,7 @@ namespace EHR.Crewmate public override void Init() { PlayerIdList = []; + CameraPosition = Main.CurrentMap switch { MapNames.Skeld => new(-13.5f, -5.5f), @@ -72,10 +78,7 @@ namespace EHR.Crewmate public override void OnEnterVent(PlayerControl pc, Vent vent) { - if (pc == null) - { - return; - } + if (pc == null) return; if (pc.GetAbilityUseLimit() >= 1) { @@ -84,47 +87,31 @@ namespace EHR.Crewmate LateTask.New(() => { BasePos = pc.Pos(); - if (pc.TP(CameraPosition)) - { - IsTeleported = true; - } + if (pc.TP(CameraPosition)) IsTeleported = true; }, 2f, "CameraMan Teleport"); } else - { pc.Notify(Translator.GetString("OutOfAbilityUsesDoMoreTasks")); - } } public override void OnPet(PlayerControl pc) { - if (pc == null) - { - return; - } + if (pc == null) return; if (pc.GetAbilityUseLimit() >= 1) { pc.RpcRemoveAbilityUse(); BasePos = pc.Pos(); - if (pc.TP(CameraPosition)) - { - IsTeleported = true; - } + if (pc.TP(CameraPosition)) IsTeleported = true; } else - { pc.Notify(Translator.GetString("OutOfAbilityUsesDoMoreTasks")); - } } public override void OnFixedUpdate(PlayerControl pc) { - if (!IsTeleported || !TPBackWhenMoveAway.GetBool() || !pc.IsAlive() || !GameStates.IsInTask || Vector2.Distance(pc.Pos(), CameraPosition) <= DisableDevice.UsableDistance) - { - return; - } + if (!IsTeleported || !TPBackWhenMoveAway.GetBool() || !pc.IsAlive() || !GameStates.IsInTask || Vector2.Distance(pc.Pos(), CameraPosition) <= DisableDevice.UsableDistance) return; IsTeleported = false; LateTask.New(() => pc.TP(BasePos), 2f, "CameraMan Teleport Back"); diff --git a/Roles/Crewmate/CandleLighter.cs b/Roles/Crewmate/CandleLighter.cs index 797e03939..02611afee 100644 --- a/Roles/Crewmate/CandleLighter.cs +++ b/Roles/Crewmate/CandleLighter.cs @@ -28,23 +28,30 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Ignitor); + OptionTaskStartVision = new FloatOptionItem(Id + 2, "CandleLighterStartVision", new(0.5f, 5f, 0.1f), 0.8f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ignitor]) .SetValueFormat(OptionFormat.Multiplier); + OptionCountStartTime = new IntegerOptionItem(Id + 3, "CandleLighterCountStartTime", new(0, 50, 5), 0, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ignitor]) .SetValueFormat(OptionFormat.Seconds); + OptionTaskEndVisionTime = new IntegerOptionItem(Id + 4, "CandleLighterEndVisionTime", new(20, 200, 10), 50, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ignitor]) .SetValueFormat(OptionFormat.Seconds); + OptionTaskEndVision = new FloatOptionItem(Id + 5, "CandleLighterEndVision", new(0f, 0.5f, 0.05f), 0.1f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ignitor]) .SetValueFormat(OptionFormat.Multiplier); + OptionTaskTimeMoveMeeting = new BooleanOptionItem(Id + 6, "CandleLighterTimeMoveMeeting", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ignitor]); + OptionTasksFinishedVision = new FloatOptionItem(Id + 7, "CandleLighterTasksFinishedVision", new(0.5f, 5f, 0.1f), 0.5f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ignitor]) .SetValueFormat(OptionFormat.Multiplier); + OverrideTasksData.Create(Id + 8, TabGroup.CrewmateRoles, CustomRoles.Ignitor); } @@ -65,71 +72,44 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte id) { float Vision; - if (!Active) - { - Vision = OptionTasksFinishedVision.GetFloat(); - } - else if (ElapsedTime > OptionTaskEndVisionTime.GetInt()) - { - Vision = OptionTaskStartVision.GetFloat(); - } - else - { - Vision = OptionTaskStartVision.GetFloat() * (ElapsedTime / OptionTaskEndVisionTime.GetInt()); - } - if (Vision <= OptionTaskEndVision.GetFloat()) - { - Vision = OptionTaskEndVision.GetFloat(); - } + if (!Active) + Vision = OptionTasksFinishedVision.GetFloat(); + else if (ElapsedTime > OptionTaskEndVisionTime.GetInt()) + Vision = OptionTaskStartVision.GetFloat(); + else + Vision = OptionTaskStartVision.GetFloat() * (ElapsedTime / OptionTaskEndVisionTime.GetInt()); + + if (Vision <= OptionTaskEndVision.GetFloat()) Vision = OptionTaskEndVision.GetFloat(); opt.SetFloat(FloatOptionNames.CrewLightMod, Vision); - if (Utils.IsActive(SystemTypes.Electrical)) - { - opt.SetFloat(FloatOptionNames.CrewLightMod, Vision * 5); - } + if (Utils.IsActive(SystemTypes.Electrical)) opt.SetFloat(FloatOptionNames.CrewLightMod, Vision * 5); } public override void OnTaskComplete(PlayerControl pc, int completedTaskCount, int totalTaskCount) { if (completedTaskCount + 1 >= totalTaskCount) - { Active = false; - } else - { ElapsedTime = OptionTaskEndVisionTime.GetInt(); - } pc.MarkDirtySettings(); } public override void OnFixedUpdate(PlayerControl player) { - if (!GameStates.IsInTask && !OptionTaskTimeMoveMeeting.GetBool()) - { - return; - } + if (!GameStates.IsInTask && !OptionTaskTimeMoveMeeting.GetBool()) return; - if (!Active) - { - return; - } + if (!Active) return; UpdateTime -= Time.fixedDeltaTime; - if (UpdateTime < 0) - { - UpdateTime = 1.0f; - } + if (UpdateTime < 0) UpdateTime = 1.0f; if (ElapsedTime > 0f) { ElapsedTime -= Time.fixedDeltaTime; - if (Math.Abs(UpdateTime - 1.0f) < 0.01f) - { - player.MarkDirtySettings(); - } + if (Math.Abs(UpdateTime - 1.0f) < 0.01f) player.MarkDirtySettings(); } } } diff --git a/Roles/Crewmate/Car.cs b/Roles/Crewmate/Car.cs index d04c6e398..a45f11970 100644 --- a/Roles/Crewmate/Car.cs +++ b/Roles/Crewmate/Car.cs @@ -21,6 +21,7 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(5647, TabGroup.CrewmateRoles, CustomRoles.Car); + PropelDistance = new FloatOptionItem(5649, "Car.PropelDistance", new(1f, 20f, 0.5f), 5f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Car]); } @@ -40,23 +41,14 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) - { - return; - } + if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) return; - if (Count++ < 5) - { - return; - } + if (Count++ < 5) return; Count = 0; Vector2 pos = pc.Pos(); - if (Vector2.Distance(pos, LastPosition) < 0.1f) - { - return; - } + if (Vector2.Distance(pos, LastPosition) < 0.1f) return; Direction direction = pos.x < LastPosition.x ? pos.y < LastPosition.y @@ -78,10 +70,7 @@ namespace EHR.Crewmate LastPosition = pos; - if (Main.AllAlivePlayerControls.Without(pc).FindFirst(x => Vector2.Distance(pos, x.Pos()) < 1.2f, out PlayerControl target) && CurrentlyPropelling.Add(target.PlayerId)) - { - Main.Instance.StartCoroutine(Propel(pc, target, direction)); - } + if (Main.AllAlivePlayerControls.Without(pc).FindFirst(x => Vector2.Distance(pos, x.Pos()) < 1.2f, out PlayerControl target) && CurrentlyPropelling.Add(target.PlayerId)) Main.Instance.StartCoroutine(Propel(pc, target, direction)); } private IEnumerator Propel(PlayerControl car, PlayerControl target, Direction direction) @@ -91,6 +80,7 @@ namespace EHR.Crewmate target.MarkDirtySettings(); Vector2 pos = car.Pos(); + Vector2 addVector = direction switch { Direction.Left => new(-0.25f, 0), @@ -106,12 +96,10 @@ namespace EHR.Crewmate float distance = PropelDistance.GetFloat(); Collider2D collider = target.Collider; + for (Vector2 newPos = target.Pos(); Vector2.Distance(pos, newPos) < distance && GameStates.IsInTask; newPos += addVector) { - if (PhysicsHelpers.AnythingBetween(collider, collider.bounds.center, newPos, Constants.ShipOnlyMask, false)) - { - break; - } + if (PhysicsHelpers.AnythingBetween(collider, collider.bounds.center, newPos, Constants.ShipOnlyMask, false)) break; target.TP(newPos, log: false); yield return new WaitForSeconds(0.05f); diff --git a/Roles/Crewmate/Catcher.cs b/Roles/Crewmate/Catcher.cs index 178b67d50..8dd7a9720 100644 --- a/Roles/Crewmate/Catcher.cs +++ b/Roles/Crewmate/Catcher.cs @@ -27,7 +27,7 @@ namespace EHR.Crewmate public override void SetupCustomOption() { - int id = 648650; + var id = 648650; const TabGroup tab = TabGroup.CrewmateRoles; const CustomRoles role = CustomRoles.Catcher; @@ -38,21 +38,27 @@ namespace EHR.Crewmate AbilityCooldown = new FloatOptionItem(++id, "AbilityCooldown", new(0f, 180f, 0.5f), 10f, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Seconds); + TrapPlaceDelay = new FloatOptionItem(++id, "Catcher.TrapPlaceDelay", new(0f, 180f, 1f), 5f, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Seconds); + CatchRange = new FloatOptionItem(++id, "Catcher.CatchRange", new(0f, 10f, 0.25f), 1.5f, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Multiplier); + MinPlayersTrappedToShowInfo = new IntegerOptionItem(++id, "Catcher.MinPlayersTrappedToShowInfo", new(1, 10, 1), 2, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Players); + AbilityUseLimit = new IntegerOptionItem(++id, "AbilityUseLimit", new(0, 20, 1), 3, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Times); + AbilityUseGainWithEachTaskCompleted = new FloatOptionItem(++id, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 1f, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(++id, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Times); @@ -76,10 +82,7 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (Options.UsePets.GetBool()) - { - return; - } + if (Options.UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = AbilityCooldown.GetFloat(); AURoleOptions.EngineerInVentMaxTime = 1f; @@ -87,10 +90,7 @@ namespace EHR.Crewmate private void PlaceTrap(PlayerControl pc) { - if (pc.GetAbilityUseLimit() < 1) - { - return; - } + if (pc.GetAbilityUseLimit() < 1) return; pc.RpcRemoveAbilityUse(); @@ -113,16 +113,10 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance || Options.UsePets.GetBool() || DelayStartTS == 0) - { - return; - } + if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance || Options.UsePets.GetBool() || DelayStartTS == 0) return; long now = Utils.TimeStamp; - if (now == LastUpdate) - { - return; - } + if (now == LastUpdate) return; LastUpdate = now; @@ -139,34 +133,22 @@ namespace EHR.Crewmate public override void OnCheckPlayerPosition(PlayerControl pc) { - if (CaughtRoles.ContainsKey(pc.PlayerId) || pc.PlayerId == CatcherId) - { - return; - } + if (CaughtRoles.ContainsKey(pc.PlayerId) || pc.PlayerId == CatcherId) return; Vector2 pos = pc.Pos(); float range = CatchRange.GetFloat(); - if (Traps.Keys.Any(x => Vector2.Distance(x, pos) <= range)) - { - CaughtRoles[pc.PlayerId] = pc.GetCustomRole(); - } + if (Traps.Keys.Any(x => Vector2.Distance(x, pos) <= range)) CaughtRoles[pc.PlayerId] = pc.GetCustomRole(); } public override void OnReportDeadBody() { - if (Traps.Count == 0) - { - return; - } + if (Traps.Count == 0) return; Traps.Values.Do(x => x.Despawn()); Traps = []; PlayerControl catcher = CatcherId.GetPlayer(); - if (catcher == null || !catcher.IsAlive()) - { - return; - } + if (catcher == null || !catcher.IsAlive()) return; LateTask.New(() => { @@ -176,9 +158,7 @@ namespace EHR.Crewmate Utils.SendMessage("\n", CatcherId, Translator.GetString("Catcher.CaughtRoles") + roles); } else - { Utils.SendMessage("\n", CatcherId, Translator.GetString("Catcher.NotEnoughCaughtRoles")); - } CaughtRoles = []; }, 10f, "Send Catcher Caught Roles"); @@ -196,10 +176,7 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != CatcherId || meeting || (seer.IsModClient() && !hud) || DelayStartTS == 0 || Options.UsePets.GetBool()) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != CatcherId || meeting || (seer.IsModClient() && !hud) || DelayStartTS == 0 || Options.UsePets.GetBool()) return string.Empty; return string.Format(Translator.GetString("Catcher.Suffix"), TrapPlaceDelay.GetInt() - (Utils.TimeStamp - DelayStartTS)); } diff --git a/Roles/Crewmate/Chameleon.cs b/Roles/Crewmate/Chameleon.cs index b8fb3b1d3..1b11965fc 100644 --- a/Roles/Crewmate/Chameleon.cs +++ b/Roles/Crewmate/Chameleon.cs @@ -17,29 +17,30 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Chameleon); + ChameleonCooldown = new FloatOptionItem(Id + 2, "ChameleonCooldown", new(1f, 60f, 1f), 20f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Chameleon]) .SetValueFormat(OptionFormat.Seconds); + ChameleonDuration = new FloatOptionItem(Id + 3, "ChameleonDuration", new(1f, 30f, 1f), 15f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Chameleon]) .SetValueFormat(OptionFormat.Seconds); + UseLimitOpt = new IntegerOptionItem(Id + 4, "AbilityUseLimit", new(0, 20, 1), 1, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Chameleon]) .SetValueFormat(OptionFormat.Times); + ChameleonAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 5, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.5f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Chameleon]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 6, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Chameleon]) .SetValueFormat(OptionFormat.Times); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Crewmate/Chef.cs b/Roles/Crewmate/Chef.cs index acc859565..ffabf57f7 100644 --- a/Roles/Crewmate/Chef.cs +++ b/Roles/Crewmate/Chef.cs @@ -34,28 +34,36 @@ namespace EHR.Crewmate public override void SetupCustomOption() { - int id = 648750; + var id = 648750; Options.SetupRoleOptions(id++, TabGroup.CrewmateRoles, CustomRoles.Chef); + EventTarget = new StringOptionItem(++id, "Chef.EventTarget", EventTargets, 0, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Chef]); + RottenTime = new IntegerOptionItem(++id, "Chef.RottenTime", new(1, 60, 1), 15, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Chef]) .SetValueFormat(OptionFormat.Seconds); + SpitOutTime = new IntegerOptionItem(++id, "Chef.SpitOutTime", new(1, 60, 1), 10, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Chef]) .SetValueFormat(OptionFormat.Seconds); + IncreasedSpeed = new FloatOptionItem(++id, "IncreasedSpeed", new(0f, 3f, 0.05f), 1.75f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Chef]) .SetValueFormat(OptionFormat.Multiplier); + IncreasedSpeedDuration = new IntegerOptionItem(++id, "IncreasedSpeedDuration", new(1, 60, 1), 10, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Chef]) .SetValueFormat(OptionFormat.Seconds); + IncreasedVision = new FloatOptionItem(++id, "IncreasedVision", new(0f, 3f, 0.05f), 1.5f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Chef]) .SetValueFormat(OptionFormat.Multiplier); + IncreasedVisionDuration = new IntegerOptionItem(++id, "IncreasedVisionDuration", new(1, 60, 1), 10, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Chef]) .SetValueFormat(OptionFormat.Seconds); + ShieldDuration = new IntegerOptionItem(++id, "ShieldDuration", new(1, 60, 1), 10, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Chef]) .SetValueFormat(OptionFormat.Seconds); @@ -78,10 +86,7 @@ namespace EHR.Crewmate public override void OnTaskComplete(PlayerControl pc, int completedTaskCount, int totalTaskCount) { - if (!pc.IsAlive()) - { - return; - } + if (!pc.IsAlive()) return; Vector2 pos = pc.Pos(); PlayerControl[] aapc = Main.AllAlivePlayerControls.Without(pc).ToArray(); @@ -158,15 +163,9 @@ namespace EHR.Crewmate public override void OnGlobalFixedUpdate(PlayerControl pc, bool lowLoad) { - if (lowLoad || !pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) - { - return; - } + if (lowLoad || !pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) return; - if (ActiveEvents.TryGetValue(pc.PlayerId, out List events)) - { - events.ToArray().Do(x => x.Update()); - } + if (ActiveEvents.TryGetValue(pc.PlayerId, out List events)) events.ToArray().Do(x => x.Update()); if (RottenFood.TryGetValue(pc.PlayerId, out long ts)) { @@ -240,21 +239,12 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (meeting) - { - return string.Empty; - } + if (meeting) return string.Empty; long now = Utils.TimeStamp; - if (ActiveEvents.TryGetValue(target.PlayerId, out List events) && (seer.PlayerId == target.PlayerId || seer.PlayerId == ChefId)) - { - return $"{string.Join('\n', events.Select(e => string.Format(Translator.GetString("ChefBoostSuffix"), GetEventString(e), e.Duration - (now - e.StartTimeStamp))))}"; - } + if (ActiveEvents.TryGetValue(target.PlayerId, out List events) && (seer.PlayerId == target.PlayerId || seer.PlayerId == ChefId)) return $"{string.Join('\n', events.Select(e => string.Format(Translator.GetString("ChefBoostSuffix"), GetEventString(e), e.Duration - (now - e.StartTimeStamp))))}"; - if (RottenFood.TryGetValue(seer.PlayerId, out long ts) && seer.PlayerId == target.PlayerId) - { - return string.Format(Translator.GetString("ChefRottenSuffix"), RottenTime.GetInt() - (now - ts)); - } + if (RottenFood.TryGetValue(seer.PlayerId, out long ts) && seer.PlayerId == target.PlayerId) return string.Format(Translator.GetString("ChefRottenSuffix"), RottenTime.GetInt() - (now - ts)); return string.Empty; @@ -281,13 +271,9 @@ namespace EHR.Crewmate protected void AddEventToDictionary() { if (!Instance.ActiveEvents.ContainsKey(Player.PlayerId)) - { Instance.ActiveEvents[Player.PlayerId] = [this]; - } else - { Instance.ActiveEvents[Player.PlayerId].Add(this); - } } } diff --git a/Roles/Crewmate/Clairvoyant.cs b/Roles/Crewmate/Clairvoyant.cs index c243f8fa5..52bc676d5 100644 --- a/Roles/Crewmate/Clairvoyant.cs +++ b/Roles/Crewmate/Clairvoyant.cs @@ -15,11 +15,13 @@ namespace EHR.Crewmate { Options.SetupRoleOptions(644970, TabGroup.CrewmateRoles, CustomRoles.Clairvoyant); - int i = 2; + var i = 2; + foreach (Options.GameStateInfo s in Enum.GetValues()) { Settings[s] = new BooleanOptionItem(644970 + i, $"GameStateCommand.Show{s}", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Clairvoyant]); + i++; } } @@ -36,10 +38,7 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (Options.UsePets.GetBool()) - { - return; - } + if (Options.UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = 1f; AURoleOptions.EngineerInVentMaxTime = 1f; diff --git a/Roles/Crewmate/Cleanser.cs b/Roles/Crewmate/Cleanser.cs index d9c305fb3..e82ca3377 100644 --- a/Roles/Crewmate/Cleanser.cs +++ b/Roles/Crewmate/Cleanser.cs @@ -27,11 +27,14 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Cleanser); + CleanserUsesOpt = new IntegerOptionItem(Id + 10, "MaxCleanserUses", new(1, 14, 1), 3, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Cleanser]) .SetValueFormat(OptionFormat.Times); + CleansedCanGetAddon = new BooleanOptionItem(Id + 11, "CleansedCanGetAddon", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Cleanser]); + CancelVote = CreateVoteCancellingUseSetting(Id + 12, CustomRoles.Cleanser, TabGroup.CrewmateRoles); } @@ -63,10 +66,7 @@ namespace EHR.Crewmate public void SendRPC(byte playerId) { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetCleanserCleanLimit, SendOption.Reliable); writer.Write(playerId); @@ -77,10 +77,7 @@ namespace EHR.Crewmate public static void ReceiveRPC(MessageReader reader) { byte CleanserId = reader.ReadByte(); - if (Main.PlayerStates[CleanserId].Role is not Cleanser cs) - { - return; - } + if (Main.PlayerStates[CleanserId].Role is not Cleanser cs) return; int Limit = reader.ReadInt32(); cs.CleanserUses = Limit; @@ -88,16 +85,10 @@ namespace EHR.Crewmate public override bool OnVote(PlayerControl voter, PlayerControl target) { - if (DidVote[voter.PlayerId] || Main.DontCancelVoteList.Contains(voter.PlayerId)) - { - return false; - } + if (DidVote[voter.PlayerId] || Main.DontCancelVoteList.Contains(voter.PlayerId)) return false; DidVote[voter.PlayerId] = true; - if (CleanserUses >= CleanserUsesOpt.GetInt()) - { - return false; - } + if (CleanserUses >= CleanserUsesOpt.GetInt()) return false; if (target.PlayerId == voter.PlayerId) { @@ -105,10 +96,7 @@ namespace EHR.Crewmate return false; } - if (CleanserTarget != byte.MaxValue) - { - return false; - } + if (CleanserTarget != byte.MaxValue) return false; CleanserUses++; CleanserTarget = target.PlayerId; @@ -123,17 +111,11 @@ namespace EHR.Crewmate public override void AfterMeetingTasks() { - if (CleanserTarget == byte.MaxValue || CleanserId == byte.MaxValue) - { - return; - } + if (CleanserTarget == byte.MaxValue || CleanserId == byte.MaxValue) return; DidVote[CleanserId] = false; PlayerControl targetPc = Utils.GetPlayerById(CleanserTarget); - if (targetPc == null) - { - return; - } + if (targetPc == null) return; targetPc.RpcSetCustomRole(CustomRoles.Cleansed); Logger.Info($"Removed all the add ons of {targetPc.GetNameWithRole().RemoveHtmlTags()}", "Cleanser"); diff --git a/Roles/Crewmate/Convener.cs b/Roles/Crewmate/Convener.cs index d66ee5009..ea03fa051 100644 --- a/Roles/Crewmate/Convener.cs +++ b/Roles/Crewmate/Convener.cs @@ -17,12 +17,15 @@ namespace EHR.Crewmate { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Convener); CD = Options.CreateCDSetting(Id + 2, TabGroup.CrewmateRoles, CustomRoles.Convener); + Limit = new IntegerOptionItem(Id + 3, "AbilityUseLimit", new(0, 20, 1), 0, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Convener]) .SetValueFormat(OptionFormat.Times); + ConvenerAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 4, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.4f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Convener]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 5, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Convener]) .SetValueFormat(OptionFormat.Times); @@ -41,10 +44,7 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (Options.UsePets.GetBool()) - { - return; - } + if (Options.UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = CD.GetFloat(); AURoleOptions.EngineerInVentMaxTime = 1f; @@ -62,15 +62,10 @@ namespace EHR.Crewmate private static void PullEveryone(PlayerControl pc, int ventId = 0, bool isPet = false) { - if (pc == null || pc.GetAbilityUseLimit() < 1f) - { - return; - } + if (pc == null || pc.GetAbilityUseLimit() < 1f) return; if (isPet) - { Utils.TPAll(pc.Pos()); - } else { LateTask.New(() => pc.MyPhysics.RpcBootFromVent(ventId), 0.5f, "Convener RpcBootFromVent"); diff --git a/Roles/Crewmate/CopyCat.cs b/Roles/Crewmate/CopyCat.cs index 7c7513aef..21db31b23 100644 --- a/Roles/Crewmate/CopyCat.cs +++ b/Roles/Crewmate/CopyCat.cs @@ -24,16 +24,21 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.CopyCat); + KillCooldown = new FloatOptionItem(Id + 10, "CopyCatCopyCooldown", new(0f, 60f, 1f), 15f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.CopyCat]) .SetValueFormat(OptionFormat.Seconds); + CanKill = new BooleanOptionItem(Id + 11, "CopyCatCanKill", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.CopyCat]); + CopyCrewVar = new BooleanOptionItem(Id + 13, "CopyCrewVar", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.CopyCat]); + MiscopyLimitOpt = new IntegerOptionItem(Id + 12, "CopyCatMiscopyLimit", new(0, 14, 1), 2, TabGroup.CrewmateRoles) .SetParent(CanKill) .SetValueFormat(OptionFormat.Times); + UsePet = CreatePetUseSetting(Id + 14, CustomRoles.CopyCat); } @@ -66,6 +71,7 @@ namespace EHR.Crewmate private void ResetRole() { CustomRoles role = CopyCatPC.GetCustomRole(); + // Remove settings for current role switch (role) { diff --git a/Roles/Crewmate/CrewmateVanillaRoles.cs b/Roles/Crewmate/CrewmateVanillaRoles.cs index 4516c8f8b..d6adfdaea 100644 --- a/Roles/Crewmate/CrewmateVanillaRoles.cs +++ b/Roles/Crewmate/CrewmateVanillaRoles.cs @@ -19,35 +19,49 @@ namespace EHR.Crewmate public void SetupCustomOption() { SetupRoleOptions(5020, Tab, CustomRoles.CrewmateEHR); + VanillaCrewmateCannotBeGuessed = new BooleanOptionItem(5022, "VanillaCrewmateCannotBeGuessed", false, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.CrewmateEHR]); + SetupRoleOptions(5000, Tab, CustomRoles.EngineerEHR); + EngineerCD = new FloatOptionItem(5002, "VentCooldown", new(1f, 250f, 1f), 30f, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.EngineerEHR]) .SetValueFormat(OptionFormat.Seconds); + EngineerDur = new FloatOptionItem(5003, "MaxInVentTime", new(1f, 250f, 1f), 15f, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.EngineerEHR]) .SetValueFormat(OptionFormat.Seconds); + SetupRoleOptions(5040, Tab, CustomRoles.NoisemakerEHR); + NoiseMakerImpostorAlert = new BooleanOptionItem(5042, "NoisemakerImpostorAlert", false, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.NoisemakerEHR]); + NoisemakerAlertDuration = new FloatOptionItem(5043, "NoisemakerAlertDuration", new(1f, 250f, 1f), 5f, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.NoisemakerEHR]) .SetValueFormat(OptionFormat.Seconds); + SetupRoleOptions(5100, Tab, CustomRoles.ScientistEHR); + ScientistCD = new FloatOptionItem(5102, "VitalsCooldown", new(1f, 250f, 1f), 3f, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ScientistEHR]) .SetValueFormat(OptionFormat.Seconds); + ScientistDur = new FloatOptionItem(5103, "VitalsDuration", new(1f, 250f, 1f), 15f, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ScientistEHR]) .SetValueFormat(OptionFormat.Seconds); + SetupRoleOptions(5060, Tab, CustomRoles.TrackerEHR); + TrackerCooldown = new FloatOptionItem(5062, "TrackerCooldown", new(1f, 250f, 1f), 25f, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.TrackerEHR]) .SetValueFormat(OptionFormat.Seconds); + TrackerDuration = new FloatOptionItem(5063, "TrackerDuration", new(1f, 250f, 1f), 20f, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.TrackerEHR]) .SetValueFormat(OptionFormat.Seconds); + TrackerDelay = new FloatOptionItem(5064, "TrackerDelay", new(1f, 250f, 1f), 5f, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.TrackerEHR]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/Crewmate/Crusader.cs b/Roles/Crewmate/Crusader.cs index 823815931..77c030068 100644 --- a/Roles/Crewmate/Crusader.cs +++ b/Roles/Crewmate/Crusader.cs @@ -21,12 +21,15 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Crusader); + SkillCooldown = new FloatOptionItem(Id + 10, "CrusaderSkillCooldown", new(2.5f, 60f, 2.5f), 30f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Crusader]) .SetValueFormat(OptionFormat.Seconds); + SkillLimitOpt = new IntegerOptionItem(Id + 11, "CrusaderSkillLimit", new(1, 10, 1), 1, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Crusader]) .SetValueFormat(OptionFormat.Times); + UsePet = Options.CreatePetUseSetting(Id + 12, CustomRoles.Crusader); } @@ -66,10 +69,7 @@ namespace EHR.Crewmate public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.GetAbilityUseLimit() <= 0) - { - return false; - } + if (killer.GetAbilityUseLimit() <= 0) return false; ForCrusade.Remove(target.PlayerId); ForCrusade.Add(target.PlayerId); diff --git a/Roles/Crewmate/CyberStar.cs b/Roles/Crewmate/CyberStar.cs index 140c40375..8e2ce6523 100644 --- a/Roles/Crewmate/CyberStar.cs +++ b/Roles/Crewmate/CyberStar.cs @@ -9,18 +9,16 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(5300, TabGroup.CrewmateRoles, CustomRoles.CyberStar); + ImpKnowCyberStarDead = new BooleanOptionItem(5400, "ImpKnowCyberStarDead", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.CyberStar]); + NeutralKnowCyberStarDead = new BooleanOptionItem(5500, "NeutralKnowCyberStarDead", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.CyberStar]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Crewmate/Dad.cs b/Roles/Crewmate/Dad.cs index 89e9b2855..635fc29b3 100644 --- a/Roles/Crewmate/Dad.cs +++ b/Roles/Crewmate/Dad.cs @@ -59,7 +59,7 @@ namespace EHR.Crewmate public override void SetupCustomOption() { - int id = 648450; + var id = 648450; const TabGroup tab = TabGroup.CrewmateRoles; const CustomRoles role = CustomRoles.Dad; @@ -70,36 +70,48 @@ namespace EHR.Crewmate AlcoholDecreaseOnKilled = new IntegerOptionItem(++id, "Dad.AlcoholDecreaseOnKilled", new(0, 100, 1), 10, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Percent); + AlcoholDecreaseOnVotedOut = new IntegerOptionItem(++id, "Dad.AlcoholDecreaseOnVotedOut", new(0, 100, 1), 5, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Percent); + NormalAlcoholDecreaseFrequency = new IntegerOptionItem(++id, "Dad.NormalAlcoholDecreaseFrequency", new(1, 60, 1), 10, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Seconds); + NormalAlcoholDecreaseValue = new IntegerOptionItem(++id, "Dad.NormalAlcoholDecreaseValue", new(0, 100, 1), 1, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Percent); + AlcoholIncreaseOnBeerPurchase = new IntegerOptionItem(++id, "Dad.AlcoholIncreaseOnBeerPurchase", new(0, 100, 1), 10, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Percent); + ShowWarningWhenAlcoholIsBelow = new IntegerOptionItem(++id, "Dad.ShowWarningWhenAlcoholIsBelow", new(0, 100, 1), 20, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Percent); + StartingAlcohol = new IntegerOptionItem(++id, "Dad.StartingAlcohol", new(0, 100, 1), 15, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Percent); + StartingMoney = new IntegerOptionItem(++id, "Dad.StartingMoney", new(0, 100, 1), 0, tab) .SetParent(parent); + MoneyGainOnTaskComplete = new IntegerOptionItem(++id, "Dad.MoneyGainOnTaskComplete", new(0, 100, 1), 15, tab) .SetParent(parent); + AlcoholCost = new IntegerOptionItem(++id, "Dad.AlcoholCost", new(0, 100, 1), 10, tab) .SetParent(parent); + SuperVisionDuration = new IntegerOptionItem(++id, "Dad.SuperVisionDuration", new(1, 90, 1), 20, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Seconds); + GivingDrinkRange = new FloatOptionItem(++id, "Dad.GivingDrinkRange", new(0.5f, 10f, 0.5f), 4f, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Multiplier); + DrunkRoleIncorrectChance = new IntegerOptionItem(++id, "Dad.DrunkRoleIncorrectChance", new(0, 100, 1), 50, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Percent); @@ -176,13 +188,11 @@ namespace EHR.Crewmate { int chance = DrunkRoleIncorrectChance.GetInt(); List allRoles = Enum.GetValues().Where(x => x.IsEnable() && !x.IsAdditionRole() && !HnSManager.AllHnSRoles.Contains(x) && !x.IsForOtherGameMode()).ToList(); + foreach (byte id in DrunkPlayers) { PlayerControl pc = Utils.GetPlayerById(id); - if (pc == null) - { - continue; - } + if (pc == null) continue; CustomRoles selfRole = Main.PlayerStates[id].MainRole; CustomRoles rndRole = allRoles.Without(selfRole).RandomElement(); @@ -201,10 +211,7 @@ namespace EHR.Crewmate public override void AfterMeetingTasks() { - if (UsingAbilities.Contains(Ability.GoForMilk)) - { - LateTask.New(() => Utils.GetPlayerById(DadId)?.TP(Pelican.GetBlackRoomPS()), 1f, log: false); - } + if (UsingAbilities.Contains(Ability.GoForMilk)) LateTask.New(() => Utils.GetPlayerById(DadId)?.TP(Pelican.GetBlackRoomPS()), 1f, log: false); } public override void OnPet(PlayerControl pc) @@ -215,10 +222,7 @@ namespace EHR.Crewmate public override void OnCoEnterVent(PlayerPhysics physics, int ventId) { - if (ventId == Shop.Id || UsingAbilities.Contains(Ability.Sleep)) - { - return; - } + if (ventId == Shop.Id || UsingAbilities.Contains(Ability.Sleep)) return; if (AbilityAlcoholRequirement[SelectedAbility].GetInt() > Alcohol) { @@ -271,13 +275,11 @@ namespace EHR.Crewmate public override void OnExitVent(PlayerControl pc, Vent vent) { - if (vent.Id != Shop.Id) - { - return; - } + if (vent.Id != Shop.Id) return; int cost = AlcoholCost.GetInt(); int get = AlcoholIncreaseOnBeerPurchase.GetInt(); + for (float money = pc.GetAbilityUseLimit(); money >= cost; money -= cost) { pc.SetAbilityUseLimit(money - cost); @@ -302,33 +304,22 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) - { - return; - } + if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) return; - if (Count++ < 15) - { - return; - } + if (Count++ < 15) return; Count = 0; Vector2 pos = pc.Pos(); - if (UsingAbilities.Contains(Ability.Rage) && Main.AllAlivePlayerControls.FindFirst(x => Vector2.Distance(pos, x.Pos()) < 1.3f, out PlayerControl target) && pc.RpcCheckAndMurder(target)) - { - UsingAbilities.Remove(Ability.Rage); - } + if (UsingAbilities.Contains(Ability.Rage) && Main.AllAlivePlayerControls.FindFirst(x => Vector2.Distance(pos, x.Pos()) < 1.3f, out PlayerControl target) && pc.RpcCheckAndMurder(target)) UsingAbilities.Remove(Ability.Rage); bool notify = Vector2.Distance(pc.Pos(), Shop.transform.position) < 2f; long now = Utils.TimeStamp; + if (now - LastUpdate < NormalAlcoholDecreaseFrequency.GetInt()) { - if (notify) - { - Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - } + if (notify) Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); return; } @@ -338,6 +329,7 @@ namespace EHR.Crewmate if (UsingAbilities.Contains(Ability.GoForMilk)) { MilkTimer--; + if (MilkTimer <= 0) { pc.TPToRandomVent(); @@ -353,19 +345,12 @@ namespace EHR.Crewmate pc.MarkDirtySettings(); } - if (UsingAbilities.Contains(Ability.Sleep)) - { - return; - } + if (UsingAbilities.Contains(Ability.Sleep)) return; if (UsingAbilities.Contains(Ability.BecomeGodOfAlcohol)) - { Alcohol += NormalAlcoholDecreaseValue.GetInt(); - } else - { Alcohol -= NormalAlcoholDecreaseValue.GetInt(); - } if (Alcohol <= 0) { @@ -383,16 +368,14 @@ namespace EHR.Crewmate Alcohol -= AlcoholDecreaseOnKilled.GetInt(); NotifyIfNecessary(target); }, 5f, log: false); + return false; } public static bool OnVotedOut(byte id) { Dad dad = Instances.FirstOrDefault(d => d.DadId == id); - if (dad == null) - { - return false; - } + if (dad == null) return false; dad.Alcohol -= AlcoholDecreaseOnVotedOut.GetInt(); dad.NotifyIfNecessary(Utils.GetPlayerById(dad.DadId)); @@ -408,25 +391,16 @@ namespace EHR.Crewmate public static bool OnAnyoneCheckMurderStart(PlayerControl target) { Dad dad = Instances.FirstOrDefault(d => d.DadId == target.PlayerId); - if (dad == null) - { - return false; - } + if (dad == null) return false; return dad.UsingAbilities.Contains(Ability.Sleep); } private void NotifyIfNecessary(PlayerControl pc, bool force = false) { - if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) - { - return; - } + if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) return; - if (force || Alcohol <= ShowWarningWhenAlcoholIsBelow.GetInt()) - { - Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - } + if (force || Alcohol <= ShowWarningWhenAlcoholIsBelow.GetInt()) Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); Utils.SendRPC(CustomRPC.SyncRoleData, DadId, 3, Alcohol); } @@ -450,12 +424,9 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != DadId || meeting || (seer.IsModClient() && !hud)) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != DadId || meeting || (seer.IsModClient() && !hud)) return string.Empty; - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); if (Vector2.Distance(seer.Pos(), Shop.transform.position) <= 2f) { @@ -465,28 +436,19 @@ namespace EHR.Crewmate if (Alcohol <= ShowWarningWhenAlcoholIsBelow.GetInt()) { - if (sb.Length > 0) - { - sb.Append('\n'); - } + if (sb.Length > 0) sb.Append('\n'); sb.Append(string.Format(Translator.GetString("Dad.LowAlcoholSuffix"), Alcohol)); } if (Arrows.Length > 0) { - if (sb.Length > 0) - { - sb.Append('\n'); - } + if (sb.Length > 0) sb.Append('\n'); sb.Append(Arrows); } - if (sb.Length > 0) - { - sb.Append("\n\n"); - } + if (sb.Length > 0) sb.Append("\n\n"); sb.Append(string.Format(Translator.GetString("Dad.SelectedAbilitySuffix"), Translator.GetString($"Dad.Ability.{SelectedAbility}"))); sb.Append('\n'); diff --git a/Roles/Crewmate/Demolitionist.cs b/Roles/Crewmate/Demolitionist.cs index d2bc90a98..8fccb3ab7 100644 --- a/Roles/Crewmate/Demolitionist.cs +++ b/Roles/Crewmate/Demolitionist.cs @@ -10,25 +10,24 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(5550, TabGroup.CrewmateRoles, CustomRoles.Demolitionist); + DemolitionistVentTime = new FloatOptionItem(5552, "DemolitionistVentTime", new(0f, 90f, 1f), 5f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Demolitionist]) .SetValueFormat(OptionFormat.Seconds); + DemolitionistKillerDiesOnMeetingCall = new BooleanOptionItem(5553, "DemolitionistKillerDiesOnMeetingCall", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Demolitionist]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } public static void OnDeath(PlayerControl killer, PlayerControl target) { killer.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Demolitionist), Translator.GetString("OnDemolitionistDead"))); killer.KillFlash(); + LateTask.New(() => { if (!killer.inVent && killer.PlayerId != target.PlayerId) @@ -42,13 +41,9 @@ namespace EHR.Crewmate else { if (killer.IsModClient()) - { RPC.PlaySoundRPC(killer.PlayerId, Sounds.TaskComplete); - } else - { killer.RpcGuardAndKill(killer); - } killer.SetKillCooldown(Main.AllPlayerKillCooldown[killer.PlayerId] - (DemolitionistVentTime.GetFloat() + 0.5f)); } diff --git a/Roles/Crewmate/Deputy.cs b/Roles/Crewmate/Deputy.cs index ef99ea213..7d08dc339 100644 --- a/Roles/Crewmate/Deputy.cs +++ b/Roles/Crewmate/Deputy.cs @@ -21,14 +21,19 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Deputy); + HandcuffCooldown = new FloatOptionItem(Id + 10, "DeputyHandcuffCooldown", new(0f, 60f, 2.5f), 17.5f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Deputy]) .SetValueFormat(OptionFormat.Seconds); + DeputyHandcuffCDForTarget = new FloatOptionItem(Id + 14, "DeputyHandcuffCDForTarget", new(0f, 180f, 2.5f), 15f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Deputy]) .SetValueFormat(OptionFormat.Seconds); + HandcuffMax = new IntegerOptionItem(Id + 12, "DeputyHandcuffMax", new(1, 20, 1), 4, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Deputy]) .SetValueFormat(OptionFormat.Times); + DeputyHandcuffDelay = new IntegerOptionItem(Id + 11, "DeputyHandcuffDelay", new(0, 20, 1), 5, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Deputy]) .SetValueFormat(OptionFormat.Seconds); + UsePet = CreatePetUseSetting(Id + 13, CustomRoles.Deputy); } @@ -65,10 +70,7 @@ namespace EHR.Crewmate public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.GetAbilityUseLimit() < 1) - { - return false; - } + if (killer.GetAbilityUseLimit() < 1) return false; if (target != null && !target.Is(CustomRoles.Deputy)) { @@ -82,15 +84,9 @@ namespace EHR.Crewmate { target.SetKillCooldown(DeputyHandcuffCDForTarget.GetFloat()); target.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Deputy), GetString("HandcuffedByDeputy"))); - if (target.IsModClient()) - { - target.RpcResetAbilityCooldown(); - } + if (target.IsModClient()) target.RpcResetAbilityCooldown(); - if (!target.IsModClient()) - { - target.RpcGuardAndKill(target); - } + if (!target.IsModClient()) target.RpcGuardAndKill(target); } }, DeputyHandcuffDelay.GetInt(), "DeputyHandcuffDelay"); diff --git a/Roles/Crewmate/Detective.cs b/Roles/Crewmate/Detective.cs index d1bf9f1a6..394ca401d 100644 --- a/Roles/Crewmate/Detective.cs +++ b/Roles/Crewmate/Detective.cs @@ -18,23 +18,23 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(6600, TabGroup.CrewmateRoles, CustomRoles.Detective); + DetectiveCanknowKiller = new BooleanOptionItem(6610, "DetectiveCanknowKiller", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Detective]); + DetectiveCanknowDeathReason = new BooleanOptionItem(6611, "DetectiveCanknowDeathReason", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Detective]); + DetectiveCanknowAddons = new BooleanOptionItem(6612, "DetectiveCanknowAddons", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Detective]); + DetectiveCanknowKillTime = new BooleanOptionItem(6613, "DetectiveCanknowKillTime", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Detective]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } public static void OnReportDeadBody(PlayerControl player, PlayerControl tpc) { @@ -43,25 +43,16 @@ namespace EHR.Crewmate if (DetectiveCanknowKiller.GetBool()) { PlayerControl realKiller = tpc.GetRealKiller(); + if (realKiller == null) - { msg += ";" + Translator.GetString("DetectiveNoticeKillerNotFound"); - } else - { msg += ";" + string.Format(Translator.GetString("DetectiveNoticeKiller"), realKiller.GetCustomRole().ToColoredString()); - } } - if (DetectiveCanknowDeathReason.GetBool()) - { - msg += ";" + string.Format(Translator.GetString("DetectiveNoticeDeathReason"), Translator.GetString($"DeathReason.{Main.PlayerStates[tpc.PlayerId].deathReason}")); - } + if (DetectiveCanknowDeathReason.GetBool()) msg += ";" + string.Format(Translator.GetString("DetectiveNoticeDeathReason"), Translator.GetString($"DeathReason.{Main.PlayerStates[tpc.PlayerId].deathReason}")); - if (DetectiveCanknowAddons.GetBool()) - { - msg += ";" + string.Format(Translator.GetString("DetectiveNoticeAddons"), string.Join(", ", tpc.GetCustomSubRoles().Select(x => x.ToColoredString()))); - } + if (DetectiveCanknowAddons.GetBool()) msg += ";" + string.Format(Translator.GetString("DetectiveNoticeAddons"), string.Join(", ", tpc.GetCustomSubRoles().Select(x => x.ToColoredString()))); if (DetectiveCanknowKillTime.GetBool()) { diff --git a/Roles/Crewmate/Detour.cs b/Roles/Crewmate/Detour.cs index 64d196c23..9e4a21df4 100644 --- a/Roles/Crewmate/Detour.cs +++ b/Roles/Crewmate/Detour.cs @@ -9,12 +9,8 @@ Options.SetupRoleOptions(5590, TabGroup.CrewmateRoles, CustomRoles.Detour); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Crewmate/Dictator.cs b/Roles/Crewmate/Dictator.cs index 30b5be777..f7ab5a076 100644 --- a/Roles/Crewmate/Dictator.cs +++ b/Roles/Crewmate/Dictator.cs @@ -9,12 +9,8 @@ Options.SetupRoleOptions(9100, TabGroup.CrewmateRoles, CustomRoles.Dictator); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Crewmate/Divinator.cs b/Roles/Crewmate/Divinator.cs index 0aea97e1f..914f4111a 100644 --- a/Roles/Crewmate/Divinator.cs +++ b/Roles/Crewmate/Divinator.cs @@ -30,21 +30,28 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Divinator); + CheckLimitOpt = new IntegerOptionItem(Id + 10, "DivinatorSkillLimit", new(0, 20, 1), 1, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Divinator]) .SetValueFormat(OptionFormat.Times); + AccurateCheckMode = new BooleanOptionItem(Id + 12, "AccurateCheckMode", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Divinator]); + ShowSpecificRole = new BooleanOptionItem(Id + 13, "ShowSpecificRole", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Divinator]); + HideVote = new BooleanOptionItem(Id + 14, "DivinatorHideVote", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Divinator]); + AbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 15, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 1f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Divinator]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 16, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Divinator]) .SetValueFormat(OptionFormat.Times); + CancelVote = CreateVoteCancellingUseSetting(Id + 11, CustomRoles.Divinator, TabGroup.CrewmateRoles); OverrideTasksData.Create(Id + 21, TabGroup.CrewmateRoles, CustomRoles.Divinator); } @@ -64,6 +71,7 @@ namespace EHR.Crewmate { PlayerControl[] players = Main.AllPlayerControls; int rolesNeeded = players.Length * (RolesPerCategory - 1); + (List RoleList, PlayerControl Player)[] roleList = Enum.GetValues() .Where(x => !x.IsVanilla() && !x.IsAdditionRole() && x is not CustomRoles.GM and not CustomRoles.Convict and not CustomRoles.NotAssigned && !x.IsForOtherGameMode() && !CustomRoleSelector.RoleResult.ContainsValue(x)) .OrderBy(x => x.IsEnable() ? IRandom.Instance.Next(10) : IRandom.Instance.Next(10, 100)) @@ -71,6 +79,7 @@ namespace EHR.Crewmate .Chunk(RolesPerCategory - 1) .Zip(players, (Array, Player) => (RoleList: Array.ToList(), Player)) .ToArray(); + roleList.Do(x => x.RoleList.Insert(IRandom.Instance.Next(x.RoleList.Count), x.Player.GetCustomRole())); AllPlayerRoleList = roleList.ToDictionary(x => x.Player.PlayerId, x => x.RoleList.ToHashSet()); @@ -80,15 +89,9 @@ namespace EHR.Crewmate public override bool OnVote(PlayerControl player, PlayerControl target) { - if (player == null || target == null) - { - return false; - } + if (player == null || target == null) return false; - if (DidVote.Contains(player.PlayerId) || Main.DontCancelVoteList.Contains(player.PlayerId)) - { - return false; - } + if (DidVote.Contains(player.PlayerId) || Main.DontCancelVoteList.Contains(player.PlayerId)) return false; DidVote.Add(player.PlayerId); @@ -109,9 +112,7 @@ namespace EHR.Crewmate string msg; if ((player.AllTasksCompleted() || AccurateCheckMode.GetBool()) && ShowSpecificRole.GetBool()) - { msg = string.Format(GetString("DivinatorCheck.TaskDone"), target.GetRealName(), target.GetCustomRole().ToColoredString()); - } else { string roles = string.Join(", ", AllPlayerRoleList[target.PlayerId].Select(x => x.ToColoredString())); diff --git a/Roles/Crewmate/Doctor.cs b/Roles/Crewmate/Doctor.cs index a523100d8..6753d5ab5 100644 --- a/Roles/Crewmate/Doctor.cs +++ b/Roles/Crewmate/Doctor.cs @@ -10,9 +10,11 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(5600, TabGroup.CrewmateRoles, CustomRoles.Doctor); + Options.DoctorTaskCompletedBatteryCharge = new FloatOptionItem(5610, "DoctorTaskCompletedBatteryCharge", new(0f, 300f, 1f), 90f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Doctor]) .SetValueFormat(OptionFormat.Seconds); + Options.DoctorVisibleToEveryone = new BooleanOptionItem(5611, "DoctorVisibleToEveryone", false, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Doctor]); } diff --git a/Roles/Crewmate/DonutDelivery.cs b/Roles/Crewmate/DonutDelivery.cs index 2569249a3..93d8a5b08 100644 --- a/Roles/Crewmate/DonutDelivery.cs +++ b/Roles/Crewmate/DonutDelivery.cs @@ -30,26 +30,35 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.DonutDelivery); + CD = new FloatOptionItem(Id + 10, "DonutDeliverCD", new(2.5f, 60f, 2.5f), 30f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.DonutDelivery]) .SetValueFormat(OptionFormat.Seconds); + UseLimit = new IntegerOptionItem(Id + 12, "AbilityUseLimit", new(1, 20, 1), 5, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.DonutDelivery]) .SetValueFormat(OptionFormat.Times); + SpeedEffect = new BooleanOptionItem(Id + 14, "DonutDeliverSpeedEffect", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.DonutDelivery]); + SEDelay = new FloatOptionItem(Id + 15, "DonutDeliverSEDelay", new(0f, 30f, 0.5f), 3f, TabGroup.CrewmateRoles) .SetParent(SpeedEffect) .SetValueFormat(OptionFormat.Seconds); + SEAmount = new FloatOptionItem(Id + 16, "DonutDeliverSEAmount", new(0.05f, 3f, 0.05f), 0.5f, TabGroup.CrewmateRoles) .SetParent(SpeedEffect); + SEDuration = new FloatOptionItem(Id + 17, "DonutDeliverSEDuration", new(0.5f, 60f, 0.5f), 5f, TabGroup.CrewmateRoles) .SetParent(SpeedEffect) .SetValueFormat(OptionFormat.Seconds); + SEEvilsGetDecreased = new BooleanOptionItem(Id + 18, "DonutDeliverSEEvilsGetDecreased", true, TabGroup.CrewmateRoles) .SetParent(SpeedEffect); + SEEvilsDecreaseAmount = new FloatOptionItem(Id + 19, "DonutDeliverSEEvilsDecreaseAmount", new(0.1f, 5f, 0.1f), 1f, TabGroup.CrewmateRoles) .SetParent(SEEvilsGetDecreased); + UsePet = CreatePetUseSetting(Id + 13, CustomRoles.DonutDelivery); } @@ -84,10 +93,7 @@ namespace EHR.Crewmate public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!IsEnable || killer == null || target == null || killer.GetAbilityUseLimit() <= 0) - { - return false; - } + if (!IsEnable || killer == null || target == null || killer.GetAbilityUseLimit() <= 0) return false; killer.RpcRemoveAbilityUse(); @@ -103,13 +109,9 @@ namespace EHR.Crewmate LateTask.New(() => { if (target.IsCrewmate() || target.GetCustomRole().IsNonNK() || !SEEvilsGetDecreased.GetBool()) - { Main.AllPlayerSpeed[target.PlayerId] += SEAmount.GetFloat(); - } else - { Main.AllPlayerSpeed[target.PlayerId] -= SEEvilsDecreaseAmount.GetFloat(); - } target.MarkDirtySettings(); @@ -133,12 +135,8 @@ namespace EHR.Crewmate public static bool IsUnguessable(PlayerControl guesser, PlayerControl target) { foreach (DonutDelivery instance in Instances) - { if (instance.DonutDeliveryId == target.PlayerId && instance.Players.Contains(guesser.PlayerId)) - { return true; - } - } return false; } diff --git a/Roles/Crewmate/Doormaster.cs b/Roles/Crewmate/Doormaster.cs index 21ebe481e..94e9db859 100644 --- a/Roles/Crewmate/Doormaster.cs +++ b/Roles/Crewmate/Doormaster.cs @@ -21,13 +21,17 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Doormaster); + VentCooldown = new FloatOptionItem(Id + 10, "VentCooldown", new(0f, 70f, 1f), 15f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Doormaster]) .SetValueFormat(OptionFormat.Seconds); + UseLimitOpt = new IntegerOptionItem(Id + 11, "AbilityUseLimit", new(0, 20, 1), 1, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Doormaster]) .SetValueFormat(OptionFormat.Times); + DoormasterAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 12, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 1f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Doormaster]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 13, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Doormaster]) .SetValueFormat(OptionFormat.Times); @@ -46,10 +50,7 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = VentCooldown.GetFloat(); AURoleOptions.EngineerInVentMaxTime = 1f; @@ -67,15 +68,9 @@ namespace EHR.Crewmate private static void OpenDoors(PlayerControl pc) { - if (pc == null) - { - return; - } + if (pc == null) return; - if (!pc.Is(CustomRoles.Doormaster)) - { - return; - } + if (!pc.Is(CustomRoles.Doormaster)) return; if (pc.GetAbilityUseLimit() >= 1) { @@ -83,9 +78,7 @@ namespace EHR.Crewmate DoorsReset.OpenAllDoors(); } else - { pc.Notify(Translator.GetString("OutOfAbilityUsesDoMoreTasks")); - } } } } \ No newline at end of file diff --git a/Roles/Crewmate/DovesOfNeace.cs b/Roles/Crewmate/DovesOfNeace.cs index efc0f4ebc..3efa89f47 100644 --- a/Roles/Crewmate/DovesOfNeace.cs +++ b/Roles/Crewmate/DovesOfNeace.cs @@ -14,15 +14,19 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(7700, TabGroup.CrewmateRoles, CustomRoles.DovesOfNeace); + DovesOfNeaceCooldown = new FloatOptionItem(7710, "DovesOfNeaceCooldown", new(0f, 180f, 1f), 7f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.DovesOfNeace]) .SetValueFormat(OptionFormat.Seconds); + DovesOfNeaceMaxOfUseage = new IntegerOptionItem(7711, "DovesOfNeaceMaxOfUseage", new(0, 180, 1), 0, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.DovesOfNeace]) .SetValueFormat(OptionFormat.Times); + DovesOfNeaceAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(7712, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.DovesOfNeace]) .SetValueFormat(OptionFormat.Times); + DovesOfNeaceAbilityChargesWhenFinishedTasks = new FloatOptionItem(7713, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.DovesOfNeace]) .SetValueFormat(OptionFormat.Times); @@ -42,10 +46,7 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = DovesOfNeaceCooldown.GetFloat(); AURoleOptions.EngineerInVentMaxTime = 1f; @@ -54,13 +55,9 @@ namespace EHR.Crewmate public override void SetButtonTexts(HudManager hud, byte id) { if (UsePets.GetBool()) - { hud.PetButton.buttonLabelText.text = Translator.GetString("DovesOfNeaceVentButtonText"); - } else - { hud.AbilityButton.buttonLabelText.text = Translator.GetString("DovesOfNeaceVentButtonText"); - } } public override void OnPet(PlayerControl pc) @@ -83,6 +80,7 @@ namespace EHR.Crewmate pc.RpcRemoveAbilityUse(); bool isMadMate = pc.Is(CustomRoles.Madmate); + Main.AllAlivePlayerControls .Where(x => isMadMate ? x.CanUseKillButton() && x.IsCrewmate() : x.CanUseKillButton()) .Do(x => @@ -90,13 +88,11 @@ namespace EHR.Crewmate x.RPCPlayCustomSound("Dove"); x.ResetKillCooldown(); x.SetKillCooldown(); - if (Main.PlayerStates[x.PlayerId].Role is SerialKiller sk) - { - sk.OnReportDeadBody(); - } + if (Main.PlayerStates[x.PlayerId].Role is SerialKiller sk) sk.OnReportDeadBody(); x.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.DovesOfNeace), Translator.GetString("DovesOfNeaceSkillNotify"))); }); + pc.RPCPlayCustomSound("Dove"); pc.Notify(string.Format(Translator.GetString("DovesOfNeaceOnGuard"), pc.GetAbilityUseLimit())); } diff --git a/Roles/Crewmate/Drainer.cs b/Roles/Crewmate/Drainer.cs index 11401537b..3ce21533e 100644 --- a/Roles/Crewmate/Drainer.cs +++ b/Roles/Crewmate/Drainer.cs @@ -22,15 +22,19 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Drainer); + VentCD = new IntegerOptionItem(Id + 10, "VentCooldown", new(1, 60, 1), 30, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Drainer]) .SetValueFormat(OptionFormat.Seconds); + UseLimit = new IntegerOptionItem(Id + 11, "AbilityUseLimit", new(1, 20, 1), 1, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Drainer]) .SetValueFormat(OptionFormat.Times); + DrainerAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 12, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.5f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Drainer]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 13, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Drainer]) .SetValueFormat(OptionFormat.Times); @@ -55,68 +59,45 @@ namespace EHR.Crewmate public static void OnAnyoneExitVent(PlayerControl pc) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; - if (pc != null) - { - PlayersInVents.Remove(pc.PlayerId); - } + if (pc != null) PlayersInVents.Remove(pc.PlayerId); } public override void OnEnterVent(PlayerControl pc, Vent vent) { - if (pc.GetAbilityUseLimit() <= 0) - { - return; - } + if (pc.GetAbilityUseLimit() <= 0) return; pc.RpcRemoveAbilityUse(); Vent[] vents = vent.NearbyVents.Where(v => v != null).Append(vent).ToArray(); - foreach (Vent ventToDrain in vents) - { - KillPlayersInVent(pc, ventToDrain); - } + foreach (Vent ventToDrain in vents) KillPlayersInVent(pc, ventToDrain); } public static void OnAnyoneEnterVent(PlayerControl pc, Vent vent) { - if (!AmongUsClient.Instance.AmHost || pc == null || vent == null || pc.Is(CustomRoles.Drainer)) - { - return; - } + if (!AmongUsClient.Instance.AmHost || pc == null || vent == null || pc.Is(CustomRoles.Drainer)) return; PlayersInVents[pc.PlayerId] = vent.Id; } private void KillPlayersInVent(PlayerControl pc, Vent vent) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; int ventId = vent.Id; - if (!PlayersInVents.ContainsValue(ventId)) - { - return; - } + if (!PlayersInVents.ContainsValue(ventId)) return; foreach (KeyValuePair venterId in PlayersInVents.Where(x => x.Value == ventId).ToArray()) { PlayerControl venter = Utils.GetPlayerById(venterId.Key); - if (venter == null) - { - continue; - } + if (venter == null) continue; if (pc != null && pc.RpcCheckAndMurder(venter, true)) { venter.MyPhysics.RpcBootFromVent(ventId); + LateTask.New(() => { venter.Suicide(PlayerState.DeathReason.Demolished, pc); @@ -128,10 +109,7 @@ namespace EHR.Crewmate public override void OnReportDeadBody() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; PlayersInVents.Clear(); } diff --git a/Roles/Crewmate/Druid.cs b/Roles/Crewmate/Druid.cs index 697e1825e..d19f9ec60 100644 --- a/Roles/Crewmate/Druid.cs +++ b/Roles/Crewmate/Druid.cs @@ -32,18 +32,23 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Druid); + VentCooldown = new IntegerOptionItem(Id + 10, "VentCooldown", new(0, 60, 1), 15, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Druid]) .SetValueFormat(OptionFormat.Seconds); + TriggerPlaceDelay = new IntegerOptionItem(Id + 11, "DruidTriggerPlaceDelayOpt", new(1, 20, 1), 7, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Druid]) .SetValueFormat(OptionFormat.Seconds); + UseLimitOpt = new IntegerOptionItem(Id + 12, "AbilityUseLimit", new(0, 20, 1), 3, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Druid]) .SetValueFormat(OptionFormat.Times); + DruidAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 13, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 1f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Druid]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 14, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Druid]) .SetValueFormat(OptionFormat.Times); @@ -74,20 +79,14 @@ namespace EHR.Crewmate public static void SendRPCAddTrigger(bool add, byte playerId, Vector2 position, string roomName = "") { - if (!DoRPC) - { - return; - } + if (!DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.DruidAddTrigger, SendOption.Reliable); writer.Write(add); writer.Write(playerId); writer.Write(position.x); writer.Write(position.y); - if (add) - { - writer.Write(roomName); - } + if (add) writer.Write(roomName); AmongUsClient.Instance.FinishRpcImmediately(writer); } @@ -97,10 +96,7 @@ namespace EHR.Crewmate bool add = reader.ReadBoolean(); byte playerId = reader.ReadByte(); - if (Main.PlayerStates[playerId].Role is not Druid { IsEnable: true } di) - { - return; - } + if (Main.PlayerStates[playerId].Role is not Druid { IsEnable: true } di) return; float x = reader.ReadSingle(); float y = reader.ReadSingle(); @@ -115,9 +111,7 @@ namespace EHR.Crewmate di.Triggers.TryAdd(position, roomName); } else - { di.Triggers.Remove(position); - } } public override void OnPet(PlayerControl pc) @@ -132,20 +126,11 @@ namespace EHR.Crewmate private void PlaceTrigger(PlayerControl pc, bool isPet = false) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - if (pc == null || !GameStates.IsInTask) - { - return; - } + if (pc == null || !GameStates.IsInTask) return; - if (pc.GetAbilityUseLimit() < 1) - { - return; - } + if (pc.GetAbilityUseLimit() < 1) return; long now = TimeStamp; @@ -158,19 +143,14 @@ namespace EHR.Crewmate TriggerIds.TryAdd(location, id); } else - { TriggerDelay = now; - } pc.RpcRemoveAbilityUse(); } public override void OnCheckPlayerPosition(PlayerControl pc) { - if (!GameStates.IsInTask || Triggers.Count <= 0 || PlayerIdList.Contains(pc.PlayerId)) - { - return; - } + if (!GameStates.IsInTask || Triggers.Count <= 0 || PlayerIdList.Contains(pc.PlayerId)) return; foreach (KeyValuePair trigger in Triggers.Where(trigger => Vector2.Distance(trigger.Key, pc.Pos()) <= 1.5f)) { @@ -183,10 +163,7 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (!IsEnable || !GameStates.IsInTask || TriggerDelay == 0 || pc == null) - { - return; - } + if (!IsEnable || !GameStates.IsInTask || TriggerDelay == 0 || pc == null) return; long now = TimeStamp; @@ -203,32 +180,20 @@ namespace EHR.Crewmate } long timeLeft = TriggerPlaceDelay.GetInt() - (now - TriggerDelay); - if (lastUpdate < now) - { - pc.Notify(string.Format(GetString("DruidTimeLeft"), timeLeft, 2f)); - } + if (lastUpdate < now) pc.Notify(string.Format(GetString("DruidTimeLeft"), timeLeft, 2f)); lastUpdate = now; } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (hud) - { - return GetHUDText(seer); - } + if (hud) return GetHUDText(seer); - if (seer == null || seer.IsModClient() || seer.PlayerId != target.PlayerId || seer.PlayerId != DruidPC.PlayerId) - { - return string.Empty; - } + if (seer == null || seer.IsModClient() || seer.PlayerId != target.PlayerId || seer.PlayerId != DruidPC.PlayerId) return string.Empty; - if (Triggers.Count == 0) - { - return string.Empty; - } + if (Triggers.Count == 0) return string.Empty; - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.Append("\n"); sb.AppendLine($"<#00ffa5>{Triggers.Count} trigger{(Triggers.Count == 1 ? string.Empty : 's')} active"); @@ -240,12 +205,9 @@ namespace EHR.Crewmate private string GetHUDText(PlayerControl pc) { - if (pc == null || Triggers.Count == 0) - { - return string.Empty; - } + if (pc == null || Triggers.Count == 0) return string.Empty; - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.AppendLine($"<#00ffa5>{Triggers.Count} trigger{(Triggers.Count == 1 ? string.Empty : 's')} active"); sb.Append(string.Join('\n', Triggers.Select(trigger => $"Trigger {GetFormattedRoomName(trigger.Value)} {GetFormattedVectorText(trigger.Key)}"))); diff --git a/Roles/Crewmate/Electric.cs b/Roles/Crewmate/Electric.cs index 5157ccfa9..6f93e7b2c 100644 --- a/Roles/Crewmate/Electric.cs +++ b/Roles/Crewmate/Electric.cs @@ -25,6 +25,7 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Electric); + FreezeDuration = new FloatOptionItem(Id + 2, "GamblerFreezeDur", new(0.5f, 90f, 0.5f), 3f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Electric]) .SetValueFormat(OptionFormat.Seconds); @@ -32,22 +33,17 @@ namespace EHR.Crewmate public override void OnTaskComplete(PlayerControl pc, int completedTaskCount, int totalTaskCount) { - if (pc == null) - { - return; - } + if (pc == null) return; List targetList = Main.AllAlivePlayerControls.Where(x => !x.Is(Team.Crewmate)).ToList(); - if (targetList.Count == 0) - { - return; - } + if (targetList.Count == 0) return; PlayerControl target = targetList.RandomElement(); float beforeSpeed = Main.AllPlayerSpeed[target.PlayerId]; Main.AllPlayerSpeed[target.PlayerId] = Main.MinSpeed; target.MarkDirtySettings(); + LateTask.New(() => { Main.AllPlayerSpeed[target.PlayerId] = beforeSpeed; diff --git a/Roles/Crewmate/Enigma.cs b/Roles/Crewmate/Enigma.cs index 7e45fd6c6..5b85f078b 100644 --- a/Roles/Crewmate/Enigma.cs +++ b/Roles/Crewmate/Enigma.cs @@ -54,21 +54,27 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Enigma); + EnigmaClueStage1Tasks = new FloatOptionItem(Id + 11, "EnigmaClueStage1Tasks", new(0f, 10f, 1f), 1f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Enigma]) .SetValueFormat(OptionFormat.Times); + EnigmaClueStage2Tasks = new FloatOptionItem(Id + 12, "EnigmaClueStage2Tasks", new(0f, 10f, 1f), 3f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Enigma]) .SetValueFormat(OptionFormat.Times); + EnigmaClueStage3Tasks = new FloatOptionItem(Id + 13, "EnigmaClueStage3Tasks", new(0f, 10f, 1f), 7f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Enigma]) .SetValueFormat(OptionFormat.Times); + EnigmaClueStage2Probability = new IntegerOptionItem(Id + 14, "EnigmaClueStage2Probability", new(0, 100, 5), 75, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Enigma]) .SetValueFormat(OptionFormat.Percent); + EnigmaClueStage3Probability = new IntegerOptionItem(Id + 15, "EnigmaClueStage3Probability", new(0, 100, 5), 60, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Enigma]) .SetValueFormat(OptionFormat.Percent); + EnigmaGetCluesWithoutReporting = new BooleanOptionItem(Id + 16, "EnigmaClueGetCluesWithoutReporting", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Enigma]); @@ -91,41 +97,26 @@ namespace EHR.Crewmate public static void OnReportDeadBody(PlayerControl player, NetworkedPlayerInfo targetInfo) { - if (targetInfo == null) - { - return; - } + if (targetInfo == null) return; PlayerControl target = Utils.GetPlayerById(targetInfo.PlayerId); - if (target == null) - { - return; - } + if (target == null) return; PlayerControl killer = target.GetRealKiller(); - if (killer == null) - { - return; - } + if (killer == null) return; - IRandom rd = IRandom.Instance; + var rd = IRandom.Instance; foreach (byte playerId in PlayerIdList) { - if (!EnigmaGetCluesWithoutReporting.GetBool() && playerId != player.PlayerId) - { - continue; - } + if (!EnigmaGetCluesWithoutReporting.GetBool() && playerId != player.PlayerId) continue; PlayerControl enigmaPlayer = Utils.GetPlayerById(playerId); - if (enigmaPlayer == null) - { - continue; - } + if (enigmaPlayer == null) continue; int tasksCompleted = enigmaPlayer.GetTaskState().CompletedTasksCount; - int stage = 0; - bool showStageClue = false; + var stage = 0; + var showStageClue = false; if (tasksCompleted >= EnigmaClueStage3Tasks.GetInt()) { @@ -137,23 +128,15 @@ namespace EHR.Crewmate stage = 2; showStageClue = rd.Next(0, 100) < EnigmaClueStage2Probability.GetInt(); } - else if (tasksCompleted >= EnigmaClueStage1Tasks.GetInt()) - { - stage = 1; - } + else if (tasksCompleted >= EnigmaClueStage1Tasks.GetInt()) stage = 1; List clues = EnigmaClues.Where(a => a.ClueStage <= stage && !ShownClues[playerId].Any(b => b.EnigmaClueType == a.EnigmaClueType && b.ClueStage == a.ClueStage)) .ToList(); - if (clues.Count == 0) - { - continue; - } - if (showStageClue && clues.Any(a => a.ClueStage == stage)) - { - clues = clues.Where(a => a.ClueStage == stage).ToList(); - } + if (clues.Count == 0) continue; + + if (showStageClue && clues.Any(a => a.ClueStage == stage)) clues = clues.Where(a => a.ClueStage == stage).ToList(); EnigmaClue clue = clues[rd.Next(0, clues.Count - 1)]; string title = clue.Title; @@ -183,10 +166,7 @@ namespace EHR.Crewmate public override string GetMessage(PlayerControl killer, bool showStageClue) { NetworkedPlayerInfo.PlayerOutfit killerOutfit = Camouflage.PlayerSkins[killer.PlayerId]; - if (killerOutfit.HatId == "hat_EmptyHat") - { - return GetString("EnigmaClueHat2"); - } + if (killerOutfit.HatId == "hat_EmptyHat") return GetString("EnigmaClueHat2"); return ClueStage switch { @@ -205,10 +185,7 @@ namespace EHR.Crewmate public override string GetMessage(PlayerControl killer, bool showStageClue) { NetworkedPlayerInfo.PlayerOutfit killerOutfit = Camouflage.PlayerSkins[killer.PlayerId]; - if (killerOutfit.VisorId == "visor_EmptyVisor") - { - return GetString("EnigmaClueVisor2"); - } + if (killerOutfit.VisorId == "visor_EmptyVisor") return GetString("EnigmaClueVisor2"); return ClueStage switch { @@ -227,10 +204,7 @@ namespace EHR.Crewmate public override string GetMessage(PlayerControl killer, bool showStageClue) { NetworkedPlayerInfo.PlayerOutfit killerOutfit = Camouflage.PlayerSkins[killer.PlayerId]; - if (killerOutfit.SkinId == "skin_EmptySkin") - { - return GetString("EnigmaClueSkin2"); - } + if (killerOutfit.SkinId == "skin_EmptySkin") return GetString("EnigmaClueSkin2"); return ClueStage switch { @@ -249,10 +223,7 @@ namespace EHR.Crewmate public override string GetMessage(PlayerControl killer, bool showStageClue) { NetworkedPlayerInfo.PlayerOutfit killerOutfit = Camouflage.PlayerSkins[killer.PlayerId]; - if (killerOutfit.PetId == "pet_EmptyPet") - { - return GetString("EnigmaCluePet2"); - } + if (killerOutfit.PetId == "pet_EmptyPet") return GetString("EnigmaCluePet2"); return ClueStage switch { @@ -280,22 +251,13 @@ namespace EHR.Crewmate case 1: return GetStage1Clue(killer, letter); case 2: - if (showStageClue) - { - GetStage2Clue(letter); - } + if (showStageClue) GetStage2Clue(letter); return GetStage1Clue(killer, letter); case 3: - if (showStageClue) - { - return GetStage3Clue(killerName, letter); - } + if (showStageClue) return GetStage3Clue(killerName, letter); - if (rd.Next(0, 100) < EnigmaClueStage2Probability.GetInt()) - { - return GetStage2Clue(letter); - } + if (rd.Next(0, 100) < EnigmaClueStage2Probability.GetInt()) return GetStage2Clue(letter); return GetStage1Clue(killer, letter); } @@ -317,12 +279,9 @@ namespace EHR.Crewmate private string GetStage3Clue(string killerName, string letter) { - string letter2 = string.Empty; + var letter2 = string.Empty; string tmpName = killerName.Replace(letter, string.Empty); - if (!string.IsNullOrEmpty(tmpName)) - { - letter2 = tmpName[rd.Next(0, tmpName.Length - 1)].ToString().ToLower(); - } + if (!string.IsNullOrEmpty(tmpName)) letter2 = tmpName[rd.Next(0, tmpName.Length - 1)].ToString().ToLower(); return string.Format(GetString("EnigmaClueName3"), letter, letter2); } @@ -373,10 +332,7 @@ namespace EHR.Crewmate int start = length - rd.Next(0, 2); int end = length + rd.Next(0, 2); - if (start == end) - { - return GetStage3Clue(length); - } + if (start == end) return GetStage3Clue(length); start = start < 0 ? 0 : start; end = end > 10 ? 10 : end; @@ -424,16 +380,13 @@ namespace EHR.Crewmate public override string GetMessage(PlayerControl killer, bool showStageClue) { - string room = string.Empty; + var room = string.Empty; PlainShipRoom targetRoom = Main.PlayerStates[killer.PlayerId].LastRoom; + if (targetRoom == null) - { room += GetString("FailToTrack"); - } else - { room += GetString(targetRoom.RoomId.ToString()); - } return string.Format(GetString("EnigmaClueLocation"), room); } @@ -456,6 +409,7 @@ namespace EHR.Crewmate public override string GetMessage(PlayerControl killer, bool showStageClue) { CustomRoles role = killer.GetCustomRole(); + return ClueStage switch { 1 => role.IsImpostor() ? GetString("EnigmaClueRole1") : GetString(role.IsNeutral() ? "EnigmaClueRole2" : "EnigmaClueRole3"), @@ -474,7 +428,7 @@ namespace EHR.Crewmate public override string GetMessage(PlayerControl killer, bool showStageClue) { - int level = (int)killer.Data.PlayerLevel; + var level = (int)killer.Data.PlayerLevel; return ClueStage switch { diff --git a/Roles/Crewmate/Escort.cs b/Roles/Crewmate/Escort.cs index 4d063893d..e8bba2842 100644 --- a/Roles/Crewmate/Escort.cs +++ b/Roles/Crewmate/Escort.cs @@ -19,13 +19,17 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Escort); + CD = new FloatOptionItem(Id + 10, "RoleBlockCooldown", new(2.5f, 60f, 2.5f), 30f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Escort]) .SetValueFormat(OptionFormat.Seconds); + UseLimit = new IntegerOptionItem(Id + 11, "AbilityUseLimit", new(1, 20, 1), 3, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Escort]) .SetValueFormat(OptionFormat.Times); + UsePet = Options.CreatePetUseSetting(Id + 12, CustomRoles.Escort); + Duration = new FloatOptionItem(Id + 13, "RoleBlockDuration", new(1f, 60f, 1f), 15f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Escort]) .SetValueFormat(OptionFormat.Seconds); @@ -59,10 +63,7 @@ namespace EHR.Crewmate public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!IsEnable || killer == null || target == null || killer.GetAbilityUseLimit() <= 0) - { - return false; - } + if (!IsEnable || killer == null || target == null || killer.GetAbilityUseLimit() <= 0) return false; killer.RpcRemoveAbilityUse(); killer.SetKillCooldown(); diff --git a/Roles/Crewmate/Express.cs b/Roles/Crewmate/Express.cs index 88881f7e2..a525b009d 100644 --- a/Roles/Crewmate/Express.cs +++ b/Roles/Crewmate/Express.cs @@ -13,9 +13,11 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(5585, TabGroup.CrewmateRoles, CustomRoles.Express); + Options.ExpressSpeed = new FloatOptionItem(5587, "ExpressSpeed", new(0.25f, 5f, 0.25f), 1.5f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Express]) .SetValueFormat(OptionFormat.Multiplier); + Options.ExpressSpeedDur = new IntegerOptionItem(5588, "ExpressSpeedDur", new(0, 90, 1), 5, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Express]) .SetValueFormat(OptionFormat.Seconds); @@ -33,10 +35,7 @@ namespace EHR.Crewmate public override void OnTaskComplete(PlayerControl player, int completedTaskCount, int totalTaskCount) { - if (!SpeedUp.ContainsKey(player.PlayerId)) - { - SpeedNormal[player.PlayerId] = Main.AllPlayerSpeed[player.PlayerId]; - } + if (!SpeedUp.ContainsKey(player.PlayerId)) SpeedNormal[player.PlayerId] = Main.AllPlayerSpeed[player.PlayerId]; Main.AllPlayerSpeed[player.PlayerId] = Options.ExpressSpeed.GetFloat(); SpeedUp[player.PlayerId] = Utils.TimeStamp; @@ -45,13 +44,11 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl player) { - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; byte playerId = player.PlayerId; long now = Utils.TimeStamp; + if (SpeedUp.TryGetValue(playerId, out long etime) && etime + Options.ExpressSpeedDur.GetInt() < now) { SpeedUp.Remove(playerId); diff --git a/Roles/Crewmate/Farseer.cs b/Roles/Crewmate/Farseer.cs index c66cce940..be5b99ab2 100644 --- a/Roles/Crewmate/Farseer.cs +++ b/Roles/Crewmate/Farseer.cs @@ -35,15 +35,19 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Farseer); + FarseerCooldown = new FloatOptionItem(Id + 10, "FarseerRevealCooldown", new(0f, 60f, 2.5f), 15f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Farseer]) .SetValueFormat(OptionFormat.Seconds); + FarseerRevealTime = new FloatOptionItem(Id + 11, "FarseerRevealTime", new(0f, 30f, 1f), 10f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Farseer]) .SetValueFormat(OptionFormat.Seconds); + Vision = new FloatOptionItem(Id + 12, "FarseerVision", new(0f, 1f, 0.05f), 0.25f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Farseer]) .SetValueFormat(OptionFormat.Multiplier); + UsePet = CreatePetUseSetting(Id + 13, CustomRoles.Farseer); } @@ -56,10 +60,7 @@ namespace EHR.Crewmate { On = true; - foreach (PlayerControl ar in Main.AllPlayerControls) - { - IsRevealed[(playerId, ar.PlayerId)] = false; - } + foreach (PlayerControl ar in Main.AllPlayerControls) IsRevealed[(playerId, ar.PlayerId)] = false; RandomRole[playerId] = GetRandomCrewRoleString(); } @@ -84,6 +85,7 @@ namespace EHR.Crewmate public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { killer.SetKillCooldown(FarseerRevealTime.GetFloat()); + if (!IsRevealed[(killer.PlayerId, target.PlayerId)] && !FarseerTimer.ContainsKey(killer.PlayerId)) { FarseerTimer.TryAdd(killer.PlayerId, (target, 0f)); @@ -108,20 +110,15 @@ namespace EHR.Crewmate { PlayerControl arTarget = FarseerTimer[player.PlayerId].PLAYER; float arTime = FarseerTimer[player.PlayerId].TIMER; + if (!arTarget.IsAlive()) - { FarseerTimer.Remove(player.PlayerId); - } else if (arTime >= FarseerRevealTime.GetFloat()) { if (UsePets.GetBool() && UsePet.GetBool()) - { player.AddKCDAsAbilityCD(); - } else - { player.SetKillCooldown(); - } FarseerTimer.Remove(player.PlayerId); IsRevealed[(player.PlayerId, arTarget.PlayerId)] = true; @@ -133,10 +130,9 @@ namespace EHR.Crewmate { float range = NormalGameOptionsV08.KillDistances[Mathf.Clamp(player.Is(CustomRoles.Reach) ? 2 : Main.NormalOptions.KillDistance, 0, 2)] + 0.5f; float dis = Vector2.Distance(player.transform.position, arTarget.transform.position); + if (dis <= range) - { FarseerTimer[player.PlayerId] = (arTarget, arTime + Time.fixedDeltaTime); - } else { FarseerTimer.Remove(player.PlayerId); @@ -160,10 +156,7 @@ namespace EHR.Crewmate public static string GetTaskState() { KeyValuePair[] playersWithTasks = Main.PlayerStates.Where(a => a.Value.TaskState.HasTasks).ToArray(); - if (playersWithTasks.Length == 0) - { - return "\r\n"; - } + if (playersWithTasks.Length == 0) return "\r\n"; KeyValuePair randomPlayer = playersWithTasks.RandomElement(); TaskState taskState = randomPlayer.Value.TaskState; diff --git a/Roles/Crewmate/Gaulois.cs b/Roles/Crewmate/Gaulois.cs index f9dda8ec5..122b74900 100644 --- a/Roles/Crewmate/Gaulois.cs +++ b/Roles/Crewmate/Gaulois.cs @@ -21,15 +21,19 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Gaulois); + CD = new FloatOptionItem(Id + 5, "AbilityCooldown", new(0f, 60f, 2.5f), 30f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Gaulois]) .SetValueFormat(OptionFormat.Seconds); + AdditionalSpeed = new FloatOptionItem(Id + 6, "GauloisSpeedBoost", new(0f, 2f, 0.05f), 0.5f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Gaulois]) .SetValueFormat(OptionFormat.Multiplier); + UseLimitOpt = new IntegerOptionItem(Id + 7, "AbilityUseLimit", new(1, 14, 1), 3, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Gaulois]) .SetValueFormat(OptionFormat.Times); + UsePet = CreatePetUseSetting(Id + 8, CustomRoles.Gaulois); } @@ -47,10 +51,7 @@ namespace EHR.Crewmate public override void SetKillCooldown(byte playerId) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; Main.AllPlayerKillCooldown[playerId] = playerId.GetAbilityUseLimit() > 0 ? CD.GetFloat() : 300f; } @@ -67,10 +68,7 @@ namespace EHR.Crewmate public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!IsEnable || killer == null || target == null || killer.GetAbilityUseLimit() <= 0) - { - return false; - } + if (!IsEnable || killer == null || target == null || killer.GetAbilityUseLimit() <= 0) return false; Main.AllPlayerSpeed[target.PlayerId] += AdditionalSpeed.GetFloat(); IncreasedSpeedPlayerList.Add(target.PlayerId); diff --git a/Roles/Crewmate/Goose.cs b/Roles/Crewmate/Goose.cs index 06dfc1f3d..e5f4a321a 100644 --- a/Roles/Crewmate/Goose.cs +++ b/Roles/Crewmate/Goose.cs @@ -15,27 +15,28 @@ public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Goose); + OptionAbductTimerLimit = new FloatOptionItem(Id + 11, "PenguinAbductTimerLimit", new(1f, 20f, 1f), 10f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Goose]) .SetValueFormat(OptionFormat.Seconds); + OptionSpeedDuringDrag = new FloatOptionItem(Id + 13, "PenguinSpeedDuringDrag", new(0.1f, 3f, 0.1f), 1f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Goose]) .SetValueFormat(OptionFormat.Multiplier); + OptionVictimCanUseAbilities = new BooleanOptionItem(Id + 14, "PenguinVictimCanUseAbilities", false, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Goose]); + CanBeGuessed = new BooleanOptionItem(Id + 15, "CanBeGuessed", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Goose]); + Cooldown = new FloatOptionItem(Id + 16, "AbilityCooldown", new(0f, 180f, 0.5f), 15f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Goose]) .SetValueFormat(OptionFormat.Seconds); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Crewmate/Grappler.cs b/Roles/Crewmate/Grappler.cs index 1ce3bee02..1dd2d036e 100644 --- a/Roles/Crewmate/Grappler.cs +++ b/Roles/Crewmate/Grappler.cs @@ -49,9 +49,7 @@ namespace EHR.Crewmate GrapplerId.GetPlayer().RpcRemoveAbilityUse(); } else - { InUse = false; - } Utils.SendRPC(CustomRPC.SyncRoleData, GrapplerId, InUse); } @@ -68,10 +66,7 @@ namespace EHR.Crewmate public static bool OnAnyoneCheckMurder(PlayerControl target) { - if (new[] { SystemTypes.Electrical, SystemTypes.Reactor, SystemTypes.Laboratory, SystemTypes.LifeSupp, SystemTypes.Comms, SystemTypes.HeliSabotage, SystemTypes.MushroomMixupSabotage }.Any(Utils.IsActive)) - { - return true; - } + if (new[] { SystemTypes.Electrical, SystemTypes.Reactor, SystemTypes.Laboratory, SystemTypes.LifeSupp, SystemTypes.Comms, SystemTypes.HeliSabotage, SystemTypes.MushroomMixupSabotage }.Any(Utils.IsActive)) return true; foreach (Grappler instance in Instances) { diff --git a/Roles/Crewmate/Grenadier.cs b/Roles/Crewmate/Grenadier.cs index 69b27b2a4..134c3625b 100644 --- a/Roles/Crewmate/Grenadier.cs +++ b/Roles/Crewmate/Grenadier.cs @@ -18,23 +18,30 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(6800, TabGroup.CrewmateRoles, CustomRoles.Grenadier); + GrenadierSkillCooldown = new FloatOptionItem(6810, "GrenadierSkillCooldown", new(0f, 180f, 1f), 25f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Grenadier]) .SetValueFormat(OptionFormat.Seconds); + GrenadierSkillDuration = new FloatOptionItem(6811, "GrenadierSkillDuration", new(0f, 180f, 1f), 10f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Grenadier]) .SetValueFormat(OptionFormat.Seconds); + GrenadierCauseVision = new FloatOptionItem(6812, "GrenadierCauseVision", new(0f, 5f, 0.05f), 0.3f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Grenadier]) .SetValueFormat(OptionFormat.Multiplier); + GrenadierCanAffectNeutral = new BooleanOptionItem(6813, "GrenadierCanAffectNeutral", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Grenadier]); + GrenadierSkillMaxOfUseage = new IntegerOptionItem(6814, "GrenadierSkillMaxOfUseage", new(0, 180, 1), 2, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Grenadier]) .SetValueFormat(OptionFormat.Times); + GrenadierAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(6815, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.5f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Grenadier]) .SetValueFormat(OptionFormat.Times); + GrenadierAbilityChargesWhenFinishedTasks = new FloatOptionItem(6816, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Grenadier]) .SetValueFormat(OptionFormat.Times); @@ -53,10 +60,7 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = GrenadierSkillCooldown.GetFloat(); AURoleOptions.EngineerInVentMaxTime = 1; @@ -64,7 +68,7 @@ namespace EHR.Crewmate public override string GetProgressText(byte playerId, bool comms) { - StringBuilder ProgressText = new StringBuilder(); + var ProgressText = new StringBuilder(); ProgressText.Append(Utils.GetAbilityUseLimitDisplay(playerId, GrenadierBlinding.ContainsKey(playerId))); ProgressText.Append(Utils.GetTaskCount(playerId, comms)); @@ -75,13 +79,9 @@ namespace EHR.Crewmate public override void SetButtonTexts(HudManager hud, byte id) { if (UsePets.GetBool()) - { hud.PetButton.buttonLabelText.text = Translator.GetString("GrenadierVentButtonText"); - } else - { hud.AbilityButton.buttonLabelText.text = Translator.GetString("GrenadierVentButtonText"); - } } public override void OnPet(PlayerControl pc) @@ -96,10 +96,7 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl player) { - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; byte playerId = player.PlayerId; long now = Utils.TimeStamp; @@ -123,10 +120,7 @@ namespace EHR.Crewmate private static void BlindPlayers(PlayerControl pc) { - if (GrenadierBlinding.ContainsKey(pc.PlayerId) || MadGrenadierBlinding.ContainsKey(pc.PlayerId)) - { - return; - } + if (GrenadierBlinding.ContainsKey(pc.PlayerId) || MadGrenadierBlinding.ContainsKey(pc.PlayerId)) return; if (pc.GetAbilityUseLimit() >= 1) { @@ -149,9 +143,7 @@ namespace EHR.Crewmate Utils.MarkEveryoneDirtySettingsV3(); } else - { pc.Notify(Translator.GetString("OutOfAbilityUsesDoMoreTasks")); - } } } } \ No newline at end of file diff --git a/Roles/Crewmate/GuessManager.cs b/Roles/Crewmate/GuessManager.cs index 3f3e95c0d..bfc26b53c 100644 --- a/Roles/Crewmate/GuessManager.cs +++ b/Roles/Crewmate/GuessManager.cs @@ -26,10 +26,7 @@ namespace EHR.Crewmate public static void OnGuess(PlayerControl dp, PlayerControl pc) { - foreach (byte guessManager in PlayerIdList) - { - LateTask.New(() => { Utils.SendMessage(dp == pc ? string.Format(GetString("GuessManagerMessageAboutMisguess"), dp.GetRealName().Replace("\n", " + ")) : string.Format(GetString("GuessManagerMessageAboutGuessedRole"), dp.GetAllRoleName().Replace("\n", " + ")), guessManager); }, 1f, "Guess Manager Messages"); - } + foreach (byte guessManager in PlayerIdList) LateTask.New(() => { Utils.SendMessage(dp == pc ? string.Format(GetString("GuessManagerMessageAboutMisguess"), dp.GetRealName().Replace("\n", " + ")) : string.Format(GetString("GuessManagerMessageAboutGuessedRole"), dp.GetAllRoleName().Replace("\n", " + ")), guessManager); }, 1f, "Guess Manager Messages"); } } } \ No newline at end of file diff --git a/Roles/Crewmate/Inquirer.cs b/Roles/Crewmate/Inquirer.cs index 17ad70182..a02349dfe 100644 --- a/Roles/Crewmate/Inquirer.cs +++ b/Roles/Crewmate/Inquirer.cs @@ -12,23 +12,25 @@ public override void SetupCustomOption() { Options.SetupRoleOptions(649710, TabGroup.CrewmateRoles, CustomRoles.Inquirer); + FailChance = new IntegerOptionItem(649712, "Inquirer.FailChance", new(0, 100, 5), 20, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Inquirer]) .SetValueFormat(OptionFormat.Percent); + AbilityUseLimit = new IntegerOptionItem(649713, "Inquirer.AbilityUseLimit", new(0, 10, 1), 1, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Inquirer]) .SetValueFormat(OptionFormat.Times); + AbilityUseGainWithEachTaskCompleted = new FloatOptionItem(649714, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.8f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Inquirer]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(649715, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Inquirer]) .SetValueFormat(OptionFormat.Times); } - public override void Init() - { - } + public override void Init() { } public override void Add(byte playerId) { diff --git a/Roles/Crewmate/Insight.cs b/Roles/Crewmate/Insight.cs index b613e1342..2ee37ad02 100644 --- a/Roles/Crewmate/Insight.cs +++ b/Roles/Crewmate/Insight.cs @@ -33,6 +33,7 @@ namespace EHR.Crewmate public override void OnTaskComplete(PlayerControl player, int completedTaskCount, int totalTaskCount) { List list = Main.AllPlayerControls.Where(x => !KnownRolesOfPlayerIds.Contains(x.PlayerId) && !x.Is(CustomRoles.Insight) && !x.Is(CustomRoles.GM) && !x.Is(CustomRoles.NotAssigned)).ToList(); + if (list.Count != 0) { PlayerControl target = list.RandomElement(); diff --git a/Roles/Crewmate/Jailer.cs b/Roles/Crewmate/Jailer.cs index 54f67903d..5bd712bba 100644 --- a/Roles/Crewmate/Jailer.cs +++ b/Roles/Crewmate/Jailer.cs @@ -24,11 +24,14 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Jailor); + JailCooldown = new FloatOptionItem(Id + 10, "JailorJailCooldown", new(0f, 60f, 1f), 15f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Jailor]) .SetValueFormat(OptionFormat.Seconds); + NotifyJailedOnMeeting = new BooleanOptionItem(Id + 18, "notifyJailedOnMeeting", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Jailor]); + UsePet = CreatePetUseSetting(Id + 11, CustomRoles.Jailor); } @@ -63,12 +66,10 @@ namespace EHR.Crewmate private void SendRPC(byte jailerId, byte targetId = byte.MaxValue, bool setTarget = true) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer; + if (!setTarget) { writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetJailorExeLimit, SendOption.Reliable); @@ -87,10 +88,7 @@ namespace EHR.Crewmate public static void ReceiveRPC(MessageReader reader, bool setTarget = true) { byte jailerId = reader.ReadByte(); - if (Main.PlayerStates[jailerId].Role is not Jailor jl) - { - return; - } + if (Main.PlayerStates[jailerId].Role is not Jailor jl) return; if (!setTarget) { @@ -104,10 +102,7 @@ namespace EHR.Crewmate public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null) - { - return false; - } + if (killer == null || target == null) return false; if (JailorTarget != byte.MaxValue) { @@ -125,26 +120,14 @@ namespace EHR.Crewmate public override void OnReportDeadBody() { - if (!NotifyJailedOnMeeting.GetBool()) - { - return; - } + if (!NotifyJailedOnMeeting.GetBool()) return; - if (JailorTarget == byte.MaxValue) - { - return; - } + if (JailorTarget == byte.MaxValue) return; PlayerControl tpc = Utils.GetPlayerById(JailorTarget); - if (tpc == null) - { - return; - } + if (tpc == null) return; - if (tpc.IsAlive()) - { - LateTask.New(() => { Utils.SendMessage(GetString("JailedNotifyMsg"), JailorTarget, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Jailor), GetString("JailorTitle"))); }, 0.3f, "JailorNotifyJailed"); - } + if (tpc.IsAlive()) LateTask.New(() => { Utils.SendMessage(GetString("JailedNotifyMsg"), JailorTarget, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Jailor), GetString("JailorTitle"))); }, 0.3f, "JailorNotifyJailed"); } } } \ No newline at end of file diff --git a/Roles/Crewmate/Journalist.cs b/Roles/Crewmate/Journalist.cs index 8006171f1..9c7ac2a74 100644 --- a/Roles/Crewmate/Journalist.cs +++ b/Roles/Crewmate/Journalist.cs @@ -33,12 +33,10 @@ namespace EHR.Crewmate public static void OnReceiveCommand(PlayerControl pc, string[] args) { - if (Main.PlayerStates[pc.PlayerId].Role is not Journalist journalist) - { - return; - } + if (Main.PlayerStates[pc.PlayerId].Role is not Journalist journalist) return; + + var error = string.Empty; - string error = string.Empty; try { switch (args[1]) @@ -47,10 +45,7 @@ namespace EHR.Crewmate journalist.Notes.Add(string.Join(' ', args[2..])); break; case "remove": - if (args.Length == 2 || !int.TryParse(args[2], out int index)) - { - index = journalist.Notes.Count; - } + if (args.Length == 2 || !int.TryParse(args[2], out int index)) index = journalist.Notes.Count; index--; journalist.Notes.RemoveAt(index); @@ -69,6 +64,7 @@ namespace EHR.Crewmate catch (Exception e) { string usage = Translator.GetString("Journalist.CommandUsage"); + switch (e) { case IndexOutOfRangeException: // Not enough arguments @@ -84,18 +80,12 @@ namespace EHR.Crewmate } } - if (error != string.Empty) - { - Utils.SendMessage(error, pc.PlayerId); - } + if (error != string.Empty) Utils.SendMessage(error, pc.PlayerId); } public override void OnReportDeadBody() { - if (Sent || JournalistId.GetPlayer()?.IsAlive() == true) - { - return; - } + if (Sent || JournalistId.GetPlayer()?.IsAlive() == true) return; LateTask.New(() => Utils.SendMessage(string.Join('\n', Notes), title: Translator.GetString("JournalistNotesTitle")), 10f, "Send Journalist Notes"); Sent = true; diff --git a/Roles/Crewmate/Judge.cs b/Roles/Crewmate/Judge.cs index 3e6afbb73..05c7b1447 100644 --- a/Roles/Crewmate/Judge.cs +++ b/Roles/Crewmate/Judge.cs @@ -67,45 +67,28 @@ namespace EHR.Crewmate public override void OnReportDeadBody() { byte[] list = [.. PlayerIdList]; - foreach (byte pid in list) - { - pid.SetAbilityUseLimit(TrialLimitPerMeeting.GetInt()); - } + foreach (byte pid in list) pid.SetAbilityUseLimit(TrialLimitPerMeeting.GetInt()); } public static bool TrialMsg(PlayerControl pc, string msg, bool isUI = false) { string originMsg = msg; - if (!AmongUsClient.Instance.AmHost) - { - return false; - } + if (!AmongUsClient.Instance.AmHost) return false; - if (!GameStates.IsInGame || pc == null) - { - return false; - } + if (!GameStates.IsInGame || pc == null) return false; - if (!pc.Is(CustomRoles.Judge)) - { - return false; - } + if (!pc.Is(CustomRoles.Judge)) return false; int operate; // 1:ID 2:Trial msg = msg.ToLower().TrimStart().TrimEnd(); + if (CheckCommand(ref msg, "id|guesslist|gl编号|玩家编号|玩家id|id列表|玩家列表|列表|所有id|全部id")) - { operate = 1; - } else if (CheckCommand(ref msg, "shoot|guess|bet|st|gs|bt|猜|赌|sp|jj|tl|trial|审判|判|审", false)) - { operate = 2; - } else - { return false; - } if (!pc.IsAlive()) { @@ -121,13 +104,8 @@ namespace EHR.Crewmate case 2: { if (TryHideMsg.GetBool()) /*GuessManager.TryHideMsg();*/ - { ChatManager.SendPreviousMessagesToAll(); - } - else if (pc.AmOwner) - { - Utils.SendMessage(originMsg, 255, pc.GetRealName()); - } + else if (pc.AmOwner) Utils.SendMessage(originMsg, 255, pc.GetRealName()); if (!MsgToPlayerAndRole(msg, out byte targetId, out string error)) { @@ -136,20 +114,18 @@ namespace EHR.Crewmate } PlayerControl target = Utils.GetPlayerById(targetId); + if (target != null) { Logger.Info($"{pc.GetNameWithRole().RemoveHtmlTags()} trialed {target.GetNameWithRole().RemoveHtmlTags()}", "Judge"); bool judgeSuicide; + if (pc.GetAbilityUseLimit() < 1 || GlobalUseLimit[pc.PlayerId] < 1) { if (!isUI) - { Utils.SendMessage(GetString("JudgeTrialMax"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("JudgeTrialMax")); - } return true; } @@ -157,13 +133,9 @@ namespace EHR.Crewmate if (Jailor.PlayerIdList.Any(x => Main.PlayerStates[x].Role is Jailor { IsEnable: true } jl && jl.JailorTarget == target.PlayerId)) { if (!isUI) - { Utils.SendMessage(GetString("CanNotTrialJailed"), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Jailor), GetString("JailorTitle"))); - } else - { pc.ShowPopUp(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Jailor), GetString("JailorTitle")) + "\n" + GetString("CanNotTrialJailed")); - } return true; } @@ -171,13 +143,9 @@ namespace EHR.Crewmate if (Medic.InProtect(target.PlayerId) && !Medic.JudgingIgnoreShield.GetBool()) { if (!isUI) - { Utils.SendMessage(GetString("CanNotTrialProtected"), pc.PlayerId, CustomRoles.Medic.ToColoredString()); - } else - { pc.ShowPopUp($"{CustomRoles.Medic.ToColoredString()}\n{GetString("CanNotTrialProtected")}"); - } return true; } @@ -185,97 +153,55 @@ namespace EHR.Crewmate if (pc.PlayerId == target.PlayerId) { if (!isUI) - { Utils.SendMessage(GetString("LaughToWhoTrialSelf"), pc.PlayerId, Utils.ColorString(Color.cyan, GetString("MessageFromKPD"))); - } else - { pc.ShowPopUp(Utils.ColorString(Color.cyan, GetString("MessageFromKPD")) + "\n" + GetString("LaughToWhoTrialSelf")); - } judgeSuicide = true; } else if (pc.Is(CustomRoles.Madmate)) - { judgeSuicide = false; - } else if (pc.Is(CustomRoles.Charmed)) - { judgeSuicide = false; - } else if (pc.Is(CustomRoles.Recruit)) - { judgeSuicide = false; - } else if (pc.Is(CustomRoles.Contagious)) - { judgeSuicide = false; - } else if (target.Is(CustomRoles.Rascal)) - { judgeSuicide = false; - } else if (target.Is(CustomRoles.Pestilence)) - { judgeSuicide = true; - } else if (target.Is(CustomRoles.Trickster)) - { judgeSuicide = true; - } else if (target.Is(CustomRoles.Madmate) && CanTrialMadmate.GetBool()) - { judgeSuicide = false; - } else if (target.IsConverted() && CanTrialConverted.GetBool()) - { judgeSuicide = false; - } else if (target.IsNeutralKiller() && CanTrialNeutralK.GetBool()) - { judgeSuicide = false; - } else { CustomRoles targetRole = target.GetCustomRole(); + if (targetRole.GetCrewmateRoleCategory() == RoleOptionType.Crewmate_Killing && CanTrialCrewKilling.GetBool()) - { judgeSuicide = false; - } else if (targetRole.GetNeutralRoleCategory() == RoleOptionType.Neutral_Benign && CanTrialNeutralB.GetBool()) - { judgeSuicide = false; - } else if (targetRole.GetNeutralRoleCategory() == RoleOptionType.Neutral_Evil && CanTrialNeutralE.GetBool()) - { judgeSuicide = false; - } else if (targetRole.IsNonNK() && !CanTrialNeutralB.GetBool() && !CanTrialNeutralE.GetBool() && targetRole.GetNeutralRoleCategory() is not RoleOptionType.Neutral_Benign and not RoleOptionType.Neutral_Evil && CanTrialNeutralK.GetBool()) - { judgeSuicide = false; - } else if (targetRole.IsImpostor()) - { judgeSuicide = false; - } else if (targetRole.IsMadmate() && CanTrialMadmate.GetBool()) - { judgeSuicide = false; - } else if (targetRole is CustomRoles.Necromancer or CustomRoles.Deathknight or CustomRoles.Sidekick && CanTrialNeutralK.GetBool()) - { judgeSuicide = false; - } else - { judgeSuicide = true; - } } - if (pc.GetCustomSubRoles().Any(x => x.IsConverted() || x == CustomRoles.Bloodlust) && !target.Is(CustomRoles.Pestilence)) - { - judgeSuicide = false; - } + if (pc.GetCustomSubRoles().Any(x => x.IsConverted() || x == CustomRoles.Bloodlust) && !target.Is(CustomRoles.Pestilence)) judgeSuicide = false; PlayerControl dp = judgeSuicide ? pc : target; @@ -292,7 +218,7 @@ namespace EHR.Crewmate Utils.AfterPlayerDeathTasks(dp, true); - Utils.NotifyRoles(false, NoCache: true); + Utils.NotifyRoles(NoCache: true); LateTask.New(() => { Utils.SendMessage(string.Format(GetString("TrialKill"), Name), 255, Utils.ColorString(Utils.GetRoleColor(CustomRoles.NiceGuesser), GetString("TrialKillTitle"))); }, 0.6f, "Guess Msg"); }, 0.2f, "Trial Kill"); @@ -307,23 +233,15 @@ namespace EHR.Crewmate private static bool MsgToPlayerAndRole(string msg, out byte id, out string error) { - if (msg.StartsWith("/")) - { - msg = msg.Replace("/", string.Empty); - } + if (msg.StartsWith("/")) msg = msg.Replace("/", string.Empty); Regex r = new("\\d+"); MatchCollection mc = r.Matches(msg); - string result = string.Empty; - for (int i = 0; i < mc.Count; i++) - { - result += mc[i]; - } + var result = string.Empty; + for (var i = 0; i < mc.Count; i++) result += mc[i]; if (int.TryParse(result, out int num)) - { id = Convert.ToByte(num); - } else { id = byte.MaxValue; @@ -332,6 +250,7 @@ namespace EHR.Crewmate } PlayerControl target = Utils.GetPlayerById(id); + if (target == null || target.Data.IsDead) { error = GetString("TrialNull"); @@ -345,14 +264,12 @@ namespace EHR.Crewmate public static bool CheckCommand(ref string msg, string command, bool exact = true) { string[] comList = command.Split('|'); + foreach (string str in comList) { if (exact) { - if (msg == "/" + str) - { - return true; - } + if (msg == "/" + str) return true; } else { @@ -369,10 +286,7 @@ namespace EHR.Crewmate private static void SendRPC(byte playerId) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.Judge, SendOption.Reliable); writer.Write(playerId); @@ -389,19 +303,12 @@ namespace EHR.Crewmate { Logger.Msg($"Click: ID {playerId}", "Judge UI"); PlayerControl pc = Utils.GetPlayerById(playerId); - if (pc == null || !pc.IsAlive() || !GameStates.IsVoting) - { - return; - } + if (pc == null || !pc.IsAlive() || !GameStates.IsVoting) return; if (AmongUsClient.Instance.AmHost) - { TrialMsg(PlayerControl.LocalPlayer, $"/tl {playerId}", true); - } else - { SendRPC(playerId); - } } public static void CreateJudgeButton(MeetingHud __instance) @@ -409,18 +316,15 @@ namespace EHR.Crewmate foreach (PlayerVoteArea pva in __instance.playerStates) { PlayerControl pc = Utils.GetPlayerById(pva.TargetPlayerId); - if (pc == null || !pc.IsAlive()) - { - continue; - } + if (pc == null || !pc.IsAlive()) continue; GameObject template = pva.Buttons.transform.Find("CancelButton").gameObject; GameObject targetBox = Object.Instantiate(template, pva.transform); targetBox.name = "ShootButton"; targetBox.transform.localPosition = new(-0.35f, 0.03f, -1.31f); - SpriteRenderer renderer = targetBox.GetComponent(); + var renderer = targetBox.GetComponent(); renderer.sprite = CustomButton.Get("JudgeIcon"); - PassiveButton button = targetBox.GetComponent(); + var button = targetBox.GetComponent(); button.OnClick.RemoveAllListeners(); button.OnClick.AddListener((Action)(() => JudgeOnClick(pva.TargetPlayerId /*, __instance*/))); } @@ -431,10 +335,7 @@ namespace EHR.Crewmate { public static void Postfix(MeetingHud __instance) { - if (PlayerControl.LocalPlayer.Is(CustomRoles.Judge) && PlayerControl.LocalPlayer.IsAlive()) - { - CreateJudgeButton(__instance); - } + if (PlayerControl.LocalPlayer.Is(CustomRoles.Judge) && PlayerControl.LocalPlayer.IsAlive()) CreateJudgeButton(__instance); } } } diff --git a/Roles/Crewmate/Leery.cs b/Roles/Crewmate/Leery.cs index 1386bb1ff..15f00ef3b 100644 --- a/Roles/Crewmate/Leery.cs +++ b/Roles/Crewmate/Leery.cs @@ -46,10 +46,7 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask || ExileController.Instance || !pc.IsAlive() || Count++ < 5) - { - return; - } + if (!GameStates.IsInTask || ExileController.Instance || !pc.IsAlive() || Count++ < 5) return; Count = 0; @@ -67,10 +64,7 @@ namespace EHR.Crewmate PlayerControl nearestPlayer = nearbyPlayers.MinBy(p => Vector2.Distance(pos, p.Pos())); - if (nearestPlayer.PlayerId == CurrentTarget && InvestigationEndTS == 0) - { - return; - } + if (nearestPlayer.PlayerId == CurrentTarget && InvestigationEndTS == 0) return; if (nearestPlayer.PlayerId != CurrentTarget) { @@ -80,17 +74,11 @@ namespace EHR.Crewmate return; } - if (Utils.TimeStamp < InvestigationEndTS) - { - return; - } + if (Utils.TimeStamp < InvestigationEndTS) return; InvestigationEndTS = 0; SendRPC(); - if (!nearestPlayer.IsCrewmate()) - { - pc.Notify(Translator.GetString("LeeryNotify")); - } + if (!nearestPlayer.IsCrewmate()) pc.Notify(Translator.GetString("LeeryNotify")); } private void SendRPC() @@ -106,16 +94,10 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != LeeryId || seer.PlayerId != target.PlayerId || meeting || hud || !ShowNearestPlayerName.GetBool() || InvestigationEndTS == 0) - { - return string.Empty; - } + if (seer.PlayerId != LeeryId || seer.PlayerId != target.PlayerId || meeting || hud || !ShowNearestPlayerName.GetBool() || InvestigationEndTS == 0) return string.Empty; string text = string.Format(Translator.GetString("LeerySuffix"), CurrentTarget.ColoredPlayerName()); - if (ShowProgress.GetBool()) - { - text += $" {Math.Ceiling(InvestigationEndTS / (float)Utils.TimeStamp * 100)}%"; - } + if (ShowProgress.GetBool()) text += $" {Math.Ceiling(InvestigationEndTS / (float)Utils.TimeStamp * 100)}%"; return text; } diff --git a/Roles/Crewmate/Lighter.cs b/Roles/Crewmate/Lighter.cs index 06cf3d0ba..746970420 100644 --- a/Roles/Crewmate/Lighter.cs +++ b/Roles/Crewmate/Lighter.cs @@ -14,24 +14,31 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(6850, TabGroup.CrewmateRoles, CustomRoles.Lighter); + LighterSkillCooldown = new FloatOptionItem(6852, "LighterSkillCooldown", new(0f, 180f, 1f), 25f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Lighter]) .SetValueFormat(OptionFormat.Seconds); + LighterSkillDuration = new FloatOptionItem(6853, "LighterSkillDuration", new(0f, 180f, 1f), 10f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Lighter]) .SetValueFormat(OptionFormat.Seconds); + LighterVisionNormal = new FloatOptionItem(6854, "LighterVisionNormal", new(0f, 5f, 0.05f), 0.9f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Lighter]) .SetValueFormat(OptionFormat.Multiplier); + LighterVisionOnLightsOut = new FloatOptionItem(6855, "LighterVisionOnLightsOut", new(0f, 5f, 0.05f), 0.35f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Lighter]) .SetValueFormat(OptionFormat.Multiplier); + LighterSkillMaxOfUseage = new IntegerOptionItem(6856, "AbilityUseLimit", new(0, 180, 1), 2, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Lighter]) .SetValueFormat(OptionFormat.Times); + LighterAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(6857, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 1.5f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Lighter]) .SetValueFormat(OptionFormat.Times); + LighterAbilityChargesWhenFinishedTasks = new FloatOptionItem(6858, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Lighter]) .SetValueFormat(OptionFormat.Times); @@ -63,20 +70,17 @@ namespace EHR.Crewmate if (IsAbilityActive) { opt.SetVision(false); + if (Utils.IsActive(SystemTypes.Electrical)) - { opt.SetFloat(FloatOptionNames.CrewLightMod, LighterVisionOnLightsOut.GetFloat() * 5); - } else - { opt.SetFloat(FloatOptionNames.CrewLightMod, LighterVisionNormal.GetFloat()); - } } } public override string GetProgressText(byte playerId, bool comms) { - StringBuilder ProgressText = new StringBuilder(); + var ProgressText = new StringBuilder(); ProgressText.Append(Utils.GetAbilityUseLimitDisplay(playerId, IsAbilityActive)); ProgressText.Append(Utils.GetTaskCount(playerId, comms)); @@ -87,13 +91,9 @@ namespace EHR.Crewmate public override void SetButtonTexts(HudManager hud, byte id) { if (UsePets.GetBool()) - { hud.PetButton.buttonLabelText.text = Translator.GetString("LighterVentButtonText"); - } else - { hud.AbilityButton.buttonLabelText.text = Translator.GetString("LighterVentButtonText"); - } } public override void OnPet(PlayerControl pc) @@ -108,10 +108,7 @@ namespace EHR.Crewmate private void Light(PlayerControl pc) { - if (IsAbilityActive) - { - return; - } + if (IsAbilityActive) return; if (pc.GetAbilityUseLimit() >= 1) { @@ -123,9 +120,7 @@ namespace EHR.Crewmate pc.MarkDirtySettings(); } else - { pc.Notify(Translator.GetString("OutOfAbilityUsesDoMoreTasks")); - } } public override void OnReportDeadBody() @@ -136,10 +131,7 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl player) { - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; if (IsAbilityActive && ActivateTimeStamp + LighterSkillDuration.GetInt() < Utils.TimeStamp) { diff --git a/Roles/Crewmate/Lookout.cs b/Roles/Crewmate/Lookout.cs index 1d69f77b0..63bf74df8 100644 --- a/Roles/Crewmate/Lookout.cs +++ b/Roles/Crewmate/Lookout.cs @@ -26,40 +26,25 @@ namespace EHR.Crewmate public override void OnPet(PlayerControl pc) { PlayerControl[] aapc = Main.AllAlivePlayerControls; - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < aapc.Length; i++) - { - if (i % 3 == 0) - { - sb.AppendLine(); - } - } + var sb = new StringBuilder(); - for (int i = 0; i < aapc.Length; i++) + for (var i = 0; i < aapc.Length; i++) + if (i % 3 == 0) + sb.AppendLine(); + + for (var i = 0; i < aapc.Length; i++) { PlayerControl player = aapc[i]; - if (player == null) - { - continue; - } + if (player == null) continue; - if (i != 0) - { - sb.Append("; "); - } + if (i != 0) sb.Append("; "); string name = player.GetRealName(); byte id = player.PlayerId; - if (Main.PlayerColors.TryGetValue(id, out Color32 color)) - { - name = Utils.ColorString(color, name); - } + if (Main.PlayerColors.TryGetValue(id, out Color32 color)) name = Utils.ColorString(color, name); sb.Append($"{name} {id}"); - if (i % 3 == 0 && i != aapc.Length - 1) - { - sb.AppendLine(); - } + if (i % 3 == 0 && i != aapc.Length - 1) sb.AppendLine(); } pc.Notify(sb.ToString()); diff --git a/Roles/Crewmate/Luckey.cs b/Roles/Crewmate/Luckey.cs index 93b3324a0..9e5a5afbb 100644 --- a/Roles/Crewmate/Luckey.cs +++ b/Roles/Crewmate/Luckey.cs @@ -8,6 +8,7 @@ public override void SetupCustomOption() { Options.SetupRoleOptions(5800, TabGroup.CrewmateRoles, CustomRoles.Luckey); + Options.LuckeyProbability = new IntegerOptionItem(5900, "LuckeyProbability", new(0, 100, 5), 50, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Luckey]) .SetValueFormat(OptionFormat.Percent); @@ -25,7 +26,8 @@ public override bool OnCheckMurderAsTarget(PlayerControl killer, PlayerControl target) { - IRandom rd = IRandom.Instance; + var rd = IRandom.Instance; + if (rd.Next(0, 100) < Options.LuckeyProbability.GetInt()) { killer.SetKillCooldown(15f); diff --git a/Roles/Crewmate/Lyncher.cs b/Roles/Crewmate/Lyncher.cs index 31f7dc053..f48988157 100644 --- a/Roles/Crewmate/Lyncher.cs +++ b/Roles/Crewmate/Lyncher.cs @@ -32,15 +32,19 @@ namespace EHR.Crewmate public override void SetupCustomOption() { - int id = 648550; + var id = 648550; Options.SetupRoleOptions(id++, TabGroup.CrewmateRoles, CustomRoles.Lyncher); + TaskNum = new IntegerOptionItem(++id, "Lyncher.TaskNum", new(1, 10, 1), 3, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Lyncher]); + GuessMode = new StringOptionItem(++id, "Lyncher.GuessMode", GuessModes, 1, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Lyncher]); + Vision = new FloatOptionItem(++id, "Vision", new(0f, 1.5f, 0.05f), 0.5f, TabGroup.CrewmateRoles) .SetValueFormat(OptionFormat.Multiplier) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Lyncher]); + Options.OverrideTasksData.Create(++id, TabGroup.CrewmateRoles, CustomRoles.Lyncher); } @@ -62,13 +66,9 @@ namespace EHR.Crewmate Utils.SendRPC(CustomRPC.SyncRoleData, LyncherId, 1, TasksCompleted); if (Main.HasJustStarted) - { LateTask.New(Action, 12f, log: false); - } else - { Action(); - } return; @@ -87,12 +87,10 @@ namespace EHR.Crewmate public override void OnTaskComplete(PlayerControl pc, int completedTaskCount, int totalTaskCount) { - if (!pc.IsAlive()) - { - return; - } + if (!pc.IsAlive()) return; TasksCompleted++; + if (TasksCompleted >= TaskNum.GetInt()) { RevealLetter(); @@ -100,9 +98,7 @@ namespace EHR.Crewmate Utils.NotifyRoles(SpecifySeer: pc); } else - { Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - } Utils.SendRPC(CustomRPC.SyncRoleData, LyncherId, 1, TasksCompleted); } @@ -110,6 +106,7 @@ namespace EHR.Crewmate private void RevealLetter() { Dictionary nextLetters = AllRoleNames.ToDictionary(x => x.Key, x => x.Value.Except(KnownCharacters[x.Key]).RandomElement()); + KnownCharacters.Do(x => { x.Value.Add(nextLetters[x.Key]); @@ -145,10 +142,7 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != LyncherId) - { - return string.Empty; - } + if (seer.PlayerId != LyncherId) return string.Empty; return (seer.PlayerId == target.PlayerId) switch { diff --git a/Roles/Crewmate/Markseeker.cs b/Roles/Crewmate/Markseeker.cs index 64492222e..8b59425c2 100644 --- a/Roles/Crewmate/Markseeker.cs +++ b/Roles/Crewmate/Markseeker.cs @@ -35,10 +35,7 @@ namespace EHR.Crewmate public override bool OnVote(PlayerControl player, PlayerControl target) { - if (player == null || target == null || player.PlayerId == target.PlayerId || MarkedId != byte.MaxValue || Main.DontCancelVoteList.Contains(player.PlayerId)) - { - return false; - } + if (player == null || target == null || player.PlayerId == target.PlayerId || MarkedId != byte.MaxValue || Main.DontCancelVoteList.Contains(player.PlayerId)) return false; MarkedId = target.PlayerId; @@ -48,10 +45,7 @@ namespace EHR.Crewmate public static void OnDeath(PlayerControl player) { - if (Main.PlayerStates[player.PlayerId].Role is not Markseeker { IsEnable: true } ms || ms.MarkedId == byte.MaxValue) - { - return; - } + if (Main.PlayerStates[player.PlayerId].Role is not Markseeker { IsEnable: true } ms || ms.MarkedId == byte.MaxValue) return; ms.TargetRevealed = true; } diff --git a/Roles/Crewmate/Marshall.cs b/Roles/Crewmate/Marshall.cs index 3ca16a53d..6ec72efb6 100644 --- a/Roles/Crewmate/Marshall.cs +++ b/Roles/Crewmate/Marshall.cs @@ -17,13 +17,16 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Marshall); + Enum.GetValues().Do(x => { SeeingTeamOptions[x] = new BooleanOptionItem(Id + 2 + (int)x, $"{x}CanFindMarshall", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Marshall]); }); + CanBeGuessedOnTaskCompletion = new BooleanOptionItem(Id + 10, "MarshallCanBeGuessedOnTaskCompletion", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Marshall]); + OverrideTasksData.Create(Id + 20, TabGroup.CrewmateRoles, CustomRoles.Marshall); } @@ -46,6 +49,7 @@ namespace EHR.Crewmate { Team team = seer.GetTeam(); bool madmate = seer.IsMadmate(); + return team switch { Team.Crewmate when !madmate => true, diff --git a/Roles/Crewmate/Mathematician.cs b/Roles/Crewmate/Mathematician.cs index 700d7706e..551a9b4f7 100644 --- a/Roles/Crewmate/Mathematician.cs +++ b/Roles/Crewmate/Mathematician.cs @@ -31,10 +31,7 @@ namespace EHR.Crewmate { try { - if (pc == null || !pc.IsAlive() || !GameStates.IsMeeting || State.AskedQuestion || !int.TryParse(num1Str, out int num1) || !int.TryParse(num2Str, out int num2)) - { - return; - } + if (pc == null || !pc.IsAlive() || !GameStates.IsMeeting || State.AskedQuestion || !int.TryParse(num1Str, out int num1) || !int.TryParse(num2Str, out int num2)) return; State.AskedQuestion = true; State.Answer = num1 + num2; @@ -54,10 +51,7 @@ namespace EHR.Crewmate { try { - if (pc == null || !pc.IsAlive() || !GameStates.IsMeeting || !State.AskedQuestion || State.MathematicianPlayerId == pc.PlayerId || !int.TryParse(answerStr, out int answer)) - { - return; - } + if (pc == null || !pc.IsAlive() || !GameStates.IsMeeting || !State.AskedQuestion || State.MathematicianPlayerId == pc.PlayerId || !int.TryParse(answerStr, out int answer)) return; if (answer == State.Answer) { diff --git a/Roles/Crewmate/Mayor.cs b/Roles/Crewmate/Mayor.cs index 799758754..1332e5df0 100644 --- a/Roles/Crewmate/Mayor.cs +++ b/Roles/Crewmate/Mayor.cs @@ -31,33 +31,24 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = !MayorUsedButtonCount.TryGetValue(playerId, out int count) || count < MayorNumOfUseButton.GetInt() ? opt.GetInt(Int32OptionNames.EmergencyCooldown) : 300f; + AURoleOptions.EngineerInVentMaxTime = 1f; } public override void SetButtonTexts(HudManager hud, byte id) { - if (!MayorHasPortableButton.GetBool()) - { - return; - } + if (!MayorHasPortableButton.GetBool()) return; if (UsePets.GetBool()) - { hud.PetButton.buttonLabelText.text = Translator.GetString("MayorVentButtonText"); - } else - { hud.AbilityButton.buttonLabelText.text = Translator.GetString("MayorVentButtonText"); - } } public override void OnPet(PlayerControl pc) @@ -73,34 +64,35 @@ namespace EHR.Crewmate private static void Button(PlayerControl pc) { - if (!MayorHasPortableButton.GetBool()) - { - return; - } + if (!MayorHasPortableButton.GetBool()) return; - if (MayorUsedButtonCount.TryGetValue(pc.PlayerId, out int count) && count < MayorNumOfUseButton.GetInt()) - { - pc.ReportDeadBody(null); - } + if (MayorUsedButtonCount.TryGetValue(pc.PlayerId, out int count) && count < MayorNumOfUseButton.GetInt()) pc.ReportDeadBody(null); } public override void SetupCustomOption() { SetupRoleOptions(9500, TabGroup.CrewmateRoles, CustomRoles.Mayor); + MayorAdditionalVote = new IntegerOptionItem(9510, "MayorAdditionalVote", new(0, 90, 1), 2, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mayor]) .SetValueFormat(OptionFormat.Votes); + MayorHasPortableButton = new BooleanOptionItem(9511, "MayorHasPortableButton", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mayor]); + MayorNumOfUseButton = new IntegerOptionItem(9512, "MayorNumOfUseButton", new(1, 90, 1), 1, TabGroup.CrewmateRoles) .SetParent(MayorHasPortableButton) .SetValueFormat(OptionFormat.Times); + MayorHideVote = new BooleanOptionItem(9513, "MayorHideVote", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mayor]); + MayorRevealWhenDoneTasks = new BooleanOptionItem(9514, "MayorRevealWhenDoneTasks", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mayor]); + MayorSeesVoteColorsWhenDoneTasks = new BooleanOptionItem(9515, "MayorSeesVoteColorsWhenDoneTasks", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mayor]); + OverrideTasksData.Create(9516, TabGroup.CrewmateRoles, CustomRoles.Mayor); } } diff --git a/Roles/Crewmate/Medic.cs b/Roles/Crewmate/Medic.cs index a96622ac4..6e1c87f57 100644 --- a/Roles/Crewmate/Medic.cs +++ b/Roles/Crewmate/Medic.cs @@ -47,28 +47,40 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Medic); + WhoCanSeeProtect = new StringOptionItem(Id + 2, "MedicWhoCanSeeProtect", MedicWhoCanSeeProtectName, 0, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Medic]); + KnowShieldBroken = new StringOptionItem(Id + 3, "MedicKnowShieldBroken", MedicWhoCanSeeProtectName, 1, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Medic]); + ShieldDeactivatesWhenMedicDies = new BooleanOptionItem(Id + 4, "MedicShieldDeactivatesWhenMedicDies", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Medic]); + ShieldDeactivationIsVisible = new StringOptionItem(Id + 5, "MedicShielDeactivationIsVisible", ShieldDeactivationIsVisibleOption, 0, TabGroup.CrewmateRoles) .SetParent(ShieldDeactivatesWhenMedicDies); + ShieldBreaksOnKillAttempt = new BooleanOptionItem(Id + 6, "MedicShieldBreaksOnKillAttempt", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Medic]); + ShieldBreakIsVisible = new StringOptionItem(Id + 7, "MedicShieldBreakIsVisible", ShieldDeactivationIsVisibleOption, 0, TabGroup.CrewmateRoles) .SetParent(ShieldBreaksOnKillAttempt); + ResetCooldown = new FloatOptionItem(Id + 8, "MedicResetCooldown", new(0f, 120f, 1f), 15f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Medic]) .SetValueFormat(OptionFormat.Seconds); + GuesserIgnoreShield = new BooleanOptionItem(Id + 9, "MedicShieldedCanBeGuessed", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Medic]); + JudgingIgnoreShield = new BooleanOptionItem(Id + 10, "MedicShieldedCanBeJudged", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Medic]); + AmountOfShields = new IntegerOptionItem(Id + 11, "MedicAmountOfShields", new(1, 14, 1), 1, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Medic]); + UsePet = Options.CreatePetUseSetting(Id + 12, CustomRoles.Medic); + CD = new FloatOptionItem(Id + 13, "AbilityCooldown", new(0f, 180f, 2.5f), 7.5f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Medic]) .SetValueFormat(OptionFormat.Seconds); @@ -90,10 +102,7 @@ namespace EHR.Crewmate private static void SendRPCForProtectList() { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetMedicalerProtectList, SendOption.Reliable); writer.Write(ProtectList.Count); @@ -105,10 +114,7 @@ namespace EHR.Crewmate { int count = reader.ReadInt32(); ProtectList = []; - for (int i = 0; i < count; i++) - { - ProtectList.Add(reader.ReadByte()); - } + for (var i = 0; i < count; i++) ProtectList.Add(reader.ReadByte()); } public override bool CanUseKillButton(PlayerControl pc) @@ -139,20 +145,11 @@ namespace EHR.Crewmate public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null) - { - return false; - } + if (killer == null || target == null) return false; - if (!CanUseKillButton(killer)) - { - return false; - } + if (!CanUseKillButton(killer)) return false; - if (ProtectList.Contains(target.PlayerId)) - { - return false; - } + if (ProtectList.Contains(target.PlayerId)) return false; killer.RpcRemoveAbilityUse(); @@ -184,15 +181,9 @@ namespace EHR.Crewmate public static bool OnAnyoneCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null) - { - return false; - } + if (killer == null || target == null) return false; - if (!ProtectList.Contains(target.PlayerId)) - { - return false; - } + if (!ProtectList.Contains(target.PlayerId)) return false; killer.SetKillCooldown(ResetCooldown.GetFloat()); @@ -231,28 +222,21 @@ namespace EHR.Crewmate public static void OnCheckMark() { - bool notify = false; + var notify = false; notify |= CheckMedicDeath(); notify |= CheckShieldBreak(); if (notify) { foreach (byte id in PlayerIdList) - { - foreach (byte id2 in ProtectList) - { - Utils.NotifyRoles(SpecifySeer: Utils.GetPlayerById(id), SpecifyTarget: Utils.GetPlayerById(id2)); - } - } + foreach (byte id2 in ProtectList) + Utils.NotifyRoles(SpecifySeer: Utils.GetPlayerById(id), SpecifyTarget: Utils.GetPlayerById(id2)); } } private static bool CheckMedicDeath() { - if (!ShieldDeactivatesWhenMedicDies.GetBool()) - { - return false; - } + if (!ShieldDeactivatesWhenMedicDies.GetBool()) return false; if ((Visible)ShieldDeactivationIsVisible.GetInt() == Visible.AfterMeeting) { @@ -265,10 +249,7 @@ namespace EHR.Crewmate private static bool CheckShieldBreak() { - if (!ShieldBreaksOnKillAttempt.GetBool()) - { - return false; - } + if (!ShieldBreaksOnKillAttempt.GetBool()) return false; if ((Visible)ShieldBreakIsVisible.GetInt() == Visible.AfterMeeting) { @@ -281,15 +262,9 @@ namespace EHR.Crewmate public static void IsDead(PlayerControl target) { - if (!target.Is(CustomRoles.Medic)) - { - return; - } + if (!target.Is(CustomRoles.Medic)) return; - if (!ShieldDeactivatesWhenMedicDies.GetBool()) - { - return; - } + if (!ShieldDeactivatesWhenMedicDies.GetBool()) return; Utils.NotifyRoles(SpecifySeer: target); @@ -301,10 +276,7 @@ namespace EHR.Crewmate { TempMarkProtectedList = []; - foreach (byte pc in ProtectList) - { - Utils.NotifyRoles(SpecifySeer: Utils.GetPlayerById(pc), SpecifyTarget: target); - } + foreach (byte pc in ProtectList) Utils.NotifyRoles(SpecifySeer: Utils.GetPlayerById(pc), SpecifyTarget: target); } } @@ -312,7 +284,7 @@ namespace EHR.Crewmate { if (ProtectList.Count > 0) { - string shieldMark = $" ●"; + var shieldMark = $" ●"; bool self = seer.PlayerId == target.PlayerId; bool seerIsMedic = seer.Is(CustomRoles.Medic); @@ -323,20 +295,11 @@ namespace EHR.Crewmate bool seerHasMark = TempMarkProtectedList.Contains(seer.PlayerId); bool targetHasMark = TempMarkProtectedList.Contains(target.PlayerId); - if (self && (seerProtected || seerHasMark) && targetSeesProtection) - { - return shieldMark; - } + if (self && (seerProtected || seerHasMark) && targetSeesProtection) return shieldMark; - if (seerIsMedic && (targetProtected || targetHasMark) && medicSeesProtection) - { - return shieldMark; - } + if (seerIsMedic && (targetProtected || targetHasMark) && medicSeesProtection) return shieldMark; - if (seer.Data.IsDead && targetProtected && !seerIsMedic) - { - return shieldMark; - } + if (seer.Data.IsDead && targetProtected && !seerIsMedic) return shieldMark; } return string.Empty; diff --git a/Roles/Crewmate/Mediumshiper.cs b/Roles/Crewmate/Mediumshiper.cs index 6a50a47eb..1966f81b2 100644 --- a/Roles/Crewmate/Mediumshiper.cs +++ b/Roles/Crewmate/Mediumshiper.cs @@ -21,14 +21,18 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Mediumshiper); + ContactLimitOpt = new IntegerOptionItem(Id + 10, "MediumshiperContactLimit", new(0, 15, 1), 1, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Mediumshiper]) .SetValueFormat(OptionFormat.Times); + OnlyReceiveMsgFromCrew = new BooleanOptionItem(Id + 11, "MediumshiperOnlyReceiveMsgFromCrew", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Mediumshiper]); + MediumAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 12, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 1f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Mediumshiper]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 13, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Mediumshiper]) .SetValueFormat(OptionFormat.Times); @@ -49,17 +53,11 @@ namespace EHR.Crewmate public static void OnReportDeadBody(NetworkedPlayerInfo target) { ContactPlayer = []; - if (target == null || target.Object == null) - { - return; - } + if (target == null || target.Object == null) return; foreach (PlayerControl pc in Main.AllAlivePlayerControls.Where(x => PlayerIdList.Contains(x.PlayerId) && x.PlayerId != target.PlayerId).ToArray()) { - if (pc.GetAbilityUseLimit() < 1) - { - continue; - } + if (pc.GetAbilityUseLimit() < 1) continue; pc.RpcRemoveAbilityUse(); ContactPlayer.TryAdd(target.PlayerId, pc.PlayerId); @@ -69,46 +67,25 @@ namespace EHR.Crewmate public static bool MsMsg(PlayerControl pc, string msg) { - if (!AmongUsClient.Instance.AmHost) - { - return false; - } + if (!AmongUsClient.Instance.AmHost) return false; - if (!GameStates.IsMeeting || pc == null) - { - return false; - } + if (!GameStates.IsMeeting || pc == null) return false; - if (!ContactPlayer.ContainsKey(pc.PlayerId)) - { - return false; - } + if (!ContactPlayer.ContainsKey(pc.PlayerId)) return false; - if (OnlyReceiveMsgFromCrew.GetBool() && !pc.IsCrewmate()) - { - return false; - } + if (OnlyReceiveMsgFromCrew.GetBool() && !pc.IsCrewmate()) return false; - if (pc.IsAlive()) - { - return false; - } + if (pc.IsAlive()) return false; msg = msg.ToLower().Trim(); - if (!CheckCommand(ref msg, "通灵|ms|mediumship|medium", false)) - { - return false; - } + if (!CheckCommand(ref msg, "通灵|ms|mediumship|medium", false)) return false; bool ans; + if (msg.Contains('n') || msg.Contains(GetString("No")) || msg.Contains('错') || msg.Contains("不是")) - { ans = false; - } else if (msg.Contains('y') || msg.Contains(GetString("Yes")) || msg.Contains('对')) - { ans = true; - } else { Utils.SendMessage(GetString("MediumshipHelp"), pc.PlayerId); @@ -126,12 +103,10 @@ namespace EHR.Crewmate private static bool CheckCommand(ref string msg, string command, bool exact = true) { string[] comList = command.Split('|'); + foreach (string str in comList) { - if (exact && msg == "/" + str) - { - return true; - } + if (exact && msg == "/" + str) return true; if (msg.StartsWith("/" + str)) { diff --git a/Roles/Crewmate/Merchant.cs b/Roles/Crewmate/Merchant.cs index da362a350..489c3ac80 100644 --- a/Roles/Crewmate/Merchant.cs +++ b/Roles/Crewmate/Merchant.cs @@ -69,29 +69,17 @@ namespace EHR.Crewmate GroupedAddons = Options.GroupedAddons.ToDictionary(x => x.Key, x => x.Value.ToList()); - if (!OptionCanSellHarmful.GetBool()) - { - GroupedAddons.Remove(AddonTypes.Harmful); - } + if (!OptionCanSellHarmful.GetBool()) GroupedAddons.Remove(AddonTypes.Harmful); - if (!OptionCanSellHelpful.GetBool()) - { - GroupedAddons.Remove(AddonTypes.Helpful); - } + if (!OptionCanSellHelpful.GetBool()) GroupedAddons.Remove(AddonTypes.Helpful); - if (!OptionCanSellMixed.GetBool()) - { - GroupedAddons.Remove(AddonTypes.Mixed); - } + if (!OptionCanSellMixed.GetBool()) GroupedAddons.Remove(AddonTypes.Mixed); GroupedAddons.Remove(AddonTypes.ImpOnly); Addons = GroupedAddons.Values.Flatten().ToList(); - if (OptionSellOnlyEnabledAddons.GetBool()) - { - Addons.RemoveAll(x => x.GetMode() == 0); - } + if (OptionSellOnlyEnabledAddons.GetBool()) Addons.RemoveAll(x => x.GetMode() == 0); Addons.RemoveAll(StartGameHostPatch.BasisChangingAddons.ContainsKey); Addons.RemoveAll(x => x.IsNotAssignableMidGame()); @@ -106,10 +94,7 @@ namespace EHR.Crewmate public override void OnTaskComplete(PlayerControl player, int completedTaskCount, int totalTaskCount) { - if (!player.IsAlive() || !player.Is(CustomRoles.Merchant) || AddonsSold[player.PlayerId] >= OptionMaxSell.GetInt()) - { - return; - } + if (!player.IsAlive() || !player.Is(CustomRoles.Merchant) || AddonsSold[player.PlayerId] >= OptionMaxSell.GetInt()) return; if (Addons.Count == 0) { @@ -132,23 +117,14 @@ namespace EHR.Crewmate (OptionCanTargetNeutral.GetBool() && (x.GetCustomRole().IsNeutral() || x.IsNeutralKiller()))) ).ToList(); - if (availableTargets.Count <= 0) - { - return; - } + if (availableTargets.Count <= 0) return; bool helpfulAddon = GroupedAddons.TryGetValue(AddonTypes.Helpful, out List helpful) && helpful.Contains(addon); bool harmfulAddon = GroupedAddons.TryGetValue(AddonTypes.Harmful, out List harmful) && harmful.Contains(addon); - if (helpfulAddon && OptionSellOnlyHarmfulToEvil.GetBool()) - { - availableTargets.RemoveAll(x => !x.Is(Team.Crewmate)); - } + if (helpfulAddon && OptionSellOnlyHarmfulToEvil.GetBool()) availableTargets.RemoveAll(x => !x.Is(Team.Crewmate)); - if (harmfulAddon && OptionSellOnlyHelpfulToCrew.GetBool()) - { - availableTargets.RemoveAll(x => x.Is(Team.Crewmate)); - } + if (harmfulAddon && OptionSellOnlyHelpfulToCrew.GetBool()) availableTargets.RemoveAll(x => x.Is(Team.Crewmate)); if (availableTargets.Count == 0) { @@ -193,17 +169,11 @@ namespace EHR.Crewmate private static void NotifyBribery(PlayerControl killer, PlayerControl target) { - if (OptionGivesAllMoneyOnBribe.GetBool()) - { - AddonsSold[target.PlayerId] = 0; - } + if (OptionGivesAllMoneyOnBribe.GetBool()) AddonsSold[target.PlayerId] = 0; killer.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Merchant), GetString("BribedByMerchant"))); - if (OptionNotifyBribery.GetBool()) - { - target.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Merchant), GetString("MerchantKillAttemptBribed"))); - } + if (OptionNotifyBribery.GetBool()) target.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Merchant), GetString("MerchantKillAttemptBribed"))); } } } \ No newline at end of file diff --git a/Roles/Crewmate/Mole.cs b/Roles/Crewmate/Mole.cs index 4de6c2822..fa9d9fa74 100644 --- a/Roles/Crewmate/Mole.cs +++ b/Roles/Crewmate/Mole.cs @@ -25,6 +25,7 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Mole); + CD = new FloatOptionItem(Id + 2, "AbilityCooldown", new(0f, 120f, 0.5f), 15f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mole]) .SetValueFormat(OptionFormat.Seconds); @@ -32,10 +33,7 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.EngineerInVentMaxTime = 1f; AURoleOptions.EngineerCooldown = CD.GetFloat(); @@ -43,10 +41,7 @@ namespace EHR.Crewmate public override void OnExitVent(PlayerControl pc, Vent vent) { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; LateTask.New(() => { pc.TPToRandomVent(); }, 0.5f, "Mole TP"); } diff --git a/Roles/Crewmate/Monarch.cs b/Roles/Crewmate/Monarch.cs index 0c399cc8f..a258fee0f 100644 --- a/Roles/Crewmate/Monarch.cs +++ b/Roles/Crewmate/Monarch.cs @@ -19,12 +19,15 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Monarch); + KnightCooldown = new FloatOptionItem(Id + 10, "MonarchKnightCooldown", new(0f, 60f, 2.5f), 15f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Monarch]) .SetValueFormat(OptionFormat.Seconds); + KnightMax = new IntegerOptionItem(Id + 12, "MonarchKnightMax", new(1, 15, 1), 2, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Monarch]) .SetValueFormat(OptionFormat.Times); + UsePet = CreatePetUseSetting(Id + 11, CustomRoles.Monarch); } @@ -61,10 +64,7 @@ namespace EHR.Crewmate public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.GetAbilityUseLimit() < 1) - { - return false; - } + if (killer.GetAbilityUseLimit() < 1) return false; if (target != null && !target.GetCustomRole().IsNotKnightable() && !target.Is(CustomRoles.Knighted) && !target.Is(CustomRoles.TicketsStealer)) { diff --git a/Roles/Crewmate/Monitor.cs b/Roles/Crewmate/Monitor.cs index 514c55fdf..5f0909d67 100644 --- a/Roles/Crewmate/Monitor.cs +++ b/Roles/Crewmate/Monitor.cs @@ -23,8 +23,10 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Monitor); + CanCheckCamera = new BooleanOptionItem(Id + 10, "CanCheckCamera", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Monitor]); + CanVent = new BooleanOptionItem(Id + 14, "CanVent", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Monitor]); } diff --git a/Roles/Crewmate/Mortician.cs b/Roles/Crewmate/Mortician.cs index d26ee6f60..15ae4a766 100644 --- a/Roles/Crewmate/Mortician.cs +++ b/Roles/Crewmate/Mortician.cs @@ -21,6 +21,7 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Mortician); + ShowArrows = new BooleanOptionItem(Id + 2, "ShowArrows", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mortician]); } @@ -41,16 +42,15 @@ namespace EHR.Crewmate public static void OnPlayerDead(PlayerControl target) { Vector2 pos = target.Pos(); - float minDis = float.MaxValue; - string minName = string.Empty; + var minDis = float.MaxValue; + var minName = string.Empty; + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (pc.PlayerId == target.PlayerId) - { - continue; - } + if (pc.PlayerId == target.PlayerId) continue; float dis = Vector2.Distance(pc.Pos(), pos); + if (dis < minDis && dis < 1.5f) { minDis = dis; @@ -59,13 +59,11 @@ namespace EHR.Crewmate } LastPlayerName.TryAdd(target.PlayerId, minName); + foreach (byte pc in PlayerIdList) { PlayerControl player = Utils.GetPlayerById(pc); - if (player == null || !player.IsAlive()) - { - continue; - } + if (player == null || !player.IsAlive()) continue; LocateArrow.Add(pc, target.transform.position); } @@ -73,15 +71,9 @@ namespace EHR.Crewmate public static void OnReportDeadBody(PlayerControl pc, NetworkedPlayerInfo target) { - foreach (byte apc in PlayerIdList) - { - LocateArrow.RemoveAllTarget(apc); - } + foreach (byte apc in PlayerIdList) LocateArrow.RemoveAllTarget(apc); - if (!pc.Is(CustomRoles.Mortician) || target == null || pc.PlayerId == target.PlayerId) - { - return; - } + if (!pc.Is(CustomRoles.Mortician) || target == null || pc.PlayerId == target.PlayerId) return; LastPlayerName.TryGetValue(target.PlayerId, out string name); MsgToSend.Add(pc.PlayerId, name == "" ? string.Format(Translator.GetString("MorticianGetNoInfo"), target.PlayerName) : string.Format(Translator.GetString("MorticianGetInfo"), target.PlayerName, name)); @@ -91,15 +83,9 @@ namespace EHR.Crewmate { if (ShowArrows.GetBool()) { - if (target != null && seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (target != null && seer.PlayerId != target.PlayerId) return string.Empty; - if (seer.PlayerId != MorticianId) - { - return string.Empty; - } + if (seer.PlayerId != MorticianId) return string.Empty; return GameStates.IsMeeting ? string.Empty : Utils.ColorString(Color.white, LocateArrow.GetArrows(seer)); } diff --git a/Roles/Crewmate/Needy.cs b/Roles/Crewmate/Needy.cs index 6a8ff3f9e..1b4141b28 100644 --- a/Roles/Crewmate/Needy.cs +++ b/Roles/Crewmate/Needy.cs @@ -9,12 +9,8 @@ Options.SetupRoleOptions(5700, TabGroup.CrewmateRoles, CustomRoles.Needy); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Crewmate/Negotiator.cs b/Roles/Crewmate/Negotiator.cs index e210f86f9..6268ee4ae 100644 --- a/Roles/Crewmate/Negotiator.cs +++ b/Roles/Crewmate/Negotiator.cs @@ -55,6 +55,7 @@ namespace EHR.Crewmate public static void OnAnyoneApplyGameOptions(IGameOptions opt, byte id) { bool lowVision = false, lowSpeed = false; + foreach (Negotiator instance in Instances) { if (instance.PermanentPenalties.TryGetValue(id, out HashSet penalties)) @@ -73,10 +74,7 @@ namespace EHR.Crewmate opt.SetFloat(FloatOptionNames.ImpostorLightMod, vision); } - if (lowSpeed) - { - Main.AllPlayerSpeed[id] = LowSpeed.GetFloat(); - } + if (lowSpeed) Main.AllPlayerSpeed[id] = LowSpeed.GetFloat(); } public override void AfterMeetingTasks() @@ -85,10 +83,7 @@ namespace EHR.Crewmate { PlayerControl target = TargetId.GetPlayer(); TargetId = byte.MaxValue; - if (target == null || !target.IsAlive()) - { - return; - } + if (target == null || !target.IsAlive()) return; PlayerControl negotiator = NegotiatorId.GetPlayer(); @@ -99,22 +94,15 @@ namespace EHR.Crewmate break; case NegotiationType.HarmfulAddon: CustomRoles addon = Options.GroupedAddons[AddonTypes.Harmful].Shuffle().FirstOrDefault(x => CustomRolesHelper.CheckAddonConflict(x, target)); - if (addon != default) - { - target.RpcSetCustomRole(addon); - } + if (addon != default) target.RpcSetCustomRole(addon); break; case NegotiationType.LowVision: case NegotiationType.LowSpeed: if (PermanentPenalties.TryGetValue(target.PlayerId, out HashSet penalties)) - { penalties.Add(Penalty); - } else - { PermanentPenalties[target.PlayerId] = [Penalty]; - } break; } @@ -125,10 +113,7 @@ namespace EHR.Crewmate public override bool OnVote(PlayerControl voter, PlayerControl target) { - if (target == null || voter == null || voter.PlayerId == target.PlayerId || TargetId != byte.MaxValue || voter.GetAbilityUseLimit() < 1f || MinVotingTimeLeftToNegotiate.GetInt() > MeetingTimeManager.VotingTimeLeft || Main.DontCancelVoteList.Contains(voter.PlayerId)) - { - return false; - } + if (target == null || voter == null || voter.PlayerId == target.PlayerId || TargetId != byte.MaxValue || voter.GetAbilityUseLimit() < 1f || MinVotingTimeLeftToNegotiate.GetInt() > MeetingTimeManager.VotingTimeLeft || Main.DontCancelVoteList.Contains(voter.PlayerId)) return false; TargetId = target.PlayerId; Penalty = NegotiationType.Suicide; @@ -145,12 +130,9 @@ namespace EHR.Crewmate { foreach (Negotiator instance in Instances) { - if (pc.PlayerId != instance.TargetId || !pc.IsAlive()) - { - continue; - } + if (pc.PlayerId != instance.TargetId || !pc.IsAlive()) continue; - NegotiationType type = (NegotiationType)index; + var type = (NegotiationType)index; instance.Penalty = type; string text = string.Format(Translator.GetString("Negotiator.TargetPickSuccess"), Translator.GetString($"Negotiator.Type.{type}")); Utils.SendMessage(text, pc.PlayerId, Translator.GetString("Negotiator.Title")); diff --git a/Roles/Crewmate/NiceEraser.cs b/Roles/Crewmate/NiceEraser.cs index 5ad4e0ee9..78db63b48 100644 --- a/Roles/Crewmate/NiceEraser.cs +++ b/Roles/Crewmate/NiceEraser.cs @@ -21,8 +21,10 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupSingleRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.NiceEraser); + EraseLimitOpt = new IntegerOptionItem(Id + 2, "EraseLimit", new(1, 15, 1), 1, TabGroup.CrewmateRoles).SetParent(Options.CustomRoleSpawnChances[CustomRoles.NiceEraser]) .SetValueFormat(OptionFormat.Times); + HideVote = new BooleanOptionItem(Id + 3, "NiceEraserHideVote", false, TabGroup.CrewmateRoles).SetParent(Options.CustomRoleSpawnChances[CustomRoles.NiceEraser]); CancelVote = Options.CreateVoteCancellingUseSetting(Id + 4, CustomRoles.NiceEraser, TabGroup.CrewmateRoles); } @@ -41,22 +43,13 @@ namespace EHR.Crewmate public override bool OnVote(PlayerControl player, PlayerControl target) { - if (player == null || target == null) - { - return false; - } + if (player == null || target == null) return false; - if (DidVote.Contains(player.PlayerId) || Main.DontCancelVoteList.Contains(player.PlayerId)) - { - return false; - } + if (DidVote.Contains(player.PlayerId) || Main.DontCancelVoteList.Contains(player.PlayerId)) return false; DidVote.Add(player.PlayerId); - if (player.GetAbilityUseLimit() < 1) - { - return false; - } + if (player.GetAbilityUseLimit() < 1) return false; if (target.PlayerId == player.PlayerId) { @@ -72,17 +65,11 @@ namespace EHR.Crewmate player.RpcRemoveAbilityUse(); - if (!PlayerToErase.Contains(target.PlayerId)) - { - PlayerToErase.Add(target.PlayerId); - } + if (!PlayerToErase.Contains(target.PlayerId)) PlayerToErase.Add(target.PlayerId); Utils.SendMessage(string.Format(GetString("EraserEraseNotice"), target.GetRealName()), player.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.NiceEraser), GetString("EraserEraseMsgTitle"))); - if (GameStates.IsInTask) - { - Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: target); - } + if (GameStates.IsInTask) Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: target); Main.DontCancelVoteList.Add(player.PlayerId); return true; @@ -99,10 +86,7 @@ namespace EHR.Crewmate foreach (byte pc in PlayerToErase.ToArray()) { PlayerControl player = Utils.GetPlayerById(pc); - if (player == null) - { - continue; - } + if (player == null) continue; player.RpcSetCustomRole(player.GetCustomRole().GetErasedRole()); player.Notify(GetString("LostRoleByNiceEraser")); diff --git a/Roles/Crewmate/NiceGuesser.cs b/Roles/Crewmate/NiceGuesser.cs index 4277dcf98..b2191b27d 100644 --- a/Roles/Crewmate/NiceGuesser.cs +++ b/Roles/Crewmate/NiceGuesser.cs @@ -10,24 +10,24 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(8600, TabGroup.CrewmateRoles, CustomRoles.NiceGuesser); + GGCanGuessTime = new IntegerOptionItem(8610, "GuesserCanGuessTimes", new(0, 15, 1), 15, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.NiceGuesser]) .SetValueFormat(OptionFormat.Times); + GGCanGuessCrew = new BooleanOptionItem(8611, "GGCanGuessCrew", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.NiceGuesser]); + GGCanGuessAdt = new BooleanOptionItem(8612, "GGCanGuessAdt", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.NiceGuesser]); + GGTryHideMsg = new BooleanOptionItem(8613, "GuesserTryHideMsg", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.NiceGuesser]) .SetColor(Color.green); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Crewmate/NiceHacker.cs b/Roles/Crewmate/NiceHacker.cs index eb5c55f18..c1943facb 100644 --- a/Roles/Crewmate/NiceHacker.cs +++ b/Roles/Crewmate/NiceHacker.cs @@ -34,20 +34,27 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.NiceHacker); + AbilityCD = new FloatOptionItem(Id + 10, "AbilityCD", new(0f, 70f, 1f), 15f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.NiceHacker]) .SetValueFormat(OptionFormat.Seconds); + UseLimitOpt = new IntegerOptionItem(Id + 11, "AbilityUseLimit", new(1, 20, 1), 2, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.NiceHacker]) .SetValueFormat(OptionFormat.Times); + NiceHackerAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 12, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 1f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.NiceHacker]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 13, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.NiceHacker]) .SetValueFormat(OptionFormat.Times); + ModdedClientAbilityUseSecondsMultiplier = new FloatOptionItem(Id + 14, "NiceHackerModdedClientAbilityUseSecondsMultiplier", new(0f, 70f, 1f), 3f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.NiceHacker]) .SetValueFormat(OptionFormat.Seconds); + ModdedClientCanMoveWhileViewingMap = new BooleanOptionItem(Id + 15, "NiceHackerModdedClientCanMoveWhileViewingMap", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.NiceHacker]); + VanillaClientSeesInfoFor = new FloatOptionItem(Id + 16, "NiceHackerVanillaClientSeesInfoFor", new(0f, 70f, 1f), 4f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.NiceHacker]) .SetValueFormat(OptionFormat.Seconds); } @@ -63,22 +70,16 @@ namespace EHR.Crewmate public override void Add(byte playerId) { PlayerIdList.TryAdd(playerId, GetPlayerById(playerId).IsModClient()); + if (!GetPlayerById(playerId).IsModClient()) - { UseLimit.Add(playerId, UseLimitOpt.GetInt()); - } else - { UseLimitSeconds.Add(playerId, UseLimitOpt.GetInt() * ModdedClientAbilityUseSecondsMultiplier.GetInt()); - } } public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = AbilityCD.GetFloat(); AURoleOptions.EngineerInVentMaxTime = 1f; @@ -86,10 +87,7 @@ namespace EHR.Crewmate public static void SendRPC(byte playerId, float secondsLeft) { - if (!DoRPC) - { - return; - } + if (!DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetNiceHackerLimit, SendOption.Reliable); writer.Write(playerId); @@ -99,10 +97,7 @@ namespace EHR.Crewmate public static void ReceiveRPC(MessageReader reader) { - if (AmongUsClient.Instance.AmHost) - { - return; - } + if (AmongUsClient.Instance.AmHost) return; byte playerId = reader.ReadByte(); float secondsLeft = reader.ReadSingle(); @@ -122,59 +117,39 @@ namespace EHR.Crewmate private static void UseAbility(PlayerControl pc) { - if (pc == null) - { - return; - } + if (pc == null) return; - if (pc.IsModClient() || !UseLimit.ContainsKey(pc.PlayerId)) - { - return; - } + if (pc.IsModClient() || !UseLimit.ContainsKey(pc.PlayerId)) return; if (UseLimit[pc.PlayerId] >= 1) { UseLimit[pc.PlayerId] -= 1; Dictionary list = GetAllPlayerLocationsCount(); - StringBuilder sb = new StringBuilder(); - foreach (KeyValuePair location in list) - { - sb.Append($"\n{location.Key}: {location.Value}"); - } + var sb = new StringBuilder(); + foreach (KeyValuePair location in list) sb.Append($"\n{location.Key}: {location.Value}"); pc.Notify(sb.ToString(), VanillaClientSeesInfoFor.GetFloat()); } else - { pc.Notify(GetString("OutOfAbilityUsesDoMoreTasks")); - } } public override void OnFixedUpdate(PlayerControl pc) { - if (pc == null) - { - return; - } + if (pc == null) return; - if (GameStates.IsMeeting) - { - return; - } + if (GameStates.IsMeeting) return; if (Main.PlayerStates[pc.PlayerId].TaskState.IsTaskFinished) { LastUpdate.TryAdd(pc.PlayerId, TimeStamp); + if (LastUpdate[pc.PlayerId] + 5 < TimeStamp) { if (pc.IsModClient()) - { UseLimitSeconds[pc.PlayerId] += AbilityChargesWhenFinishedTasks.GetFloat() * ModdedClientAbilityUseSecondsMultiplier.GetInt(); - } else - { UseLimit[pc.PlayerId] += AbilityChargesWhenFinishedTasks.GetFloat(); - } LastUpdate[pc.PlayerId] = TimeStamp; } @@ -201,10 +176,7 @@ namespace EHR.Crewmate private static void MapCountdown(PlayerControl pc, MapBehaviour map, MapOptions opts, int seconds) { - if (!map.IsOpen) - { - return; - } + if (!map.IsOpen) return; if (seconds <= 0) { @@ -221,22 +193,16 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (!hud || seer == null) - { - return string.Empty; - } + if (!hud || seer == null) return string.Empty; return !seer.Is(CustomRoles.NiceHacker) ? string.Empty : $"{GetString("NiceHackerAbilitySecondsLeft")}: {(int)UseLimitSeconds[seer.PlayerId]}s"; } public override string GetProgressText(byte playerId, bool comms) { - if (playerId.IsPlayerModClient() || !UseLimit.ContainsKey(playerId)) - { - return string.Empty; - } + if (playerId.IsPlayerModClient() || !UseLimit.ContainsKey(playerId)) return string.Empty; - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.Append(GetTaskCount(playerId, comms)); sb.Append(ColorString(UseLimit[playerId] < 1 ? Color.red : Color.white, $" - {Math.Round(UseLimit[playerId], 1)}")); diff --git a/Roles/Crewmate/NiceSwapper.cs b/Roles/Crewmate/NiceSwapper.cs index eec254922..cc92369c3 100644 --- a/Roles/Crewmate/NiceSwapper.cs +++ b/Roles/Crewmate/NiceSwapper.cs @@ -32,16 +32,21 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupSingleRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.NiceSwapper); + SwapMax = new IntegerOptionItem(Id + 3, "NiceSwapperMax", new(0, 20, 1), 1, TabGroup.CrewmateRoles).SetParent(Options.CustomRoleSpawnChances[CustomRoles.NiceSwapper]) .SetValueFormat(OptionFormat.Times); + CanSwapSelf = new BooleanOptionItem(Id + 2, "CanSwapSelfVotes", true, TabGroup.CrewmateRoles).SetParent(Options.CustomRoleSpawnChances[CustomRoles.NiceSwapper]); CanStartMeeting = new BooleanOptionItem(Id + 4, "JesterCanUseButton", true, TabGroup.CrewmateRoles).SetParent(Options.CustomRoleSpawnChances[CustomRoles.NiceSwapper]); + NiceSwapperAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 6, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.3f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.NiceSwapper]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 7, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.NiceSwapper]) .SetValueFormat(OptionFormat.Times); + HideMsg = new BooleanOptionItem(Id + 5, "SwapperHideMsg", true, TabGroup.CrewmateRoles).SetParent(Options.CustomRoleSpawnChances[CustomRoles.NiceSwapper]); } @@ -61,27 +66,19 @@ namespace EHR.Crewmate { string originMsg = msg; - if (!AmongUsClient.Instance.AmHost || !GameStates.IsInGame || pc == null || pc.GetCustomRole() != CustomRoles.NiceSwapper) - { - return false; - } + if (!AmongUsClient.Instance.AmHost || !GameStates.IsInGame || pc == null || pc.GetCustomRole() != CustomRoles.NiceSwapper) return false; Logger.Info($"{pc.GetNameWithRole()} : {msg} (UI: {isUI})", "Swapper"); int operate; msg = msg.ToLower().TrimStart().TrimEnd(); + if (CheckCommand(ref msg, "id|guesslist|gl编号|玩家编号|玩家id|id列表|玩家列表|列表|所有id|全部id")) - { operate = 1; - } else if (CheckCommand(ref msg, "sw|换票|换|swap|st", false)) - { operate = 2; - } else - { return false; - } switch (operate) { @@ -92,10 +89,7 @@ namespace EHR.Crewmate { if (!pc.IsAlive()) { - if (!isUI) - { - Utils.SendMessage(GetString("SwapDead"), pc.PlayerId); - } + if (!isUI) Utils.SendMessage(GetString("SwapDead"), pc.PlayerId); pc.ShowPopUp(GetString("SwapDead")); return true; @@ -103,23 +97,15 @@ namespace EHR.Crewmate if (pc.GetAbilityUseLimit() < 1) { - if (!isUI) - { - Utils.SendMessage(GetString("NiceSwapperTrialMax"), pc.PlayerId); - } + if (!isUI) Utils.SendMessage(GetString("NiceSwapperTrialMax"), pc.PlayerId); pc.ShowPopUp(GetString("NiceSwapperTrialMax")); return true; } if (HideMsg.GetBool() && !isUI) - { ChatManager.SendPreviousMessagesToAll(); - } - else if (pc.AmOwner && !isUI) - { - Utils.SendMessage(originMsg, 255, pc.GetRealName()); - } + else if (pc.AmOwner && !isUI) Utils.SendMessage(originMsg, 255, pc.GetRealName()); if (!byte.TryParse(msg.Replace(" ", string.Empty), out byte targetId)) { @@ -128,10 +114,7 @@ namespace EHR.Crewmate } PlayerControl target = Utils.GetPlayerById(targetId); - if (target == null) - { - break; - } + if (target == null) break; bool targetIsntSelected = SwapTargets.Item1 != target.PlayerId && SwapTargets.Item2 != target.PlayerId; // Whether the picked target isn't already being swapped @@ -143,10 +126,7 @@ namespace EHR.Crewmate { SwapTargets.Item1 = target.PlayerId; - if (!isUI) - { - Utils.SendMessage(GetString("Swap1"), pc.PlayerId); - } + if (!isUI) Utils.SendMessage(GetString("Swap1"), pc.PlayerId); Logger.Info($"{pc.GetNameWithRole().RemoveHtmlTags()} chose to swap {target.GetNameWithRole()} (first target)", "Swapper"); } @@ -155,10 +135,7 @@ namespace EHR.Crewmate { SwapTargets.Item2 = target.PlayerId; - if (!isUI) - { - Utils.SendMessage(GetString("Swap2"), pc.PlayerId); - } + if (!isUI) Utils.SendMessage(GetString("Swap2"), pc.PlayerId); Logger.Info($"{pc.GetNameWithRole().RemoveHtmlTags()} chose to swap {target.GetNameWithRole()} (second target)", "Swapper"); } @@ -167,10 +144,7 @@ namespace EHR.Crewmate { SwapTargets.Item1 = byte.MaxValue; - if (!isUI) - { - Utils.SendMessage(GetString("CancelSwap1"), pc.PlayerId); - } + if (!isUI) Utils.SendMessage(GetString("CancelSwap1"), pc.PlayerId); Logger.Info($"{pc.GetNameWithRole().RemoveHtmlTags()} canceled swapping on {target.GetNameWithRole()} (first target)", "Swapper"); } @@ -179,10 +153,7 @@ namespace EHR.Crewmate { SwapTargets.Item2 = byte.MaxValue; - if (!isUI) - { - Utils.SendMessage(GetString("CancelSwap2"), pc.PlayerId); - } + if (!isUI) Utils.SendMessage(GetString("CancelSwap2"), pc.PlayerId); Logger.Info($"{pc.GetNameWithRole().RemoveHtmlTags()} canceled swapping on {target.GetNameWithRole()} (second target)", "Swapper"); } @@ -190,13 +161,9 @@ namespace EHR.Crewmate else if (!selfCheck) // When the Swapper tries to swap themselves, but they aren't allowed to { if (!isUI) - { Utils.SendMessage(GetString("CantSwapSelf"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("CantSwapSelf")); - } } LateTask.New(() => Utils.NotifyRoles(true, NoCache: true), 0.2f, "NiceSwapperNotifyRoles"); @@ -219,10 +186,7 @@ namespace EHR.Crewmate public static void OnCheckForEndVoting() { - if (NiceSwapperId == byte.MaxValue || SwapTargets.Item1 == byte.MaxValue || SwapTargets.Item2 == byte.MaxValue) - { - return; - } + if (NiceSwapperId == byte.MaxValue || SwapTargets.Item1 == byte.MaxValue || SwapTargets.Item2 == byte.MaxValue) return; CheckForEndVotingPatch.RunRoleCode = false; @@ -234,38 +198,30 @@ namespace EHR.Crewmate playerStates.DoIf(x => x.VotedFor == SwapTargets.Item1, x => { x.UnsetVote(); + if (x.TargetPlayerId.IsHost()) - { MeetingHud.Instance.CmdCastVote(x.TargetPlayerId, SwapTargets.Item2); - } else - { MeetingHud.Instance.CastVote(x.TargetPlayerId, SwapTargets.Item2); - } x.VotedFor = SwapTargets.Item2; }); + playerStates.DoIf(votedFor2.Contains, x => { x.UnsetVote(); + if (x.TargetPlayerId.IsHost()) - { MeetingHud.Instance.CmdCastVote(x.TargetPlayerId, SwapTargets.Item1); - } else - { MeetingHud.Instance.CastVote(x.TargetPlayerId, SwapTargets.Item1); - } x.VotedFor = SwapTargets.Item1; }); PlayerControl Target1 = Utils.GetPlayerById(SwapTargets.Item1); PlayerControl Target2 = Utils.GetPlayerById(SwapTargets.Item2); - if (Target1 == null || Target2 == null) - { - return; - } + if (Target1 == null || Target2 == null) return; Utils.SendMessage(string.Format(GetString("SwapVote"), Target1.GetRealName(), Target2.GetRealName()), 255, Utils.ColorString(Utils.GetRoleColor(CustomRoles.NiceSwapper), GetString("SwapTitle"))); } @@ -278,14 +234,12 @@ namespace EHR.Crewmate private static bool CheckCommand(ref string msg, string command, bool exact = true) { string[] comList = command.Split('|'); + foreach (string str in comList) { if (exact) { - if (msg == "/" + str) - { - return true; - } + if (msg == "/" + str) return true; } else { @@ -302,10 +256,7 @@ namespace EHR.Crewmate private static void SendRPC(byte playerId) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetNiceSwapperVotes, SendOption.Reliable); writer.Write(playerId); @@ -323,30 +274,21 @@ namespace EHR.Crewmate Logger.Msg($"Click: ID {playerId}", "NiceSwapper UI"); PlayerControl pc = Utils.GetPlayerById(playerId); - if (pc == null || !pc.IsAlive() || !GameStates.IsVoting) - { - return; - } + if (pc == null || !pc.IsAlive() || !GameStates.IsVoting) return; if (AmongUsClient.Instance.AmHost) - { SwapMsg(PlayerControl.LocalPlayer, $"/sw {playerId}", true); - } else - { SendRPC(playerId); - } if (PlayerControl.LocalPlayer.GetCustomRole() == CustomRoles.NiceSwapper && PlayerControl.LocalPlayer.IsAlive()) { __instance.playerStates.ToList().ForEach(x => { Transform swapButton = x.transform.FindChild("ShootButton"); - if (swapButton != null) - { - Object.Destroy(swapButton.gameObject); - } + if (swapButton != null) Object.Destroy(swapButton.gameObject); }); + CreateSwapperButton(__instance); } } @@ -356,27 +298,20 @@ namespace EHR.Crewmate foreach (PlayerVoteArea pva in __instance.playerStates) { PlayerControl pc = Utils.GetPlayerById(pva.TargetPlayerId); - if (pc == null || !pc.IsAlive()) - { - continue; - } + if (pc == null || !pc.IsAlive()) continue; GameObject template = pva.Buttons.transform.Find("CancelButton").gameObject; GameObject targetBox = Object.Instantiate(template, pva.transform); targetBox.name = "ShootButton"; targetBox.transform.localPosition = new(-0.35f, 0.03f, -1.31f); - SpriteRenderer renderer = targetBox.GetComponent(); + var renderer = targetBox.GetComponent(); if (pc.PlayerId == pva.TargetPlayerId && (SwapTargets.Item1 == pc.PlayerId || SwapTargets.Item2 == pc.PlayerId)) - { renderer.sprite = CustomButton.Get("SwapYes"); - } else - { renderer.sprite = CustomButton.Get("SwapNo"); - } - PassiveButton button = targetBox.GetComponent(); + var button = targetBox.GetComponent(); button.OnClick.RemoveAllListeners(); button.OnClick.AddListener((Action)(() => SwapperOnClick(pva.TargetPlayerId, __instance))); } @@ -388,10 +323,7 @@ namespace EHR.Crewmate // ReSharper disable once UnusedMember.Local public static void Postfix(MeetingHud __instance) { - if (PlayerControl.LocalPlayer.GetCustomRole() == CustomRoles.NiceSwapper && PlayerControl.LocalPlayer.IsAlive()) - { - CreateSwapperButton(__instance); - } + if (PlayerControl.LocalPlayer.GetCustomRole() == CustomRoles.NiceSwapper && PlayerControl.LocalPlayer.IsAlive()) CreateSwapperButton(__instance); } } } diff --git a/Roles/Crewmate/Observer.cs b/Roles/Crewmate/Observer.cs index fc865330b..f0ec69f70 100644 --- a/Roles/Crewmate/Observer.cs +++ b/Roles/Crewmate/Observer.cs @@ -9,12 +9,8 @@ Options.SetupRoleOptions(7500, TabGroup.CrewmateRoles, CustomRoles.Observer); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Crewmate/Oracle.cs b/Roles/Crewmate/Oracle.cs index ef0ec1e42..338c3fb02 100644 --- a/Roles/Crewmate/Oracle.cs +++ b/Roles/Crewmate/Oracle.cs @@ -23,20 +23,26 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Oracle); + CheckLimitOpt = new IntegerOptionItem(Id + 10, "OracleSkillLimit", new(0, 10, 1), 0, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Oracle]) .SetValueFormat(OptionFormat.Times); + HideVote = new BooleanOptionItem(Id + 12, "OracleHideVote", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Oracle]); + FailChance = new IntegerOptionItem(Id + 13, "FailChance", new(0, 100, 5), 20, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Oracle]) .SetValueFormat(OptionFormat.Percent); + OracleAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 14, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Oracle]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 15, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Oracle]) .SetValueFormat(OptionFormat.Times); + CancelVote = CreateVoteCancellingUseSetting(Id + 11, CustomRoles.Oracle, TabGroup.CrewmateRoles); } @@ -53,15 +59,9 @@ namespace EHR.Crewmate public override bool OnVote(PlayerControl player, PlayerControl target) { - if (player == null || target == null) - { - return false; - } + if (player == null || target == null) return false; - if (DidVote.Contains(player.PlayerId) || Main.DontCancelVoteList.Contains(player.PlayerId)) - { - return false; - } + if (DidVote.Contains(player.PlayerId) || Main.DontCancelVoteList.Contains(player.PlayerId)) return false; DidVote.Add(player.PlayerId); @@ -82,24 +82,20 @@ namespace EHR.Crewmate string text; if (target.GetCustomRole().IsImpostor()) - { text = "Imp"; - } else if (target.GetCustomRole().IsNeutral()) - { text = "Neut"; - } else - { text = "Crew"; - } if (FailChance.GetInt() > 0) { int random_number_1 = IRandom.Instance.Next(1, 101); + if (random_number_1 <= FailChance.GetInt()) { int random_number_2 = IRandom.Instance.Next(1, 3); + text = text switch { "Crew" => random_number_2 switch diff --git a/Roles/Crewmate/Oxyman.cs b/Roles/Crewmate/Oxyman.cs index e45d9ea3c..d21155751 100644 --- a/Roles/Crewmate/Oxyman.cs +++ b/Roles/Crewmate/Oxyman.cs @@ -25,24 +25,30 @@ namespace EHR.Crewmate public override void SetupCustomOption() { - int id = 647700; + var id = 647700; Options.SetupRoleOptions(id++, TabGroup.CrewmateRoles, CustomRoles.Oxyman); (List trueList, List falseList) = Enum.GetValues().Without(Level.None).Split(x => x <= Level.Slow); + trueList.ForEach(x => LevelSettings[x] = new IntegerOptionItem(++id, $"Oxyman.{x}.BelowPercentage", new(0, 100, 1), x == Level.Blind ? 10 : 30, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Oxyman]) .SetValueFormat(OptionFormat.Percent)); + falseList.ForEach(x => LevelSettings[x] = new IntegerOptionItem(++id, $"Oxyman.{x}.AbovePercentage", new(0, 100, 1), x == Level.Fast ? 60 : 80, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Oxyman]) .SetValueFormat(OptionFormat.Percent)); + IncrementByVenting = new IntegerOptionItem(++id, "Oxyman.IncrementByVenting", new(0, 100, 1), 7, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Oxyman]) .SetValueFormat(OptionFormat.Percent); + DecreasementEachSecond = new IntegerOptionItem(++id, "Oxyman.DecreasementEachSecond", new(0, 10, 1), 1, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Oxyman]) .SetValueFormat(OptionFormat.Percent); + IncreasedSpeed = new FloatOptionItem(++id, "IncreasedSpeed", new(0f, 3f, 0.05f), 1.75f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Oxyman]) .SetValueFormat(OptionFormat.Multiplier); + DecreasedSpeed = new FloatOptionItem(++id, "DecreasedSpeed", new(0f, 3f, 0.05f), 1f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Oxyman]) .SetValueFormat(OptionFormat.Multiplier); @@ -74,16 +80,10 @@ namespace EHR.Crewmate Level previousLevel = GetCurrentLevel(); OxygenLevel += IncrementByVenting.GetValue(); - if (OxygenLevel > 100) - { - OxygenLevel = 100; - } + if (OxygenLevel > 100) OxygenLevel = 100; Level nowLevel = GetCurrentLevel(); - if (nowLevel != previousLevel) - { - ApplyLevelEffect(pc, nowLevel); - } + if (nowLevel != previousLevel) ApplyLevelEffect(pc, nowLevel); Utils.SendRPC(CustomRPC.SyncRoleData, pc.PlayerId, OxygenLevel); Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); @@ -91,16 +91,10 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) - { - return; - } + if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) return; long now = Utils.TimeStamp; - if (now == LastUpdate) - { - return; - } + if (now == LastUpdate) return; LastUpdate = now; @@ -118,10 +112,7 @@ namespace EHR.Crewmate Level nowLevel = GetCurrentLevel(); - if (nowLevel != previousLevel) - { - ApplyLevelEffect(pc, nowLevel); - } + if (nowLevel != previousLevel) ApplyLevelEffect(pc, nowLevel); } private void ApplyLevelEffect(PlayerControl pc, Level nowLevel) @@ -160,25 +151,13 @@ namespace EHR.Crewmate private Level GetCurrentLevel() { // ReSharper disable ConvertIfStatementToReturnStatement - if (OxygenLevel <= LevelSettings[Level.Blind].GetInt()) - { - return Level.Blind; - } + if (OxygenLevel <= LevelSettings[Level.Blind].GetInt()) return Level.Blind; - if (OxygenLevel <= LevelSettings[Level.Slow].GetInt()) - { - return Level.Slow; - } + if (OxygenLevel <= LevelSettings[Level.Slow].GetInt()) return Level.Slow; - if (OxygenLevel >= LevelSettings[Level.Invulnerable].GetInt()) - { - return Level.Invulnerable; - } + if (OxygenLevel >= LevelSettings[Level.Invulnerable].GetInt()) return Level.Invulnerable; - if (OxygenLevel >= LevelSettings[Level.Fast].GetInt()) - { - return Level.Fast; - } + if (OxygenLevel >= LevelSettings[Level.Fast].GetInt()) return Level.Fast; return Level.None; // ReSharper restore ConvertIfStatementToReturnStatement @@ -203,10 +182,7 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != OxymanId || (seer.IsModClient() && !hud)) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != OxymanId || (seer.IsModClient() && !hud)) return string.Empty; return $"<#ff0000>O2: {Utils.ColorString(GetLevelColor(), OxygenLevel.ToString())}%"; } diff --git a/Roles/Crewmate/Paranoia.cs b/Roles/Crewmate/Paranoia.cs index 74e2bbc23..a5d5eadad 100644 --- a/Roles/Crewmate/Paranoia.cs +++ b/Roles/Crewmate/Paranoia.cs @@ -14,9 +14,11 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(7800, TabGroup.CrewmateRoles, CustomRoles.Paranoia); + ParanoiaNumOfUseButton = new IntegerOptionItem(7810, "ParanoiaNumOfUseButton", new(0, 90, 1), 3, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Paranoia]) .SetValueFormat(OptionFormat.Times); + ParanoiaVentCooldown = new FloatOptionItem(7811, "ParanoiaVentCooldown", new(0, 180, 1), 10, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Paranoia]) .SetValueFormat(OptionFormat.Seconds); @@ -35,28 +37,22 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = !ParaUsedButtonCount.TryGetValue(playerId, out int count2) || count2 < ParanoiaNumOfUseButton.GetInt() ? ParanoiaVentCooldown.GetFloat() : 300f; + AURoleOptions.EngineerInVentMaxTime = 1f; } public override void SetButtonTexts(HudManager hud, byte id) { if (UsePets.GetBool()) - { hud.PetButton.buttonLabelText.text = Translator.GetString("ParanoiaVentButtonText"); - } else - { hud.AbilityButton.buttonLabelText.text = Translator.GetString("ParanoiaVentButtonText"); - } } public override void OnPet(PlayerControl pc) @@ -75,10 +71,7 @@ namespace EHR.Crewmate if (ParaUsedButtonCount.TryGetValue(pc.PlayerId, out int count2) && count2 < ParanoiaNumOfUseButton.GetInt()) { ParaUsedButtonCount[pc.PlayerId] += 1; - if (AmongUsClient.Instance.AmHost) - { - LateTask.New(() => { Utils.SendMessage(Translator.GetString("SkillUsedLeft") + (ParanoiaNumOfUseButton.GetInt() - ParaUsedButtonCount[pc.PlayerId]), pc.PlayerId); }, 4.0f, "Paranoia Skill Remain Message"); - } + if (AmongUsClient.Instance.AmHost) LateTask.New(() => { Utils.SendMessage(Translator.GetString("SkillUsedLeft") + (ParanoiaNumOfUseButton.GetInt() - ParaUsedButtonCount[pc.PlayerId]), pc.PlayerId); }, 4.0f, "Paranoia Skill Remain Message"); pc.NoCheckStartMeeting(pc.Data); } diff --git a/Roles/Crewmate/ParityCop.cs b/Roles/Crewmate/ParityCop.cs index e074243fa..09d2ace93 100644 --- a/Roles/Crewmate/ParityCop.cs +++ b/Roles/Crewmate/ParityCop.cs @@ -40,31 +40,42 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.ParityCop); + TryHideMsg = new BooleanOptionItem(Id + 10, "ParityCopTryHideMsg", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.ParityCop]) .SetColor(Color.green); + ParityCheckLimitMax = new IntegerOptionItem(Id + 11, "MaxParityCheckLimit", new(0, 20, 1), 2, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.ParityCop]) .SetValueFormat(OptionFormat.Times); + ParityCheckLimitPerMeeting = new IntegerOptionItem(Id + 12, "ParityCheckLimitPerMeeting", new(1, 20, 1), 1, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.ParityCop]) .SetValueFormat(OptionFormat.Times); + ParityCheckEgoistCountType = new StringOptionItem(Id + 13, "ParityCheckEgoistickCountMode", PcEgoistCountMode, 0, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.ParityCop]); + ParityCheckBaitCountType = new BooleanOptionItem(Id + 14, "ParityCheckBaitCountMode", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.ParityCop]); + ParityCheckTargetKnow = new BooleanOptionItem(Id + 15, "ParityCheckTargetKnow", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.ParityCop]); + ParityCheckOtherTargetKnow = new BooleanOptionItem(Id + 16, "ParityCheckOtherTargetKnow", true, TabGroup.CrewmateRoles) .SetParent(ParityCheckTargetKnow); + ParityCheckRevealTargetTeam = new BooleanOptionItem(Id + 17, "ParityCheckRevealTarget", false, TabGroup.CrewmateRoles) .SetParent(ParityCheckOtherTargetKnow); + ParityAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 18, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 1.5f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.ParityCop]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 19, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.ParityCop]) .SetValueFormat(OptionFormat.Times); + OverrideTasksData.Create(Id + 20, TabGroup.CrewmateRoles, CustomRoles.ParityCop); } @@ -90,45 +101,28 @@ namespace EHR.Crewmate public override void OnReportDeadBody() { RoundCheckLimit.Clear(); - foreach (byte pc in PlayerIdList) - { - RoundCheckLimit.Add(pc, ParityCheckLimitPerMeeting.GetInt()); - } + foreach (byte pc in PlayerIdList) RoundCheckLimit.Add(pc, ParityCheckLimitPerMeeting.GetInt()); } public static bool ParityCheckMsg(PlayerControl pc, string msg, bool isUI = false) { string originMsg = msg; - if (!AmongUsClient.Instance.AmHost) - { - return false; - } + if (!AmongUsClient.Instance.AmHost) return false; - if (!GameStates.IsInGame || pc == null) - { - return false; - } + if (!GameStates.IsInGame || pc == null) return false; - if (!pc.Is(CustomRoles.ParityCop)) - { - return false; - } + if (!pc.Is(CustomRoles.ParityCop)) return false; int operate; // 1:ID 2:Check msg = msg.ToLower().TrimStart().TrimEnd(); + if (CheckCommand(ref msg, "id|guesslist|gl编号|玩家编号|玩家id|id列表|玩家列表|列表|所有id|全部id")) - { operate = 1; - } else if (CheckCommand(ref msg, "compare|cp|cmp|比较", false)) - { operate = 2; - } else - { return false; - } if (!pc.IsAlive()) { @@ -144,13 +138,8 @@ namespace EHR.Crewmate case 2: { if (TryHideMsg.GetBool()) /*TryHideMsgForCompare();*/ - { ChatManager.SendPreviousMessagesToAll(); - } - else if (pc.AmOwner) - { - Utils.SendMessage(originMsg, 255, pc.GetRealName()); - } + else if (pc.AmOwner) Utils.SendMessage(originMsg, 255, pc.GetRealName()); if (!MsgToPlayerAndRole(msg, out byte targetId1, out byte targetId2, out string error)) { @@ -160,11 +149,13 @@ namespace EHR.Crewmate PlayerControl target1 = Utils.GetPlayerById(targetId1); PlayerControl target2 = Utils.GetPlayerById(targetId2); + if (target1 != null && target2 != null) { Logger.Info($"{pc.GetNameWithRole().RemoveHtmlTags()} checked {target1.GetNameWithRole().RemoveHtmlTags()} and {target2.GetNameWithRole().RemoveHtmlTags()}", "ParityCop"); bool outOfUses = pc.GetAbilityUseLimit() < 1; + if (outOfUses || RoundCheckLimit[pc.PlayerId] < 1) { if (outOfUses) @@ -172,13 +163,9 @@ namespace EHR.Crewmate LateTask.New(() => { if (!isUI) - { Utils.SendMessage(GetString("ParityCheckMax"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("ParityCheckMax")); - } Logger.Msg("Check attempted at max checks per game", "Parity Cop"); }, 0.2f, "ParityCop 0"); @@ -188,13 +175,9 @@ namespace EHR.Crewmate LateTask.New(() => { if (!isUI) - { Utils.SendMessage(GetString("ParityCheckRound"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("ParityCheckRound")); - } Logger.Msg("Check attempted at max checks per meeting", "Parity Cop"); }, 0.2f, "ParityCop 1"); @@ -208,16 +191,13 @@ namespace EHR.Crewmate LateTask.New(() => { if (!isUI) - { Utils.SendMessage(GetString("ParityCheckSelf"), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.ParityCop), GetString("ParityCheckTitle"))); - } else - { pc.ShowPopUp(Utils.ColorString(Utils.GetRoleColor(CustomRoles.ParityCop), GetString("ParityCheckSelf")) + "\n" + GetString("ParityCheckTitle")); - } Logger.Msg("Check attempted on self", "Parity Cop"); }, 0.2f, "ParityCop 2"); + return true; } @@ -226,16 +206,13 @@ namespace EHR.Crewmate LateTask.New(() => { if (!isUI) - { Utils.SendMessage(GetString("ParityCheckReveal"), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.ParityCop), GetString("ParityCheckTitle"))); - } else - { pc.ShowPopUp(Utils.ColorString(Utils.GetRoleColor(CustomRoles.ParityCop), GetString("ParityCheckReveal")) + "\n" + GetString("ParityCheckTitle")); - } Logger.Msg("Check attempted on revealed role", "Parity Cop"); }, 0.2f, "ParityCop 3"); + return true; } @@ -244,13 +221,9 @@ namespace EHR.Crewmate LateTask.New(() => { if (!isUI) - { Utils.SendMessage(string.Format(GetString("ParityCheckTrue"), target1.GetRealName(), target2.GetRealName()), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.ParityCop), GetString("ParityCheckTitle"))); - } else - { pc.ShowPopUp(Utils.ColorString(Utils.GetRoleColor(CustomRoles.ParityCop), GetString("ParityCheckTrue")) + "\n" + GetString("ParityCheckTitle")); - } Logger.Msg("Check attempt, result TRUE", "Parity Cop"); }, 0.2f, "ParityCop 4"); @@ -260,13 +233,9 @@ namespace EHR.Crewmate LateTask.New(() => { if (!isUI) - { Utils.SendMessage(string.Format(GetString("ParityCheckFalse"), target1.GetRealName(), target2.GetRealName()), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.ParityCop), GetString("ParityCheckTitle"))); - } else - { pc.ShowPopUp(Utils.ColorString(Utils.GetRoleColor(CustomRoles.ParityCop), GetString("ParityCheckFalse")) + "\n" + GetString("ParityCheckTitle")); - } Logger.Msg("Check attempt, result FALSE", "Parity Cop"); }, 0.2f, "ParityCop 5"); @@ -274,21 +243,16 @@ namespace EHR.Crewmate if (ParityCheckTargetKnow.GetBool()) { - string textToSend = $"{target1.GetRealName()}"; - if (ParityCheckOtherTargetKnow.GetBool()) - { - textToSend += $" and {target2.GetRealName()}"; - } + var textToSend = $"{target1.GetRealName()}"; + if (ParityCheckOtherTargetKnow.GetBool()) textToSend += $" and {target2.GetRealName()}"; textToSend += GetString("ParityCheckTargetMsg"); - string textToSend1 = $"{target2.GetRealName()}"; - if (ParityCheckOtherTargetKnow.GetBool()) - { - textToSend1 += $" and {target1.GetRealName()}"; - } + var textToSend1 = $"{target2.GetRealName()}"; + if (ParityCheckOtherTargetKnow.GetBool()) textToSend1 += $" and {target1.GetRealName()}"; textToSend1 += GetString("ParityCheckTargetMsg"); + LateTask.New(() => { Utils.SendMessage(textToSend, target1.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.ParityCop), GetString("ParityCheckTitle"))); @@ -300,29 +264,19 @@ namespace EHR.Crewmate if (ParityCheckRevealTargetTeam.GetBool() && pc.AllTasksCompleted()) { string roleT1 = string.Empty, roleT2 = string.Empty; + if (target1.Is(Team.Impostor) || target1.GetCustomSubRoles().Any(role => role.IsImpostorTeamV2())) - { roleT1 = "Impostor"; - } else if (target1.Is(Team.Neutral) || target1.GetCustomSubRoles().Any(role => role.IsNeutralTeamV2())) - { roleT1 = "Neutral"; - } else if (target1.Is(Team.Crewmate) && (target1.GetCustomSubRoles().Any(role => role.IsCrewmateTeamV2()) || target1.GetCustomSubRoles().Count == 0)) { if (target2.Is(Team.Impostor) || target2.GetCustomSubRoles().Any(role => role.IsImpostorTeamV2())) - { roleT2 = "Impostor"; - } else if (target2.Is(Team.Neutral) || target2.GetCustomSubRoles().Any(role => role.IsNeutralTeamV2())) - { roleT2 = "Neutral"; - } - else if (target2.Is(Team.Crewmate) && (target2.GetCustomSubRoles().Any(role => role.IsCrewmateTeamV2()) || target2.GetCustomSubRoles().Count == 0)) - { - roleT2 = "Crewmate"; - } + else if (target2.Is(Team.Crewmate) && (target2.GetCustomSubRoles().Any(role => role.IsCrewmateTeamV2()) || target2.GetCustomSubRoles().Count == 0)) roleT2 = "Crewmate"; } LateTask.New(() => @@ -375,35 +329,24 @@ namespace EHR.Crewmate case Necromancer when firstRoleClass is Deathknight: return true; } - if (CustomTeamManager.AreInSameCustomTeam(first.PlayerId, second.PlayerId)) - { - return true; - } + if (CustomTeamManager.AreInSameCustomTeam(first.PlayerId, second.PlayerId)) return true; - if (firstSubRoles.Contains(CustomRoles.Bloodlust) || secondSubRoles.Contains(CustomRoles.Bloodlust)) - { - return false; - } + if (firstSubRoles.Contains(CustomRoles.Bloodlust) || secondSubRoles.Contains(CustomRoles.Bloodlust)) return false; - if (firstRole.IsNeutral() && secondRole.IsNeutral()) - { - return false; - } + if (firstRole.IsNeutral() && secondRole.IsNeutral()) return false; return firstTeam == secondTeam || firstRole == secondRole; } private static bool MsgToPlayerAndRole(string msg, out byte id1, out byte id2, out string error) { - if (msg.StartsWith("/")) - { - msg = msg.Replace("/", string.Empty); - } + if (msg.StartsWith("/")) msg = msg.Replace("/", string.Empty); msg = msg.TrimStart().TrimEnd(); Logger.Msg(msg, "ParityCop"); string[] nums = msg.Split(" "); + if (nums.Length != 2 || !int.TryParse(nums[0], out int num1) || !int.TryParse(nums[1], out int num2)) { Logger.Msg($"nums.Length {nums.Length}, nums0 {nums[0]}, nums1 {nums[1]}", "ParityCop"); @@ -418,6 +361,7 @@ namespace EHR.Crewmate PlayerControl target1 = Utils.GetPlayerById(id1); PlayerControl target2 = Utils.GetPlayerById(id2); + if (target1 == null || target1.Data.IsDead || target2 == null || target2.Data.IsDead) { error = GetString("ParityCheckNull"); @@ -431,14 +375,12 @@ namespace EHR.Crewmate public static bool CheckCommand(ref string msg, string command, bool exact = true) { string[] comList = command.Split('|'); + foreach (string str in comList) { if (exact) { - if (msg == "/" + str) - { - return true; - } + if (msg == "/" + str) return true; } else { @@ -458,10 +400,7 @@ namespace EHR.Crewmate Logger.Msg($"Click: ID {playerId}", "Inspector UI"); PlayerControl pc = Utils.GetPlayerById(playerId); byte lpcId = PlayerControl.LocalPlayer.PlayerId; - if (pc == null || !pc.IsAlive() || !GameStates.IsVoting || !AmongUsClient.Instance.AmHost) - { - return; - } + if (pc == null || !pc.IsAlive() || !GameStates.IsVoting || !AmongUsClient.Instance.AmHost) return; if (FirstPick.TryGetValue(lpcId, out byte firstPick)) { @@ -469,9 +408,7 @@ namespace EHR.Crewmate FirstPick.Remove(lpcId); } else - { FirstPick.Add(lpcId, playerId); - } } public static void CreateParityCopButton(MeetingHud __instance) @@ -479,18 +416,15 @@ namespace EHR.Crewmate foreach (PlayerVoteArea pva in __instance.playerStates) { PlayerControl pc = Utils.GetPlayerById(pva.TargetPlayerId); - if (pc == null || !pc.IsAlive()) - { - continue; - } + if (pc == null || !pc.IsAlive()) continue; GameObject template = pva.Buttons.transform.Find("CancelButton").gameObject; GameObject targetBox = Object.Instantiate(template, pva.transform); targetBox.name = "ShootButton"; targetBox.transform.localPosition = new(-0.35f, 0.03f, -1.31f); - SpriteRenderer renderer = targetBox.GetComponent(); + var renderer = targetBox.GetComponent(); renderer.sprite = CustomButton.Get("ParityCopIcon"); - PassiveButton button = targetBox.GetComponent(); + var button = targetBox.GetComponent(); button.OnClick.RemoveAllListeners(); button.OnClick.AddListener((Action)(() => ParityCopOnClick(pva.TargetPlayerId /*, __instance*/))); } @@ -501,10 +435,7 @@ namespace EHR.Crewmate { public static void Postfix(MeetingHud __instance) { - if (PlayerControl.LocalPlayer.Is(CustomRoles.ParityCop) && PlayerControl.LocalPlayer.IsAlive() && AmongUsClient.Instance.AmHost) - { - CreateParityCopButton(__instance); - } + if (PlayerControl.LocalPlayer.Is(CustomRoles.ParityCop) && PlayerControl.LocalPlayer.IsAlive() && AmongUsClient.Instance.AmHost) CreateParityCopButton(__instance); } } } diff --git a/Roles/Crewmate/Perceiver.cs b/Roles/Crewmate/Perceiver.cs index 164e21545..f43fdadb3 100644 --- a/Roles/Crewmate/Perceiver.cs +++ b/Roles/Crewmate/Perceiver.cs @@ -19,16 +19,21 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Perceiver); + Radius = new FloatOptionItem(Id + 2, "PerceiverRadius", new(0.25f, 10f, 0.25f), 2.5f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Perceiver]) .SetValueFormat(OptionFormat.Multiplier); + CD = Options.CreateCDSetting(Id + 3, TabGroup.CrewmateRoles, CustomRoles.Perceiver); + Limit = new IntegerOptionItem(Id + 4, "AbilityUseLimit", new(0, 20, 1), 0, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Perceiver]) .SetValueFormat(OptionFormat.Times); + PerceiverAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 5, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.4f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Perceiver]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 6, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Perceiver]) .SetValueFormat(OptionFormat.Times); @@ -47,10 +52,7 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (Options.UsePets.GetBool()) - { - return; - } + if (Options.UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = CD.GetFloat(); AURoleOptions.EngineerInVentMaxTime = 1f; @@ -68,10 +70,7 @@ namespace EHR.Crewmate public static void UseAbility(PlayerControl pc) { - if (pc == null || pc.GetAbilityUseLimit() < 1f) - { - return; - } + if (pc == null || pc.GetAbilityUseLimit() < 1f) return; PlayerControl[] killers = Main.AllAlivePlayerControls.Where(x => !x.Is(Team.Crewmate) && x.HasKillButton() && Vector2.Distance(x.Pos(), pc.Pos()) <= Radius.GetFloat()).ToArray(); pc.Notify(string.Format(Translator.GetString("PerceiverNotify"), killers.Length), 7f); diff --git a/Roles/Crewmate/Philantropist.cs b/Roles/Crewmate/Philantropist.cs index 1728cf98b..c79809556 100644 --- a/Roles/Crewmate/Philantropist.cs +++ b/Roles/Crewmate/Philantropist.cs @@ -1,6 +1,4 @@ namespace EHR.Crewmate { - internal class Philantropist - { - } + internal class Philantropist { } } \ No newline at end of file diff --git a/Roles/Crewmate/President.cs b/Roles/Crewmate/President.cs index 559888f7c..61ea70326 100644 --- a/Roles/Crewmate/President.cs +++ b/Roles/Crewmate/President.cs @@ -54,10 +54,11 @@ namespace EHR.Crewmate public override void SetupCustomOption() { - int id = 647850; + var id = 647850; const TabGroup tab = TabGroup.CrewmateRoles; const CustomRoles role = CustomRoles.President; Options.SetupSingleRoleOptions(id++, tab, role, hideMaxSetting: true); + foreach (Decree decree in Enum.GetValues()) { DecreeSettings[decree] = @@ -76,10 +77,12 @@ namespace EHR.Crewmate new BooleanOptionItem(++id, "President.Reveal.ConvertedPresidentCanReveal", false, tab) .SetParent(DecreeSettings[decree][0]) ]); + break; case Decree.GovernmentRecruiting: DecreeSettings[decree].Add(new StringOptionItem(++id, "President.GovernmentRecruiting.RecruitedRole", GovernmentRecruitRoles.Select(x => x.ToColoredString()).ToArray(), 0, tab, noTranslation: true) .SetParent(DecreeSettings[decree][0])); + break; } } @@ -115,10 +118,7 @@ namespace EHR.Crewmate public static void OnAnyoneApplyGameOptions(IGameOptions opt) { bool value = Main.RealOptionsData.GetBool(BoolOptionNames.AnonymousVotes); - if (Instances.Any(x => x.IsDeclassification)) - { - value = false; - } + if (Instances.Any(x => x.IsDeclassification)) value = false; opt.SetBool(BoolOptionNames.AnonymousVotes, value); } @@ -126,16 +126,14 @@ namespace EHR.Crewmate public static void UseDecree(PlayerControl pc, string message) { President president = Instances.FirstOrDefault(x => x.PresidentId == pc.PlayerId); + if (president == null || president.Used) { Utils.SendMessage(Translator.GetString("President.DecreeAlreadyChosenThisMeetingMessage"), pc.PlayerId); return; } - if (!Utils.GetPlayerById(president.PresidentId).IsAlive()) - { - return; - } + if (!Utils.GetPlayerById(president.PresidentId).IsAlive()) return; if (!int.TryParse(message, out int num) || num > 5) { @@ -143,7 +141,8 @@ namespace EHR.Crewmate return; } - Decree decree = (Decree)num; + var decree = (Decree)num; + if (!decree.IsEnabled() || president.UsedDecrees.Contains(decree)) { Utils.SendMessage(Translator.GetString("President.DecreeAlreadyUsedMessage"), pc.PlayerId); @@ -153,15 +152,9 @@ namespace EHR.Crewmate switch (decree) { case Decree.Reveal: - if (!DecreeSettings[decree][1].GetBool()) - { - pc.RpcSetCustomRole(CustomRoles.Loyal); - } + if (!DecreeSettings[decree][1].GetBool()) pc.RpcSetCustomRole(CustomRoles.Loyal); - if ((!DecreeSettings[decree][2].GetBool() && pc.IsConverted()) || pc.Is(CustomRoles.Bloodlust)) - { - return; - } + if ((!DecreeSettings[decree][2].GetBool() && pc.IsConverted()) || pc.Is(CustomRoles.Bloodlust)) return; Utils.SendMessage(string.Format(Translator.GetString("President.UsedDecreeMessage.Everyone"), Translator.GetString($"President.Decree.{decree}"))); Utils.SendMessage(string.Format(Translator.GetString("President.UsedDecreeMessage.RevealMessage"), pc.PlayerId.ColoredPlayerName())); @@ -178,10 +171,7 @@ namespace EHR.Crewmate case Decree.GovernmentSupport: foreach (PlayerControl player in Main.AllPlayerControls) { - if (!player.IsCrewmate()) - { - continue; - } + if (!player.IsCrewmate()) continue; switch (Main.PlayerStates[player.PlayerId].Role) { @@ -203,10 +193,7 @@ namespace EHR.Crewmate Utils.SendMessage("\n", pc.PlayerId, Utils.GetRemainingKillers(president: true)); break; case Decree.GovernmentRecruiting: - if (MeetingHud.Instance?.playerStates?.FirstOrDefault(x => x.TargetPlayerId == pc.PlayerId)?.DidVote == true) - { - return; - } + if (MeetingHud.Instance?.playerStates?.FirstOrDefault(x => x.TargetPlayerId == pc.PlayerId)?.DidVote == true) return; president.IsRecruiting = true; break; @@ -230,20 +217,14 @@ namespace EHR.Crewmate public override bool KnowRole(PlayerControl seer, PlayerControl target) { - if (base.KnowRole(seer, target)) - { - return true; - } + if (base.KnowRole(seer, target)) return true; return target.PlayerId == PresidentId && IsRevealed; } public override bool OnVote(PlayerControl voter, PlayerControl target) { - if (voter.PlayerId != PresidentId || !IsRecruiting || Main.DontCancelVoteList.Contains(voter.PlayerId)) - { - return false; - } + if (voter.PlayerId != PresidentId || !IsRecruiting || Main.DontCancelVoteList.Contains(voter.PlayerId)) return false; if (!target.Is(CustomRoleTypes.Crewmate) || target.IsConverted()) { @@ -252,10 +233,7 @@ namespace EHR.Crewmate } CustomRoles role = GovernmentRecruitRoles[DecreeSettings[Decree.GovernmentRecruiting][1].GetValue()]; - if (role.IsDesyncRole() && target.GetRoleTypes() != role.GetDYRole()) - { - role = CustomRoles.NiceGuesser; - } + if (role.IsDesyncRole() && target.GetRoleTypes() != role.GetDYRole()) role = CustomRoles.NiceGuesser; target.RpcSetCustomRole(role); Utils.SendMessage("\n", target.PlayerId, Translator.GetString("President.Recruit.TargetNotifyMessage")); diff --git a/Roles/Crewmate/Psychic.cs b/Roles/Crewmate/Psychic.cs index 9e7316063..6d68253db 100644 --- a/Roles/Crewmate/Psychic.cs +++ b/Roles/Crewmate/Psychic.cs @@ -27,15 +27,20 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Psychic); + CanSeeNum = new IntegerOptionItem(Id + 2, "PsychicCanSeeNum", new(1, 10, 1), 3, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Psychic]) .SetValueFormat(OptionFormat.Pieces); + Fresh = new BooleanOptionItem(Id + 6, "PsychicFresh", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Psychic]); + CkshowEvil = new BooleanOptionItem(Id + 3, "CrewKillingRed", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Psychic]); + NBshowEvil = new BooleanOptionItem(Id + 4, "NBareRed", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Psychic]); + NEshowEvil = new BooleanOptionItem(Id + 5, "NEareRed", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Psychic]); } @@ -56,18 +61,12 @@ namespace EHR.Crewmate private void SendRPC() { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncPsychicRedList, SendOption.Reliable); writer.Write(PsychicId); writer.Write(RedPlayer.Count); - foreach (byte pc in RedPlayer) - { - writer.Write(pc); - } + foreach (byte pc in RedPlayer) writer.Write(pc); AmongUsClient.Instance.FinishRpcImmediately(writer); } @@ -75,53 +74,32 @@ namespace EHR.Crewmate public static void ReceiveRPC(MessageReader reader) { byte playerId = reader.ReadByte(); - if (Main.PlayerStates[playerId].Role is not Psychic ph) - { - return; - } + if (Main.PlayerStates[playerId].Role is not Psychic ph) return; int count = reader.ReadInt32(); ph.RedPlayer = []; - for (int i = 0; i < count; i++) - { - ph.RedPlayer.Add(reader.ReadByte()); - } + for (var i = 0; i < count; i++) ph.RedPlayer.Add(reader.ReadByte()); } public static bool IsRedForPsy(PlayerControl target, PlayerControl seer) { - if (target == null || seer == null) - { - return false; - } + if (target == null || seer == null) return false; - if (Main.PlayerStates[seer.PlayerId].Role is not Psychic ph) - { - return false; - } + if (Main.PlayerStates[seer.PlayerId].Role is not Psychic ph) return false; - if (seer.Is(CustomRoles.Madmate)) - { - return target.GetCustomRole().IsNeutral() || target.GetCustomRole().GetCrewmateRoleCategory() == RoleOptionType.Crewmate_Killing; - } + if (seer.Is(CustomRoles.Madmate)) return target.GetCustomRole().IsNeutral() || target.GetCustomRole().GetCrewmateRoleCategory() == RoleOptionType.Crewmate_Killing; return ph.RedPlayer != null && ph.RedPlayer.Contains(target.PlayerId); } public override void OnReportDeadBody() { - if (Fresh.GetBool() || RedPlayer == null || RedPlayer.Count == 0) - { - GetRedName(); - } + if (Fresh.GetBool() || RedPlayer == null || RedPlayer.Count == 0) GetRedName(); } private void GetRedName() { - if (!IsEnable || !AmongUsClient.Instance.AmHost) - { - return; - } + if (!IsEnable || !AmongUsClient.Instance.AmHost) return; List BadListPc = Main.AllAlivePlayerControls.Where(x => (x.Is(CustomRoleTypes.Impostor) && !x.Is(CustomRoles.Trickster)) || x.Is(CustomRoles.Madmate) || x.Is(CustomRoles.Rascal) || Framer.FramedPlayers.Contains(x.PlayerId) || x.IsConverted() || @@ -135,33 +113,29 @@ namespace EHR.Crewmate List AllList = []; Main.AllAlivePlayerControls.Where(x => !BadList.Contains(x.PlayerId) && !x.Is(CustomRoles.Psychic)).Do(x => AllList.Add(x.PlayerId)); - int ENum = 1; - for (int i = 1; i < CanSeeNum.GetInt(); i++) - { + var ENum = 1; + + for (var i = 1; i < CanSeeNum.GetInt(); i++) if (IRandom.Instance.Next(0, 100) < 18) - { ENum++; - } - } int BNum = CanSeeNum.GetInt() - ENum; ENum = Math.Min(ENum, BadList.Count); BNum = Math.Min(BNum, AllList.Count); - if (ENum < 1) - { - goto EndOfSelect; - } + if (ENum < 1) goto EndOfSelect; RedPlayer = []; - for (int i = 0; i < ENum && BadList.Count > 0; i++) + + for (var i = 0; i < ENum && BadList.Count > 0; i++) { RedPlayer.Add(BadList.RandomElement()); BadList.RemoveAll(RedPlayer.Contains); } AllList.RemoveAll(RedPlayer.Contains); - for (int i = 0; i < BNum && AllList.Count > 0; i++) + + for (var i = 0; i < BNum && AllList.Count > 0; i++) { RedPlayer.Add(AllList.RandomElement()); AllList.RemoveAll(RedPlayer.Contains); diff --git a/Roles/Crewmate/Rabbit.cs b/Roles/Crewmate/Rabbit.cs index 7fb7f4e64..4b4e70d5d 100644 --- a/Roles/Crewmate/Rabbit.cs +++ b/Roles/Crewmate/Rabbit.cs @@ -17,8 +17,10 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Rabbit); + OptionTaskTrigger = new IntegerOptionItem(Id + 2, "RabbitMinTasks", new(0, 90, 1), 3, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Rabbit]); + Options.OverrideTasksData.Create(Id + 3, TabGroup.CrewmateRoles, CustomRoles.Rabbit); } @@ -42,20 +44,14 @@ namespace EHR.Crewmate public override void OnTaskComplete(PlayerControl pc, int completedTaskCount, int totalTaskCount) { - if (pc == null || !RabbitStates.TryGetValue(pc.PlayerId, out RabbitState state)) - { - return; - } + if (pc == null || !RabbitStates.TryGetValue(pc.PlayerId, out RabbitState state)) return; state.OnTaskComplete(); } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer == null || seer.PlayerId != target.PlayerId || !RabbitStates.TryGetValue(seer.PlayerId, out RabbitState state)) - { - return string.Empty; - } + if (seer == null || seer.PlayerId != target.PlayerId || !RabbitStates.TryGetValue(seer.PlayerId, out RabbitState state)) return string.Empty; string suffix = state.Suffix; return hud ? $"{suffix}" : suffix; @@ -73,17 +69,11 @@ namespace EHR.Crewmate public void OnTaskComplete() { - if (!Player.IsAlive() || (MyTaskState.CompletedTasksCount < TaskTrigger && !MyTaskState.IsTaskFinished)) - { - return; - } + if (!Player.IsAlive() || (MyTaskState.CompletedTasksCount < TaskTrigger && !MyTaskState.IsTaskFinished)) return; PlayerControl[] impostors = Main.AllAlivePlayerControls.Where(pc => pc.Is(CustomRoleTypes.Impostor)).ToArray(); PlayerControl target = impostors.RandomElement(); - if (target == null) - { - return; - } + if (target == null) return; Vector2 pos = target.Pos(); LocateArrow.Add(Player.PlayerId, pos); diff --git a/Roles/Crewmate/Randomizer.cs b/Roles/Crewmate/Randomizer.cs index d014d5fc2..7fa265e5d 100644 --- a/Roles/Crewmate/Randomizer.cs +++ b/Roles/Crewmate/Randomizer.cs @@ -32,10 +32,7 @@ namespace EHR.Crewmate public static void Apply(this Effect effect, PlayerControl randomizer) { - if (!Exists) - { - return; - } + if (!Exists) return; try { @@ -46,6 +43,7 @@ namespace EHR.Crewmate PlayerControl pc = PickRandomPlayer(); AddEffectForPlayer(pc, effect); } + break; case Effect.ShieldAll: { @@ -55,6 +53,7 @@ namespace EHR.Crewmate NotifyAboutRNG(pc); } } + break; case Effect.TPEveryoneToVents: { @@ -64,6 +63,7 @@ namespace EHR.Crewmate NotifyAboutRNG(pc); } } + break; case Effect.PullEveryone: Utils.TPAll(randomizer.Pos()); @@ -71,18 +71,13 @@ namespace EHR.Crewmate case Effect.Twist: { List changePositionPlayers = []; + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (changePositionPlayers.Contains(pc.PlayerId) || Pelican.IsEaten(pc.PlayerId) || pc.onLadder || pc.inVent || pc.inMovingPlat || GameStates.IsMeeting) - { - continue; - } + if (changePositionPlayers.Contains(pc.PlayerId) || Pelican.IsEaten(pc.PlayerId) || pc.onLadder || pc.inVent || pc.inMovingPlat || GameStates.IsMeeting) continue; PlayerControl[] filtered = Main.AllAlivePlayerControls.Where(a => !a.inVent && !Pelican.IsEaten(a.PlayerId) && !a.onLadder && a.PlayerId != pc.PlayerId && !changePositionPlayers.Contains(a.PlayerId)).ToArray(); - if (filtered.Length == 0) - { - break; - } + if (filtered.Length == 0) break; PlayerControl target = filtered.RandomElement(); @@ -99,6 +94,7 @@ namespace EHR.Crewmate NotifyAboutRNG(pc); } } + break; case Effect.SuperSpeedForRandomPlayer: { @@ -109,6 +105,7 @@ namespace EHR.Crewmate pc.MarkDirtySettings(); NotifyAboutRNG(pc); } + break; case Effect.SuperSpeedForAll: { @@ -122,6 +119,7 @@ namespace EHR.Crewmate Utils.MarkEveryoneDirtySettings(); } + break; case Effect.FreezeRandomPlayer: { @@ -132,6 +130,7 @@ namespace EHR.Crewmate pc.MarkDirtySettings(); NotifyAboutRNG(pc); } + break; case Effect.SuperVisionForRandomPlayer: { @@ -141,6 +140,7 @@ namespace EHR.Crewmate pc.MarkDirtySettings(); NotifyAboutRNG(pc); } + break; case Effect.SuperVisionForAll: { @@ -153,6 +153,7 @@ namespace EHR.Crewmate Utils.MarkEveryoneDirtySettings(); } + break; case Effect.BlindnessForRandomPlayer: { @@ -162,6 +163,7 @@ namespace EHR.Crewmate pc.MarkDirtySettings(); NotifyAboutRNG(pc); } + break; case Effect.BlindnessForAll: { @@ -174,6 +176,7 @@ namespace EHR.Crewmate Utils.MarkEveryoneDirtySettings(); } + break; case Effect.AllKCDsReset: { @@ -186,6 +189,7 @@ namespace EHR.Crewmate } } } + break; case Effect.AllKCDsTo0: { @@ -198,33 +202,30 @@ namespace EHR.Crewmate } } } + break; case Effect.Meeting when TimeSinceLastMeeting > Math.Max(Main.NormalOptions.EmergencyCooldown, 30): { PlayerControl pc = PickRandomPlayer(); pc.CmdReportDeadBody(null); } + break; case Effect.Rift: Rifts.TryAdd(PickRandomPlayer().Pos(), PickRandomPlayer().Pos()); + try { - List riftsToRemove = new List(); + var riftsToRemove = new List(); + foreach (KeyValuePair rift1 in Rifts) { foreach (KeyValuePair rift2 in Rifts) - { if (rift1.Key != rift2.Key && Vector2.Distance(rift1.Key, rift2.Key) <= 4f) - { riftsToRemove.Add(rift2.Key); - } - } } - foreach (Vector2 rift in riftsToRemove) - { - Rifts.Remove(rift); - } + foreach (Vector2 rift in riftsToRemove) Rifts.Remove(rift); } catch (Exception ex) { @@ -242,15 +243,13 @@ namespace EHR.Crewmate case Effect.RevertToBaseRole when TimeSinceLastMeeting > 40f: // To make this less frequent than the others { PlayerControl pc = PickRandomPlayer(); - if (pc.PlayerId == randomizer.PlayerId) - { - break; - } + if (pc.PlayerId == randomizer.PlayerId) break; pc.RpcSetCustomRole(pc.GetCustomRole().GetErasedRole()); pc.SyncSettings(); NotifyAboutRNG(pc); } + break; case Effect.InvertControls: { @@ -264,36 +263,33 @@ namespace EHR.Crewmate Utils.MarkEveryoneDirtySettings(); } + break; case Effect.AddonAssign: { CustomRoles[] addons = Enum.GetValues().Where(x => x.IsAdditionRole() && x != CustomRoles.NotAssigned).ToArray(); PlayerControl pc = PickRandomPlayer(); CustomRoles addon = addons.RandomElement(); - if (Main.PlayerStates[pc.PlayerId].SubRoles.Contains(addon)) - { - break; - } + if (Main.PlayerStates[pc.PlayerId].SubRoles.Contains(addon)) break; Main.PlayerStates[pc.PlayerId].SetSubRole(addon); pc.MarkDirtySettings(); NotifyAboutRNG(pc); } + break; case Effect.AddonRemove: { PlayerControl pc = PickRandomPlayer(); List addons = Main.PlayerStates[pc.PlayerId].SubRoles; - if (addons.Count == 0) - { - break; - } + if (addons.Count == 0) break; CustomRoles addon = addons.RandomElement(); Main.PlayerStates[pc.PlayerId].RemoveSubRole(addon); pc.MarkDirtySettings(); NotifyAboutRNG(pc); } + break; case Effect.HandcuffRandomPlayer: { @@ -302,6 +298,7 @@ namespace EHR.Crewmate pc.BlockRole(IRandom.Instance.Next(MinimumEffectDuration, MaximumEffectDuration)); NotifyAboutRNG(pc); } + break; case Effect.HandcuffAll: { @@ -312,23 +309,20 @@ namespace EHR.Crewmate NotifyAboutRNG(pc); } } + break; case Effect.DonutForAll: { - foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { - DonutDelivery.RandomNotifyTarget(pc); - } + foreach (PlayerControl pc in Main.AllAlivePlayerControls) DonutDelivery.RandomNotifyTarget(pc); } + break; case Effect.AllDoorsOpen: try { DoorsReset.OpenAllDoors(); } - catch - { - } + catch { } break; case Effect.AllDoorsClose: @@ -336,9 +330,7 @@ namespace EHR.Crewmate { DoorsReset.CloseAllDoors(); } - catch - { - } + catch { } break; case Effect.SetDoorsRandomly: @@ -346,35 +338,32 @@ namespace EHR.Crewmate { DoorsReset.OpenOrCloseAllDoorsRandomly(); } - catch - { - } + catch { } break; case Effect.Patrol: { PlayerControl pc = PickRandomPlayer(); - PatrollingState state = new PatrollingState(pc.PlayerId, IRandom.Instance.Next(MinimumEffectDuration, MaximumEffectDuration), RandomFloat, pc); + var state = new PatrollingState(pc.PlayerId, IRandom.Instance.Next(MinimumEffectDuration, MaximumEffectDuration), RandomFloat, pc); Sentinel.PatrolStates.Add(state); state.StartPatrolling(); } + break; case Effect.GhostPlayer when TimeSinceLastMeeting > Options.DefaultKillCooldown: { PlayerControl killer = PickRandomPlayer(); PlayerControl[] allPc = Main.AllAlivePlayerControls.Where(x => x.PlayerId != killer.PlayerId).ToArray(); - if (allPc.Length == 0) - { - break; - } + if (allPc.Length == 0) break; PlayerControl target = allPc.RandomElement(); BallLightning.CheckBallLightningMurder(killer, target, true); NotifyAboutRNG(target); } + break; case Effect.Camouflage when TimeSinceLastMeeting > Camouflager.CamouflageCooldown.GetFloat(): - Camouflager camouflager = new Camouflager(); + var camouflager = new Camouflager(); camouflager.Init(); camouflager.Add(randomizer.PlayerId); camouflager.OnShapeshift(randomizer, randomizer, true); @@ -382,33 +371,33 @@ namespace EHR.Crewmate break; case Effect.Deathpact: { - Deathpact deathpact = new Deathpact(); + var deathpact = new Deathpact(); deathpact.Init(); deathpact.Add(randomizer.PlayerId); deathpact.OnShapeshift(randomizer, PickRandomPlayer(), true); } + break; case Effect.DevourRandomPlayer: { - Devourer devourer = new Devourer(); + var devourer = new Devourer(); devourer.Init(); devourer.Add(randomizer.PlayerId); devourer.OnShapeshift(randomizer, PickRandomPlayer(), true); } + break; case Effect.Duel: { PlayerControl pc1 = PickRandomPlayer(); PlayerControl[] allPc = Main.AllAlivePlayerControls.Where(x => x.CanUseKillButton() && x.PlayerId != pc1.PlayerId).ToArray(); - if (allPc.Length == 0) - { - break; - } + if (allPc.Length == 0) break; PlayerControl pc2 = allPc.RandomElement(); - Duellist duellist = new Duellist(); + var duellist = new Duellist(); duellist.OnShapeshift(pc1, pc2, true); } + break; default: Logger.Info("Effect wasn't applied", "Randomizer"); @@ -497,10 +486,7 @@ namespace EHR.Crewmate public static void NotifyAboutRNG(PlayerControl pc) { - if (!Notify) - { - return; - } + if (!Notify) return; pc.Notify(RNGString, IRandom.Instance.Next(2, 7), log: false); } @@ -523,15 +509,19 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Randomizer); + EffectFrequencyOpt = new IntegerOptionItem(Id + 2, "RandomizerEffectFrequency", new(1, 90, 1), 10, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Randomizer]) .SetValueFormat(OptionFormat.Seconds); + EffectDurMin = new IntegerOptionItem(Id + 3, "RandomizerEffectDurMin", new(1, 90, 1), 5, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Randomizer]) .SetValueFormat(OptionFormat.Seconds); + EffectDurMax = new IntegerOptionItem(Id + 4, "RandomizerEffectDurMax", new(1, 90, 1), 15, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Randomizer]) .SetValueFormat(OptionFormat.Seconds); + NotifyOpt = new BooleanOptionItem(Id + 5, "RandomizerNotifyOpt", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Randomizer]); } @@ -570,10 +560,7 @@ namespace EHR.Crewmate public static PlayerControl PickRandomPlayer() { PlayerControl[] allPc = Main.AllAlivePlayerControls; - if (allPc.Length == 0) - { - return null; - } + if (allPc.Length == 0) return null; PlayerControl pc = allPc.RandomElement(); return pc; @@ -581,15 +568,9 @@ namespace EHR.Crewmate public static void AddEffectForPlayer(PlayerControl pc, Effect effect) { - if (pc == null || !Exists) - { - return; - } + if (pc == null || !Exists) return; - if (!CurrentEffects.ContainsKey(pc.PlayerId)) - { - CurrentEffects[pc.PlayerId] = []; - } + if (!CurrentEffects.ContainsKey(pc.PlayerId)) CurrentEffects[pc.PlayerId] = []; int duration = IRandom.Instance.Next(MinimumEffectDuration, MaximumEffectDuration + 1); CurrentEffects[pc.PlayerId].TryAdd(effect, (Utils.TimeStamp, duration)); @@ -606,10 +587,7 @@ namespace EHR.Crewmate if (effect == Effect.GhostPlayer) { - if (LastDeathEffect + 60 > now) - { - return Effect.AddonRemove; - } + if (LastDeathEffect + 60 > now) return Effect.AddonRemove; LastDeathEffect = now; } @@ -623,18 +601,12 @@ namespace EHR.Crewmate { try { - if (pc == null || !Exists) - { - return; - } + if (pc == null || !Exists) return; if (CurrentEffects.TryGetValue(pc.PlayerId, out Dictionary effects) && effects.Any(x => x.Key.IsSpeedChangingEffect())) { Main.AllPlayerSpeed[pc.PlayerId] = AllPlayerDefaultSpeed[pc.PlayerId]; - if (sync) - { - pc.MarkDirtySettings(); - } + if (sync) pc.MarkDirtySettings(); IEnumerable keys = effects.Keys.AsEnumerable(); keys.DoIf(x => x.IsSpeedChangingEffect(), x => effects.Remove(x), false); @@ -650,19 +622,13 @@ namespace EHR.Crewmate { try { - if (pc == null || !Exists) - { - return; - } + if (pc == null || !Exists) return; if (CurrentEffects.TryGetValue(pc.PlayerId, out Dictionary effects) && effects.Any(x => x.Key.IsVisionChangingEffect())) { IEnumerable keys = effects.Keys.AsEnumerable(); keys.DoIf(x => x.IsVisionChangingEffect(), x => effects.Remove(x), false); - if (sync) - { - pc.MarkDirtySettings(); - } + if (sync) pc.MarkDirtySettings(); } } catch (Exception e) @@ -675,10 +641,7 @@ namespace EHR.Crewmate { try { - if (!Exists) - { - return; - } + if (!Exists) return; RevertSpeedChangesForPlayer(pc, false); RevertVisionChangesForPlayer(pc, false); @@ -694,16 +657,14 @@ namespace EHR.Crewmate public override void OnReportDeadBody() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; TimeSinceLastMeeting = 0; LastDeathEffect = Utils.TimeStamp; Rifts.Clear(); Bombs.Clear(); Utils.SendRPC(CustomRPC.SyncRoleData, PlayerIdList[0], 3); + foreach (PlayerControl pc in Main.AllPlayerControls) { RevertSpeedChangesForPlayer(pc, false); @@ -713,10 +674,7 @@ namespace EHR.Crewmate public override void AfterMeetingTasks() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; TimeSinceLastMeeting = 0; LastDeathEffect = Utils.TimeStamp; @@ -726,10 +684,7 @@ namespace EHR.Crewmate { try { - if (lowLoad || !Exists || !GameStates.IsInTask || Bombs.Count == 0 || Main.HasJustStarted) - { - return; - } + if (lowLoad || !Exists || !GameStates.IsInTask || Bombs.Count == 0 || Main.HasJustStarted) return; long now = Utils.TimeStamp; PlayerControl randomizer = Utils.GetPlayerById(PlayerIdList.FirstOrDefault()); @@ -739,10 +694,7 @@ namespace EHR.Crewmate if (bomb.Value.PlaceTimeStamp + bomb.Value.ExplosionDelay < now) { IEnumerable players = Utils.GetPlayersInRadius(RandomFloat, bomb.Key); - foreach (PlayerControl pc in players) - { - pc.Suicide(PlayerState.DeathReason.RNG, randomizer); - } + foreach (PlayerControl pc in players) pc.Suicide(PlayerState.DeathReason.RNG, randomizer); Bombs.Remove(bomb.Key); Utils.SendRPC(CustomRPC.SyncRoleData, randomizer.PlayerId, 2, bomb.Key); @@ -773,10 +725,7 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer == null || seer.PlayerId != target.PlayerId || Bombs.Count == 0) - { - return string.Empty; - } + if (seer == null || seer.PlayerId != target.PlayerId || Bombs.Count == 0) return string.Empty; KeyValuePair bomb = Bombs.FirstOrDefault(x => Vector2.Distance(x.Key, seer.Pos()) <= 5f); long time = bomb.Value.ExplosionDelay - (Utils.TimeStamp - bomb.Value.PlaceTimeStamp) + 1; @@ -787,17 +736,11 @@ namespace EHR.Crewmate { try { - if (!IsEnable || !GameStates.IsInTask || Main.HasJustStarted) - { - return; - } + if (!IsEnable || !GameStates.IsInTask || Main.HasJustStarted) return; TimeSinceLastMeeting += Time.fixedDeltaTime; - if (pc == null || !pc.IsAlive() || TimeSinceLastMeeting <= 10f) - { - return; - } + if (pc == null || !pc.IsAlive() || TimeSinceLastMeeting <= 10f) return; long now = Utils.TimeStamp; @@ -807,9 +750,7 @@ namespace EHR.Crewmate effect.Apply(pc); } else - { LastEffectPick.TryAdd(pc.PlayerId, now); - } } catch (Exception ex) { @@ -821,16 +762,10 @@ namespace EHR.Crewmate { try { - if (!IsEnable || !GameStates.IsInTask || Main.HasJustStarted) - { - return; - } + if (!IsEnable || !GameStates.IsInTask || Main.HasJustStarted) return; long now = Utils.TimeStamp; - if (LastTP[pc.PlayerId] + 5 > now) - { - return; - } + if (LastTP[pc.PlayerId] + 5 > now) return; Vector2 pos = pc.Pos(); @@ -861,10 +796,7 @@ namespace EHR.Crewmate { try { - if (!Exists || pc == null || !pc.IsAlive() || !GameStates.IsInTask || Main.HasJustStarted) - { - return; - } + if (!Exists || pc == null || !pc.IsAlive() || !GameStates.IsInTask || Main.HasJustStarted) return; if (CurrentEffects.TryGetValue(pc.PlayerId, out Dictionary effects)) { @@ -874,15 +806,9 @@ namespace EHR.Crewmate { if (item.Value.StartTimeStamp + item.Value.Duration < now) { - if (item.Key.IsVisionChangingEffect()) - { - RevertVisionChangesForPlayer(pc, true); - } + if (item.Key.IsVisionChangingEffect()) RevertVisionChangesForPlayer(pc, true); - if (item.Key.IsSpeedChangingEffect()) - { - RevertSpeedChangesForPlayer(pc, true); - } + if (item.Key.IsSpeedChangingEffect()) RevertSpeedChangesForPlayer(pc, true); effects.Remove(item.Key); } diff --git a/Roles/Crewmate/Rhapsode.cs b/Roles/Crewmate/Rhapsode.cs index 94f4dacc4..5fc2fa4c1 100644 --- a/Roles/Crewmate/Rhapsode.cs +++ b/Roles/Crewmate/Rhapsode.cs @@ -26,22 +26,28 @@ namespace EHR.Crewmate public override void SetupCustomOption() { - int id = 647650; + var id = 647650; Options.SetupRoleOptions(id++, TabGroup.CrewmateRoles, CustomRoles.Rhapsode); + AbilityCooldown = new IntegerOptionItem(++id, "AbilityCooldown", new(0, 60, 1), 30, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Rhapsode]) .SetValueFormat(OptionFormat.Seconds); + AbilityDuration = new IntegerOptionItem(++id, "AbilityDuration", new(0, 60, 1), 10, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Rhapsode]) .SetValueFormat(OptionFormat.Seconds); + ExcludeCrewmates = new BooleanOptionItem(++id, "Rhapsode.ExcludeCrewmates", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Rhapsode]); + AbilityUseLimit = new IntegerOptionItem(++id, "AbilityUseLimit", new(0, 20, 1), 1, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Rhapsode]) .SetValueFormat(OptionFormat.Times); + RhapsodeAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(++id, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.3f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Rhapsode]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(++id, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Rhapsode]) .SetValueFormat(OptionFormat.Times); @@ -66,10 +72,7 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (Options.UsePets.GetBool()) - { - return; - } + if (Options.UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = AbilityCooldown.GetInt(); AURoleOptions.EngineerInVentMaxTime = 1f; @@ -96,10 +99,7 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { long now = Utils.TimeStamp; - if (now == LastUpdate) - { - return; - } + if (now == LastUpdate) return; LastUpdate = now; @@ -114,10 +114,7 @@ namespace EHR.Crewmate public static bool CheckAbilityUse(PlayerControl pc) { - if (pc.IsCrewmate() && ExcludeCrewmates.GetBool()) - { - return true; - } + if (pc.IsCrewmate() && ExcludeCrewmates.GetBool()) return true; return !Instances.Any(x => x.AbilityActive); } @@ -125,18 +122,12 @@ namespace EHR.Crewmate public void ReceiveRPC(MessageReader reader) { AbilityActive = reader.ReadBoolean(); - if (AbilityActive) - { - ActivateTimeStamp = Utils.TimeStamp; - } + if (AbilityActive) ActivateTimeStamp = Utils.TimeStamp; } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != RhapsodeId || hud || meeting || !AbilityActive) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != RhapsodeId || hud || meeting || !AbilityActive) return string.Empty; return $"\u25b6 ({AbilityDuration.GetInt() - (Utils.TimeStamp - ActivateTimeStamp)}s)"; } diff --git a/Roles/Crewmate/Ricochet.cs b/Roles/Crewmate/Ricochet.cs index df3412e17..669e37b8a 100644 --- a/Roles/Crewmate/Ricochet.cs +++ b/Roles/Crewmate/Ricochet.cs @@ -24,14 +24,18 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Ricochet); + UseLimitOpt = new IntegerOptionItem(Id + 10, "AbilityUseLimit", new(0, 20, 1), 1, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Ricochet]) .SetValueFormat(OptionFormat.Times); + RicochetAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 11, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.5f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ricochet]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 13, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ricochet]) .SetValueFormat(OptionFormat.Times); + CancelVote = CreateVoteCancellingUseSetting(Id + 12, CustomRoles.Ricochet, TabGroup.CrewmateRoles); } @@ -52,10 +56,7 @@ namespace EHR.Crewmate private void SendRPCSyncTarget(byte targetId) { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetRicochetTarget, SendOption.Reliable); writer.Write(RicochetId); @@ -66,25 +67,16 @@ namespace EHR.Crewmate public static void ReceiveRPCSyncTarget(MessageReader reader) { byte id = reader.ReadByte(); - if (Main.PlayerStates[id].Role is not Ricochet rc) - { - return; - } + if (Main.PlayerStates[id].Role is not Ricochet rc) return; rc.ProtectAgainst = reader.ReadByte(); } public override bool OnCheckMurderAsTarget(PlayerControl killer, PlayerControl target) { - if (killer == null) - { - return false; - } + if (killer == null) return false; - if (target == null) - { - return false; - } + if (target == null) return false; if (ProtectAgainst == killer.PlayerId) { @@ -97,10 +89,7 @@ namespace EHR.Crewmate public override bool OnVote(PlayerControl pc, PlayerControl target) { - if (target == null || pc == null || pc.PlayerId == target.PlayerId || Main.DontCancelVoteList.Contains(pc.PlayerId)) - { - return false; - } + if (target == null || pc == null || pc.PlayerId == target.PlayerId || Main.DontCancelVoteList.Contains(pc.PlayerId)) return false; if (pc.GetAbilityUseLimit() >= 1) { diff --git a/Roles/Crewmate/SabotageMaster.cs b/Roles/Crewmate/SabotageMaster.cs index 814508b8b..17b1a2f3f 100644 --- a/Roles/Crewmate/SabotageMaster.cs +++ b/Roles/Crewmate/SabotageMaster.cs @@ -35,28 +35,38 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.SabotageMaster); + SkillLimit = new IntegerOptionItem(Id + 10, "SabotageMasterSkillLimit", new(0, 80, 1), 2, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SabotageMaster]) .SetValueFormat(OptionFormat.Times); + FixesDoors = new BooleanOptionItem(Id + 11, "SabotageMasterFixesDoors", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SabotageMaster]); + FixesReactors = new BooleanOptionItem(Id + 12, "SabotageMasterFixesReactors", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SabotageMaster]); + FixesOxygens = new BooleanOptionItem(Id + 13, "SabotageMasterFixesOxygens", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SabotageMaster]); + FixesComms = new BooleanOptionItem(Id + 14, "SabotageMasterFixesCommunications", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SabotageMaster]); + FixesElectrical = new BooleanOptionItem(Id + 15, "SabotageMasterFixesElectrical", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SabotageMaster]); + SmAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 16, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 3f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SabotageMaster]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 19, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SabotageMaster]) .SetValueFormat(OptionFormat.Times); + UsesUsedWhenFixingReactorOrO2 = new FloatOptionItem(Id + 17, "SMUsesUsedWhenFixingReactorOrO2", new(0f, 5f, 0.1f), 4f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SabotageMaster]) .SetValueFormat(OptionFormat.Times); + UsesUsedWhenFixingLightsOrComms = new FloatOptionItem(Id + 18, "SMUsesUsedWhenFixingLightsOrComms", new(0f, 5f, 0.1f), 1f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SabotageMaster]) .SetValueFormat(OptionFormat.Times); @@ -91,10 +101,7 @@ namespace EHR.Crewmate public void SendRPC() { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetSabotageMasterLimit, SendOption.Reliable); writer.Write(SMId); @@ -105,35 +112,23 @@ namespace EHR.Crewmate public static void ReceiveRPC(MessageReader reader) { byte id = reader.ReadByte(); - if (Main.PlayerStates[id].Role is not SabotageMaster sm) - { - return; - } + if (Main.PlayerStates[id].Role is not SabotageMaster sm) return; sm.UsedSkillCount = reader.ReadSingle(); } public static void RepairSystem(byte playerId, SystemTypes systemType, byte amount) { - if (Main.PlayerStates[playerId].Role is not SabotageMaster sm) - { - return; - } + if (Main.PlayerStates[playerId].Role is not SabotageMaster sm) return; switch (systemType) { case SystemTypes.Reactor: case SystemTypes.Laboratory: { - if (!FixesReactors.GetBool()) - { - break; - } + if (!FixesReactors.GetBool()) break; - if (SkillLimit.GetFloat() > 0 && sm.UsedSkillCount + UsesUsedWhenFixingReactorOrO2.GetFloat() - 1 >= SkillLimit.GetFloat()) - { - break; - } + if (SkillLimit.GetFloat() > 0 && sm.UsedSkillCount + UsesUsedWhenFixingReactorOrO2.GetFloat() - 1 >= SkillLimit.GetFloat()) break; if (amount.HasAnyBit(ReactorSystemType.AddUserOp)) { @@ -146,21 +141,12 @@ namespace EHR.Crewmate } case SystemTypes.HeliSabotage: { - if (!FixesReactors.GetBool()) - { - break; - } + if (!FixesReactors.GetBool()) break; - if (SkillLimit.GetFloat() > 0 && sm.UsedSkillCount + UsesUsedWhenFixingReactorOrO2.GetFloat() - 1 >= SkillLimit.GetFloat()) - { - break; - } + if (SkillLimit.GetFloat() > 0 && sm.UsedSkillCount + UsesUsedWhenFixingReactorOrO2.GetFloat() - 1 >= SkillLimit.GetFloat()) break; - HeliSabotageSystem.Tags tags = (HeliSabotageSystem.Tags)(amount & HeliSabotageSystem.TagMask); - if (tags == HeliSabotageSystem.Tags.ActiveBit) - { - sm.fixedSabotage = false; - } + var tags = (HeliSabotageSystem.Tags)(amount & HeliSabotageSystem.TagMask); + if (tags == HeliSabotageSystem.Tags.ActiveBit) sm.fixedSabotage = false; if (!sm.fixedSabotage && tags == HeliSabotageSystem.Tags.FixBit) { @@ -176,15 +162,9 @@ namespace EHR.Crewmate } case SystemTypes.LifeSupp: { - if (!FixesOxygens.GetBool()) - { - break; - } + if (!FixesOxygens.GetBool()) break; - if (SkillLimit.GetFloat() > 0 && sm.UsedSkillCount + UsesUsedWhenFixingReactorOrO2.GetFloat() - 1 >= SkillLimit.GetFloat()) - { - break; - } + if (SkillLimit.GetFloat() > 0 && sm.UsedSkillCount + UsesUsedWhenFixingReactorOrO2.GetFloat() - 1 >= SkillLimit.GetFloat()) break; if (amount.HasAnyBit(LifeSuppSystemType.AddUserOp)) { @@ -197,21 +177,12 @@ namespace EHR.Crewmate } case SystemTypes.Comms when Main.CurrentMap == MapNames.Mira: { - if (!FixesComms.GetBool()) - { - break; - } + if (!FixesComms.GetBool()) break; - if (SkillLimit.GetFloat() > 0 && sm.UsedSkillCount + UsesUsedWhenFixingLightsOrComms.GetFloat() - 1 >= SkillLimit.GetFloat()) - { - break; - } + if (SkillLimit.GetFloat() > 0 && sm.UsedSkillCount + UsesUsedWhenFixingLightsOrComms.GetFloat() - 1 >= SkillLimit.GetFloat()) break; - HqHudSystemType.Tags tags = (HqHudSystemType.Tags)(amount & HqHudSystemType.TagMask); - if (tags == HqHudSystemType.Tags.ActiveBit) - { - sm.fixedSabotage = false; - } + var tags = (HqHudSystemType.Tags)(amount & HqHudSystemType.TagMask); + if (tags == HqHudSystemType.Tags.ActiveBit) sm.fixedSabotage = false; if (!sm.fixedSabotage && tags == HqHudSystemType.Tags.FixBit) { @@ -227,25 +198,17 @@ namespace EHR.Crewmate } case SystemTypes.Doors: { - if (!FixesDoors.GetBool()) - { - break; - } + if (!FixesDoors.GetBool()) break; - if (DoorsProgressing) - { - break; - } + if (DoorsProgressing) break; int mapId = Main.NormalOptions.MapId; - if (AmongUsClient.Instance.NetworkMode == NetworkModes.FreePlay) - { - mapId = AmongUsClient.Instance.TutorialMapId; - } + if (AmongUsClient.Instance.NetworkMode == NetworkModes.FreePlay) mapId = AmongUsClient.Instance.TutorialMapId; - ShipStatus shipStatus = ShipStatus.Instance; + var shipStatus = ShipStatus.Instance; DoorsProgressing = true; + switch (mapId) { case 2: // Polus @@ -270,20 +233,16 @@ namespace EHR.Crewmate { int openedDoorId = amount & DoorsSystemType.IdMask; OpenableDoor openedDoor = shipStatus.AllDoors.FirstOrDefault(door => door.Id == openedDoorId); + if (openedDoor == null) - { Logger.Warn($"An unknown door has been opened: {openedDoorId}", nameof(SabotageMaster)); - } else { SystemTypes room = openedDoor.Room; + foreach (OpenableDoor door in shipStatus.AllDoors) - { if (door.Id != openedDoorId && door.Room == room) - { door.SetDoorway(true); - } - } } break; @@ -298,20 +257,11 @@ namespace EHR.Crewmate public static void SwitchSystemRepair(byte playerId, SwitchSystem switchSystem, byte amount) { - if (!FixesElectrical.GetBool() || Main.PlayerStates[playerId].Role is not SabotageMaster sm) - { - return; - } + if (!FixesElectrical.GetBool() || Main.PlayerStates[playerId].Role is not SabotageMaster sm) return; - if (SkillLimit.GetFloat() > 0 && sm.UsedSkillCount + UsesUsedWhenFixingLightsOrComms.GetFloat() - 1 >= SkillLimit.GetFloat()) - { - return; - } + if (SkillLimit.GetFloat() > 0 && sm.UsedSkillCount + UsesUsedWhenFixingLightsOrComms.GetFloat() - 1 >= SkillLimit.GetFloat()) return; - if (amount.HasBit(SwitchSystem.DamageSystem)) - { - return; - } + if (amount.HasBit(SwitchSystem.DamageSystem)) return; int fixbit = 1 << amount; switchSystem.ActualSwitches = (byte)(switchSystem.ExpectedSwitches ^ fixbit); diff --git a/Roles/Crewmate/Safeguard.cs b/Roles/Crewmate/Safeguard.cs index b3f6b839d..dd21fac2c 100644 --- a/Roles/Crewmate/Safeguard.cs +++ b/Roles/Crewmate/Safeguard.cs @@ -20,14 +20,17 @@ namespace EHR.Crewmate { const TabGroup tab = TabGroup.CrewmateRoles; const CustomRoles role = CustomRoles.Safeguard; - int id = 645500; + var id = 645500; Options.SetupRoleOptions(id++, tab, role); + ShieldDuration = new FloatOptionItem(++id, "AidDur", new(0.5f, 60f, 0.5f), 5f, tab) .SetParent(Options.CustomRoleSpawnChances[role]) .SetValueFormat(OptionFormat.Seconds); + MinTasks = new IntegerOptionItem(++id, "MinTasksToActivateAbility", new(1, 10, 1), 3, tab) .SetParent(Options.CustomRoleSpawnChances[role]); + Options.OverrideTasksData.Create(++id, tab, role); } @@ -45,31 +48,19 @@ namespace EHR.Crewmate public override void OnTaskComplete(PlayerControl pc, int completedTaskCount, int totalTaskCount) { - if (!pc.IsAlive()) - { - return; - } + if (!pc.IsAlive()) return; - if (completedTaskCount + 1 >= MinTasks.GetInt()) - { - Timer += ShieldDuration.GetFloat(); - } + if (completedTaskCount + 1 >= MinTasks.GetInt()) Timer += ShieldDuration.GetFloat(); } public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive()) - { - return; - } + if (!pc.IsAlive()) return; if (Shielded) { Timer -= Time.fixedDeltaTime; - if (Timer <= 0) - { - Timer = 0; - } + if (Timer <= 0) Timer = 0; } } @@ -80,10 +71,7 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != SafeguardId || meeting || (seer.IsModClient() && !hud) || !Shielded) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != SafeguardId || meeting || (seer.IsModClient() && !hud) || !Shielded) return string.Empty; return seer.IsHost() ? string.Format(Translator.GetString("SafeguardSuffixTimer"), (int)Math.Ceiling(Timer)) : Translator.GetString("SafeguardSuffix"); } diff --git a/Roles/Crewmate/Scout.cs b/Roles/Crewmate/Scout.cs index 3a359e495..75b67b50f 100644 --- a/Roles/Crewmate/Scout.cs +++ b/Roles/Crewmate/Scout.cs @@ -31,21 +31,28 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Scout); + TrackLimitOpt = new IntegerOptionItem(Id + 5, "DivinatorSkillLimit", new(0, 20, 1), 1, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Scout]) .SetValueFormat(OptionFormat.Times); + CanGetColoredArrow = new BooleanOptionItem(Id + 6, "TrackerCanGetArrowColor", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Scout]); + OptionCanSeeLastRoomInMeeting = new BooleanOptionItem(Id + 7, "EvilTrackerCanSeeLastRoomInMeeting", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Scout]); + HideVote = new BooleanOptionItem(Id + 8, "TrackerHideVote", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Scout]); + TrackerAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 9, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 1f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Scout]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 3, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Scout]) .SetValueFormat(OptionFormat.Times); + CancelVote = CreateVoteCancellingUseSetting(Id + 4, CustomRoles.Scout, TabGroup.CrewmateRoles); } @@ -66,10 +73,7 @@ namespace EHR.Crewmate public static void SendRPC(byte trackerId = byte.MaxValue, byte targetId = byte.MaxValue) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetTrackerTarget, SendOption.Reliable); writer.Write(trackerId); @@ -94,10 +98,7 @@ namespace EHR.Crewmate public override bool OnVote(PlayerControl player, PlayerControl target) { - if (player == null || target == null || player.GetAbilityUseLimit() < 1f || player.PlayerId == target.PlayerId || TrackerTarget[player.PlayerId].Contains(target.PlayerId) || Main.DontCancelVoteList.Contains(player.PlayerId)) - { - return false; - } + if (player == null || target == null || player.GetAbilityUseLimit() < 1f || player.PlayerId == target.PlayerId || TrackerTarget[player.PlayerId].Contains(target.PlayerId) || Main.DontCancelVoteList.Contains(player.PlayerId)) return false; player.RpcRemoveAbilityUse(); @@ -112,25 +113,13 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer == null || seer.PlayerId != TrackerId) - { - return string.Empty; - } + if (seer == null || seer.PlayerId != TrackerId) return string.Empty; - if (target != null && seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (target != null && seer.PlayerId != target.PlayerId) return string.Empty; - if (!TrackerTarget.ContainsKey(seer.PlayerId)) - { - return string.Empty; - } + if (!TrackerTarget.ContainsKey(seer.PlayerId)) return string.Empty; - if (GameStates.IsMeeting) - { - return string.Empty; - } + if (GameStates.IsMeeting) return string.Empty; return TrackerTarget[seer.PlayerId].Aggregate(string.Empty, (current, trackTarget) => current + Utils.ColorString(CanGetColoredArrow.GetBool() ? Main.PlayerColors[trackTarget] : Color.white, TargetArrow.GetArrows(seer, trackTarget))) + LocateArrow.GetArrows(seer); } @@ -144,34 +133,25 @@ namespace EHR.Crewmate public static string GetArrowAndLastRoom(PlayerControl seer, PlayerControl target) { - if (seer == null || target == null) - { - return string.Empty; - } + if (seer == null || target == null) return string.Empty; Color roleColor = Utils.GetRoleColor(CustomRoles.Scout); string text = Utils.ColorString(roleColor, TargetArrow.GetArrows(seer, target.PlayerId)); text += Utils.ColorString(roleColor, LocateArrow.GetArrows(seer)); PlainShipRoom room = Main.PlayerStates[target.PlayerId].LastRoom; + if (room == null) - { text += Utils.ColorString(Color.gray, "@" + GetString("FailToTrack")); - } else - { text += Utils.ColorString(roleColor, "@" + GetString(room.RoomId.ToString())); - } return text; } public static void OnPlayerDeath(PlayerControl player) { - if (player == null) - { - return; - } + if (player == null) return; foreach (KeyValuePair> kvp in TrackerTarget) { @@ -189,9 +169,11 @@ namespace EHR.Crewmate foreach (KeyValuePair> kvp in TrackerTarget) { LocateArrow.RemoveAllTarget(kvp.Key); + foreach (byte id in kvp.Value.ToArray()) { PlayerControl pc = Utils.GetPlayerById(id); + if (pc == null || !pc.IsAlive()) { kvp.Value.Remove(id); diff --git a/Roles/Crewmate/SecurityGuard.cs b/Roles/Crewmate/SecurityGuard.cs index ffe4b5421..7b0b6a424 100644 --- a/Roles/Crewmate/SecurityGuard.cs +++ b/Roles/Crewmate/SecurityGuard.cs @@ -15,18 +15,23 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(6860, TabGroup.CrewmateRoles, CustomRoles.SecurityGuard); + SecurityGuardSkillCooldown = new FloatOptionItem(6862, "SecurityGuardSkillCooldown", new(0f, 180f, 1f), 15f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.SecurityGuard]) .SetValueFormat(OptionFormat.Seconds); + SecurityGuardSkillDuration = new FloatOptionItem(6863, "SecurityGuardSkillDuration", new(0f, 180f, 1f), 10f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.SecurityGuard]) .SetValueFormat(OptionFormat.Seconds); + SecurityGuardSkillMaxOfUseage = new IntegerOptionItem(6866, "AbilityUseLimit", new(0, 180, 1), 1, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.SecurityGuard]) .SetValueFormat(OptionFormat.Times); + SecurityGuardAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(6867, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.4f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.SecurityGuard]) .SetValueFormat(OptionFormat.Times); + SecurityGuardAbilityChargesWhenFinishedTasks = new FloatOptionItem(6868, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.SecurityGuard]) .SetValueFormat(OptionFormat.Times); @@ -45,10 +50,7 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.EngineerInVentMaxTime = 1; AURoleOptions.EngineerCooldown = SecurityGuardSkillCooldown.GetFloat(); @@ -56,7 +58,7 @@ namespace EHR.Crewmate public override string GetProgressText(byte playerId, bool comms) { - StringBuilder ProgressText = new StringBuilder(); + var ProgressText = new StringBuilder(); ProgressText.Append(Utils.GetAbilityUseLimitDisplay(playerId, BlockSabo.ContainsKey(playerId))); ProgressText.Append(Utils.GetTaskCount(playerId, comms)); @@ -67,13 +69,9 @@ namespace EHR.Crewmate public override void SetButtonTexts(HudManager hud, byte id) { if (UsePets.GetBool()) - { hud.PetButton.buttonLabelText.text = Translator.GetString("SecurityGuardVentButtonText"); - } else - { hud.AbilityButton.buttonLabelText.text = Translator.GetString("SecurityGuardVentButtonText"); - } } public override void OnPet(PlayerControl pc) @@ -88,10 +86,7 @@ namespace EHR.Crewmate private static void Guard(PlayerControl pc) { - if (BlockSabo.ContainsKey(pc.PlayerId)) - { - return; - } + if (BlockSabo.ContainsKey(pc.PlayerId)) return; if (pc.GetAbilityUseLimit() >= 1) { @@ -101,14 +96,13 @@ namespace EHR.Crewmate pc.RpcRemoveAbilityUse(); } else - { pc.Notify(Translator.GetString("OutOfAbilityUsesDoMoreTasks")); - } } public override void OnFixedUpdate(PlayerControl player) { byte playerId = player.PlayerId; + if (BlockSabo.TryGetValue(playerId, out long stime) && stime + SecurityGuardSkillDuration.GetInt() < Utils.TimeStamp) { BlockSabo.Remove(playerId); diff --git a/Roles/Crewmate/Sentinel.cs b/Roles/Crewmate/Sentinel.cs index 4204a579e..4b987f411 100644 --- a/Roles/Crewmate/Sentinel.cs +++ b/Roles/Crewmate/Sentinel.cs @@ -35,55 +35,34 @@ namespace EHR.Crewmate public void StartPatrolling() { - if (IsPatrolling) - { - return; - } + if (IsPatrolling) return; IsPatrolling = true; StartingPosition = Sentinel.Pos(); PatrolStartTimeStamp = TimeStamp; - foreach (PlayerControl pc in NearbyKillers) - { - pc.Notify(string.Format(GetString("KillerNotifyPatrol"), PatrolDuration)); - } + foreach (PlayerControl pc in NearbyKillers) pc.Notify(string.Format(GetString("KillerNotifyPatrol"), PatrolDuration)); Sentinel.MarkDirtySettings(); } public void Update() { - if (!IsPatrolling) - { - return; - } + if (!IsPatrolling) return; long now = TimeStamp; - if (LastUpdate >= now) - { - return; - } + if (LastUpdate >= now) return; LastUpdate = now; - if (PatrolStartTimeStamp + PatrolDuration < now) - { - FinishPatrolling(); - } + if (PatrolStartTimeStamp + PatrolDuration < now) FinishPatrolling(); } public void OnCheckPlayerPosition(PlayerControl pc) { - if (!IsPatrolling) - { - return; - } + if (!IsPatrolling) return; long now = TimeStamp; - if (LastUpdate >= now) - { - return; - } + if (LastUpdate >= now) return; LastUpdate = now; @@ -93,15 +72,9 @@ namespace EHR.Crewmate bool wasInRange = LastNearbyKillers.Contains(pc.PlayerId); long timeLeft = PatrolDuration - (TimeStamp - PatrolStartTimeStamp); - if (wasInRange && !nowInRange) - { - pc.Notify(GetString("KillerEscapedFromSentinel")); - } + if (wasInRange && !nowInRange) pc.Notify(GetString("KillerEscapedFromSentinel")); - if (nowInRange && timeLeft >= 0) - { - pc.Notify(string.Format(GetString("KillerNotifyPatrol"), timeLeft)); - } + if (nowInRange && timeLeft >= 0) pc.Notify(string.Format(GetString("KillerNotifyPatrol"), timeLeft)); LastNearbyKillers = killers.Select(x => x.PlayerId).ToList(); } @@ -109,15 +82,9 @@ namespace EHR.Crewmate public void FinishPatrolling() { IsPatrolling = false; - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; - foreach (PlayerControl pc in NearbyKillers) - { - pc.Suicide(realKiller: Sentinel); - } + foreach (PlayerControl pc in NearbyKillers) pc.Suicide(realKiller: Sentinel); Sentinel.MarkDirtySettings(); } @@ -139,12 +106,15 @@ namespace EHR.Crewmate { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Sentinel); PatrolCooldown = CreateCDSetting(Id + 2, TabGroup.CrewmateRoles, CustomRoles.Sentinel); + PatrolDuration = new IntegerOptionItem(Id + 3, "SentinelPatrolDuration", new(1, 90, 1), 5, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sentinel]) .SetValueFormat(OptionFormat.Seconds); + LoweredVision = new FloatOptionItem(Id + 4, "FFA_LowerVision", new(0.05f, 3f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sentinel]) .SetValueFormat(OptionFormat.Multiplier); + PatrolRadius = new FloatOptionItem(Id + 5, "SentinelPatrolRadius", new(0.1f, 25f, 0.1f), 5f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sentinel]) .SetValueFormat(OptionFormat.Multiplier); @@ -157,7 +127,7 @@ namespace EHR.Crewmate public override void Add(byte playerId) { - PatrollingState newPatrolState = new PatrollingState(playerId, PatrolDuration.GetInt(), PatrolRadius.GetFloat()); + var newPatrolState = new PatrollingState(playerId, PatrolDuration.GetInt(), PatrolRadius.GetFloat()); PatrolStates.Add(newPatrolState); LateTask.New(newPatrolState.SetPlayer, 8f, log: false); } @@ -184,17 +154,11 @@ namespace EHR.Crewmate public static bool OnAnyoneCheckMurder(PlayerControl killer) { - if (killer == null || !PatrolStates.Any(x => x.IsPatrolling)) - { - return true; - } + if (killer == null || !PatrolStates.Any(x => x.IsPatrolling)) return true; foreach (PatrollingState state in PatrolStates) { - if (!state.IsPatrolling) - { - continue; - } + if (!state.IsPatrolling) continue; if (state.NearbyKillers.Any(x => x.PlayerId == killer.PlayerId)) { @@ -214,46 +178,27 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - foreach (PatrollingState state in PatrolStates) - { - state.Update(); - } + foreach (PatrollingState state in PatrolStates) state.Update(); } public override void OnCheckPlayerPosition(PlayerControl pc) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - foreach (PatrollingState state in PatrolStates) - { - state.OnCheckPlayerPosition(pc); - } + foreach (PatrollingState state in PatrolStates) state.OnCheckPlayerPosition(pc); } public override void OnReportDeadBody() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; LateTask.New(() => { foreach (PatrollingState state in PatrolStates) - { if (state.IsPatrolling) - { state.FinishPatrolling(); - } - } }, 0.1f, "SentinelFinishPatrol"); } } diff --git a/Roles/Crewmate/Sentry.cs b/Roles/Crewmate/Sentry.cs index 4d8aeabf6..86fb7c027 100644 --- a/Roles/Crewmate/Sentry.cs +++ b/Roles/Crewmate/Sentry.cs @@ -23,11 +23,11 @@ namespace EHR.Crewmate private static Vector2[] AvailableDevices = []; + private readonly Dictionary LastInfoSend = []; + private readonly HashSet LastNotified = []; private HashSet DeadBodiesInRoom; - - private readonly Dictionary LastInfoSend = []; public PlainShipRoom MonitoredRoom; private PlayerControl SentryPC; @@ -37,31 +37,41 @@ namespace EHR.Crewmate public override void SetupCustomOption() { - int id = 11370; + var id = 11370; Options.SetupRoleOptions(id++, TabGroup.CrewmateRoles, CustomRoles.Sentry); + ShowInfoCooldown = new IntegerOptionItem(++id, "AbilityCooldown", new(1, 60, 1), 15, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Sentry]) .SetValueFormat(OptionFormat.Seconds); + ShowInfoDuration = new IntegerOptionItem(++id, "Sentry.ShowInfoDuration", new(1, 60, 1), 5, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Sentry]) .SetValueFormat(OptionFormat.Seconds); + PlayersKnowAboutCamera = new BooleanOptionItem(++id, "Sentry.PlayersKnowAboutCamera", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Sentry]); + CannotSeeInfoDuringComms = new BooleanOptionItem(++id, "Sentry.CannotSeeInfoDuringComms", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Sentry]); + UsableDevicesForInfoView = new StringOptionItem(++id, "Sentry.UsableDevicesForInfoView", Enum.GetNames(), 0, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Sentry]); + AdditionalDevicesForInfoView = new StringOptionItem(++id, "Sentry.AdditionalDevicesForInfoView", Enum.GetNames(), 0, TabGroup.CrewmateRoles) .SetParent(UsableDevicesForInfoView); + Enum.GetValues().Do(x => { TeamsCanSeeInfo[x] = new BooleanOptionItem(++id, "Sentry.TeamsCanSeeInfo." + x, true, TabGroup.CrewmateRoles) .SetParent(UsableDevicesForInfoView); }); + AbilityUseLimit = new IntegerOptionItem(++id, "AbilityUseLimit", new(0, 20, 1), 0, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Sentry]); + AbilityUseGainWithEachTaskCompleted = new FloatOptionItem(++id, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 1f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Sentry]); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(++id, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Sentry]); } @@ -79,10 +89,12 @@ namespace EHR.Crewmate public override void Init() { On = false; + AvailableDevices = DisableDevice.DevicePos.Where(x => { bool correctMap = x.Key.Contains(Main.CurrentMap.ToString(), StringComparison.OrdinalIgnoreCase); - UsableDevicesStrings devicesOpt = (UsableDevicesStrings)UsableDevicesForInfoView.GetValue(); + var devicesOpt = (UsableDevicesStrings)UsableDevicesForInfoView.GetValue(); + bool enabled = devicesOpt switch { UsableDevicesStrings.None => false, @@ -91,6 +103,7 @@ namespace EHR.Crewmate UsableDevicesStrings.CamerasAndAdmin => x.Key.Contains("Camera") || x.Key.Contains("Admin"), _ => false }; + if (!enabled && devicesOpt != UsableDevicesStrings.None) { enabled |= (AdditionalDevicesStrings)AdditionalDevicesForInfoView.GetValue() switch @@ -125,24 +138,16 @@ namespace EHR.Crewmate Utils.SendRPC(CustomRPC.SyncSentry, pc.PlayerId); } else - { DisplayRoomInfo(pc, false); - } } private void DisplayRoomInfo(PlayerControl pc, bool fromDevice) { - if (CannotSeeInfoDuringComms.GetBool() && Utils.IsActive(SystemTypes.Comms)) - { - return; - } + if (CannotSeeInfoDuringComms.GetBool() && Utils.IsActive(SystemTypes.Comms)) return; if (!fromDevice) { - if (pc.GetAbilityUseLimit() < 1) - { - return; - } + if (pc.GetAbilityUseLimit() < 1) return; pc.RpcRemoveAbilityUse(); } @@ -152,15 +157,9 @@ namespace EHR.Crewmate string bodies = GetColoredNames(DeadBodiesInRoom); string noDataString = Translator.GetString("Sentry.Notify.Info.NoData"); - if (players.Length == 0) - { - players = noDataString; - } + if (players.Length == 0) players = noDataString; - if (bodies.Length == 0) - { - bodies = noDataString; - } + if (bodies.Length == 0) bodies = noDataString; pc.Notify(string.Format(Translator.GetString("Sentry.Notify.Info"), roomName, players, bodies), ShowInfoDuration.GetInt()); return; @@ -183,6 +182,7 @@ namespace EHR.Crewmate bool shapeshifting = shapeshifter.PlayerId != target.PlayerId; PlayerControl ssTarget = shapeshifting ? target : shapeshifter; PlayerControl ss = shapeshifting ? shapeshifter : Utils.GetPlayerById(shapeshifter.shapeshiftTargetPlayerId); + string text = "\n" + string.Format( Translator.GetString("Sentry.Notify.Shapeshifted"), Utils.ColorString(Main.PlayerColors[ss.PlayerId], ss.GetRealName()), @@ -204,20 +204,13 @@ namespace EHR.Crewmate public static void OnAnyoneMurder(PlayerControl target) { foreach (PlayerState state in Main.PlayerStates.Values) - { if (state.Role is Sentry st && st.IsInMonitoredRoom(target)) - { st.DeadBodiesInRoom.Add(target.PlayerId); - } - } } public static void OnAnyoneEnterVent(PlayerControl pc) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; foreach (PlayerState state in Main.PlayerStates.Values) { @@ -243,38 +236,22 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is Sentry s && s.MonitoredRoom != null) - { - return string.Format(Translator.GetString("Sentry.Suffix.Self"), Translator.GetString($"{s.MonitoredRoom.RoomId}")); - } + if (Main.PlayerStates[seer.PlayerId].Role is Sentry s && s.MonitoredRoom != null) return string.Format(Translator.GetString("Sentry.Suffix.Self"), Translator.GetString($"{s.MonitoredRoom.RoomId}")); - if (!PlayersKnowAboutCamera.GetBool()) - { - return string.Empty; - } + if (!PlayersKnowAboutCamera.GetBool()) return string.Empty; foreach (PlayerState state in Main.PlayerStates.Values) - { if (state.Role is Sentry st && st.IsInMonitoredRoom(seer)) - { return string.Format(Translator.GetString("Sentry.Suffix.MonitoredRoom"), CustomRoles.Sentry.ToColoredString()); - } - } return string.Empty; } public override void OnGlobalFixedUpdate(PlayerControl pc, bool lowLoad) { - if (!GameStates.IsInTask || lowLoad) - { - return; - } + if (!GameStates.IsInTask || lowLoad) return; bool nowInMonitoredRoom = IsInMonitoredRoom(pc); bool wasInMonitoredRoom = LastNotified.Contains(pc.PlayerId); @@ -294,25 +271,17 @@ namespace EHR.Crewmate public override void OnCheckPlayerPosition(PlayerControl pc) { - if (MonitoredRoom == null || MonitoredRoom == default || MonitoredRoom == default(PlainShipRoom)) - { - return; - } + if (MonitoredRoom == null || MonitoredRoom == default || MonitoredRoom == default(PlainShipRoom)) return; - if (LastInfoSend.TryGetValue(pc.PlayerId, out long ts) && ts == Utils.TimeStamp) - { - return; - } + if (LastInfoSend.TryGetValue(pc.PlayerId, out long ts) && ts == Utils.TimeStamp) return; LastInfoSend[pc.PlayerId] = Utils.TimeStamp; - if (!CheckTeam(pc)) - { - return; - } + if (!CheckTeam(pc)) return; Vector2 pos = pc.Pos(); float range = DisableDevice.UsableDistance - 1f; + if (!AvailableDevices.Any(x => Vector2.Distance(pos, x) <= range)) { if (UsingDevice.Contains(pc.PlayerId)) @@ -338,6 +307,7 @@ namespace EHR.Crewmate Team.Neutral => pc.IsNeutralKiller() ? SimpleTeam.NK : SimpleTeam.NNK, _ => SimpleTeam.Crewmate }; + return TeamsCanSeeInfo[team].GetBool(); } diff --git a/Roles/Crewmate/Sheriff.cs b/Roles/Crewmate/Sheriff.cs index 3d652f718..0b234ac8e 100644 --- a/Roles/Crewmate/Sheriff.cs +++ b/Roles/Crewmate/Sheriff.cs @@ -140,12 +140,10 @@ namespace EHR.Crewmate { CustomRoles cRole = player.GetCustomRole(); List subRole = player.GetCustomSubRoles(); - if (subRole.Contains(CustomRoles.Rascal)) - { - return true; - } + if (subRole.Contains(CustomRoles.Rascal)) return true; + + var CanKill = false; - bool CanKill = false; foreach (CustomRoles SubRoleTarget in subRole) { CanKill = SubRoleTarget switch diff --git a/Roles/Crewmate/Shiftguard.cs b/Roles/Crewmate/Shiftguard.cs index 88dfd8d81..77075d703 100644 --- a/Roles/Crewmate/Shiftguard.cs +++ b/Roles/Crewmate/Shiftguard.cs @@ -9,12 +9,8 @@ Options.SetupRoleOptions(5594, TabGroup.CrewmateRoles, CustomRoles.Shiftguard); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Crewmate/Snitch.cs b/Roles/Crewmate/Snitch.cs index b78fdfa92..39d81304f 100644 --- a/Roles/Crewmate/Snitch.cs +++ b/Roles/Crewmate/Snitch.cs @@ -76,10 +76,7 @@ namespace EHR.Crewmate private static bool GetExpose(PlayerControl pc) { - if (!IsThisRole(pc.PlayerId) || !pc.IsAlive() || pc.Is(CustomRoles.Madmate)) - { - return false; - } + if (!IsThisRole(pc.PlayerId) || !pc.IsAlive() || pc.Is(CustomRoles.Madmate)) return false; byte snitchId = pc.PlayerId; return IsExposed[snitchId]; @@ -92,10 +89,7 @@ namespace EHR.Crewmate public static void CheckTask(PlayerControl snitch) { - if (!snitch.IsAlive() || snitch.Is(CustomRoles.Madmate)) - { - return; - } + if (!snitch.IsAlive() || snitch.Is(CustomRoles.Madmate)) return; byte snitchId = snitch.PlayerId; TaskState snitchTask = snitch.GetTaskState(); @@ -104,10 +98,7 @@ namespace EHR.Crewmate { foreach (PlayerControl target in Main.AllAlivePlayerControls) { - if (!IsSnitchTarget(target)) - { - continue; - } + if (!IsSnitchTarget(target)) continue; TargetArrow.Add(target.PlayerId, snitchId); } @@ -115,35 +106,22 @@ namespace EHR.Crewmate IsExposed[snitchId] = true; } - if (IsComplete[snitchId] || !snitchTask.IsTaskFinished) - { - return; - } + if (IsComplete[snitchId] || !snitchTask.IsTaskFinished) return; foreach (PlayerControl target in Main.AllAlivePlayerControls) { - if (!IsSnitchTarget(target)) - { - continue; - } + if (!IsSnitchTarget(target)) continue; byte targetId = target.PlayerId; NameColorManager.Add(snitchId, targetId); - if (!EnableTargetArrow) - { - continue; - } + if (!EnableTargetArrow) continue; TargetArrow.Add(snitchId, targetId); if (TargetList.Add(targetId)) - { if (CanGetColoredArrow) - { TargetColorlist.Add(targetId, target.GetRoleColor()); - } - } } snitch.Notify(Translator.GetString("SnitchDoneTasks")); @@ -158,54 +136,34 @@ namespace EHR.Crewmate public static string GetWarningArrow(PlayerControl seer, PlayerControl target = null) { - if (GameStates.IsMeeting || !IsSnitchTarget(seer)) - { - return string.Empty; - } + if (GameStates.IsMeeting || !IsSnitchTarget(seer)) return string.Empty; - if (target != null && seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (target != null && seer.PlayerId != target.PlayerId) return string.Empty; IEnumerable exposedSnitch = PlayerIdList.Where(s => !Main.PlayerStates[s].IsDead && IsExposed[s]); byte[] snitch = exposedSnitch as byte[] ?? exposedSnitch.ToArray(); - if (snitch.Length == 0) - { - return string.Empty; - } + if (snitch.Length == 0) return string.Empty; + + var warning = $"\n{Translator.GetString("Snitch")} "; - string warning = $"\n{Translator.GetString("Snitch")} "; if (EnableTargetArrow) - { warning += TargetArrow.GetArrows(seer, snitch); - } else - { warning += "⚠"; - } return Utils.ColorString(RoleColor, warning); } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.Is(CustomRoles.Madmate)) - { - return string.Empty; - } + if (seer.Is(CustomRoles.Madmate)) return string.Empty; - if (!EnableTargetArrow || GameStates.IsMeeting || seer.PlayerId != SnitchId) - { - return string.Empty; - } + if (!EnableTargetArrow || GameStates.IsMeeting || seer.PlayerId != SnitchId) return string.Empty; - if (target != null && seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (target != null && seer.PlayerId != target.PlayerId) return string.Empty; + + var arrows = string.Empty; - string arrows = string.Empty; foreach (byte targetId in TargetList) { string arrow = TargetArrow.GetArrows(seer, targetId); @@ -217,10 +175,7 @@ namespace EHR.Crewmate public static void OnCompleteTask(PlayerControl player) { - if (!IsThisRole(player.PlayerId) || player.Is(CustomRoles.Madmate)) - { - return; - } + if (!IsThisRole(player.PlayerId) || player.Is(CustomRoles.Madmate)) return; CheckTask(player); } diff --git a/Roles/Crewmate/Socialite.cs b/Roles/Crewmate/Socialite.cs index e4142890c..c399c2558 100644 --- a/Roles/Crewmate/Socialite.cs +++ b/Roles/Crewmate/Socialite.cs @@ -21,11 +21,13 @@ namespace EHR.Crewmate public override void SetupCustomOption() { - int id = 647300; + var id = 647300; Options.SetupRoleOptions(id++, TabGroup.CrewmateRoles, CustomRoles.Socialite); + Cooldown = new FloatOptionItem(++id, "AbilityCooldown", new(0f, 60f, 1f), 15f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Socialite]) .SetValueFormat(OptionFormat.Seconds); + UsePet = Options.CreatePetUseSetting(++id, CustomRoles.Socialite); CancelVote = Options.CreateVoteCancellingUseSetting(++id, CustomRoles.Socialite, TabGroup.CrewmateRoles); } @@ -62,10 +64,7 @@ namespace EHR.Crewmate public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!base.OnCheckMurder(killer, target) || MarkedPlayerId != byte.MaxValue) - { - return false; - } + if (!base.OnCheckMurder(killer, target) || MarkedPlayerId != byte.MaxValue) return false; MarkedPlayerId = target.PlayerId; Utils.SendRPC(CustomRPC.SyncRoleData, SocialiteId, 1, MarkedPlayerId); @@ -96,10 +95,7 @@ namespace EHR.Crewmate public override bool OnVote(PlayerControl pc, PlayerControl target) { - if (pc == null || target == null || pc.PlayerId == target.PlayerId || Main.DontCancelVoteList.Contains(pc.PlayerId)) - { - return false; - } + if (pc == null || target == null || pc.PlayerId == target.PlayerId || Main.DontCancelVoteList.Contains(pc.PlayerId)) return false; if (GuestList.Add(target.PlayerId)) { @@ -126,10 +122,7 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != SocialiteId || seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud)) - { - return string.Empty; - } + if (seer.PlayerId != SocialiteId || seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud)) return string.Empty; return string.Format(Translator.GetString("Socialite.Suffix"), MarkedPlayerId.ColoredPlayerName()); } diff --git a/Roles/Crewmate/Soothsayer.cs b/Roles/Crewmate/Soothsayer.cs index 49b9c3305..8f31bc346 100644 --- a/Roles/Crewmate/Soothsayer.cs +++ b/Roles/Crewmate/Soothsayer.cs @@ -37,15 +37,9 @@ namespace EHR.Crewmate public override bool OnVote(PlayerControl player, PlayerControl target) { - if (player == null || target == null || player.PlayerId == target.PlayerId) - { - return false; - } + if (player == null || target == null || player.PlayerId == target.PlayerId) return false; - if (Target != byte.MaxValue || Main.DontCancelVoteList.Contains(player.PlayerId)) - { - return false; - } + if (Target != byte.MaxValue || Main.DontCancelVoteList.Contains(player.PlayerId)) return false; Target = target.PlayerId; diff --git a/Roles/Crewmate/SpeedBooster.cs b/Roles/Crewmate/SpeedBooster.cs index b2e21bc6e..f8ddef260 100644 --- a/Roles/Crewmate/SpeedBooster.cs +++ b/Roles/Crewmate/SpeedBooster.cs @@ -26,9 +26,11 @@ { PlayerControl target = Main.AllAlivePlayerControls.RandomElement(); Main.AllPlayerSpeed[target.PlayerId] += 0.5f; + target.Notify(Main.AllPlayerSpeed[target.PlayerId] > 3 ? Translator.GetString("SpeedBoosterSpeedLimit") : string.Format(Translator.GetString("SpeedBoosterTaskDone"), Main.AllPlayerSpeed[player.PlayerId].ToString("0.0#####"))); + target.MarkDirtySettings(); } } diff --git a/Roles/Crewmate/Speedrunner.cs b/Roles/Crewmate/Speedrunner.cs index 807b19cdf..0c5968d4d 100644 --- a/Roles/Crewmate/Speedrunner.cs +++ b/Roles/Crewmate/Speedrunner.cs @@ -30,13 +30,17 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupSingleRoleOptions(9170, TabGroup.CrewmateRoles, CustomRoles.Speedrunner, zeroOne: true); + SpeedrunnerNotifyKillers = new BooleanOptionItem(9178, "SpeedrunnerNotifyKillers", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Speedrunner]); + SpeedrunnerNotifyAtXTasksLeft = new IntegerOptionItem(9179, "SpeedrunnerNotifyAtXTasksLeft", new(0, 90, 1), 3, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Speedrunner]); + SpeedrunnerSpeed = new FloatOptionItem(9177, "SpeedrunnerSpeed", new(0.1f, 3f, 0.1f), 1.5f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Speedrunner]) .SetValueFormat(OptionFormat.Multiplier); + OverrideTasksData.Create(9180, TabGroup.CrewmateRoles, CustomRoles.Speedrunner); } @@ -47,24 +51,20 @@ namespace EHR.Crewmate public override void OnTaskComplete(PlayerControl player, int CompletedTasksCount, int AllTasksCount) { - if (!player.IsAlive()) - { - return; - } + if (!player.IsAlive()) return; int completedTasks = CompletedTasksCount + 1; + if (completedTasks >= AllTasksCount) { Logger.Info("Speedrunner finished tasks", "Speedrunner"); player.RPCPlayCustomSound("Congrats"); GameData.Instance.CompletedTasks = GameData.Instance.TotalTasks; Logger.Info($"TotalTaskCounts = {GameData.Instance.CompletedTasks}/{GameData.Instance.TotalTasks}", "TaskState.Update"); + LateTask.New(() => { - if (!GameStates.IsEnded) - { - CustomWinnerHolder.ResetAndSetWinner(CustomWinner.Crewmate); - } + if (!GameStates.IsEnded) CustomWinnerHolder.ResetAndSetWinner(CustomWinner.Crewmate); }, 1f, log: false); } else if (completedTasks >= SpeedrunnerNotifyAtXTasksLeft.GetInt() && SpeedrunnerNotifyKillers.GetBool()) @@ -72,28 +72,18 @@ namespace EHR.Crewmate LateTask.New(() => { foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { if (!pc.Is(Team.Crewmate)) - { Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - } - } }, 0.1f, log: false); } } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.Is(Team.Crewmate) || meeting || SpeedrunnerPC == null) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.Is(Team.Crewmate) || meeting || SpeedrunnerPC == null) return string.Empty; TaskState ts = SpeedrunnerPC.GetTaskState(); - if (ts.CompletedTasksCount < SpeedrunnerNotifyAtXTasksLeft.GetInt() || !SpeedrunnerNotifyKillers.GetBool()) - { - return string.Empty; - } + if (ts.CompletedTasksCount < SpeedrunnerNotifyAtXTasksLeft.GetInt() || !SpeedrunnerNotifyKillers.GetBool()) return string.Empty; string speedrunnerName = SpeedrunnerPC.PlayerId.ColoredPlayerName(); string notifyString = Translator.GetString("SpeedrunnerHasXTasksLeft"); diff --git a/Roles/Crewmate/Spiritualist.cs b/Roles/Crewmate/Spiritualist.cs index 5e576ee85..ee5a9dd6b 100644 --- a/Roles/Crewmate/Spiritualist.cs +++ b/Roles/Crewmate/Spiritualist.cs @@ -41,9 +41,11 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Spiritualist); + ShowGhostArrowEverySeconds = new FloatOptionItem(Id + 10, "SpiritualistShowGhostArrowEverySeconds", new(1f, 60f, 1f), 15f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spiritualist]) .SetValueFormat(OptionFormat.Seconds); + ShowGhostArrowForSeconds = new FloatOptionItem(Id + 11, "SpiritualistShowGhostArrowForSeconds", new(1f, 60f, 1f), 2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spiritualist]) .SetValueFormat(OptionFormat.Seconds); @@ -68,15 +70,9 @@ namespace EHR.Crewmate public static void OnReportDeadBody(NetworkedPlayerInfo target) { - if (target == null) - { - return; - } + if (target == null) return; - if (SpiritualistTarget != byte.MaxValue) - { - RemoveTarget(); - } + if (SpiritualistTarget != byte.MaxValue) RemoveTarget(); SpiritualistTarget = target.PlayerId; } @@ -86,37 +82,35 @@ namespace EHR.Crewmate foreach (byte spiritualist in PlayerIdList) { PlayerControl player = Main.AllPlayerControls.FirstOrDefault(a => a.PlayerId == spiritualist); - if (!player.IsAlive()) - { - continue; - } + if (!player.IsAlive()) continue; LastGhostArrowShowTime = 0; ShowGhostArrowUntil = 0; PlayerControl target = Main.AllPlayerControls.FirstOrDefault(a => a.PlayerId == SpiritualistTarget); - if (target == null) - { - continue; - } + if (target == null) continue; target.Notify(GetString("SpiritualistTargetMessage")); TargetArrow.Add(spiritualist, target.PlayerId); - CustomRpcSender writer = CustomRpcSender.Create("SpiritualistSendMessage"); + var writer = CustomRpcSender.Create("SpiritualistSendMessage"); writer.StartMessage(target.GetClientId()); + writer.StartRpc(target.NetId, (byte)RpcCalls.SetName) .Write(target.Data.NetId) .Write(GetString("SpiritualistNoticeTitle")) .EndRpc(); + writer.StartRpc(target.NetId, (byte)RpcCalls.SendChat) .Write(GetString("SpiritualistNoticeMessage")) .EndRpc(); + writer.StartRpc(target.NetId, (byte)RpcCalls.SetName) .Write(target.Data.NetId) .Write(target.Data.PlayerName) .EndRpc(); + writer.EndMessage(); writer.SendMessage(); } @@ -124,30 +118,18 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (!seer.IsAlive() || seer.PlayerId != SpiritualistId) - { - return string.Empty; - } + if (!seer.IsAlive() || seer.PlayerId != SpiritualistId) return string.Empty; - if (target != null && seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (target != null && seer.PlayerId != target.PlayerId) return string.Empty; - if (GameStates.IsMeeting) - { - return string.Empty; - } + if (GameStates.IsMeeting) return string.Empty; return SpiritualistTarget != byte.MaxValue && ShowArrow ? Utils.ColorString(seer.GetRoleColor(), TargetArrow.GetArrows(seer, SpiritualistTarget)) : string.Empty; } public static void RemoveTarget() { - foreach (byte spiritualist in PlayerIdList) - { - TargetArrow.Remove(spiritualist, SpiritualistTarget); - } + foreach (byte spiritualist in PlayerIdList) TargetArrow.Remove(spiritualist, SpiritualistTarget); SpiritualistTarget = byte.MaxValue; } diff --git a/Roles/Crewmate/Spy.cs b/Roles/Crewmate/Spy.cs index 684268fe1..53584336c 100644 --- a/Roles/Crewmate/Spy.cs +++ b/Roles/Crewmate/Spy.cs @@ -25,15 +25,19 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Spy); + UseLimitOpt = new IntegerOptionItem(Id + 10, "AbilityUseLimit", new(0, 20, 1), 1, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spy]) .SetValueFormat(OptionFormat.Times); + SpyRedNameDur = new FloatOptionItem(Id + 11, "SpyRedNameDur", new(0f, 70f, 1f), 3f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spy]) .SetValueFormat(OptionFormat.Seconds); + SpyAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 12, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.5f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spy]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 13, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spy]) .SetValueFormat(OptionFormat.Times); @@ -54,13 +58,11 @@ namespace EHR.Crewmate private static void SendRPC(int operate, byte id = byte.MaxValue, bool changeColor = false) { - if (!DoRPC) - { - return; - } + if (!DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncSpy, SendOption.Reliable); writer.Write(operate); + switch (operate) { case 1: // Red Name Add @@ -79,15 +81,13 @@ namespace EHR.Crewmate public static void ReceiveRPC(MessageReader reader) { int operate = reader.ReadInt32(); + switch (operate) { case 1: byte susId = reader.ReadByte(); string stimeStamp = reader.ReadString(); - if (long.TryParse(stimeStamp, out long timeStamp)) - { - SpyRedNameList[susId] = timeStamp; - } + if (long.TryParse(stimeStamp, out long timeStamp)) SpyRedNameList[susId] = timeStamp; return; case 3: @@ -99,10 +99,7 @@ namespace EHR.Crewmate public static bool OnKillAttempt(PlayerControl killer, PlayerControl target) // Special handling for Spy ---- remains as a static method { - if (killer == null || target == null || !target.Is(CustomRoles.Spy) || killer.PlayerId == target.PlayerId || target.GetAbilityUseLimit() < 1) - { - return true; - } + if (killer == null || target == null || !target.Is(CustomRoles.Spy) || killer.PlayerId == target.PlayerId || target.GetAbilityUseLimit() < 1) return true; target.RpcRemoveAbilityUse(); SpyRedNameList.TryAdd(killer.PlayerId, TimeStamp); @@ -114,16 +111,10 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (pc == null || !pc.Is(CustomRoles.Spy) || SpyRedNameList.Count == 0) - { - return; - } + if (pc == null || !pc.Is(CustomRoles.Spy) || SpyRedNameList.Count == 0) return; long now = TimeStamp; - if (now == LastUpdate) - { - return; - } + if (now == LastUpdate) return; LastUpdate = now; diff --git a/Roles/Crewmate/SuperStar.cs b/Roles/Crewmate/SuperStar.cs index d527b4001..d1e110e26 100644 --- a/Roles/Crewmate/SuperStar.cs +++ b/Roles/Crewmate/SuperStar.cs @@ -10,6 +10,7 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(6000, TabGroup.CrewmateRoles, CustomRoles.SuperStar); + Options.EveryOneKnowSuperStar = new BooleanOptionItem(6010, "EveryOneKnowSuperStar", true, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SuperStar]); } diff --git a/Roles/Crewmate/SwordsMan.cs b/Roles/Crewmate/SwordsMan.cs index 9e87a28f2..5b62946ca 100644 --- a/Roles/Crewmate/SwordsMan.cs +++ b/Roles/Crewmate/SwordsMan.cs @@ -20,11 +20,14 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.SwordsMan); + CanVent = new BooleanOptionItem(Id + 11, "CanVent", false, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SwordsMan]); + KCD = new FloatOptionItem(Id + 9, "KillCooldown", new(0f, 120f, 0.5f), 15f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SwordsMan]) .SetValueFormat(OptionFormat.Seconds); + UsePet = Options.CreatePetUseSetting(Id + 10, CustomRoles.SwordsMan); } @@ -72,10 +75,7 @@ namespace EHR.Crewmate public static void SendRPC(byte playerId) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SwordsManKill, SendOption.Reliable); writer.Write(playerId); @@ -85,10 +85,7 @@ namespace EHR.Crewmate public static void ReceiveRPC(MessageReader reader) { byte SwordsManId = reader.ReadByte(); - if (!Killed.Contains(SwordsManId)) - { - Killed.Add(SwordsManId); - } + if (!Killed.Contains(SwordsManId)) Killed.Add(SwordsManId); } public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) diff --git a/Roles/Crewmate/TaskManager.cs b/Roles/Crewmate/TaskManager.cs index 8d3074f74..8b3e6070f 100644 --- a/Roles/Crewmate/TaskManager.cs +++ b/Roles/Crewmate/TaskManager.cs @@ -24,7 +24,7 @@ namespace EHR.Crewmate public override string GetProgressText(byte playerId, bool comms) { - StringBuilder ProgressText = new StringBuilder(); + var ProgressText = new StringBuilder(); ProgressText.Append(Utils.GetTaskCount(playerId, comms)); diff --git a/Roles/Crewmate/Telekinetic.cs b/Roles/Crewmate/Telekinetic.cs index 556f634f0..2d5443a6e 100644 --- a/Roles/Crewmate/Telekinetic.cs +++ b/Roles/Crewmate/Telekinetic.cs @@ -30,15 +30,19 @@ namespace EHR.Crewmate const CustomRoles role = CustomRoles.Telekinetic; Options.SetupRoleOptions(id, tab, role); + FreezeDuration = new IntegerOptionItem(id + 2, "Telekinetic.FreezeDuration", new(0, 60, 1), 10, tab) .SetParent(Options.CustomRoleSpawnChances[role]) .SetValueFormat(OptionFormat.Seconds); + ShieldDuration = new IntegerOptionItem(id + 3, "Telekinetic.ShieldDuration", new(0, 60, 1), 20, tab) .SetParent(Options.CustomRoleSpawnChances[role]) .SetValueFormat(OptionFormat.Seconds); + SpeedDuration = new IntegerOptionItem(id + 4, "Telekinetic.SpeedDuration", new(0, 60, 1), 15, tab) .SetParent(Options.CustomRoleSpawnChances[role]) .SetValueFormat(OptionFormat.Seconds); + IncreasedSpeed = new FloatOptionItem(id + 5, "Telekinetic.IncreasedSpeed", new(0.05f, 5f, 0.05f), 2f, tab) .SetParent(Options.CustomRoleSpawnChances[role]) .SetValueFormat(OptionFormat.Multiplier); @@ -65,16 +69,10 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance || Main.HasJustStarted) - { - return; - } + if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance || Main.HasJustStarted) return; long now = Utils.TimeStamp; - if (now == LastUpdate) - { - return; - } + if (now == LastUpdate) return; LastUpdate = now; @@ -118,11 +116,13 @@ namespace EHR.Crewmate float speed = Main.AllPlayerSpeed[target.PlayerId]; Main.AllPlayerSpeed[target.PlayerId] = Main.MinSpeed; target.MarkDirtySettings(); + LateTask.New(() => { Main.AllPlayerSpeed[target.PlayerId] = speed; target.MarkDirtySettings(); }, FreezeDuration.GetFloat(), "Telekinetic.Freeze"); + Timer += 35; break; case Mode.Kill when hasTarget: @@ -140,11 +140,13 @@ namespace EHR.Crewmate float selfSpeed = Main.AllPlayerSpeed[pc.PlayerId]; Main.AllPlayerSpeed[pc.PlayerId] = IncreasedSpeed.GetFloat(); pc.MarkDirtySettings(); + LateTask.New(() => { Main.AllPlayerSpeed[pc.PlayerId] = selfSpeed; pc.MarkDirtySettings(); }, SpeedDuration.GetFloat(), "Telekinetic.Speed"); + Timer += 30; break; case Mode.Doors: @@ -162,6 +164,7 @@ namespace EHR.Crewmate float speed = Main.AllPlayerSpeed[pc.PlayerId]; Main.AllPlayerSpeed[pc.PlayerId] = Main.MinSpeed; pc.MarkDirtySettings(); + LateTask.New(() => { Main.AllPlayerSpeed[pc.PlayerId] = speed; @@ -194,10 +197,7 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != TelekineticPC.PlayerId || (seer.IsModClient() && !hud) || meeting) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != TelekineticPC.PlayerId || (seer.IsModClient() && !hud) || meeting) return string.Empty; return string.Format(Translator.GetString("Telekinetic.Suffix"), Translator.GetString($"Telekinetic.Mode.{CurrentMode}")); } diff --git a/Roles/Crewmate/Tether.cs b/Roles/Crewmate/Tether.cs index f10ec1e05..c08a600e3 100644 --- a/Roles/Crewmate/Tether.cs +++ b/Roles/Crewmate/Tether.cs @@ -27,16 +27,21 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Tether); + VentCooldown = new FloatOptionItem(Id + 10, "VentCooldown", new(0f, 70f, 1f), 15f, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Tether]) .SetValueFormat(OptionFormat.Seconds); + UseLimitOpt = new IntegerOptionItem(Id + 11, "AbilityUseLimit", new(0, 20, 1), 1, TabGroup.CrewmateRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Tether]) .SetValueFormat(OptionFormat.Times); + TetherAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(Id + 12, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.4f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Tether]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 14, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Tether]) .SetValueFormat(OptionFormat.Times); + CancelVote = CreateVoteCancellingUseSetting(Id + 13, CustomRoles.Tether, TabGroup.CrewmateRoles); } @@ -57,10 +62,7 @@ namespace EHR.Crewmate private void SendRPCSyncTarget() { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetTetherTarget, SendOption.Reliable); writer.Write(TetherId); @@ -71,10 +73,7 @@ namespace EHR.Crewmate public static void ReceiveRPCSyncTarget(MessageReader reader) { byte id = reader.ReadByte(); - if (Main.PlayerStates[id].Role is not Tether th) - { - return; - } + if (Main.PlayerStates[id].Role is not Tether th) return; th.Target = reader.ReadByte(); } @@ -91,33 +90,21 @@ namespace EHR.Crewmate private void Teleport(PlayerControl pc, int ventId, bool isPet = false) { - if (pc == null) - { - return; - } + if (pc == null) return; if (Target != byte.MaxValue) { LateTask.New(() => { - if (GameStates.IsInTask) - { - pc.TP(Utils.GetPlayerById(Target).Pos()); - } + if (GameStates.IsInTask) pc.TP(Utils.GetPlayerById(Target).Pos()); }, isPet ? 0.1f : 2f, "Tether TP"); } - else if (!isPet) - { - LateTask.New(() => { pc.MyPhysics?.RpcBootFromVent(ventId); }, 0.5f, "Tether No Target Boot From Vent"); - } + else if (!isPet) LateTask.New(() => { pc.MyPhysics?.RpcBootFromVent(ventId); }, 0.5f, "Tether No Target Boot From Vent"); } public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = VentCooldown.GetFloat(); AURoleOptions.EngineerInVentMaxTime = 1f; @@ -125,10 +112,7 @@ namespace EHR.Crewmate public override bool OnVote(PlayerControl pc, PlayerControl target) { - if (pc == null || target == null || pc.PlayerId == target.PlayerId || Main.DontCancelVoteList.Contains(pc.PlayerId)) - { - return false; - } + if (pc == null || target == null || pc.PlayerId == target.PlayerId || Main.DontCancelVoteList.Contains(pc.PlayerId)) return false; if (pc.GetAbilityUseLimit() >= 1) { @@ -150,7 +134,7 @@ namespace EHR.Crewmate public override string GetProgressText(byte playerId, bool comms) { - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.Append(Utils.GetAbilityUseLimitDisplay(playerId, Target != byte.MaxValue)); sb.Append(Utils.GetTaskCount(playerId, comms)); diff --git a/Roles/Crewmate/TimeManager.cs b/Roles/Crewmate/TimeManager.cs index 4e2f90e76..ea099ebc8 100644 --- a/Roles/Crewmate/TimeManager.cs +++ b/Roles/Crewmate/TimeManager.cs @@ -15,15 +15,19 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.TimeManager); + IncreaseMeetingTime = new IntegerOptionItem(Id + 10, "TimeManagerIncreaseMeetingTime", new(1, 30, 1), 5, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.TimeManager]) .SetValueFormat(OptionFormat.Seconds); + MeetingTimeLimit = new IntegerOptionItem(Id + 11, "TimeManagerLimitMeetingTime", new(100, 500, 10), 150, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.TimeManager]) .SetValueFormat(OptionFormat.Seconds); + MadMinMeetingTimeLimit = new IntegerOptionItem(Id + 12, "MadTimeManagerLimitMeetingTime", new(5, 150, 5), 50, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.TimeManager]) .SetValueFormat(OptionFormat.Seconds); + Options.OverrideTasksData.Create(Id + 13, TabGroup.CrewmateRoles, CustomRoles.TimeManager); } @@ -45,17 +49,14 @@ namespace EHR.Crewmate public static int TotalIncreasedMeetingTime() { - int sec = 0; + var sec = 0; + foreach (byte playerId in PlayerIdList.ToArray()) { if (Utils.GetPlayerById(playerId).Is(CustomRoles.Madmate)) - { sec -= AdditionalTime(playerId); - } else - { sec += AdditionalTime(playerId); - } } Logger.Info($"{sec}second", "TimeManager.TotalIncreasedMeetingTime"); diff --git a/Roles/Crewmate/TimeMaster.cs b/Roles/Crewmate/TimeMaster.cs index a5e299163..c7440a5c7 100644 --- a/Roles/Crewmate/TimeMaster.cs +++ b/Roles/Crewmate/TimeMaster.cs @@ -15,18 +15,23 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(8950, TabGroup.CrewmateRoles, CustomRoles.TimeMaster); + TimeMasterSkillCooldown = new FloatOptionItem(8960, "TimeMasterSkillCooldown", new(0f, 180f, 1f), 20f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.TimeMaster]) .SetValueFormat(OptionFormat.Seconds); + TimeMasterSkillDuration = new FloatOptionItem(8961, "TimeMasterSkillDuration", new(0f, 180f, 1f), 15f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.TimeMaster]) .SetValueFormat(OptionFormat.Seconds); + TimeMasterMaxUses = new IntegerOptionItem(8962, "TimeMasterMaxUses", new(0, 180, 1), 1, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.TimeMaster]) .SetValueFormat(OptionFormat.Times); + TimeMasterAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(8963, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.4f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.TimeMaster]) .SetValueFormat(OptionFormat.Times); + TimeMasterAbilityChargesWhenFinishedTasks = new FloatOptionItem(8964, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.TimeMaster]) .SetValueFormat(OptionFormat.Times); @@ -45,10 +50,7 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = TimeMasterSkillCooldown.GetFloat(); AURoleOptions.EngineerInVentMaxTime = 1f; @@ -56,7 +58,7 @@ namespace EHR.Crewmate public override string GetProgressText(byte playerId, bool comms) { - StringBuilder ProgressText = new StringBuilder(); + var ProgressText = new StringBuilder(); ProgressText.Append(Utils.GetAbilityUseLimitDisplay(playerId, TimeMasterInProtect.ContainsKey(playerId))); ProgressText.Append(Utils.GetTaskCount(playerId, comms)); @@ -67,13 +69,9 @@ namespace EHR.Crewmate public override void SetButtonTexts(HudManager hud, byte id) { if (UsePets.GetBool()) - { hud.PetButton.buttonLabelText.text = Translator.GetString("TimeMasterVentButtonText"); - } else - { hud.AbilityButton.buttonLabelText.text = Translator.GetString("TimeMasterVentButtonText"); - } } public override void OnPet(PlayerControl pc) @@ -89,10 +87,7 @@ namespace EHR.Crewmate private static void Rewind(PlayerControl pc) { - if (TimeMasterInProtect.ContainsKey(pc.PlayerId)) - { - return; - } + if (TimeMasterInProtect.ContainsKey(pc.PlayerId)) return; if (pc.GetAbilityUseLimit() >= 1) { @@ -100,31 +95,23 @@ namespace EHR.Crewmate TimeMasterInProtect.Remove(pc.PlayerId); TimeMasterInProtect.Add(pc.PlayerId, Utils.TimeStamp); pc.Notify(Translator.GetString("TimeMasterOnGuard"), TimeMasterSkillDuration.GetFloat()); + foreach (PlayerControl player in Main.AllPlayerControls) { if (TimeMasterBackTrack.TryGetValue(player.PlayerId, out Vector2 position)) { if (!pc.inVent && !pc.inMovingPlat && pc.IsAlive() && !pc.onLadder && pc.MyPhysics != null && !pc.MyPhysics.Animations.IsPlayingAnyLadderAnimation() && !pc.MyPhysics.Animations.IsPlayingEnterVentAnimation() && player.PlayerId != pc.PlayerId) - { player.TP(position); - } - else if (pc.PlayerId == player.PlayerId) - { - player.MyPhysics?.RpcBootFromVent(Main.LastEnteredVent.TryGetValue(player.PlayerId, out Vent vent) ? vent.Id : player.PlayerId); - } + else if (pc.PlayerId == player.PlayerId) player.MyPhysics?.RpcBootFromVent(Main.LastEnteredVent.TryGetValue(player.PlayerId, out Vent vent) ? vent.Id : player.PlayerId); TimeMasterBackTrack.Remove(player.PlayerId); } else - { TimeMasterBackTrack.Add(player.PlayerId, player.Pos()); - } } } else - { pc.Notify(Translator.GetString("OutOfAbilityUsesDoMoreTasks")); - } } public override bool OnCheckMurderAsTarget(PlayerControl killer, PlayerControl target) @@ -132,12 +119,8 @@ namespace EHR.Crewmate if (killer.PlayerId != target.PlayerId && TimeMasterInProtect.TryGetValue(target.PlayerId, out long ts) && ts + TimeMasterSkillDuration.GetInt() >= Utils.TimeStamp) { foreach (PlayerControl player in Main.AllPlayerControls) - { if (!killer.Is(CustomRoles.Pestilence) && TimeMasterBackTrack.TryGetValue(player.PlayerId, out Vector2 pos)) - { player.TP(pos); - } - } killer.SetKillCooldown(target: target); return false; @@ -149,6 +132,7 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl player) { byte playerId = player.PlayerId; + if (TimeMasterInProtect.TryGetValue(playerId, out long ttime) && ttime + TimeMasterSkillDuration.GetInt() < Utils.TimeStamp) { TimeMasterInProtect.Remove(playerId); diff --git a/Roles/Crewmate/ToiletMaster.cs b/Roles/Crewmate/ToiletMaster.cs index f304116c2..042b4563c 100644 --- a/Roles/Crewmate/ToiletMaster.cs +++ b/Roles/Crewmate/ToiletMaster.cs @@ -39,48 +39,63 @@ namespace EHR.Crewmate public override void SetupCustomOption() { - int id = 644700; + var id = 644700; const TabGroup tab = TabGroup.CrewmateRoles; Poop[] poops = Enum.GetValues(); Dictionary replacements = poops.ToDictionary(x => x.ToString(), x => Utils.ColorString(GetPoopColor(x), x.ToString())); SetupRoleOptions(id++, tab, CustomRoles.ToiletMaster); + AbilityCooldown = new IntegerOptionItem(++id, "AbilityCooldown", new(0, 60, 1), 5, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]) .SetValueFormat(OptionFormat.Seconds); + AbilityUses = new IntegerOptionItem(++id, "AbilityUseLimit", new(0, 10, 1), 3, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]); + ToiletDuration = new IntegerOptionItem(++id, "TM.ToiletDuration", new(0, 60, 1), 10, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]) .SetValueFormat(OptionFormat.Seconds); + ToiletVisibility = new StringOptionItem(++id, "TM.ToiletVisibility", Enum.GetNames(), 0, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]); + ToiletUseRadius = new FloatOptionItem(++id, "TM.ToiletUseRadius", new(0f, 5f, 0.25f), 1f, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]) .SetValueFormat(OptionFormat.Multiplier); + ToiletUseTime = new IntegerOptionItem(++id, "TM.ToiletUseTime", new(0, 60, 1), 5, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]) .SetValueFormat(OptionFormat.Seconds); + ToiletMaxUses = new IntegerOptionItem(++id, "TM.ToiletMaxUses", new(0, 10, 1), 3, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]); + BrownPoopSpeedBoost = new FloatOptionItem(++id, "TM.BrownPoopSpeedBoost", new(0f, 3f, 0.05f), 0.5f, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]) .SetValueFormat(OptionFormat.Multiplier); + GreenPoopRadius = new FloatOptionItem(++id, "TM.GreenPoopRadius", new(0f, 5f, 0.25f), 1f, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]) .SetValueFormat(OptionFormat.Multiplier); + RedPoopRadius = new FloatOptionItem(++id, "TM.RedPoopRadius", new(0f, 5f, 0.25f), 1f, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]) .SetValueFormat(OptionFormat.Multiplier); + RedPoopRoleBlockDuration = new IntegerOptionItem(++id, "TM.RedPoopRoleBlockDuration", new(0, 60, 1), 10, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]) .SetValueFormat(OptionFormat.Seconds); + PurplePoopNotifyOnKillAttempt = new BooleanOptionItem(++id, "TM.PurplePoopNotifyOnKillAttempt", false, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]); + AbilityUseGainWithEachTaskCompleted = new FloatOptionItem(++id, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.6f, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(++id, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.1f, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ToiletMaster]); + poops.Do(x => { PoopDurationSettings[x] = new IntegerOptionItem(++id, $"TM.{x}PoopDuration", new(0, 60, 1), 10, tab) @@ -113,32 +128,29 @@ namespace EHR.Crewmate public override void OnPet(PlayerControl pc) { Vector2 pos = pc.Pos(); + IEnumerable hideList = ToiletVisible switch { ToiletVisibilityOptions.Instant => [], _ => Main.AllPlayerControls.Without(pc) }; + Toilets[pos] = (new(pos, hideList), 0, Utils.TimeStamp); pc.RpcRemoveAbilityUse(); - if (ToiletVisible == ToiletVisibilityOptions.Delayed) - { - LateTask.New(() => Toilets[pos] = (new(pos, []), Toilets[pos].Uses, Toilets[pos].PlaceTimeStamp), 5f, log: false); - } + if (ToiletVisible == ToiletVisibilityOptions.Delayed) LateTask.New(() => Toilets[pos] = (new(pos, []), Toilets[pos].Uses, Toilets[pos].PlaceTimeStamp), 5f, log: false); } public override void OnGlobalFixedUpdate(PlayerControl pc, bool lowLoad) { - if (lowLoad || !pc.IsAlive() || !GameStates.IsInTask) - { - return; - } + if (lowLoad || !pc.IsAlive() || !GameStates.IsInTask) return; if (ActivePoops.TryGetValue(pc.PlayerId, out (Poop Poop, long TimeStamp, object Data) activePoop)) { if (activePoop.TimeStamp + PoopDurationSettings[activePoop.Poop].GetInt() <= Utils.TimeStamp) { ActivePoops.Remove(pc.PlayerId); + switch (activePoop.Poop) { case Poop.Brown: @@ -146,11 +158,13 @@ namespace EHR.Crewmate break; case Poop.Red: float defaultSpeed = Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod); + ((List)activePoop.Data).DoIf(x => x != null, x => { Main.AllPlayerSpeed[x.PlayerId] = defaultSpeed; x.MarkDirtySettings(); }); + break; } } @@ -163,10 +177,7 @@ namespace EHR.Crewmate Vector2 pos = pc.Pos(); (Toilet NetObject, int Uses, long PlaceTimeStamp) toilet = Toilets.First(x => Vector2.Distance(x.Key, pos) <= ToiletUseRadius.GetFloat()).Value; - if (toilet.Uses >= AbilityUses.GetInt()) - { - return; - } + if (toilet.Uses >= AbilityUses.GetInt()) return; if (!PlayersUsingToilet.TryGetValue(pc.PlayerId, out long ts)) { @@ -174,18 +185,12 @@ namespace EHR.Crewmate return; } - if (ts + ToiletUseTime.GetInt() > Utils.TimeStamp) - { - return; - } + if (ts + ToiletUseTime.GetInt() > Utils.TimeStamp) return; toilet.Uses++; Poop poop = Enum.GetValues().RandomElement(); - if (poop != Poop.Green) - { - pc.Notify(Utils.ColorString(GetPoopColor(poop), string.Format(Translator.GetString("TM.GetPoopNotify"), poop))); - } + if (poop != Poop.Green) pc.Notify(Utils.ColorString(GetPoopColor(poop), string.Format(Translator.GetString("TM.GetPoopNotify"), poop))); switch (poop) { @@ -203,6 +208,7 @@ namespace EHR.Crewmate case Poop.Red: int duration = RedPoopRoleBlockDuration.GetInt(); List affectedPlayers = []; + Utils.GetPlayersInRadius(RedPoopRadius.GetFloat(), pos).Without(pc).Do(x => { x.BlockRole(duration); @@ -210,6 +216,7 @@ namespace EHR.Crewmate x.MarkDirtySettings(); affectedPlayers.Add(x); }); + ActivePoops[pc.PlayerId] = (poop, Utils.TimeStamp, affectedPlayers); break; case Poop.Blue: @@ -229,10 +236,7 @@ namespace EHR.Crewmate public override void AfterMeetingTasks() { - if (ToiletVisible == ToiletVisibilityOptions.AfterMeeting) - { - Toilets.Values.Do(x => x.NetObject = new(Toilets.GetKeyByValue((x.NetObject, x.Uses, x.PlaceTimeStamp)), [])); - } + if (ToiletVisible == ToiletVisibilityOptions.AfterMeeting) Toilets.Values.Do(x => x.NetObject = new(Toilets.GetKeyByValue((x.NetObject, x.Uses, x.PlaceTimeStamp)), [])); } private static Color GetPoopColor(Poop poop) @@ -250,21 +254,16 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive() || !GameStates.IsInTask) - { - return; - } + if (!pc.IsAlive() || !GameStates.IsInTask) return; long now = Utils.TimeStamp; - if (LastUpdate >= now) - { - return; - } + if (LastUpdate >= now) return; LastUpdate = now; int duration = ToiletDuration.GetInt(); int maxUses = ToiletMaxUses.GetInt(); + Toilets.DoIf(x => x.Value.PlaceTimeStamp + duration <= now || x.Value.Uses >= maxUses, x => { Toilets.Remove(x.Key); @@ -292,10 +291,7 @@ namespace EHR.Crewmate { if (tm.ActivePoops.TryGetValue(killer.PlayerId, out (Poop Poop, long TimeStamp, object Data) poop) && poop.Poop == Poop.Purple) { - if (PurplePoopNotifyOnKillAttempt.GetBool()) - { - target.Notify(Translator.GetString("TM.TryKillNotify")); - } + if (PurplePoopNotifyOnKillAttempt.GetBool()) target.Notify(Translator.GetString("TM.TryKillNotify")); return false; } diff --git a/Roles/Crewmate/Tornado.cs b/Roles/Crewmate/Tornado.cs index 7e77dde61..d7b8cb5a1 100644 --- a/Roles/Crewmate/Tornado.cs +++ b/Roles/Crewmate/Tornado.cs @@ -31,12 +31,15 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Tornado); + TornadoCooldown = new IntegerOptionItem(Id + 2, "TornadoCooldown", new(1, 90, 1), 15, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Tornado]) .SetValueFormat(OptionFormat.Seconds); + TornadoDuration = new IntegerOptionItem(Id + 3, "TornadoDuration", new(1, 90, 1), 25, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Tornado]) .SetValueFormat(OptionFormat.Seconds); + TornadoRange = new FloatOptionItem(Id + 4, "TornadoRange", new(0.5f, 25f, 0.5f), 3f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Tornado]) .SetValueFormat(OptionFormat.Multiplier); @@ -64,6 +67,7 @@ namespace EHR.Crewmate MapNames.Fungle => new RandomSpawn.FungleSpawnMap(), _ => throw new ArgumentOutOfRangeException(Main.CurrentMap.ToString(), "Unsupported Map") }; + CanUseMap = true; } catch (ArgumentOutOfRangeException) @@ -82,20 +86,14 @@ namespace EHR.Crewmate private static void SendRPCAddTornado(bool add, Vector2 pos, string roomname, long timestamp = 0) { - if (!DoRPC) - { - return; - } + if (!DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.AddTornado, SendOption.Reliable); writer.Write(add); writer.Write(pos.x); writer.Write(pos.y); writer.Write(roomname); - if (add) - { - writer.Write(timestamp.ToString()); - } + if (add) writer.Write(timestamp.ToString()); AmongUsClient.Instance.FinishRpcImmediately(writer); } @@ -113,9 +111,7 @@ namespace EHR.Crewmate Tornados.TryAdd((new(x, y), roomname), timestamp); } else - { Tornados.Remove((new(x, y), roomname)); - } } public override void OnPet(PlayerControl pc) @@ -125,10 +121,7 @@ namespace EHR.Crewmate public static void SpawnTornado(PlayerControl pc) { - if (pc == null) - { - return; - } + if (pc == null) return; (Vector2 Location, string RoomName) info = pc.GetPositionInfo(); long now = TimeStamp; @@ -139,16 +132,13 @@ namespace EHR.Crewmate public override void OnCheckPlayerPosition(PlayerControl pc) { - if (!IsEnable || !GameStates.IsInTask || Tornados.Count == 0 || pc == null) - { - return; - } + if (!IsEnable || !GameStates.IsInTask || Tornados.Count == 0 || pc == null) return; long now = TimeStamp; if (!pc.Is(CustomRoles.Tornado)) { - IRandom Random = IRandom.Instance; + var Random = IRandom.Instance; string NotifyString = GetString("TeleportedByTornado"); float tornadoRange = TornadoRange.GetFloat(); int tornadoDuration = TornadoDuration.GetInt(); @@ -158,13 +148,9 @@ namespace EHR.Crewmate if (Vector2.Distance(tornado.Key.Location, pc.Pos()) <= tornadoRange) { if (!CanUseMap || Random.Next(0, 100) < 50) - { pc.TPToRandomVent(); - } else - { Map.RandomTeleport(pc); - } pc.Notify(NotifyString); } @@ -179,10 +165,7 @@ namespace EHR.Crewmate } else { - if (LastNotify >= now || pc.HasAbilityCD()) - { - return; - } + if (LastNotify >= now || pc.HasAbilityCD()) return; NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); LastNotify = now; @@ -191,10 +174,7 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || !IsEnable || (seer.IsModClient() && !hud) || seer.PlayerId != TornadoPC.PlayerId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || !IsEnable || (seer.IsModClient() && !hud) || seer.PlayerId != TornadoPC.PlayerId) return string.Empty; return string.Join(hud ? "\n" : ", ", Tornados.Select(x => $"Tornado {GetFormattedRoomName(x.Key.RoomName)} {GetFormattedVectorText(x.Key.Location)} ({(int)(TornadoDuration.GetInt() - (TimeStamp - x.Value) + 1)}s)")); } diff --git a/Roles/Crewmate/Tracefinder.cs b/Roles/Crewmate/Tracefinder.cs index 1a5b567f6..73f1a936b 100644 --- a/Roles/Crewmate/Tracefinder.cs +++ b/Roles/Crewmate/Tracefinder.cs @@ -23,15 +23,19 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.CrewmateRoles, CustomRoles.Tracefinder); + VitalsCooldown = new FloatOptionItem(Id + 10, "VitalsCooldown", new(1f, 60f, 1f), 25f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Tracefinder]) .SetValueFormat(OptionFormat.Seconds); + VitalsDuration = new FloatOptionItem(Id + 11, "VitalsDuration", new(1f, 30f, 1f), 1f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Tracefinder]) .SetValueFormat(OptionFormat.Seconds); + ArrowDelayMin = new FloatOptionItem(Id + 12, "ArrowDelayMin", new(1f, 30f, 1f), 2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Tracefinder]) .SetValueFormat(OptionFormat.Seconds); + ArrowDelayMax = new FloatOptionItem(Id + 13, "ArrowDelayMax", new(1f, 30f, 1f), 7f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Tracefinder]) .SetValueFormat(OptionFormat.Seconds); @@ -58,28 +62,19 @@ namespace EHR.Crewmate public override void OnReportDeadBody() { - foreach (byte apc in PlayerIdList) - { - LocateArrow.RemoveAllTarget(apc); - } + foreach (byte apc in PlayerIdList) LocateArrow.RemoveAllTarget(apc); } public static void OnPlayerDead(PlayerControl target) { - if (!On || !GameStates.IsInTask || target == null || target.Data.Disconnected) - { - return; - } + if (!On || !GameStates.IsInTask || target == null || target.Data.Disconnected) return; float delay; + if (ArrowDelayMax.GetFloat() < ArrowDelayMin.GetFloat()) - { delay = 0f; - } else - { delay = IRandom.Instance.Next((int)ArrowDelayMin.GetFloat(), (int)ArrowDelayMax.GetFloat() + 1); - } delay = Math.Max(delay, 0.15f); @@ -90,10 +85,7 @@ namespace EHR.Crewmate foreach (byte id in PlayerIdList) { PlayerControl pc = Utils.GetPlayerById(id); - if (pc == null || !pc.IsAlive()) - { - continue; - } + if (pc == null || !pc.IsAlive()) continue; LocateArrow.Add(id, target.transform.position); Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); @@ -104,15 +96,9 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != TracefinderId) - { - return string.Empty; - } + if (seer.PlayerId != TracefinderId) return string.Empty; - if (target != null && seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (target != null && seer.PlayerId != target.PlayerId) return string.Empty; return Utils.ColorString(Color.white, LocateArrow.GetArrows(seer)); } diff --git a/Roles/Crewmate/Transporter.cs b/Roles/Crewmate/Transporter.cs index ea6bcf10c..f896cf6b4 100644 --- a/Roles/Crewmate/Transporter.cs +++ b/Roles/Crewmate/Transporter.cs @@ -13,9 +13,11 @@ namespace EHR.Crewmate public override void SetupCustomOption() { Options.SetupRoleOptions(6200, TabGroup.CrewmateRoles, CustomRoles.Transporter); + Options.TransporterTeleportMax = new IntegerOptionItem(6210, "TransporterTeleportMax", new(0, 90, 1), 5, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Transporter]) .SetValueFormat(OptionFormat.Times); + Options.OverrideTasksData.Create(6211, TabGroup.CrewmateRoles, CustomRoles.Transporter); } @@ -34,6 +36,7 @@ namespace EHR.Crewmate if (player.IsAlive() && completedTaskCount + 1 <= Options.TransporterTeleportMax.GetInt()) { List AllAlivePlayer = Main.AllAlivePlayerControls.Where(x => !Pelican.IsEaten(x.PlayerId) && !x.inVent && !x.onLadder).ToList(); + if (AllAlivePlayer.Count >= 2) { PlayerControl tar1 = AllAlivePlayer.RandomElement(); @@ -48,9 +51,7 @@ namespace EHR.Crewmate tar2.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Transporter), string.Format(Translator.GetString("TeleportedByTransporter"), tar1.GetRealName()))); } else - { player.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Impostor), string.Format(Translator.GetString("ErrorTeleport"), player.GetRealName()))); - } } } } diff --git a/Roles/Crewmate/Tunneler.cs b/Roles/Crewmate/Tunneler.cs index 6838735d3..69a0b72f7 100644 --- a/Roles/Crewmate/Tunneler.cs +++ b/Roles/Crewmate/Tunneler.cs @@ -27,13 +27,10 @@ namespace EHR.Crewmate public override string GetProgressText(byte playerId, bool comms) { - StringBuilder ProgressText = new StringBuilder(); + var ProgressText = new StringBuilder(); ProgressText.Append(base.GetProgressText(playerId, comms)); - if (TunnelerPositions.ContainsKey(playerId)) - { - ProgressText.Append('●'); - } + if (TunnelerPositions.ContainsKey(playerId)) ProgressText.Append('●'); return ProgressText.ToString(); } @@ -46,9 +43,7 @@ namespace EHR.Crewmate TunnelerPositions.Remove(pc.PlayerId); } else - { TunnelerPositions[pc.PlayerId] = pc.Pos(); - } } } } \ No newline at end of file diff --git a/Roles/Crewmate/Ventguard.cs b/Roles/Crewmate/Ventguard.cs index 729f38097..808cb2b20 100644 --- a/Roles/Crewmate/Ventguard.cs +++ b/Roles/Crewmate/Ventguard.cs @@ -21,18 +21,24 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupSingleRoleOptions(5525, TabGroup.CrewmateRoles, CustomRoles.Ventguard); + VentguardAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(5527, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 1f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ventguard]) .SetValueFormat(OptionFormat.Times); + VentguardAbilityChargesWhenFinishedTasks = new FloatOptionItem(5530, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ventguard]) .SetValueFormat(OptionFormat.Times); + VentguardMaxGuards = new IntegerOptionItem(5528, "VentguardMaxGuards", new(1, 30, 1), 3, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ventguard]); + VentguardBlockDoesNotAffectCrew = new BooleanOptionItem(5529, "VentguardBlockDoesNotAffectCrew", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ventguard]); + VentguardNotifyOnBlockedVentUse = new BooleanOptionItem(5531, "VentguardNotifyOnBlockedVentUse", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ventguard]); + VentguardBlocksResetOnMeeting = new BooleanOptionItem(5532, "VentguardBlocksResetOnMeeting", true, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ventguard]); } @@ -64,25 +70,17 @@ namespace EHR.Crewmate if (pc.GetAbilityUseLimit() >= 1) { pc.RpcRemoveAbilityUse(); - if (!BlockedVents.Contains(vent.Id)) - { - BlockedVents.Add(vent.Id); - } + if (!BlockedVents.Contains(vent.Id)) BlockedVents.Add(vent.Id); pc.Notify(Translator.GetString("VentBlockSuccess")); } else - { pc.Notify(Translator.GetString("OutOfAbilityUsesDoMoreTasks")); - } } public override void AfterMeetingTasks() { - if (VentguardBlocksResetOnMeeting.GetBool()) - { - BlockedVents.Clear(); - } + if (VentguardBlocksResetOnMeeting.GetBool()) BlockedVents.Clear(); } public override bool CanUseVent(PlayerControl pc, int ventId) diff --git a/Roles/Crewmate/Veteran.cs b/Roles/Crewmate/Veteran.cs index 13148433c..b3ff179d8 100644 --- a/Roles/Crewmate/Veteran.cs +++ b/Roles/Crewmate/Veteran.cs @@ -17,18 +17,23 @@ namespace EHR.Crewmate { const int id = 8990; SetupRoleOptions(id, TabGroup.CrewmateRoles, CustomRoles.Veteran); + VeteranSkillCooldown = new FloatOptionItem(id + 2, "VeteranSkillCooldown", new(0f, 180f, 1f), 20f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Veteran]) .SetValueFormat(OptionFormat.Seconds); + VeteranSkillDuration = new FloatOptionItem(id + 3, "VeteranSkillDuration", new(0f, 180f, 1f), 10f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Veteran]) .SetValueFormat(OptionFormat.Seconds); + VeteranSkillMaxOfUseage = new IntegerOptionItem(id + 4, "VeteranSkillMaxOfUseage", new(0, 180, 1), 1, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Veteran]) .SetValueFormat(OptionFormat.Times); + VeteranAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(id + 5, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 0.3f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Veteran]) .SetValueFormat(OptionFormat.Times); + VeteranAbilityChargesWhenFinishedTasks = new FloatOptionItem(id + 6, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Veteran]) .SetValueFormat(OptionFormat.Times); @@ -47,10 +52,7 @@ namespace EHR.Crewmate public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.EngineerCooldown = VeteranSkillCooldown.GetFloat(); AURoleOptions.EngineerInVentMaxTime = 1; @@ -58,7 +60,7 @@ namespace EHR.Crewmate public override string GetProgressText(byte playerId, bool comms) { - StringBuilder ProgressText = new StringBuilder(); + var ProgressText = new StringBuilder(); ProgressText.Append(Utils.GetAbilityUseLimitDisplay(playerId, VeteranInProtect.ContainsKey(playerId))); ProgressText.Append(Utils.GetTaskCount(playerId, comms)); @@ -69,13 +71,9 @@ namespace EHR.Crewmate public override void SetButtonTexts(HudManager hud, byte id) { if (UsePets.GetBool()) - { hud.PetButton.buttonLabelText.text = Translator.GetString("VeteranVentButtonText"); - } else - { hud.AbilityButton.buttonLabelText.text = Translator.GetString("VeteranVentButtonText"); - } } public override void OnPet(PlayerControl pc) @@ -90,10 +88,7 @@ namespace EHR.Crewmate private static void Alert(PlayerControl pc) { - if (VeteranInProtect.ContainsKey(pc.PlayerId)) - { - return; - } + if (VeteranInProtect.ContainsKey(pc.PlayerId)) return; if (pc.GetAbilityUseLimit() >= 1) { @@ -104,9 +99,7 @@ namespace EHR.Crewmate pc.MarkDirtySettings(); } else - { pc.Notify(Translator.GetString("OutOfAbilityUsesDoMoreTasks")); - } } public override bool OnCheckMurderAsTarget(PlayerControl killer, PlayerControl target) @@ -135,6 +128,7 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl player) { byte playerId = player.PlayerId; + if (VeteranInProtect.TryGetValue(playerId, out long vtime) && vtime + VeteranSkillDuration.GetInt() < Utils.TimeStamp) { VeteranInProtect.Remove(playerId); diff --git a/Roles/Crewmate/Whisperer.cs b/Roles/Crewmate/Whisperer.cs index e619753e7..6ab4641d4 100644 --- a/Roles/Crewmate/Whisperer.cs +++ b/Roles/Crewmate/Whisperer.cs @@ -29,20 +29,25 @@ namespace EHR.Crewmate public override void SetupCustomOption() { - int id = 649550; + var id = 649550; Options.SetupRoleOptions(id++, TabGroup.CrewmateRoles, CustomRoles.Whisperer); + Cooldown = new IntegerOptionItem(++id, "WhispererCooldown", new(0, 60, 1), 5, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Whisperer]) .SetValueFormat(OptionFormat.Seconds); + Duration = new IntegerOptionItem(++id, "WhispererDuration", new(0, 60, 1), 7, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Whisperer]) .SetValueFormat(OptionFormat.Seconds); + AbilityUseLimit = new IntegerOptionItem(++id, "AbilityUseLimit", new(0, 20, 1), 1, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Whisperer]) .SetValueFormat(OptionFormat.Times); + WhispererAbilityUseGainWithEachTaskCompleted = new FloatOptionItem(++id, "AbilityUseGainWithEachTaskCompleted", new(0f, 5f, 0.05f), 1f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Whisperer]) .SetValueFormat(OptionFormat.Times); + AbilityChargesWhenFinishedTasks = new FloatOptionItem(++id, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Whisperer]) .SetValueFormat(OptionFormat.Times); @@ -68,17 +73,11 @@ namespace EHR.Crewmate public override void OnPet(PlayerControl pc) { - if (Souls.Exists(x => x.IsQuestioning)) - { - return; - } + if (Souls.Exists(x => x.IsQuestioning)) return; Vector2 pos = pc.Pos(); List souls = Souls.FindAll(x => x.IsQuestionAble && Vector2.Distance(pos, x.Position) <= 1f); - if (souls.Count == 0) - { - return; - } + if (souls.Count == 0) return; Soul soul = souls.MinBy(x => Vector2.Distance(pos, x.Position)); soul.QuestioningTime = Duration.GetInt(); @@ -89,18 +88,13 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) - { - return; - } + if (!pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) return; Soul soul = Souls.Find(x => x.IsQuestioning); - if (soul == null) - { - return; - } + if (soul == null) return; byte soulPlayerId = soul.Player.PlayerId; + if (Vector2.Distance(pc.Pos(), soul.Position) > 1f) { soul.QuestioningTime = 0f; @@ -109,6 +103,7 @@ namespace EHR.Crewmate } soul.QuestioningTime -= Time.fixedDeltaTime; + if (soul.QuestioningTime <= 0f) { soul.QuestioningTime = 0f; @@ -125,10 +120,7 @@ namespace EHR.Crewmate PlayerState state = Main.PlayerStates[soulPlayerId]; (DateTime TimeStamp, byte ID) killer = state.RealKiller; int next = IRandom.Instance.Next(4); - if (state.deathReason == PlayerState.DeathReason.Disconnected) - { - next = 2; - } + if (state.deathReason == PlayerState.DeathReason.Disconnected) next = 2; info = next switch { @@ -138,6 +130,7 @@ namespace EHR.Crewmate 3 => string.Format(Translator.GetString("WhispererInfo.KillerRole"), Main.PlayerStates[killer.ID].MainRole.ToColoredString()), _ => string.Empty }; + info = $"{soulPlayerId.ColoredPlayerName()}: {info}"; } catch (Exception e) @@ -149,10 +142,7 @@ namespace EHR.Crewmate if (!string.IsNullOrEmpty(info)) { Info.Add(info); - if (Info.Count > 5) - { - Info.RemoveAt(0); - } + if (Info.Count > 5) Info.RemoveAt(0); pc.RpcRemoveAbilityUse(); Utils.SendRPC(CustomRPC.SyncRoleData, WhispererId, 4, info); @@ -161,10 +151,7 @@ namespace EHR.Crewmate } else { - if (Count++ < 10) - { - return; - } + if (Count++ < 10) return; Count = 0; CurrentlyQuestioning.Percent = 100 - (int)(soul.QuestioningTime * 100f / Duration.GetFloat()); @@ -180,7 +167,7 @@ namespace EHR.Crewmate private static string GetColorInfo(int colorId, out string colors) { - List darker = new List { 0, 1, 2, 6, 8, 9, 12, 15 }; + var darker = new List { 0, 1, 2, 6, 8, 9, 12, 15 }; bool isDarker = darker.Contains(colorId); Func selector = x => Utils.ColorString(Palette.PlayerColors[x], Palette.GetColorName(x)); colors = isDarker ? string.Join('/', darker.Select(selector)) : string.Join('/', Enumerable.Range(0, 18).Except(darker).Select(selector)); @@ -191,10 +178,7 @@ namespace EHR.Crewmate { foreach (Whisperer instance in Instances) { - if (instance.Souls.Exists(x => x.Player.PlayerId == target.PlayerId)) - { - continue; - } + if (instance.Souls.Exists(x => x.Player.PlayerId == target.PlayerId)) continue; instance.Souls.Add(new(target)); Utils.SendRPC(CustomRPC.SyncRoleData, instance.WhispererId, 5, target.PlayerId); @@ -233,10 +217,7 @@ namespace EHR.Crewmate break; case 4: Info.Add(reader.ReadString()); - if (Info.Count > 5) - { - Info.RemoveAt(0); - } + if (Info.Count > 5) Info.RemoveAt(0); break; case 5: @@ -247,10 +228,7 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != WhispererId || meeting || (seer.IsModClient() && !hud)) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != WhispererId || meeting || (seer.IsModClient() && !hud)) return string.Empty; return "" + string.Join('\n', Info) + (CurrentlyQuestioning.Percent > 0 ? string.Format(Translator.GetString("WhispererQuestioning"), CurrentlyQuestioning.Name, CurrentlyQuestioning.Percent) : string.Empty) + ""; } diff --git a/Roles/Crewmate/Witness.cs b/Roles/Crewmate/Witness.cs index f1fa2ff0b..a860b08de 100644 --- a/Roles/Crewmate/Witness.cs +++ b/Roles/Crewmate/Witness.cs @@ -14,12 +14,15 @@ namespace EHR.Crewmate public override void SetupCustomOption() { SetupRoleOptions(8550, TabGroup.CrewmateRoles, CustomRoles.Witness); + WitnessCD = new FloatOptionItem(8552, "AbilityCD", new(0f, 60f, 2.5f), 10f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Witness]) .SetValueFormat(OptionFormat.Seconds); + WitnessTime = new IntegerOptionItem(8553, "WitnessTime", new(0, 90, 1), 10, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Witness]) .SetValueFormat(OptionFormat.Seconds); + WitnessUsePet = CreatePetUseSetting(8554, CustomRoles.Witness); } @@ -68,10 +71,7 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (AllKillers.TryGetValue(pc.PlayerId, out long ktime) && ktime + WitnessTime.GetInt() < Utils.TimeStamp) - { - AllKillers.Remove(pc.PlayerId); - } + if (AllKillers.TryGetValue(pc.PlayerId, out long ktime) && ktime + WitnessTime.GetInt() < Utils.TimeStamp) AllKillers.Remove(pc.PlayerId); } } } \ No newline at end of file diff --git a/Roles/Crewmate/Wizard.cs b/Roles/Crewmate/Wizard.cs index 05a5f6113..eb8e56e94 100644 --- a/Roles/Crewmate/Wizard.cs +++ b/Roles/Crewmate/Wizard.cs @@ -85,12 +85,14 @@ namespace EHR.Crewmate On = true; Instances.Add(this); WizardId = playerId; + BuffValues = new() { [Buff.Speed] = 1.5f, [Buff.Vision] = 0.9f, [Buff.KCD] = 15f }; + PlayerBuffs = []; SelectedBuff = default; TaskMode = false; @@ -124,10 +126,7 @@ namespace EHR.Crewmate { foreach (Wizard instance in Instances) { - if (!instance.PlayerBuffs.TryGetValue(id, out Dictionary buffs)) - { - continue; - } + if (!instance.PlayerBuffs.TryGetValue(id, out Dictionary buffs)) continue; foreach ((Buff buff, float value) in buffs) { @@ -157,13 +156,9 @@ namespace EHR.Crewmate public override void OnPet(PlayerControl pc) { if (SelectedBuff == Buff.KCD) - { SelectedBuff = default; - } else - { SelectedBuff++; - } Utils.SendRPC(CustomRPC.SyncRoleData, WizardId, 1, (int)SelectedBuff); Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); @@ -171,10 +166,7 @@ namespace EHR.Crewmate public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (shapeshifting) - { - return false; - } + if (shapeshifting) return false; BuffValues[SelectedBuff] += SelectedBuff switch { @@ -185,13 +177,9 @@ namespace EHR.Crewmate }; if (BuffValues[SelectedBuff] > MaxBuffValues[SelectedBuff]) - { BuffValues[SelectedBuff] = MinBuffValues[SelectedBuff]; - } else - { BuffValues[SelectedBuff] = (float)Math.Round(BuffValues[SelectedBuff], 1); - } Utils.SendRPC(CustomRPC.SyncRoleData, WizardId, 2, BuffValues[SelectedBuff]); Utils.NotifyRoles(SpecifySeer: shapeshifter, SpecifyTarget: shapeshifter); @@ -200,25 +188,15 @@ namespace EHR.Crewmate public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!base.OnCheckMurder(killer, target) || killer.GetAbilityUseLimit() < 1f) - { - return false; - } + if (!base.OnCheckMurder(killer, target) || killer.GetAbilityUseLimit() < 1f) return false; float value = BuffValues[SelectedBuff]; - if (SelectedBuff == Buff.Speed) - { - value = Math.Max(value, Main.MinSpeed); - } + if (SelectedBuff == Buff.Speed) value = Math.Max(value, Main.MinSpeed); if (!PlayerBuffs.TryGetValue(target.PlayerId, out Dictionary buffs)) - { PlayerBuffs[target.PlayerId] = new() { { SelectedBuff, value } }; - } else - { buffs[SelectedBuff] = value; - } target.SyncSettings(); killer.SetKillCooldown(); @@ -233,15 +211,9 @@ namespace EHR.Crewmate public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask || ExileController.Instance) - { - return; - } + if (!GameStates.IsInTask || ExileController.Instance) return; - if (Count++ < 40) - { - return; - } + if (Count++ < 40) return; Count = 0; @@ -276,19 +248,12 @@ namespace EHR.Crewmate case 3: byte id = reader.ReadByte(); float value = BuffValues[SelectedBuff]; - if (SelectedBuff == Buff.Speed) - { - value = Math.Max(value, Main.MinSpeed); - } + if (SelectedBuff == Buff.Speed) value = Math.Max(value, Main.MinSpeed); if (!PlayerBuffs.TryGetValue(id, out Dictionary buffs)) - { PlayerBuffs[id] = new() { { SelectedBuff, value } }; - } else - { buffs[SelectedBuff] = value; - } break; } @@ -296,20 +261,11 @@ namespace EHR.Crewmate public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != WizardId || meeting) - { - return string.Empty; - } + if (seer.PlayerId != WizardId || meeting) return string.Empty; - if (PlayerBuffs.TryGetValue(target.PlayerId, out Dictionary buffs)) - { - return string.Join('\n', buffs.Select(x => $"{Translator.GetString($"Wizard.Buff.{x.Key}")}: {Math.Round(x.Value, 1):N1}{GetBuffFormat(x.Key)}")); - } + if (PlayerBuffs.TryGetValue(target.PlayerId, out Dictionary buffs)) return string.Join('\n', buffs.Select(x => $"{Translator.GetString($"Wizard.Buff.{x.Key}")}: {Math.Round(x.Value, 1):N1}{GetBuffFormat(x.Key)}")); - if (seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud)) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud)) return string.Empty; return string.Format(Translator.GetString("Wizard.SelectedBuff"), SelectedBuff, BuffValues[SelectedBuff], GetBuffFormat(SelectedBuff)); diff --git a/Roles/Impostor/Abyssbringer.cs b/Roles/Impostor/Abyssbringer.cs index 93f0d1aae..f841b38ba 100644 --- a/Roles/Impostor/Abyssbringer.cs +++ b/Roles/Impostor/Abyssbringer.cs @@ -27,22 +27,28 @@ namespace EHR.Impostor public override void SetupCustomOption() { - int id = 649800; + var id = 649800; const TabGroup tab = TabGroup.ImpostorRoles; const CustomRoles role = CustomRoles.Abyssbringer; Options.SetupRoleOptions(id++, tab, role); + BlackHolePlaceCooldown = new IntegerOptionItem(++id, "BlackHolePlaceCooldown", new(1, 180, 1), 30, tab) .SetParent(Options.CustomRoleSpawnChances[role]) .SetValueFormat(OptionFormat.Seconds); + BlackHoleDespawnMode = new StringOptionItem(++id, "BlackHoleDespawnMode", Enum.GetNames(), 0, tab) .SetParent(Options.CustomRoleSpawnChances[role]); + BlackHoleDespawnTime = new IntegerOptionItem(++id, "BlackHoleDespawnTime", new(1, 60, 1), 15, tab) .SetParent(BlackHoleDespawnMode) .SetValueFormat(OptionFormat.Seconds); + BlackHoleMovesTowardsNearestPlayer = new BooleanOptionItem(++id, "BlackHoleMovesTowardsNearestPlayer", true, tab) .SetParent(Options.CustomRoleSpawnChances[role]); + BlackHoleMoveSpeed = new FloatOptionItem(++id, "BlackHoleMoveSpeed", new(0.25f, 10f, 0.25f), 1f, tab) .SetParent(BlackHoleMovesTowardsNearestPlayer); + BlackHoleRadius = new FloatOptionItem(++id, "BlackHoleRadius", new(0.1f, 5f, 0.1f), 1.2f, tab) .SetParent(Options.CustomRoleSpawnChances[role]) .SetValueFormat(OptionFormat.Multiplier); @@ -63,9 +69,7 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte playerId) { if (Options.UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = BlackHolePlaceCooldown.GetInt(); - } else { AURoleOptions.ShapeshifterCooldown = BlackHolePlaceCooldown.GetInt(); @@ -75,10 +79,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) return true; CreateBlackHole(shapeshifter); return false; @@ -108,7 +109,7 @@ namespace EHR.Impostor { if ((DespawnMode)BlackHoleDespawnMode.GetValue() == DespawnMode.AfterMeeting) { - for (int i = 0; i < BlackHoles.Count; i++) + for (var i = 0; i < BlackHoles.Count; i++) { BlackHoles[i].NetObject.Despawn(); BlackHoles.RemoveAt(i); @@ -119,20 +120,19 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl pc) { - if (Count++ < 3) - { - return; - } + if (Count++ < 3) return; Count = 0; PlayerControl abyssbringer = AbyssbringerId.GetPlayer(); int count = BlackHoles.Count; - for (int i = 0; i < count; i++) + + for (var i = 0; i < count; i++) { BlackHoleData blackHole = BlackHoles[i]; - DespawnMode despawnMode = (DespawnMode)BlackHoleDespawnMode.GetValue(); + var despawnMode = (DespawnMode)BlackHoleDespawnMode.GetValue(); + switch (despawnMode) { case DespawnMode.AfterTime when Utils.TimeStamp - blackHole.PlaceTimeStamp > BlackHoleDespawnTime.GetInt(): @@ -144,6 +144,7 @@ namespace EHR.Impostor } PlayerControl nearestPlayer = Main.AllAlivePlayerControls.Without(pc).MinBy(x => Vector2.Distance(x.Pos(), blackHole.Position)); + if (nearestPlayer != null) { Vector2 pos = nearestPlayer.Pos(); @@ -168,10 +169,7 @@ namespace EHR.Impostor state.RealKiller = (DateTime.Now, AbyssbringerId); state.SetDead(); - if (despawnMode == DespawnMode.After1PlayerEaten) - { - RemoveBlackHole(); - } + if (despawnMode == DespawnMode.After1PlayerEaten) RemoveBlackHole(); } } @@ -213,10 +211,7 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != AbyssbringerId || meeting || (seer.IsModClient() && !hud) || BlackHoles.Count == 0) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != AbyssbringerId || meeting || (seer.IsModClient() && !hud) || BlackHoles.Count == 0) return string.Empty; return string.Format(Translator.GetString("Abyssbringer.Suffix"), BlackHoles.Count, string.Join('\n', BlackHoles.Select(x => GetBlackHoleFormatText(x.RoomName, x.PlayersConsumed)))); diff --git a/Roles/Impostor/AntiAdminer.cs b/Roles/Impostor/AntiAdminer.cs index c71a12c82..3215d298f 100644 --- a/Roles/Impostor/AntiAdminer.cs +++ b/Roles/Impostor/AntiAdminer.cs @@ -35,12 +35,16 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.AntiAdminer); + CanCheckCamera = new BooleanOptionItem(Id + 10, "CanCheckCamera", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.AntiAdminer]); + EnableExtraAbility = new BooleanOptionItem(Id + 11, "EnableExtraAbility", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.AntiAdminer]); + CanOnlyUseWhileAnyWatch = new BooleanOptionItem(Id + 12, "CanOnlyUseWhileAnyWatch", true, TabGroup.ImpostorRoles) .SetParent(EnableExtraAbility); + Delay = new FloatOptionItem(Id + 13, "AADelay", new(0f, 20f, 0.5f), 5f, TabGroup.ImpostorRoles) .SetParent(EnableExtraAbility) .SetValueFormat(OptionFormat.Seconds); @@ -66,24 +70,15 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting) - { - return true; - } + if (!shapeshifting) return true; - if (IsMonitor || !EnableExtraAbility.GetBool() || ExtraAbilityStartTimeStamp > 0 || (CanOnlyUseWhileAnyWatch.GetBool() && !IsAdminWatch && !IsVitalWatch && !IsDoorLogWatch && !IsCameraWatch)) - { - return false; - } + if (IsMonitor || !EnableExtraAbility.GetBool() || ExtraAbilityStartTimeStamp > 0 || (CanOnlyUseWhileAnyWatch.GetBool() && !IsAdminWatch && !IsVitalWatch && !IsDoorLogWatch && !IsCameraWatch)) return false; ExtraAbilityStartTimeStamp = Utils.TimeStamp; shapeshifter.RpcResetAbilityCooldown(); Utils.NotifyRoles(SpecifySeer: shapeshifter, SpecifyTarget: shapeshifter); - foreach (PlayerControl pc in PlayersNearDevices.Select(x => Utils.GetPlayerById(x)).Where(x => x != null && x.IsAlive())) - { - pc.Notify(Translator.GetString("AAWarning"), Delay.GetFloat()); - } + foreach (PlayerControl pc in PlayersNearDevices.Select(x => Utils.GetPlayerById(x)).Where(x => x != null && x.IsAlive())) pc.Notify(Translator.GetString("AAWarning"), Delay.GetFloat()); return false; } @@ -107,12 +102,9 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl player) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - bool notify = false; + var notify = false; if (!IsMonitor && ExtraAbilityStartTimeStamp > 0 && EnableExtraAbility.GetBool()) { @@ -122,43 +114,32 @@ namespace EHR.Impostor player.RpcResetAbilityCooldown(); player.Notify(Translator.GetString("AADone")); - foreach (PlayerControl pc in PlayersNearDevices.Select(x => Utils.GetPlayerById(x)).Where(x => x != null && x.IsAlive() && player.RpcCheckAndMurder(x, true))) - { - pc.Suicide(realKiller: player); - } + foreach (PlayerControl pc in PlayersNearDevices.Select(x => Utils.GetPlayerById(x)).Where(x => x != null && x.IsAlive() && player.RpcCheckAndMurder(x, true))) pc.Suicide(realKiller: player); } else { notify = true; - foreach (PlayerControl pc in PlayersNearDevices.Select(x => Utils.GetPlayerById(x)).Where(x => x != null && x.IsAlive())) - { - Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - } + foreach (PlayerControl pc in PlayersNearDevices.Select(x => Utils.GetPlayerById(x)).Where(x => x != null && x.IsAlive())) Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); } } Count--; - if (Count > 0) - { - return; - } + if (Count > 0) return; Count = notify || ExtraAbilityStartTimeStamp > 0 ? 1 : 5; PlayersNearDevices = []; bool Admin = false, Camera = false, DoorLog = false, Vital = false; float usableDistance = DisableDevice.UsableDistance; + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (pc.inVent || (pc.IsImpostor() && !IsMonitor)) - { - continue; - } + if (pc.inVent || (pc.IsImpostor() && !IsMonitor)) continue; try { Vector2 PlayerPos = pc.Pos(); - bool nearDevice = false; + var nearDevice = false; switch (Main.NormalOptions.MapId) { @@ -284,10 +265,7 @@ namespace EHR.Impostor break; } - if (nearDevice) - { - PlayersNearDevices.Add(pc.PlayerId); - } + if (nearDevice) PlayersNearDevices.Add(pc.PlayerId); } catch (Exception ex) { @@ -295,7 +273,7 @@ namespace EHR.Impostor } } - bool change = false; + var change = false; change |= IsAdminWatch != Admin; IsAdminWatch = Admin; @@ -303,16 +281,14 @@ namespace EHR.Impostor IsVitalWatch = Vital; change |= IsDoorLogWatch != DoorLog; IsDoorLogWatch = DoorLog; + if (IsMonitor ? Monitor.CanCheckCamera.GetBool() : CanCheckCamera.GetBool()) { change |= IsCameraWatch != Camera; IsCameraWatch = Camera; } - if (notify || change) - { - Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); - } + if (notify || change) Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) @@ -324,23 +300,15 @@ namespace EHR.Impostor : string.Empty; } - if (!PlayersNearDevices.Contains(seer.PlayerId)) - { - return string.Empty; - } + if (!PlayersNearDevices.Contains(seer.PlayerId)) return string.Empty; AntiAdminer aa = null; + foreach (byte id in PlayerIdList) { - if (Main.PlayerStates[id].Role is not AntiAdminer { IsEnable: true, IsMonitor: false } x || x.ExtraAbilityStartTimeStamp == 0) - { - continue; - } + if (Main.PlayerStates[id].Role is not AntiAdminer { IsEnable: true, IsMonitor: false } x || x.ExtraAbilityStartTimeStamp == 0) continue; - if (aa != null && x.ExtraAbilityStartTimeStamp >= aa.ExtraAbilityStartTimeStamp) - { - continue; - } + if (aa != null && x.ExtraAbilityStartTimeStamp >= aa.ExtraAbilityStartTimeStamp) continue; aa = x; } diff --git a/Roles/Impostor/Assassin.cs b/Roles/Impostor/Assassin.cs index f1a8a4998..27e4454ce 100644 --- a/Roles/Impostor/Assassin.cs +++ b/Roles/Impostor/Assassin.cs @@ -29,12 +29,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Assassin); + MarkCooldownOpt = new FloatOptionItem(Id + 10, "AssassinMarkCooldown", new(0f, 180f, 0.5f), 1f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Assassin]) .SetValueFormat(OptionFormat.Seconds); + AssassinateCooldownOpt = new FloatOptionItem(Id + 11, "AssassinAssassinateCooldown", new(0f, 180f, 0.5f), 18.5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Assassin]) .SetValueFormat(OptionFormat.Seconds); + CanKillAfterAssassinateOpt = new BooleanOptionItem(Id + 12, "AssassinCanKillAfterAssassinate", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Assassin]); } @@ -68,10 +71,7 @@ namespace EHR.Impostor private void SendRPC(byte playerId) { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetMarkedPlayer, SendOption.Reliable); writer.Write(playerId); @@ -84,10 +84,7 @@ namespace EHR.Impostor byte playerId = reader.ReadByte(); byte targetId = reader.ReadByte(); - if (Main.PlayerStates[playerId].Role is not Assassin assassin) - { - return; - } + if (Main.PlayerStates[playerId].Role is not Assassin assassin) return; assassin.MarkedPlayer = targetId; } @@ -100,15 +97,10 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte id) { if (UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = AssassinateCooldown; - } else { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.ShapeshifterCooldown = AssassinateCooldown; } @@ -116,10 +108,7 @@ namespace EHR.Impostor public override bool CanUseKillButton(PlayerControl pc) { - if (pc == null || !pc.IsAlive()) - { - return false; - } + if (pc == null || !pc.IsAlive()) return false; return CanKillAfterAssassinate || !pc.IsShifted(); } @@ -137,10 +126,7 @@ namespace EHR.Impostor SendRPC(killer.PlayerId); killer.ResetKillCooldown(); killer.SetKillCooldown(); - if (killer.IsModClient()) - { - killer.RpcResetAbilityCooldown(); - } + if (killer.IsModClient()) killer.RpcResetAbilityCooldown(); killer.SyncSettings(); killer.RPCPlayCustomSound("Clothe"); @@ -154,15 +140,9 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl pc, PlayerControl t, bool shapeshifting) { - if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId)) - { - return false; - } + if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId)) return false; - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; Take(pc); @@ -171,10 +151,7 @@ namespace EHR.Impostor public override bool OnVanish(PlayerControl pc) { - if (pc == null || !pc.IsAlive() || Pelican.IsEaten(pc.PlayerId)) - { - return false; - } + if (pc == null || !pc.IsAlive() || Pelican.IsEaten(pc.PlayerId)) return false; if (!IsUndertaker) { @@ -201,10 +178,7 @@ namespace EHR.Impostor pc.SyncSettings(); pc.SetKillCooldown(DefaultKillCooldown); } - else if (!tpSuccess) - { - pc.Notify(GetString("TargetCannotBeTeleported")); - } + else if (!tpSuccess) pc.Notify(GetString("TargetCannotBeTeleported")); } } @@ -212,16 +186,13 @@ namespace EHR.Impostor { bool shifted = playerId.IsPlayerShifted(); __instance.KillButton.OverrideText(!shifted ? GetString("AssassinMarkButtonText") : GetString("KillButtonText")); + if (MarkedPlayer != byte.MaxValue && !shifted) { if (!UsePets.GetBool()) - { __instance.AbilityButton.OverrideText(GetString("AssassinShapeshiftText")); - } else - { __instance.PetButton.OverrideText(GetString("AssassinShapeshiftText")); - } } } } diff --git a/Roles/Impostor/Assumer.cs b/Roles/Impostor/Assumer.cs index 0a443b048..1eb3008f8 100644 --- a/Roles/Impostor/Assumer.cs +++ b/Roles/Impostor/Assumer.cs @@ -60,38 +60,25 @@ namespace EHR.Impostor public static void OnVotingEnd(Dictionary voteNum) { - if (!On) - { - return; - } + if (!On) return; foreach (Assumer instance in Instances) { if (instance.HasAssumed && voteNum.TryGetValue(instance.Assumption.Id, out int num) && num == instance.Assumption.VoteNum) { foreach (PlayerVoteArea pva in MeetingHud.Instance.playerStates) - { if (pva.VotedFor == instance.Assumption.Id || (VoteReceiverDies.GetBool() && pva.TargetPlayerId == instance.Assumption.Id)) - { CheckForEndVotingPatch.TryAddAfterMeetingDeathPlayers(PlayerState.DeathReason.Assumed, pva.TargetPlayerId); - } - } } } } public static void Assume(byte assumerId, byte id, int num) { - if (Main.AllAlivePlayerControls.Length < MinPlayersToAssume.GetInt()) - { - return; - } + if (Main.AllAlivePlayerControls.Length < MinPlayersToAssume.GetInt()) return; Assumer assumer = Instances.Find(x => x.AssumerId == assumerId); - if (assumer == null || assumer.HasAssumed) - { - return; - } + if (assumer == null || assumer.HasAssumed) return; assumer.Assumption = (id, num); Utils.SendMessage("\n", assumerId, string.Format(Translator.GetString("Assumer.AssumedMessage"), id.ColoredPlayerName(), num)); diff --git a/Roles/Impostor/Augmenter.cs b/Roles/Impostor/Augmenter.cs index 0ef2cbd28..0c7f6013e 100644 --- a/Roles/Impostor/Augmenter.cs +++ b/Roles/Impostor/Augmenter.cs @@ -25,10 +25,7 @@ public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting) - { - return true; - } + if (!shapeshifting) return true; Target = target.PlayerId; return false; @@ -37,6 +34,7 @@ public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { PlayerControl newTarget = Utils.GetPlayerById(Target); + if (newTarget == null || !newTarget.IsAlive() || !killer.RpcCheckAndMurder(newTarget, true)) { killer.Notify(string.Format(Translator.GetString("AugmenterFail"), Target.ColoredPlayerName())); diff --git a/Roles/Impostor/BallLightning.cs b/Roles/Impostor/BallLightning.cs index 77fde1759..05cc50701 100644 --- a/Roles/Impostor/BallLightning.cs +++ b/Roles/Impostor/BallLightning.cs @@ -26,12 +26,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.BallLightning); + KillCooldown = new FloatOptionItem(Id + 10, "BallLightningKillCooldown", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.BallLightning]) .SetValueFormat(OptionFormat.Seconds); + ConvertTime = new FloatOptionItem(Id + 12, "BallLightningConvertTime", new(0f, 180f, 2.5f), 10f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.BallLightning]) .SetValueFormat(OptionFormat.Seconds); + KillerConvertGhost = new BooleanOptionItem(Id + 14, "BallLightningKillerConvertGhost", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.BallLightning]); } @@ -50,10 +53,7 @@ namespace EHR.Impostor private static void SendRPC(byte playerId) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetGhostPlayer, SendOption.Reliable); writer.Write(playerId); @@ -65,6 +65,7 @@ namespace EHR.Impostor { byte GhostId = reader.ReadByte(); bool isGhost = reader.ReadBoolean(); + if (GhostId == byte.MaxValue) { GhostPlayer = []; @@ -73,17 +74,11 @@ namespace EHR.Impostor if (isGhost) { - if (!GhostPlayer.Contains(GhostId)) - { - GhostPlayer.Add(GhostId); - } + if (!GhostPlayer.Contains(GhostId)) GhostPlayer.Add(GhostId); } else { - if (GhostPlayer.Contains(GhostId)) - { - GhostPlayer.Remove(GhostId); - } + if (GhostPlayer.Contains(GhostId)) GhostPlayer.Remove(GhostId); } } @@ -109,15 +104,9 @@ namespace EHR.Impostor public static bool CheckBallLightningMurder(PlayerControl killer, PlayerControl target, bool force = false) { - if (killer == null || target == null || (!killer.Is(CustomRoles.BallLightning) && !force)) - { - return false; - } + if (killer == null || target == null || (!killer.Is(CustomRoles.BallLightning) && !force)) return false; - if (IsGhost(target)) - { - return false; - } + if (IsGhost(target)) return false; if (!force) { @@ -138,10 +127,7 @@ namespace EHR.Impostor GhostPlayer.Add(target.PlayerId); SendRPC(target.PlayerId); RealKiller.TryAdd(target.PlayerId, killer); - if (!killer.inVent) - { - killer.SetKillCooldown(); - } + if (!killer.inVent) killer.SetKillCooldown(); Utils.NotifyRoles(SpecifySeer: killer, SpecifyTarget: target); Utils.NotifyRoles(SpecifySeer: target, SpecifyTarget: killer); @@ -152,15 +138,9 @@ namespace EHR.Impostor public static void MurderPlayer(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null || !target.Is(CustomRoles.BallLightning)) - { - return; - } + if (killer == null || target == null || !target.Is(CustomRoles.BallLightning)) return; - if (!KillerConvertGhost.GetBool() || IsGhost(killer)) - { - return; - } + if (!KillerConvertGhost.GetBool() || IsGhost(killer)) return; RealKiller.TryAdd(killer.PlayerId, target); StartConvertCountDown(target, killer); @@ -168,15 +148,14 @@ namespace EHR.Impostor public override void OnCheckPlayerPosition(PlayerControl pc) { - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; List deList = []; + foreach (byte ghost in GhostPlayer.ToArray()) { PlayerControl gs = Utils.GetPlayerById(ghost); + if (gs == null || !gs.IsAlive() || gs.Data.Disconnected) { //deList.Add(gs.PlayerId); // This will always result in a null reference exception @@ -187,10 +166,7 @@ namespace EHR.Impostor { Vector3 pos = gs.transform.position; float dis = Vector2.Distance(pos, pc.Pos()); - if (dis > 0.3f) - { - continue; - } + if (dis > 0.3f) continue; deList.Add(gs.PlayerId); gs.Suicide(PlayerState.DeathReason.Quantization, RealKiller[gs.PlayerId]); @@ -202,6 +178,7 @@ namespace EHR.Impostor if (deList.Count > 0) { GhostPlayer.RemoveAll(deList.Contains); + foreach (byte gs in deList.ToArray()) { SendRPC(gs); @@ -212,18 +189,12 @@ namespace EHR.Impostor public override void OnReportDeadBody() { - if (!(IsEnable || CustomRoles.BallLightning.IsEnable())) - { - return; - } + if (!(IsEnable || CustomRoles.BallLightning.IsEnable())) return; foreach (byte ghost in GhostPlayer.ToArray()) { PlayerControl gs = Utils.GetPlayerById(ghost); - if (gs == null) - { - continue; - } + if (gs == null) continue; CheckForEndVotingPatch.TryAddAfterMeetingDeathPlayers(PlayerState.DeathReason.Quantization, gs.PlayerId); gs.SetRealKiller(RealKiller[gs.PlayerId]); diff --git a/Roles/Impostor/Bard.cs b/Roles/Impostor/Bard.cs index 276083a5a..75e1c32e6 100644 --- a/Roles/Impostor/Bard.cs +++ b/Roles/Impostor/Bard.cs @@ -17,13 +17,12 @@ BardCreations = 0; } - public override void SetupCustomOption() - { - } + public override void SetupCustomOption() { } public static void OnMeetingHudDestroy(ref string name) { BardCreations++; + try { name = ModUpdater.Get("https://v1.hitokoto.cn/?encode=text"); diff --git a/Roles/Impostor/Blackmailer.cs b/Roles/Impostor/Blackmailer.cs index c7c5cab8d..10b25f5be 100644 --- a/Roles/Impostor/Blackmailer.cs +++ b/Roles/Impostor/Blackmailer.cs @@ -45,25 +45,13 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.GetAbilityUseLimit() < 1) - { - return true; - } + if (killer.GetAbilityUseLimit() < 1) return true; - if (NumBlackmailedThisRound >= MaxBlackmailedPlayersPerMeeting.GetInt()) - { - return true; - } + if (NumBlackmailedThisRound >= MaxBlackmailedPlayersPerMeeting.GetInt()) return true; - if (BlackmailedPlayerIds.Count >= MaxBlackmailedPlayersAtOnce.GetInt()) - { - return true; - } + if (BlackmailedPlayerIds.Count >= MaxBlackmailedPlayersAtOnce.GetInt()) return true; - if (BlackmailedPlayerIds.Contains(target.PlayerId)) - { - return true; - } + if (BlackmailedPlayerIds.Contains(target.PlayerId)) return true; return killer.CheckDoubleTrigger(target, () => { @@ -77,36 +65,24 @@ namespace EHR.Impostor public override void AfterMeetingTasks() { - if (AbilityExpires.GetValue() == 0) - { - BlackmailedPlayerIds.Clear(); - } + if (AbilityExpires.GetValue() == 0) BlackmailedPlayerIds.Clear(); } public static void OnCheckForEndVoting() { - if (!On) - { - return; - } + if (!On) return; CheckForEndVotingPatch.RunRoleCode = false; try { KeyValuePair bmState = Main.PlayerStates.FirstOrDefault(x => x.Value.MainRole == CustomRoles.Blackmailer); - if (bmState.Value.Role is not Blackmailer { IsEnable: true } bm || bm.BlackmailedPlayerIds.Count == 0) - { - return; - } + if (bmState.Value.Role is not Blackmailer { IsEnable: true } bm || bm.BlackmailedPlayerIds.Count == 0) return; byte? bmVotedForTemp = MeetingHud.Instance.playerStates.FirstOrDefault(x => x.TargetPlayerId == bmState.Key)?.VotedFor; - if (bmVotedForTemp == null) - { - return; - } + if (bmVotedForTemp == null) return; - byte bmVotedFor = (byte)bmVotedForTemp; + var bmVotedFor = (byte)bmVotedForTemp; MeetingHud.Instance.playerStates.DoIf(x => bm.BlackmailedPlayerIds.Contains(x.TargetPlayerId), x => { @@ -117,13 +93,9 @@ namespace EHR.Impostor } if (x.TargetPlayerId.IsHost()) - { MeetingHud.Instance.CmdCastVote(x.TargetPlayerId, bmVotedFor); - } else - { MeetingHud.Instance.CastVote(x.TargetPlayerId, bmVotedFor); - } x.VotedFor = bmVotedFor; }); @@ -136,10 +108,7 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (!On || !meeting || !BlackmailedPlayerIds.Contains(target.PlayerId)) - { - return string.Empty; - } + if (!On || !meeting || !BlackmailedPlayerIds.Contains(target.PlayerId)) return string.Empty; switch (WhoSeesBlackmailedPlayers.GetValue()) { diff --git a/Roles/Impostor/Bomber.cs b/Roles/Impostor/Bomber.cs index 6ce0dd930..6fa33d69f 100644 --- a/Roles/Impostor/Bomber.cs +++ b/Roles/Impostor/Bomber.cs @@ -26,29 +26,39 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(2400, TabGroup.ImpostorRoles, CustomRoles.Bomber); + BomberRadius = new FloatOptionItem(2018, "BomberRadius", new(0.5f, 5f, 0.5f), 3f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bomber]) .SetValueFormat(OptionFormat.Multiplier); + BomberCanKill = new BooleanOptionItem(2015, "CanKill", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bomber]); + BomberKillCD = new FloatOptionItem(2020, "KillCooldown", new(0f, 180f, 2.5f), 40f, TabGroup.ImpostorRoles) .SetParent(BomberCanKill) .SetValueFormat(OptionFormat.Seconds); + CooldownsResetEachOther = new BooleanOptionItem(2021, "BomberCooldownsResetEachOther", false, TabGroup.ImpostorRoles) .SetParent(BomberCanKill); + BombCooldown = new FloatOptionItem(2030, "BombCooldown", new(5f, 180f, 2.5f), 40f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bomber]) .SetValueFormat(OptionFormat.Seconds); + ImpostorsSurviveBombs = new BooleanOptionItem(2031, "ImpostorsSurviveBombs", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bomber]); + BomberDiesInExplosion = new BooleanOptionItem(2032, "BomberDiesInExplosion", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bomber]); + NukerChance = new IntegerOptionItem(2033, "NukerChance", new(0, 100, 5), 5, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bomber]) .SetValueFormat(OptionFormat.Percent); + NukeCooldown = new FloatOptionItem(2035, "NukeCooldown", new(5f, 180f, 2.5f), 60f, TabGroup.ImpostorRoles) .SetParent(NukerChance) .SetValueFormat(OptionFormat.Seconds); + NukeRadius = new FloatOptionItem(2034, "NukeRadius", new(5f, 100f, 1f), 10f, TabGroup.ImpostorRoles) .SetParent(NukerChance) .SetValueFormat(OptionFormat.Multiplier); @@ -81,43 +91,29 @@ namespace EHR.Impostor try { if (UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = IsNuker ? NukeCooldown.GetFloat() : BombCooldown.GetFloat(); - } else { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.ShapeshifterCooldown = IsNuker ? NukeCooldown.GetFloat() : BombCooldown.GetFloat(); AURoleOptions.ShapeshifterDuration = 2f; } } - catch - { - } + catch { } } public override void SetButtonTexts(HudManager hud, byte id) { if (UsePets.GetBool()) - { hud.PetButton?.OverrideText(Translator.GetString("BomberShapeshiftText")); - } else - { hud.AbilityButton?.OverrideText(Translator.GetString("BomberShapeshiftText")); - } } public override void OnMurder(PlayerControl killer, PlayerControl target) { - if (CooldownsResetEachOther.GetBool()) - { - killer.RpcResetAbilityCooldown(); - } + if (CooldownsResetEachOther.GetBool()) killer.RpcResetAbilityCooldown(); } public override void OnPet(PlayerControl pc) @@ -127,10 +123,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; Bomb(shapeshifter); @@ -149,30 +142,19 @@ namespace EHR.Impostor CustomSoundsManager.RPCPlayCustomSoundAll("Boom"); float radius = IsNuker ? NukeRadius.GetFloat() : BomberRadius.GetFloat(); + foreach (PlayerControl tg in Main.AllPlayerControls) { - if (!tg.IsModClient()) - { - tg.KillFlash(); - } + if (!tg.IsModClient()) tg.KillFlash(); Vector2 pos = pc.Pos(); float dis = Vector2.Distance(pos, tg.Pos()); - if (!tg.IsAlive() || Pelican.IsEaten(tg.PlayerId) || Medic.ProtectList.Contains(tg.PlayerId) || (tg.Is(CustomRoleTypes.Impostor) && ImpostorsSurviveBombs.GetBool()) || tg.inVent || tg.Is(CustomRoles.Pestilence)) - { - continue; - } + if (!tg.IsAlive() || Pelican.IsEaten(tg.PlayerId) || Medic.ProtectList.Contains(tg.PlayerId) || (tg.Is(CustomRoleTypes.Impostor) && ImpostorsSurviveBombs.GetBool()) || tg.inVent || tg.Is(CustomRoles.Pestilence)) continue; - if (dis > radius) - { - continue; - } + if (dis > radius) continue; - if (tg.PlayerId == pc.PlayerId) - { - continue; - } + if (tg.PlayerId == pc.PlayerId) continue; tg.Suicide(PlayerState.DeathReason.Bombed, pc); } @@ -180,18 +162,12 @@ namespace EHR.Impostor LateTask.New(() => { int totalAlive = Main.AllAlivePlayerControls.Length; - if (BomberDiesInExplosion.GetBool() && totalAlive > 1 && !GameStates.IsEnded) - { - pc.Suicide(PlayerState.DeathReason.Bombed); - } + if (BomberDiesInExplosion.GetBool() && totalAlive > 1 && !GameStates.IsEnded) pc.Suicide(PlayerState.DeathReason.Bombed); Utils.NotifyRoles(ForceLoop: true); }, 1.5f, "Bomber Suiscide"); - if (CooldownsResetEachOther.GetBool() && BomberCanKill.GetBool()) - { - pc.SetKillCooldown(); - } + if (CooldownsResetEachOther.GetBool() && BomberCanKill.GetBool()) pc.SetKillCooldown(); } } } \ No newline at end of file diff --git a/Roles/Impostor/BoobyTrap.cs b/Roles/Impostor/BoobyTrap.cs index d87f22094..2f6142708 100644 --- a/Roles/Impostor/BoobyTrap.cs +++ b/Roles/Impostor/BoobyTrap.cs @@ -19,11 +19,14 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(16500, TabGroup.ImpostorRoles, CustomRoles.BoobyTrap); + BtKillCooldown = new FloatOptionItem(16510, "KillCooldown", new(2.5f, 180f, 2.5f), 20f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.BoobyTrap]) .SetValueFormat(OptionFormat.Seconds); + TrapOnlyWorksOnTheBodyBoobyTrap = new BooleanOptionItem(16511, "TrapOnlyWorksOnTheBodyBoobyTrap", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.BoobyTrap]); + TrapConsecutiveBodies = new BooleanOptionItem(16512, "TrapConsecutiveBodies", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.BoobyTrap]); } @@ -47,10 +50,7 @@ namespace EHR.Impostor public override bool OnCheckMurderAsTarget(PlayerControl killer, PlayerControl target) { - if (TrapOnlyWorksOnTheBodyBoobyTrap.GetBool() && !GameStates.IsMeeting) - { - BoobyTrapBody.Add(target.PlayerId); - } + if (TrapOnlyWorksOnTheBodyBoobyTrap.GetBool() && !GameStates.IsMeeting) BoobyTrapBody.Add(target.PlayerId); return true; } @@ -59,15 +59,9 @@ namespace EHR.Impostor { if (!TrapOnlyWorksOnTheBodyBoobyTrap.GetBool() && killer != target) { - if (!BoobyTrapBody.Contains(target.PlayerId)) - { - BoobyTrapBody.Add(target.PlayerId); - } + if (!BoobyTrapBody.Contains(target.PlayerId)) BoobyTrapBody.Add(target.PlayerId); - if (!KillerOfBoobyTrapBody.ContainsKey(target.PlayerId)) - { - KillerOfBoobyTrapBody.Add(target.PlayerId, killer.PlayerId); - } + if (!KillerOfBoobyTrapBody.ContainsKey(target.PlayerId)) KillerOfBoobyTrapBody.Add(target.PlayerId, killer.PlayerId); killer.Suicide(); } @@ -84,10 +78,7 @@ namespace EHR.Impostor reporter.Suicide(PlayerState.DeathReason.Trapped, Utils.GetPlayerById(killerID)); RPC.PlaySoundRPC(killerID, Sounds.KillSound); - if (!BoobyTrapBody.Contains(reporter.PlayerId) && TrapConsecutiveBodies.GetBool()) - { - BoobyTrapBody.Add(reporter.PlayerId); - } + if (!BoobyTrapBody.Contains(reporter.PlayerId) && TrapConsecutiveBodies.GetBool()) BoobyTrapBody.Add(reporter.PlayerId); KillerOfBoobyTrapBody.TryAdd(reporter.PlayerId, killerID); return false; diff --git a/Roles/Impostor/BountyHunter.cs b/Roles/Impostor/BountyHunter.cs index d503d0ff6..a92f54f73 100644 --- a/Roles/Impostor/BountyHunter.cs +++ b/Roles/Impostor/BountyHunter.cs @@ -32,15 +32,19 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.BountyHunter); + OptionTargetChangeTime = new FloatOptionItem(Id + 10, "BountyTargetChangeTime", new(10f, 180f, 2.5f), 50f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.BountyHunter]) .SetValueFormat(OptionFormat.Seconds); + OptionSuccessKillCooldown = new FloatOptionItem(Id + 11, "BountySuccessKillCooldown", new(0f, 180f, 0.5f), 3f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.BountyHunter]) .SetValueFormat(OptionFormat.Seconds); + OptionFailureKillCooldown = new FloatOptionItem(Id + 12, "BountyFailureKillCooldown", new(0f, 180f, 2.5f), 35f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.BountyHunter]) .SetValueFormat(OptionFormat.Seconds); + OptionShowTargetArrow = new BooleanOptionItem(Id + 13, "BountyShowTargetArrow", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.BountyHunter]); } @@ -70,18 +74,12 @@ namespace EHR.Impostor Target = byte.MaxValue; ChangeTimer = TargetChangeTime; - if (AmongUsClient.Instance.AmHost) - { - ResetTarget(Utils.GetPlayerById(playerId)); - } + if (AmongUsClient.Instance.AmHost) ResetTarget(Utils.GetPlayerById(playerId)); } private void SendRPC() { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetBountyTarget, SendOption.Reliable); writer.Write(BountyId); @@ -96,10 +94,7 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null) - { - return false; - } + if (killer == null || target == null) return false; if (GetTarget(killer) == target.PlayerId) { @@ -125,18 +120,14 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl player) { - if (!GameStates.IsInTask || float.IsNaN(ChangeTimer)) - { - return; - } + if (!GameStates.IsInTask || float.IsNaN(ChangeTimer)) return; if (!player.IsAlive()) - { ChangeTimer = float.NaN; - } else { byte targetId = GetTarget(player); + if (ChangeTimer >= TargetChangeTime) { byte newTargetId = ResetTarget(player); @@ -148,10 +139,7 @@ namespace EHR.Impostor ChangeTimer += Time.fixedDeltaTime; int tempTimer = Timer; Timer = (int)(TargetChangeTime - ChangeTimer); - if (tempTimer != Timer && Timer <= 15 && !player.IsModClient()) - { - Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); - } + if (tempTimer != Timer && Timer <= 15 && !player.IsModClient()) Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); } if (Utils.GetPlayerById(targetId)?.IsAlive() == false) @@ -165,10 +153,7 @@ namespace EHR.Impostor public byte GetTarget(PlayerControl player) { - if (player == null) - { - return 0xff; - } + if (player == null) return 0xff; byte targetId = Target == byte.MaxValue ? ResetTarget(player) : Target; return targetId; @@ -176,10 +161,7 @@ namespace EHR.Impostor private byte ResetTarget(PlayerControl player) { - if (!AmongUsClient.Instance.AmHost) - { - return 0xff; - } + if (!AmongUsClient.Instance.AmHost) return 0xff; byte playerId = player.PlayerId; @@ -190,10 +172,7 @@ namespace EHR.Impostor List cTargets = new(Main.AllAlivePlayerControls.Where(pc => !pc.Is(CustomRoleTypes.Impostor))); - if (cTargets.Count >= 2 && Target != byte.MaxValue) - { - cTargets.RemoveAll(x => x.PlayerId == Target); - } + if (cTargets.Count >= 2 && Target != byte.MaxValue) cTargets.RemoveAll(x => x.PlayerId == Target); if (cTargets.Count == 0) { @@ -204,10 +183,7 @@ namespace EHR.Impostor PlayerControl target = cTargets.RandomElement(); byte targetId = target.PlayerId; Target = targetId; - if (ShowTargetArrow) - { - TargetArrow.Add(playerId, targetId); - } + if (ShowTargetArrow) TargetArrow.Add(playerId, targetId); Logger.Info($"{player.GetNameWithRole().RemoveHtmlTags()}'s New Target Is {target.GetNameWithRole().RemoveHtmlTags()}", "BountyHunter"); @@ -223,6 +199,7 @@ namespace EHR.Impostor { ChangeTimer = 0f; Timer = (int)TargetChangeTime; + if (Utils.GetPlayerById(id).GetCustomRole() == CustomRoles.BountyHunter) { Main.AllPlayerKillCooldown[id] = Options.DefaultKillCooldown; @@ -239,15 +216,9 @@ namespace EHR.Impostor private static string GetTargetText(PlayerControl bounty, PlayerControl tar, bool hud) { - if (GameStates.IsMeeting || bounty.PlayerId != tar.PlayerId) - { - return string.Empty; - } + if (GameStates.IsMeeting || bounty.PlayerId != tar.PlayerId) return string.Empty; - if (Main.PlayerStates[bounty.PlayerId].Role is not BountyHunter bh) - { - return string.Empty; - } + if (Main.PlayerStates[bounty.PlayerId].Role is not BountyHunter bh) return string.Empty; byte targetId = bh.GetTarget(bounty); return targetId != 0xff ? $"{(hud ? GetString("BountyCurrentTarget") : GetString("Target"))}: {Main.AllPlayerNames[targetId].RemoveHtmlTags().Replace("\r\n", string.Empty)}" : string.Empty; @@ -255,20 +226,11 @@ namespace EHR.Impostor private static string GetTargetArrow(PlayerControl seer, PlayerControl target = null) { - if (target != null && seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (target != null && seer.PlayerId != target.PlayerId) return string.Empty; - if (!ShowTargetArrow || GameStates.IsMeeting) - { - return string.Empty; - } + if (!ShowTargetArrow || GameStates.IsMeeting) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is not BountyHunter bh) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not BountyHunter bh) return string.Empty; byte targetId = bh.GetTarget(seer); return $" {TargetArrow.GetArrows(seer, targetId)}"; diff --git a/Roles/Impostor/Camouflager.cs b/Roles/Impostor/Camouflager.cs index 1311996f3..1e4cdff61 100644 --- a/Roles/Impostor/Camouflager.cs +++ b/Roles/Impostor/Camouflager.cs @@ -20,18 +20,23 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupSingleRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Camouflager); + CamouflageCooldown = new FloatOptionItem(Id + 2, "CamouflageCooldown", new(1f, 60f, 1f), 25f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Camouflager]) .SetValueFormat(OptionFormat.Seconds); + CamouflageDuration = new FloatOptionItem(Id + 3, "CamouflageDuration", new(1f, 30f, 1f), 12f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Camouflager]) .SetValueFormat(OptionFormat.Seconds); + CamoLimitOpt = new IntegerOptionItem(Id + 4, "AbilityUseLimit", new(0, 5, 1), 1, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Camouflager]) .SetValueFormat(OptionFormat.Times); + AbilityUseGainWithEachKill = new FloatOptionItem(Id + 5, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 0.3f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Camouflager]) .SetValueFormat(OptionFormat.Times); + DoesntSpawnOnFungle = new BooleanOptionItem(Id + 6, "DoesntSpawnOnFungle", false, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Camouflager]); } @@ -39,9 +44,7 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte id) { if (Options.UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = CamouflageCooldown.GetFloat(); - } else { AURoleOptions.ShapeshifterCooldown = CamouflageCooldown.GetFloat(); @@ -72,10 +75,7 @@ namespace EHR.Impostor return true; } - if (pc.GetAbilityUseLimit() < 1 && !Options.DisableShapeshiftAnimations.GetBool() && !unshift) - { - pc.SetKillCooldown(CamouflageDuration.GetFloat() + 1f); - } + if (pc.GetAbilityUseLimit() < 1 && !Options.DisableShapeshiftAnimations.GetBool() && !unshift) pc.SetKillCooldown(CamouflageDuration.GetFloat() + 1f); pc.RpcRemoveAbilityUse(); IsActive = true; @@ -85,10 +85,7 @@ namespace EHR.Impostor { LateTask.New(() => { - if (!IsActive) - { - return; - } + if (!IsActive) return; IsActive = false; Camouflage.CheckCamouflage(); diff --git a/Roles/Impostor/Cantankerous.cs b/Roles/Impostor/Cantankerous.cs index abe9a095e..4359ba6a4 100644 --- a/Roles/Impostor/Cantankerous.cs +++ b/Roles/Impostor/Cantankerous.cs @@ -17,12 +17,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Cantankerous); + KCD = new FloatOptionItem(Id + 5, "KillCooldown", new(0f, 60f, 2.5f), 22.5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Cantankerous]) .SetValueFormat(OptionFormat.Seconds); + PointsGainedPerEjection = new IntegerOptionItem(Id + 6, "CantankerousPointsGainedPerEjection", new(1, 5, 1), 2, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Cantankerous]) .SetValueFormat(OptionFormat.Times); + StartingPoints = new IntegerOptionItem(Id + 7, "CantankerousStartingPoints", new(0, 5, 1), 1, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Cantankerous]) .SetValueFormat(OptionFormat.Times); @@ -52,26 +55,17 @@ namespace EHR.Impostor public static void OnCrewmateEjected() { int value = PointsGainedPerEjection.GetInt(); + foreach (KeyValuePair state in Main.PlayerStates) - { if (state.Value.Role is Cantankerous) - { Utils.GetPlayerById(state.Key).RpcIncreaseAbilityUseLimitBy(value); - } - } } public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!base.OnCheckMurder(killer, target)) - { - return false; - } + if (!base.OnCheckMurder(killer, target)) return false; - if (killer.GetAbilityUseLimit() <= 0) - { - return false; - } + if (killer.GetAbilityUseLimit() <= 0) return false; killer.RpcRemoveAbilityUse(); diff --git a/Roles/Impostor/Capitalism.cs b/Roles/Impostor/Capitalism.cs index d1a50ae77..1ce92d959 100644 --- a/Roles/Impostor/Capitalism.cs +++ b/Roles/Impostor/Capitalism.cs @@ -13,9 +13,11 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(16600, TabGroup.ImpostorRoles, CustomRoles.Capitalism); + CapitalismSkillCooldown = new FloatOptionItem(16610, "CapitalismSkillCooldown", new(0f, 60f, 1f), 10f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Capitalism]) .SetValueFormat(OptionFormat.Seconds); + CapitalismKillCooldown = new FloatOptionItem(16611, "KillCooldown", new(2.5f, 60f, 2.5f), 25f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Capitalism]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/Impostor/Changeling.cs b/Roles/Impostor/Changeling.cs index 0782d6ca5..6c5d3eb25 100644 --- a/Roles/Impostor/Changeling.cs +++ b/Roles/Impostor/Changeling.cs @@ -57,10 +57,7 @@ namespace EHR.Impostor _ => allRoles }; - if (!CanPickPartnerRole.GetBool() && !check) - { - result = result.Where(x => !CustomRoleSelector.RoleResult.ContainsValue(x)); - } + if (!CanPickPartnerRole.GetBool() && !check) result = result.Where(x => !CustomRoleSelector.RoleResult.ContainsValue(x)); List rolesList = result.ToList(); rolesList.Remove(CustomRoles.Changeling); @@ -78,6 +75,7 @@ namespace EHR.Impostor On = true; ChangelingId = playerId; ChangedRole[playerId] = false; + try { CurrentRole = Roles.First(); @@ -127,11 +125,9 @@ namespace EHR.Impostor shapeshifter.RpcSetCustomRole(CurrentRole); ChangedRole[shapeshifter.PlayerId] = true; shapeshifter.RpcResetAbilityCooldown(); - if (!DisableShapeshiftAnimations.GetBool()) - { - LateTask.New(() => { shapeshifter.RpcShapeshift(shapeshifter, false); }, 1f, log: false); - } + if (!DisableShapeshiftAnimations.GetBool()) LateTask.New(() => { shapeshifter.RpcShapeshift(shapeshifter, false); }, 1f, log: false); }, 0.3f, log: false); + return false; } diff --git a/Roles/Impostor/Chronomancer.cs b/Roles/Impostor/Chronomancer.cs index 89fca5a72..b8d80ac98 100644 --- a/Roles/Impostor/Chronomancer.cs +++ b/Roles/Impostor/Chronomancer.cs @@ -23,12 +23,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Chronomancer); + KCD = new FloatOptionItem(Id + 11, "KillCooldown", new(0f, 180f, 2.5f), 25f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Chronomancer]) .SetValueFormat(OptionFormat.Seconds); + ChargeInterval = new IntegerOptionItem(Id + 12, "ChargeInterval", new(1, 20, 1), 5, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Chronomancer]) .SetValueFormat(OptionFormat.Percent); + ChargeLossInterval = new IntegerOptionItem(Id + 13, "ChargeLossInterval", new(1, 50, 1), 25, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Chronomancer]) .SetValueFormat(OptionFormat.Percent); @@ -36,10 +39,7 @@ namespace EHR.Impostor private void SendRPC() { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncChronomancer, SendOption.Reliable); writer.Write(ChronomancerId); @@ -81,10 +81,7 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (ChargePercent <= 0) - { - return base.OnCheckMurder(killer, target); - } + if (ChargePercent <= 0) return base.OnCheckMurder(killer, target); if (!IsRampaging) { @@ -99,34 +96,23 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl pc) { - if (pc == null) - { - return; - } + if (pc == null) return; - if (!pc.Is(CustomRoles.Chronomancer)) - { - return; - } + if (!pc.Is(CustomRoles.Chronomancer)) return; - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; - if (LastUpdate >= Utils.TimeStamp) - { - return; - } + if (LastUpdate >= Utils.TimeStamp) return; LastUpdate = Utils.TimeStamp; - bool notify = false; + var notify = false; int beforeCharge = ChargePercent; if (IsRampaging) { ChargePercent -= ChargeLossInterval.GetInt(); + if (ChargePercent <= 0) { ChargePercent = 0; @@ -141,31 +127,19 @@ namespace EHR.Impostor else if (Main.KillTimers[pc.PlayerId] <= 0 && !MeetingStates.FirstMeeting) { ChargePercent += ChargeInterval.GetInt(); - if (ChargePercent > 100) - { - ChargePercent = 100; - } + if (ChargePercent > 100) ChargePercent = 100; notify = true; } - if (notify && !pc.IsModClient()) - { - pc.Notify(string.Format(Translator.GetString("ChronomancerPercent"), ChargePercent), 300f); - } + if (notify && !pc.IsModClient()) pc.Notify(string.Format(Translator.GetString("ChronomancerPercent"), ChargePercent), 300f); - if (beforeCharge != ChargePercent && pc.IsModClient() && !pc.IsHost()) - { - SendRPC(); - } + if (beforeCharge != ChargePercent && pc.IsModClient() && !pc.IsHost()) SendRPC(); } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (!hud || seer.PlayerId != ChronomancerId) - { - return string.Empty; - } + if (!hud || seer.PlayerId != ChronomancerId) return string.Empty; return ChargePercent > 0 ? string.Format(Translator.GetString("ChronomancerPercent"), ChargePercent) : string.Empty; } diff --git a/Roles/Impostor/Cleaner.cs b/Roles/Impostor/Cleaner.cs index cc6c90a97..b3bd39475 100644 --- a/Roles/Impostor/Cleaner.cs +++ b/Roles/Impostor/Cleaner.cs @@ -25,12 +25,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(2600, TabGroup.ImpostorRoles, CustomRoles.Cleaner); + CleanerKillCooldown = new FloatOptionItem(2610, "KillCooldown", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Cleaner]) .SetValueFormat(OptionFormat.Seconds); + KillCooldownAfterCleaning = new FloatOptionItem(2611, "KillCooldownAfterCleaning", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Cleaner]) .SetValueFormat(OptionFormat.Seconds); + CannotCleanWhenKCDIsntUp = new BooleanOptionItem(2612, "CannotCleanWhenKCDIsntUp", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Cleaner]); } @@ -87,17 +90,12 @@ namespace EHR.Impostor hud.ReportButton?.OverrideText(Translator.GetString("MedusaReportButtonText")); } else - { hud.ReportButton?.OverrideText(Translator.GetString("CleanerReportButtonText")); - } } public override bool CheckReportDeadBody(PlayerControl cleaner, NetworkedPlayerInfo target, PlayerControl killer) { - if (WaitForKCDUp && Main.KillTimers[cleaner.PlayerId] > 0f) - { - return true; - } + if (WaitForKCDUp && Main.KillTimers[cleaner.PlayerId] > 0f) return true; CleanerBodies.Remove(target.PlayerId); CleanerBodies.Add(target.PlayerId); diff --git a/Roles/Impostor/Commander.cs b/Roles/Impostor/Commander.cs index 4b7f92a55..6d736ba8f 100644 --- a/Roles/Impostor/Commander.cs +++ b/Roles/Impostor/Commander.cs @@ -26,8 +26,10 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Commander); + CannotSpawnAsSoloImp = new BooleanOptionItem(Id + 2, "CannotSpawnAsSoloImp", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Commander]); + ShapeshiftCooldown = new FloatOptionItem(Id + 3, "ShapeshiftCooldown", new(0f, 60f, 1f), 1f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Commander]); } @@ -80,10 +82,7 @@ namespace EHR.Impostor public override void OnCoEnterVent(PlayerPhysics physics, int ventId) { - if (!Options.UsePets.GetBool()) - { - CycleMode(physics.myPlayer); - } + if (!Options.UsePets.GetBool()) CycleMode(physics.myPlayer); } public override void OnPet(PlayerControl pc) @@ -100,10 +99,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting) - { - return true; - } + if (!shapeshifting) return true; switch (CurrentMode) { @@ -115,17 +111,12 @@ namespace EHR.Impostor break; case Mode.KillAnyone: if (target.Is(Team.Impostor)) - { target.Notify(Translator.GetString("CommanderKillAnyoneNotify"), 7f); - } else { foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (!pc.Is(Team.Impostor) || pc.PlayerId == shapeshifter.PlayerId) - { - continue; - } + if (!pc.Is(Team.Impostor) || pc.PlayerId == shapeshifter.PlayerId) continue; pc.Notify(Translator.GetString("CommanderKillAnyoneNotify"), 7f); } @@ -134,22 +125,15 @@ namespace EHR.Impostor break; case Mode.DontKillMark: if (target.Is(Team.Impostor)) - { target.Notify(Translator.GetString("CommanderDontKillAnyoneNotify"), 7f); - } else - { MarkPlayerAsDontKill(target); - } break; case Mode.DontSabotage: foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (!pc.Is(Team.Impostor) || pc.PlayerId == shapeshifter.PlayerId) - { - continue; - } + if (!pc.Is(Team.Impostor) || pc.PlayerId == shapeshifter.PlayerId) continue; pc.Notify(Translator.GetString("CommanderDontSabotageNotify"), 7f); } @@ -157,17 +141,12 @@ namespace EHR.Impostor break; case Mode.UseAbility: if (target.Is(Team.Impostor)) - { target.Notify(Translator.GetString("CommanderUseAbilityNotify"), 7f); - } else { foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (!pc.Is(Team.Impostor) || pc.PlayerId == shapeshifter.PlayerId) - { - continue; - } + if (!pc.Is(Team.Impostor) || pc.PlayerId == shapeshifter.PlayerId) continue; pc.Notify(Translator.GetString("CommanderUseAbilityNotify"), 7f); } @@ -181,10 +160,7 @@ namespace EHR.Impostor private void Whistle(PlayerControl commander, PlayerControl target = null) { - if (IsWhistling) - { - return; - } + if (IsWhistling) return; IsWhistling = true; @@ -196,10 +172,7 @@ namespace EHR.Impostor foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (!pc.Is(Team.Impostor) || pc.Is(CustomRoles.Commander)) - { - continue; - } + if (!pc.Is(Team.Impostor) || pc.Is(CustomRoles.Commander)) continue; AddArrowAndNotify(pc); } @@ -229,10 +202,7 @@ namespace EHR.Impostor private void MarkPlayerAsDontKill(PlayerControl target) { - if (target == null) - { - return; - } + if (target == null) return; DontKillMarks.Add(target.PlayerId); Utils.SendRPC(CustomRPC.SyncRoleData, CommanderId, 2, target.PlayerId); @@ -241,10 +211,7 @@ namespace EHR.Impostor public override void OnGlobalFixedUpdate(PlayerControl pc, bool lowLoad) { - if (lowLoad || !GameStates.IsInTask || !On || !IsWhistling) - { - return; - } + if (lowLoad || !GameStates.IsInTask || !On || !IsWhistling) return; if (TargetArrow.GetArrows(pc, CommanderId) == "・") { @@ -270,17 +237,11 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer == null || !seer.Is(Team.Impostor)) - { - return string.Empty; - } + if (seer == null || !seer.Is(Team.Impostor)) return string.Empty; if (seer.PlayerId == target.PlayerId && Main.PlayerStates[seer.PlayerId].Role is Commander { IsEnable: true } cm) { - if (seer.IsModClient() && !hud) - { - return string.Empty; - } + if (seer.IsModClient() && !hud) return string.Empty; string whistlingText = cm.IsWhistling ? $"\n{Translator.GetString("CommanderWhistling")}" : string.Empty; return $"{string.Format(Translator.GetString("WMMode"), Translator.GetString($"Commander{cm.CurrentMode}Mode"))}{whistlingText}"; @@ -292,19 +253,11 @@ namespace EHR.Impostor if (seer.PlayerId == target.PlayerId) { - if (arrowToCommander.Length > 0) - { - return $"{Translator.GetString("Commander")} {arrowToCommander}"; - } + if (arrowToCommander.Length > 0) return $"{Translator.GetString("Commander")} {arrowToCommander}"; } else if (isTargetTarget) - { return Utils.ColorString(Utils.GetRoleColor(CustomRoles.Sprayer), Translator.GetString("CommanderTarget")); - } - else if (isTargetDontKill) - { - return Utils.ColorString(ColorUtility.TryParseHtmlString("#0daeff", out Color color) ? color : Utils.GetRoleColor(CustomRoles.TaskManager), Translator.GetString("CommanderDontKill")); - } + else if (isTargetDontKill) return Utils.ColorString(ColorUtility.TryParseHtmlString("#0daeff", out Color color) ? color : Utils.GetRoleColor(CustomRoles.TaskManager), Translator.GetString("CommanderDontKill")); return string.Empty; } diff --git a/Roles/Impostor/Consort.cs b/Roles/Impostor/Consort.cs index 3cf5953bb..c9e6749e5 100644 --- a/Roles/Impostor/Consort.cs +++ b/Roles/Impostor/Consort.cs @@ -17,12 +17,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Consort); + CD = new FloatOptionItem(Id + 10, "RoleBlockCooldown", new(2.5f, 60f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Consort]) .SetValueFormat(OptionFormat.Seconds); + UseLimit = new IntegerOptionItem(Id + 11, "AbilityUseLimit", new(1, 20, 1), 3, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Consort]) .SetValueFormat(OptionFormat.Times); + Duration = new FloatOptionItem(Id + 12, "RoleBlockDuration", new(1f, 60f, 1f), 15f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Consort]) .SetValueFormat(OptionFormat.Seconds); @@ -41,15 +44,9 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!IsEnable || killer == null || target == null) - { - return false; - } + if (!IsEnable || killer == null || target == null) return false; - if (killer.GetAbilityUseLimit() <= 0 || !killer.Is(CustomRoles.Consort)) - { - return true; - } + if (killer.GetAbilityUseLimit() <= 0 || !killer.Is(CustomRoles.Consort)) return true; return killer.CheckDoubleTrigger(target, () => { diff --git a/Roles/Impostor/Councillor.cs b/Roles/Impostor/Councillor.cs index 308e934cf..5ee52edce 100644 --- a/Roles/Impostor/Councillor.cs +++ b/Roles/Impostor/Councillor.cs @@ -31,22 +31,29 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Councillor); + KillCooldown = new FloatOptionItem(Id + 15, "KillCooldown", new(0f, 180f, 2.5f), 25f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Councillor]) .SetValueFormat(OptionFormat.Seconds); + MurderLimitPerGame = new IntegerOptionItem(Id + 10, "AbilityUseLimit", new(0, 15, 1), 0, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Councillor]) .SetValueFormat(OptionFormat.Times); + MurderLimitPerMeeting = new IntegerOptionItem(Id + 14, "MurderLimitPerMeeting", new(0, 5, 1), 1, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Councillor]) .SetValueFormat(OptionFormat.Times); + CanMurderMadmate = new BooleanOptionItem(Id + 12, "CouncillorCanMurderMadmate", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Councillor]); + CanMurderImpostor = new BooleanOptionItem(Id + 16, "CouncillorCanMurderImpostor", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Councillor]); + TryHideMsg = new BooleanOptionItem(Id + 11, "CouncillorTryHideMsg", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Councillor]) .SetColor(Color.green); + CouncillorAbilityUseGainWithEachKill = new FloatOptionItem(Id + 17, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 0.2f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Councillor]) .SetValueFormat(OptionFormat.Times); @@ -75,35 +82,21 @@ namespace EHR.Impostor { string originMsg = msg; - if (!AmongUsClient.Instance.AmHost) - { - return false; - } + if (!AmongUsClient.Instance.AmHost) return false; - if (!GameStates.IsInGame || pc == null) - { - return false; - } + if (!GameStates.IsInGame || pc == null) return false; - if (!pc.Is(CustomRoles.Councillor)) - { - return false; - } + if (!pc.Is(CustomRoles.Councillor)) return false; int operate; // 1:ID 2:Kill msg = msg.ToLower().TrimStart().TrimEnd(); + if (CheckCommond(ref msg, "id|guesslist|gl编号|玩家编号|玩家id|id列表|玩家列表|列表|所有id|全部id")) - { operate = 1; - } else if (CheckCommond(ref msg, "shoot|guess|bet|st|gs|bt|猜|赌|sp|jj|tl|审判|判|审", false)) - { operate = 2; - } else - { return false; - } if (!pc.IsAlive()) { @@ -119,13 +112,8 @@ namespace EHR.Impostor case 2: { if (TryHideMsg.GetBool()) - { ChatManager.SendPreviousMessagesToAll(); - } - else if (pc.AmOwner) - { - Utils.SendMessage(originMsg, 255, pc.GetRealName()); - } + else if (pc.AmOwner) Utils.SendMessage(originMsg, 255, pc.GetRealName()); if (!MsgToPlayerAndRole(msg, out byte targetId, out string error)) { @@ -134,20 +122,18 @@ namespace EHR.Impostor } PlayerControl target = Utils.GetPlayerById(targetId); + if (target != null) { Logger.Info($"{pc.GetNameWithRole().RemoveHtmlTags()} murdered {target.GetNameWithRole().RemoveHtmlTags()}", "Councillor"); - bool CouncillorSuicide = true; + var CouncillorSuicide = true; + if (pc.GetAbilityUseLimit() < 1) { if (!isUI) - { Utils.SendMessage(GetString("CouncillorMurderMax"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("CouncillorMurderMax")); - } return true; } @@ -155,13 +141,9 @@ namespace EHR.Impostor if (MeetingKillLimit[pc.PlayerId] < 1) { if (!isUI) - { Utils.SendMessage(GetString("CouncillorMurderMaxMeeting"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("CouncillorMurderMaxMeeting")); - } return true; } @@ -169,67 +151,39 @@ namespace EHR.Impostor if (Jailor.PlayerIdList.Any(x => Main.PlayerStates[x].Role is Jailor { IsEnable: true } jl && jl.JailorTarget == targetId)) { if (!isUI) - { Utils.SendMessage(GetString("CanNotTrialJailed"), pc.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Jailor), GetString("JailorTitle"))); - } else - { pc.ShowPopUp(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Jailor), GetString("JailorTitle")) + "\n" + GetString("CanNotTrialJailed")); - } return true; } - bool NoSuicide = false; + var NoSuicide = false; if (pc.PlayerId == targetId) { if (!isUI) - { Utils.SendMessage(GetString("LaughToWhoMurderSelf"), pc.PlayerId, Utils.ColorString(Color.cyan, GetString("MessageFromKPD"))); - } else - { pc.ShowPopUp(Utils.ColorString(Color.cyan, GetString("MessageFromKPD")) + "\n" + GetString("LaughToWhoMurderSelf")); - } } else if (target.IsMadmate() && CanMurderMadmate.GetBool()) - { CouncillorSuicide = false; - } else if (target.Is(CustomRoles.SuperStar)) - { NoSuicide = true; - } else if (target.Is(CustomRoles.Snitch) && target.AllTasksCompleted()) - { NoSuicide = true; - } else if (target.Is(CustomRoles.Guardian) && target.AllTasksCompleted()) - { NoSuicide = true; - } else if (target.Is(CustomRoles.Merchant) && Merchant.IsBribedKiller(pc, target)) - { NoSuicide = true; - } else if (target.IsImpostor() && CanMurderImpostor.GetBool()) - { CouncillorSuicide = false; - } else if (target.IsCrewmate()) - { CouncillorSuicide = false; - } - else if (target.GetCustomRole().IsNeutral() && !target.Is(CustomRoles.Pestilence)) - { - CouncillorSuicide = false; - } + else if (target.GetCustomRole().IsNeutral() && !target.Is(CustomRoles.Pestilence)) CouncillorSuicide = false; - if (NoSuicide) - { - return true; - } + if (NoSuicide) return true; PlayerControl dp = CouncillorSuicide ? pc : target; @@ -246,7 +200,7 @@ namespace EHR.Impostor Utils.AfterPlayerDeathTasks(dp, true); - Utils.NotifyRoles(false, NoCache: true); + Utils.NotifyRoles(NoCache: true); LateTask.New(() => Utils.SendMessage(string.Format(GetString("MurderKill"), Name), 255, Utils.ColorString(Utils.GetRoleColor(CustomRoles.NiceGuesser), GetString("MurderKillTitle"))), 0.6f, "Guess Msg"); }, 0.2f, "Murder Kill"); @@ -261,23 +215,15 @@ namespace EHR.Impostor private static bool MsgToPlayerAndRole(string msg, out byte id, out string error) { - if (msg.StartsWith("/")) - { - msg = msg.Replace("/", string.Empty); - } + if (msg.StartsWith("/")) msg = msg.Replace("/", string.Empty); Regex r = new("\\d+"); MatchCollection mc = r.Matches(msg); - string result = string.Empty; - for (int i = 0; i < mc.Count; i++) - { - result += mc[i]; - } + var result = string.Empty; + for (var i = 0; i < mc.Count; i++) result += mc[i]; if (int.TryParse(result, out int num)) - { id = Convert.ToByte(num); - } else { id = byte.MaxValue; @@ -286,6 +232,7 @@ namespace EHR.Impostor } PlayerControl target = Utils.GetPlayerById(id); + if (target == null || target.Data.IsDead) { error = GetString("MurderNull"); @@ -304,14 +251,12 @@ namespace EHR.Impostor public static bool CheckCommond(ref string msg, string command, bool exact = true) { string[] comList = command.Split('|'); + foreach (string str in comList) { if (exact) { - if (msg == "/" + str) - { - return true; - } + if (msg == "/" + str) return true; } else { @@ -328,10 +273,7 @@ namespace EHR.Impostor private static void SendRPC(byte playerId) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.MeetingKill, SendOption.Reliable); writer.Write(playerId); @@ -348,19 +290,12 @@ namespace EHR.Impostor { Logger.Msg($"Click: ID {playerId}", "Councillor UI"); PlayerControl pc = Utils.GetPlayerById(playerId); - if (pc == null || !pc.IsAlive() || !GameStates.IsVoting) - { - return; - } + if (pc == null || !pc.IsAlive() || !GameStates.IsVoting) return; if (AmongUsClient.Instance.AmHost) - { MurderMsg(PlayerControl.LocalPlayer, $"/tl {playerId}", true); - } else - { SendRPC(playerId); - } } public static void CreateCouncillorButton(MeetingHud __instance) @@ -368,18 +303,15 @@ namespace EHR.Impostor foreach (PlayerVoteArea pva in __instance.playerStates.ToArray()) { PlayerControl pc = Utils.GetPlayerById(pva.TargetPlayerId); - if (pc == null || !pc.IsAlive()) - { - continue; - } + if (pc == null || !pc.IsAlive()) continue; GameObject template = pva.Buttons.transform.Find("CancelButton").gameObject; GameObject targetBox = Object.Instantiate(template, pva.transform); targetBox.name = "ShootButton"; targetBox.transform.localPosition = new(-0.35f, 0.03f, -1.31f); - SpriteRenderer renderer = targetBox.GetComponent(); + var renderer = targetBox.GetComponent(); renderer.sprite = CustomButton.Get("MeetingKillButton"); - PassiveButton button = targetBox.GetComponent(); + var button = targetBox.GetComponent(); button.OnClick.RemoveAllListeners(); button.OnClick.AddListener((Action)(() => CouncillorOnClick(pva.TargetPlayerId /*, __instance*/))); } @@ -390,10 +322,7 @@ namespace EHR.Impostor { public static void Postfix(MeetingHud __instance) { - if (PlayerControl.LocalPlayer.Is(CustomRoles.Councillor) && PlayerControl.LocalPlayer.IsAlive()) - { - CreateCouncillorButton(__instance); - } + if (PlayerControl.LocalPlayer.Is(CustomRoles.Councillor) && PlayerControl.LocalPlayer.IsAlive()) CreateCouncillorButton(__instance); } } } diff --git a/Roles/Impostor/Crewpostor.cs b/Roles/Impostor/Crewpostor.cs index 4cba8059b..0f02863a9 100644 --- a/Roles/Impostor/Crewpostor.cs +++ b/Roles/Impostor/Crewpostor.cs @@ -17,16 +17,22 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(4800, TabGroup.ImpostorRoles, CustomRoles.Crewpostor); + CrewpostorCanKillAllies = new BooleanOptionItem(4810, "CanKillAllies", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Crewpostor]); + CrewpostorKnowsAllies = new BooleanOptionItem(4811, "CrewpostorKnowsAllies", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Crewpostor]); + AlliesKnowCrewpostor = new BooleanOptionItem(4812, "AlliesKnowCrewpostor", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Crewpostor]); + CrewpostorLungeKill = new BooleanOptionItem(4813, "CrewpostorLungeKill", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Crewpostor]); + CrewpostorKillAfterTask = new IntegerOptionItem(4814, "CrewpostorKillAfterTask", new(1, 50, 1), 1, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Crewpostor]); + OverrideTasksData.Create(4815, TabGroup.ImpostorRoles, CustomRoles.Crewpostor); } @@ -38,31 +44,27 @@ namespace EHR.Impostor public override void OnTaskComplete(PlayerControl player, int completedTaskCount, int totalTaskCount) { - if (!TasksDone.TryAdd(player.PlayerId, 0)) - { - TasksDone[player.PlayerId]++; - } + if (!TasksDone.TryAdd(player.PlayerId, 0)) TasksDone[player.PlayerId]++; SendRPC(player.PlayerId, TasksDone[player.PlayerId]); PlayerControl[] list = Main.AllAlivePlayerControls.Where(x => x.PlayerId != player.PlayerId && (CrewpostorCanKillAllies.GetBool() || !x.GetCustomRole().IsImpostorTeam())).ToArray(); + if (list.Length == 0) - { Logger.Info("No target to kill", "Crewpostor"); - } else if (TasksDone[player.PlayerId] % CrewpostorKillAfterTask.GetInt() != 0 && TasksDone[player.PlayerId] != 0) - { Logger.Info($"Crewpostor task done but kill skipped, {TasksDone[player.PlayerId]} tasks completed, but it kills after {CrewpostorKillAfterTask.GetInt()} tasks", "Crewpostor"); - } else { list = [.. list.OrderBy(x => Vector2.Distance(player.Pos(), x.Pos()))]; PlayerControl target = list[0]; + if (!target.Is(CustomRoles.Pestilence)) { if (!CrewpostorLungeKill.GetBool()) { target.SetRealKiller(player); + if (player.RpcCheckAndMurder(target, true)) { target.Suicide(PlayerState.DeathReason.Kill, player); @@ -105,10 +107,7 @@ namespace EHR.Impostor { if (PlayerControl.LocalPlayer.PlayerId == cpID) { - if (!TasksDone.TryAdd(cpID, 0)) - { - TasksDone[cpID] = tasksDone; - } + if (!TasksDone.TryAdd(cpID, 0)) TasksDone[cpID] = tasksDone; } else { @@ -123,10 +122,7 @@ namespace EHR.Impostor { byte PlayerId = reader.ReadByte(); int tasksDone = reader.ReadInt32(); - if (!TasksDone.TryAdd(PlayerId, 0)) - { - TasksDone[PlayerId] = tasksDone; - } + if (!TasksDone.TryAdd(PlayerId, 0)) TasksDone[PlayerId] = tasksDone; } public override void Init() diff --git a/Roles/Impostor/CursedWolf.cs b/Roles/Impostor/CursedWolf.cs index 2e9692c5e..103879797 100644 --- a/Roles/Impostor/CursedWolf.cs +++ b/Roles/Impostor/CursedWolf.cs @@ -17,9 +17,11 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(1000, TabGroup.ImpostorRoles, CustomRoles.CursedWolf); // From TOH_Y + Options.GuardSpellTimes = new IntegerOptionItem(1010, "GuardSpellTimes", new(1, 15, 1), 1, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.CursedWolf]) .SetValueFormat(OptionFormat.Times); + Options.killAttacker = new BooleanOptionItem(1011, "killAttacker", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.CursedWolf]); } @@ -68,20 +70,11 @@ namespace EHR.Impostor public override bool OnCheckMurderAsTarget(PlayerControl killer, PlayerControl target) { - if (target.GetAbilityUseLimit() <= 0) - { - return true; - } + if (target.GetAbilityUseLimit() <= 0) return true; - if (killer.Is(CustomRoles.Pestilence)) - { - return true; - } + if (killer.Is(CustomRoles.Pestilence)) return true; - if (killer == target) - { - return true; - } + if (killer == target) return true; float kcd = Main.KillTimers[target.PlayerId] + Main.AllPlayerKillCooldown[target.PlayerId]; diff --git a/Roles/Impostor/Dazzler.cs b/Roles/Impostor/Dazzler.cs index 47cb2cc84..32c27e839 100644 --- a/Roles/Impostor/Dazzler.cs +++ b/Roles/Impostor/Dazzler.cs @@ -25,20 +25,26 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Dazzler); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 2.5f), 25f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Dazzler]) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftCooldown = new FloatOptionItem(Id + 11, "DazzleCooldown", new(0f, 180f, 2.5f), 20f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Dazzler]) .SetValueFormat(OptionFormat.Seconds); + CauseVision = new FloatOptionItem(Id + 13, "DazzlerCauseVision", new(0f, 5f, 0.05f), 0.4f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Dazzler]) .SetValueFormat(OptionFormat.Multiplier); + DazzleLimitOpt = new IntegerOptionItem(Id + 14, "DazzlerDazzleLimit", new(0, 15, 1), 1, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Dazzler]) .SetValueFormat(OptionFormat.Times); + ResetDazzledVisionOnDeath = new BooleanOptionItem(Id + 15, "DazzlerResetDazzledVisionOnDeath", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Dazzler]); + DazzlerAbilityUseGainWithEachKill = new FloatOptionItem(Id + 16, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 0.5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Dazzler]) .SetValueFormat(OptionFormat.Times); @@ -70,10 +76,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl pc, PlayerControl target, bool shapeshifting) { - if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId) || !shapeshifting) - { - return false; - } + if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId) || !shapeshifting) return false; if (!PlayersDazzled.Contains(target.PlayerId) && PlayersDazzled.Count < pc.GetAbilityUseLimit()) { diff --git a/Roles/Impostor/Deathpact.cs b/Roles/Impostor/Deathpact.cs index de592ae5d..ddc3e2ba8 100644 --- a/Roles/Impostor/Deathpact.cs +++ b/Roles/Impostor/Deathpact.cs @@ -35,25 +35,33 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Deathpact); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 2.5f), 25f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Deathpact]) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftCooldown = new FloatOptionItem(Id + 11, "DeathPactCooldown", new(0f, 180f, 2.5f), 5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Deathpact]) .SetValueFormat(OptionFormat.Seconds); + DeathpactDuration = new FloatOptionItem(Id + 13, "DeathpactDuration", new(0f, 180f, 2.5f), 17.5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Deathpact]) .SetValueFormat(OptionFormat.Seconds); + NumberOfPlayersInPact = new IntegerOptionItem(Id + 14, "DeathpactNumberOfPlayersInPact", new(2, 5, 1), 2, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Deathpact]) .SetValueFormat(OptionFormat.Times); + ShowArrowsToOtherPlayersInPact = new BooleanOptionItem(Id + 15, "DeathpactShowArrowsToOtherPlayersInPact", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Deathpact]); + ReduceVisionWhileInPact = new BooleanOptionItem(Id + 16, "DeathpactReduceVisionWhileInPact", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Deathpact]); + VisionWhileInPact = new FloatOptionItem(Id + 17, "DeathpactVisionWhileInPact", new(0f, 5f, 0.05f), 0.4f, TabGroup.ImpostorRoles) .SetParent(ReduceVisionWhileInPact) .SetValueFormat(OptionFormat.Multiplier); + KillDeathpactPlayersOnMeeting = new BooleanOptionItem(Id + 18, "DeathpactKillPlayersInDeathpactOnMeeting", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Deathpact]); } @@ -88,10 +96,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl pc, PlayerControl target, bool shapeshifting) { - if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId) || !shapeshifting) - { - return false; - } + if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId) || !shapeshifting) return false; if (!target.IsAlive() || Pelican.IsEaten(target.PlayerId)) { @@ -99,15 +104,9 @@ namespace EHR.Impostor return false; } - if (PlayersInDeathpact.All(b => b.PlayerId != target.PlayerId)) - { - PlayersInDeathpact.Add(target); - } + if (PlayersInDeathpact.All(b => b.PlayerId != target.PlayerId)) PlayersInDeathpact.Add(target); - if (PlayersInDeathpact.Count < NumberOfPlayersInPact.GetInt()) - { - return false; - } + if (PlayersInDeathpact.Count < NumberOfPlayersInPact.GetInt()) return false; if (ReduceVisionWhileInPact.GetBool()) { @@ -142,15 +141,9 @@ namespace EHR.Impostor public static void SetDeathpactVision(PlayerControl player, IGameOptions opt) { - if (!ReduceVisionWhileInPact.GetBool()) - { - return; - } + if (!ReduceVisionWhileInPact.GetBool()) return; - if (Main.PlayerStates[player.PlayerId].Role is not Deathpact { IsEnable: true } dp) - { - return; - } + if (Main.PlayerStates[player.PlayerId].Role is not Deathpact { IsEnable: true } dp) return; if (dp.PlayersInDeathpact.Any(b => b.PlayerId == player.PlayerId) && dp.PlayersInDeathpact.Count == NumberOfPlayersInPact.GetInt()) { @@ -162,27 +155,15 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl player) { - if (!IsEnable || !GameStates.IsInTask || player.GetCustomRole() is not CustomRoles.Deathpact and not CustomRoles.Randomizer) - { - return; - } + if (!IsEnable || !GameStates.IsInTask || player.GetCustomRole() is not CustomRoles.Deathpact and not CustomRoles.Randomizer) return; - if (!ActiveDeathpacts.Contains(player.PlayerId)) - { - return; - } + if (!ActiveDeathpacts.Contains(player.PlayerId)) return; - if (CheckCancelDeathpact(player)) - { - return; - } + if (CheckCancelDeathpact(player)) return; if (DeathpactTime < TimeStamp && DeathpactTime != 0) { - foreach (PlayerControl playerInDeathpact in PlayersInDeathpact) - { - KillPlayerInDeathpact(player, playerInDeathpact); - } + foreach (PlayerControl playerInDeathpact in PlayersInDeathpact) KillPlayerInDeathpact(player, playerInDeathpact); ClearDeathpact(player.PlayerId); player.Notify(GetString("DeathpactExecuted")); @@ -191,10 +172,7 @@ namespace EHR.Impostor public static bool CheckCancelDeathpact(PlayerControl deathpact) { - if (Main.PlayerStates[deathpact.PlayerId].Role is not Deathpact { IsEnable: true } dp) - { - return true; - } + if (Main.PlayerStates[deathpact.PlayerId].Role is not Deathpact { IsEnable: true } dp) return true; if (dp.PlayersInDeathpact.Any(a => a.Data.Disconnected || a.Data.IsDead)) { @@ -203,7 +181,7 @@ namespace EHR.Impostor return true; } - bool cancelDeathpact = true; + var cancelDeathpact = true; foreach (PlayerControl player in dp.PlayersInDeathpact) { @@ -222,78 +200,48 @@ namespace EHR.Impostor public static void KillPlayerInDeathpact(PlayerControl deathpact, PlayerControl target) { - if (deathpact == null || target == null || target.Data.Disconnected) - { - return; - } + if (deathpact == null || target == null || target.Data.Disconnected) return; - if (!target.IsAlive()) - { - return; - } + if (!target.IsAlive()) return; target.Suicide(realKiller: deathpact); } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (GameStates.IsMeeting) - { - return string.Empty; - } + if (GameStates.IsMeeting) return string.Empty; - if (!ShowArrowsToOtherPlayersInPact.GetBool()) - { - return string.Empty; - } + if (!ShowArrowsToOtherPlayersInPact.GetBool()) return string.Empty; - if (target != null && seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (target != null && seer.PlayerId != target.PlayerId) return string.Empty; - if (!IsInActiveDeathpact(seer)) - { - return string.Empty; - } + if (!IsInActiveDeathpact(seer)) return string.Empty; + + var arrows = string.Empty; - string arrows = string.Empty; foreach (KeyValuePair state in Main.PlayerStates) - { if (state.Value.Role is Deathpact { IsEnable: true } dp) - { arrows = dp.PlayersInDeathpact.Where(a => a.PlayerId != seer.PlayerId).Select(otherPlayerInPact => TargetArrow.GetArrows(seer, otherPlayerInPact.PlayerId)).Aggregate(arrows, (current, arrow) => current + ColorString(GetRoleColor(CustomRoles.Crewmate), arrow)); - } - } return arrows; } public static string GetDeathpactMark(PlayerControl seer, PlayerControl target) { - if (!seer.Is(CustomRoles.Deathpact) || !IsInDeathpact(seer.PlayerId, target)) - { - return string.Empty; - } + if (!seer.Is(CustomRoles.Deathpact) || !IsInDeathpact(seer.PlayerId, target)) return string.Empty; return ColorString(Palette.ImpostorRed, "◀"); } public static bool IsInActiveDeathpact(PlayerControl player) { - if (ActiveDeathpacts.Count == 0) - { - return false; - } + if (ActiveDeathpacts.Count == 0) return false; foreach (KeyValuePair state in Main.PlayerStates) { if (state.Value.Role is Deathpact { IsEnable: true } dp) { - if (!ActiveDeathpacts.Contains(dp.DeathPactId) || dp.PlayersInDeathpact.All(b => b.PlayerId != player.PlayerId)) - { - continue; - } + if (!ActiveDeathpacts.Contains(dp.DeathPactId) || dp.PlayersInDeathpact.All(b => b.PlayerId != player.PlayerId)) continue; return true; } @@ -309,21 +257,18 @@ namespace EHR.Impostor public static string GetDeathpactString(PlayerControl player) { - string result = string.Empty; + var result = string.Empty; foreach (KeyValuePair state in Main.PlayerStates) { if (state.Value.Role is Deathpact { IsEnable: true } dp) { - if (!ActiveDeathpacts.Contains(dp.DeathPactId) || dp.PlayersInDeathpact.All(b => b.PlayerId != player.PlayerId)) - { - continue; - } + if (!ActiveDeathpacts.Contains(dp.DeathPactId) || dp.PlayersInDeathpact.All(b => b.PlayerId != player.PlayerId)) continue; string otherPlayerNames = dp.PlayersInDeathpact.Where(a => a.PlayerId != player.PlayerId).Aggregate(string.Empty, (current, otherPlayerInPact) => current + otherPlayerInPact.name.ToUpper() + ","); otherPlayerNames = otherPlayerNames.Remove(otherPlayerNames.Length - 1); - int countdown = (int)(dp.DeathpactTime - TimeStamp); + var countdown = (int)(dp.DeathpactTime - TimeStamp); result += $"{ColorString(GetRoleColor(CustomRoles.Impostor), string.Format(GetString("DeathpactActiveDeathpact"), otherPlayerNames, countdown))}"; } @@ -334,10 +279,7 @@ namespace EHR.Impostor public static void ClearDeathpact(byte deathpact) { - if (Main.PlayerStates[deathpact].Role is not Deathpact { IsEnable: true } dp) - { - return; - } + if (Main.PlayerStates[deathpact].Role is not Deathpact { IsEnable: true } dp) return; dp.DeathpactTime = 0; ActiveDeathpacts.Remove(deathpact); @@ -349,10 +291,7 @@ namespace EHR.Impostor { foreach (PlayerControl otherPlayerInPact in dp.PlayersInDeathpact.Where(a => a.PlayerId != player.PlayerId)) { - if (ShowArrowsToOtherPlayersInPact.GetBool()) - { - TargetArrow.Remove(player.PlayerId, otherPlayerInPact.PlayerId); - } + if (ShowArrowsToOtherPlayersInPact.GetBool()) TargetArrow.Remove(player.PlayerId, otherPlayerInPact.PlayerId); otherPlayerInPact.MarkDirtySettings(); player.MarkDirtySettings(); @@ -368,15 +307,9 @@ namespace EHR.Impostor if (KillDeathpactPlayersOnMeeting.GetBool()) { PlayerControl deathpactPlayer = Main.AllPlayerControls.FirstOrDefault(a => a.PlayerId == deathpact); - if (deathpactPlayer == null || deathpactPlayer.Data.IsDead) - { - continue; - } + if (deathpactPlayer == null || deathpactPlayer.Data.IsDead) continue; - foreach (PlayerControl player in PlayersInDeathpact) - { - KillPlayerInDeathpact(deathpactPlayer, player); - } + foreach (PlayerControl player in PlayersInDeathpact) KillPlayerInDeathpact(deathpactPlayer, player); } ClearDeathpact(deathpact); diff --git a/Roles/Impostor/Devourer.cs b/Roles/Impostor/Devourer.cs index fea763227..986446be9 100644 --- a/Roles/Impostor/Devourer.cs +++ b/Roles/Impostor/Devourer.cs @@ -28,18 +28,23 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Devourer); + DefaultKillCooldown = new FloatOptionItem(Id + 10, "SansDefaultKillCooldown", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Devourer]) .SetValueFormat(OptionFormat.Seconds); + ReduceKillCooldown = new FloatOptionItem(Id + 11, "SansReduceKillCooldown", new(0f, 30f, 0.5f), 1.5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Devourer]) .SetValueFormat(OptionFormat.Seconds); + MinKillCooldown = new FloatOptionItem(Id + 12, "SansMinKillCooldown", new(0f, 30f, 0.5f), 21f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Devourer]) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftCooldown = new FloatOptionItem(Id + 14, "DevourCooldown", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Devourer]) .SetValueFormat(OptionFormat.Seconds); + HideNameOfConsumedPlayer = new BooleanOptionItem(Id + 16, "DevourerHideNameConsumed", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Devourer]); } @@ -72,17 +77,11 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl pc, PlayerControl target, bool shapeshifting) { - if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId) || !shapeshifting) - { - return false; - } + if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId) || !shapeshifting) return false; if (!PlayerSkinsCosumed.Contains(target.PlayerId)) { - if (!Camouflage.IsCamouflage) - { - SetSkin(target, ConsumedOutfit); - } + if (!Camouflage.IsCamouflage) SetSkin(target, ConsumedOutfit); PlayerSkinsCosumed.Add(target.PlayerId); pc.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Devourer), GetString("DevourerEatenSkin"))); @@ -104,21 +103,16 @@ namespace EHR.Impostor public static void OnDevourerDied(byte Devourer) { - if (Main.PlayerStates[Devourer].Role is not Devourer { IsEnable: true } dv) - { - return; - } + if (Main.PlayerStates[Devourer].Role is not Devourer { IsEnable: true } dv) return; foreach (byte player in dv.PlayerSkinsCosumed.ToArray()) { Camouflage.PlayerSkins[player] = OriginalPlayerSkins[player]; + if (!Camouflage.IsCamouflage) { PlayerControl pc = Main.AllAlivePlayerControls.FirstOrDefault(a => a.PlayerId == player); - if (pc == null) - { - continue; - } + if (pc == null) continue; SetSkin(pc, OriginalPlayerSkins[player]); } @@ -129,9 +123,10 @@ namespace EHR.Impostor private static void SetSkin(PlayerControl target, NetworkedPlayerInfo.PlayerOutfit outfit) { - CustomRpcSender sender = CustomRpcSender.Create($"Camouflage.RpcSetSkin({target.Data.PlayerName})"); + var sender = CustomRpcSender.Create($"Camouflage.RpcSetSkin({target.Data.PlayerName})"); target.SetColor(outfit.ColorId); + sender.AutoStartRpc(target.NetId, (byte)RpcCalls.SetColor) .Write(target.Data.NetId) .Write((byte)outfit.ColorId) @@ -139,6 +134,7 @@ namespace EHR.Impostor target.SetHat(outfit.HatId, outfit.ColorId); target.Data.DefaultOutfit.HatSequenceId += 10; + sender.AutoStartRpc(target.NetId, (byte)RpcCalls.SetHatStr) .Write(outfit.HatId) .Write(target.GetNextRpcSequenceId(RpcCalls.SetHatStr)) @@ -146,6 +142,7 @@ namespace EHR.Impostor target.SetSkin(outfit.SkinId, outfit.ColorId); target.Data.DefaultOutfit.SkinSequenceId += 10; + sender.AutoStartRpc(target.NetId, (byte)RpcCalls.SetSkinStr) .Write(outfit.SkinId) .Write(target.GetNextRpcSequenceId(RpcCalls.SetSkinStr)) @@ -153,6 +150,7 @@ namespace EHR.Impostor target.SetVisor(outfit.VisorId, outfit.ColorId); target.Data.DefaultOutfit.VisorSequenceId += 10; + sender.AutoStartRpc(target.NetId, (byte)RpcCalls.SetVisorStr) .Write(outfit.VisorId) .Write(target.GetNextRpcSequenceId(RpcCalls.SetVisorStr)) @@ -160,6 +158,7 @@ namespace EHR.Impostor target.SetPet(outfit.PetId); target.Data.DefaultOutfit.PetSequenceId += 10; + sender.AutoStartRpc(target.NetId, (byte)RpcCalls.SetPetStr) .Write(outfit.PetId) .Write(target.GetNextRpcSequenceId(RpcCalls.SetPetStr)) diff --git a/Roles/Impostor/Disperser.cs b/Roles/Impostor/Disperser.cs index bce50f0f5..6b9b7eb08 100644 --- a/Roles/Impostor/Disperser.cs +++ b/Roles/Impostor/Disperser.cs @@ -21,15 +21,19 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Disperser); + DisperserShapeshiftCooldown = new FloatOptionItem(Id + 5, "ShapeshiftCooldown", new(1f, 60f, 1f), 15f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Disperser]) .SetValueFormat(OptionFormat.Seconds); + DisperserShapeshiftDuration = new FloatOptionItem(Id + 6, "ShapeshiftDuration", new(1f, 30f, 1f), 1f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Disperser]) .SetValueFormat(OptionFormat.Seconds); + DisperserLimitOpt = new IntegerOptionItem(Id + 7, "AbilityUseLimit", new(0, 5, 1), 1, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Disperser]) .SetValueFormat(OptionFormat.Times); + DisperserAbilityUseGainWithEachKill = new FloatOptionItem(Id + 8, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 0.3f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Disperser]) .SetValueFormat(OptionFormat.Times); @@ -49,15 +53,10 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte id) { if (UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = DisperserShapeshiftCooldown.GetFloat(); - } else { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.ShapeshifterCooldown = DisperserShapeshiftCooldown.GetFloat(); AURoleOptions.ShapeshifterDuration = DisperserShapeshiftDuration.GetFloat(); @@ -66,10 +65,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (shapeshifter == null || (!shapeshifting && !UseUnshiftTrigger.GetBool())) - { - return false; - } + if (shapeshifter == null || (!shapeshifting && !UseUnshiftTrigger.GetBool())) return false; if (shapeshifter.GetAbilityUseLimit() < 1 && !DisableShapeshiftAnimations.GetBool()) { @@ -84,10 +80,7 @@ namespace EHR.Impostor public override bool OnVanish(PlayerControl pc) { - if (pc == null || pc.GetAbilityUseLimit() < 1) - { - return false; - } + if (pc == null || pc.GetAbilityUseLimit() < 1) return false; Disperse(pc); @@ -96,10 +89,7 @@ namespace EHR.Impostor public override void OnPet(PlayerControl pc) { - if (pc == null || pc.GetAbilityUseLimit() < 1) - { - return; - } + if (pc == null || pc.GetAbilityUseLimit() < 1) return; Disperse(pc); } @@ -112,10 +102,7 @@ namespace EHR.Impostor { if (player.PlayerId == pc.PlayerId || pc.Data.IsDead || pc.onLadder || pc.inMovingPlat || pc.inVent || GameStates.IsMeeting) { - if (!pc.Is(CustomRoles.Disperser)) - { - pc.Notify(ColorString(GetRoleColor(CustomRoles.Disperser), string.Format(GetString("ErrorTeleport"), pc.GetRealName()))); - } + if (!pc.Is(CustomRoles.Disperser)) pc.Notify(ColorString(GetRoleColor(CustomRoles.Disperser), string.Format(GetString("ErrorTeleport"), pc.GetRealName()))); continue; } @@ -131,9 +118,7 @@ namespace EHR.Impostor __instance.AbilityButton.ToggleVisible(GetPlayerById(id).IsAlive()); if (UsePets.GetBool()) - { __instance.PetButton?.OverrideText(GetString("DisperserVentButtonText")); - } else { __instance.AbilityButton?.OverrideText(GetString("DisperserVentButtonText")); diff --git a/Roles/Impostor/Duellist.cs b/Roles/Impostor/Duellist.cs index 44c18137f..9ee278a46 100644 --- a/Roles/Impostor/Duellist.cs +++ b/Roles/Impostor/Duellist.cs @@ -22,6 +22,7 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Duellist); + SSCD = new FloatOptionItem(Id + 5, "ShapeshiftCooldown", new(0f, 60f, 2.5f), 15f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Duellist]) .SetValueFormat(OptionFormat.Seconds); @@ -45,47 +46,30 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl duellist, PlayerControl target, bool shapeshifting) { - if (!IsEnable) - { - return false; - } + if (!IsEnable) return false; - if (duellist == null || target == null) - { - return false; - } + if (duellist == null || target == null) return false; Vector2 pos = Pelican.GetBlackRoomPS(); if (target.TP(pos)) { - if (Main.KillTimers[duellist.PlayerId] < 1f) - { - duellist.SetKillCooldown(1f); // Give the other player a chance to kill - } + if (Main.KillTimers[duellist.PlayerId] < 1f) duellist.SetKillCooldown(1f); // Give the other player a chance to kill duellist.TP(pos); DuelPair[duellist.PlayerId] = target.PlayerId; } else - { duellist.Notify(GetString("TargetCannotBeTeleported")); - } return false; } public override void OnFixedUpdate(PlayerControl pc) { - if (DuelPair.Count == 0) - { - return; - } + if (DuelPair.Count == 0) return; - if (Count++ < 40) - { - return; - } + if (Count++ < 40) return; Count = 0; diff --git a/Roles/Impostor/Echo.cs b/Roles/Impostor/Echo.cs index 0d7511358..1ddea4dce 100644 --- a/Roles/Impostor/Echo.cs +++ b/Roles/Impostor/Echo.cs @@ -17,17 +17,20 @@ namespace EHR.Impostor public override void SetupCustomOption() { - int id = 647600; + var id = 647600; const TabGroup tab = TabGroup.ImpostorRoles; const CustomRoles role = CustomRoles.Echo; Options.SetupRoleOptions(id++, tab, role); StringOptionItem parent = Options.CustomRoleSpawnChances[role]; + ShapeshiftCooldown = new FloatOptionItem(++id, "ShapeshiftCooldown", new(0f, 180f, 0.5f), 30f, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftDuration = new FloatOptionItem(++id, "ShapeshiftDuration", new(0f, 180f, 0.5f), 10f, tab) .SetParent(parent) .SetValueFormat(OptionFormat.Seconds); + DisableVentingWhileControlling = new BooleanOptionItem(++id, "Echo.DisableVentingWhileControlling", true, tab) .SetParent(parent); } @@ -74,10 +77,7 @@ namespace EHR.Impostor if (shapeshifting) { Vector2 pos = target.Pos(); - if (!shapeshifter.RpcCheckAndMurder(target, true) || !target.TP(shapeshifter)) - { - return false; - } + if (!shapeshifter.RpcCheckAndMurder(target, true) || !target.TP(shapeshifter)) return false; target.RpcShapeshift(shapeshifter, false); Main.AllPlayerSpeed[target.PlayerId] = Main.MinSpeed; @@ -87,10 +87,7 @@ namespace EHR.Impostor else { target = Utils.GetPlayerById(shapeshifter.shapeshiftTargetPlayerId); - if (target == null) - { - return true; - } + if (target == null) return true; RevertSwap(shapeshifter, target); LateTask.New(() => target.Suicide(PlayerState.DeathReason.Kill, shapeshifter), 0.2f, "Echo Unshift Kill"); @@ -109,16 +106,10 @@ namespace EHR.Impostor public override bool OnCheckMurderAsTarget(PlayerControl killer, PlayerControl target) { - if (!target.IsShifted()) - { - return true; - } + if (!target.IsShifted()) return true; PlayerControl ssTarget = Utils.GetPlayerById(target.shapeshiftTargetPlayerId); - if (ssTarget == null || !killer.RpcCheckAndMurder(ssTarget, true)) - { - return true; - } + if (ssTarget == null || !killer.RpcCheckAndMurder(ssTarget, true)) return true; RevertSwap(target, ssTarget); LateTask.New(() => killer.Kill(ssTarget), 0.2f, log: false); @@ -128,6 +119,7 @@ namespace EHR.Impostor public void OnTargetCheckMurder(PlayerControl killer, PlayerControl target) { RevertSwap(EchoPC, target); + LateTask.New(() => { killer.RpcCheckAndMurder(EchoPC); @@ -137,16 +129,10 @@ namespace EHR.Impostor public override void OnReportDeadBody() { - if (!EchoPC.IsShifted()) - { - return; - } + if (!EchoPC.IsShifted()) return; PlayerControl ssTarget = ((byte)EchoPC.shapeshiftTargetPlayerId).GetPlayer(); - if (ssTarget == null || !ssTarget.IsAlive()) - { - return; - } + if (ssTarget == null || !ssTarget.IsAlive()) return; ssTarget.Suicide(PlayerState.DeathReason.Kill, EchoPC); } diff --git a/Roles/Impostor/Eraser.cs b/Roles/Impostor/Eraser.cs index 428a50aa2..d37bcdded 100644 --- a/Roles/Impostor/Eraser.cs +++ b/Roles/Impostor/Eraser.cs @@ -36,15 +36,20 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Eraser); + EraseMethod = new StringOptionItem(Id + 10, "EraseMethod", EraseMode, 0, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Eraser]); + WhenTargetIsNeutral = new StringOptionItem(Id + 11, "WhenTargetIsNeutral", WhenTargetIsNeutralAction, 0, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Eraser]); + EraseLimitOpt = new IntegerOptionItem(Id + 12, "EraseLimit", new(1, 15, 1), 1, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Eraser]) .SetValueFormat(OptionFormat.Times); + HideVote = new BooleanOptionItem(Id + 13, "EraserHideVote", false, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Eraser]); + CancelVote = Options.CreateVoteCancellingUseSetting(Id + 14, CustomRoles.Eraser, TabGroup.ImpostorRoles); } @@ -62,23 +67,14 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.GetAbilityUseLimit() < 1) - { - return true; - } + if (killer.GetAbilityUseLimit() < 1) return true; - if (target.PlayerId == killer.PlayerId) - { - return true; - } + if (target.PlayerId == killer.PlayerId) return true; if (target.GetCustomRole().IsNeutral() && EraseMethod.GetInt() == 0) { killer.Notify(GetString("EraserEraseNeutralNotice")); - if (WhenTargetIsNeutral.GetInt() == 1) - { - return true; - } + if (WhenTargetIsNeutral.GetInt() == 1) return true; killer.SetKillCooldown(5f); return false; @@ -91,10 +87,7 @@ namespace EHR.Impostor killer.RpcRemoveAbilityUse(); killer.SetKillCooldown(); killer.Notify(GetString("TargetErasedInRound")); - if (!PlayerToErase.Contains(target.PlayerId)) - { - PlayerToErase.Add(target.PlayerId); - } + if (!PlayerToErase.Contains(target.PlayerId)) PlayerToErase.Add(target.PlayerId); }); } @@ -103,22 +96,13 @@ namespace EHR.Impostor public override bool OnVote(PlayerControl player, PlayerControl target) { - if (player == null || target == null || EraseMethod.GetInt() == 0) - { - return false; - } + if (player == null || target == null || EraseMethod.GetInt() == 0) return false; - if (DidVote.Contains(player.PlayerId) || Main.DontCancelVoteList.Contains(player.PlayerId)) - { - return false; - } + if (DidVote.Contains(player.PlayerId) || Main.DontCancelVoteList.Contains(player.PlayerId)) return false; DidVote.Add(player.PlayerId); - if (player.GetAbilityUseLimit() < 1) - { - return false; - } + if (player.GetAbilityUseLimit() < 1) return false; if (target.PlayerId == player.PlayerId) { @@ -134,17 +118,11 @@ namespace EHR.Impostor player.RpcRemoveAbilityUse(); - if (!PlayerToErase.Contains(target.PlayerId)) - { - PlayerToErase.Add(target.PlayerId); - } + if (!PlayerToErase.Contains(target.PlayerId)) PlayerToErase.Add(target.PlayerId); Utils.SendMessage(string.Format(GetString("EraserEraseNotice"), target.GetRealName()), player.PlayerId, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Eraser), GetString("EraserEraseMsgTitle"))); - if (GameStates.IsInTask) - { - Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: target); - } + if (GameStates.IsInTask) Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: target); Main.DontCancelVoteList.Add(player.PlayerId); return true; @@ -160,10 +138,7 @@ namespace EHR.Impostor foreach (byte id in PlayerToErase) { PlayerControl pc = Utils.GetPlayerById(id); - if (pc == null || !pc.IsAlive() || pc.Is(CustomRoles.Bloodlust)) - { - continue; - } + if (pc == null || !pc.IsAlive() || pc.Is(CustomRoles.Bloodlust)) continue; CustomRoles erasedRole = pc.GetRoleTypes() is RoleTypes.Crewmate or RoleTypes.Engineer or RoleTypes.Noisemaker or RoleTypes.Scientist or RoleTypes.Tracker ? CustomRoles.CrewmateEHR : CustomRoles.ImpostorEHR; pc.RpcSetCustomRole(erasedRole); diff --git a/Roles/Impostor/Escapee.cs b/Roles/Impostor/Escapee.cs index 34cb58c02..7e34d5962 100644 --- a/Roles/Impostor/Escapee.cs +++ b/Roles/Impostor/Escapee.cs @@ -12,6 +12,7 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(3600, TabGroup.ImpostorRoles, CustomRoles.Escapee); + Options.EscapeeSSCD = new FloatOptionItem(3611, "ShapeshiftCooldown", new(1f, 180f, 1f), 5f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Escapee]) .SetValueFormat(OptionFormat.Seconds); @@ -32,27 +33,18 @@ namespace EHR.Impostor public override void SetButtonTexts(HudManager hud, byte id) { if (Options.UsePets.GetBool()) - { hud.PetButton?.OverrideText(Translator.GetString("EscapeeAbilityButtonText")); - } else - { hud.AbilityButton?.OverrideText(Translator.GetString("EscapeeAbilityButtonText")); - } } public override void ApplyGameOptions(IGameOptions opt, byte id) { if (Options.UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = Options.EscapeeSSCD.GetFloat(); - } else { - if (Options.UsePets.GetBool()) - { - return; - } + if (Options.UsePets.GetBool()) return; AURoleOptions.ShapeshifterCooldown = Options.EscapeeSSCD.GetFloat(); AURoleOptions.ShapeshifterDuration = 1f; @@ -74,23 +66,18 @@ namespace EHR.Impostor { if (EscapeeLocation != null) { - Vector2 position = (Vector2)EscapeeLocation; + var position = (Vector2)EscapeeLocation; EscapeeLocation = null; pc.TP(position); pc.RPCPlayCustomSound("Teleport"); } else - { EscapeeLocation = pc.Pos(); - } } public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (shapeshifting || Options.UseUnshiftTrigger.GetBool()) - { - TeleportOrMark(shapeshifter); - } + if (shapeshifting || Options.UseUnshiftTrigger.GetBool()) TeleportOrMark(shapeshifter); return false; } diff --git a/Roles/Impostor/EvilDiviner.cs b/Roles/Impostor/EvilDiviner.cs index c6192234b..e8fba7fdf 100644 --- a/Roles/Impostor/EvilDiviner.cs +++ b/Roles/Impostor/EvilDiviner.cs @@ -28,12 +28,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.EvilDiviner); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 2.5f), 25f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.EvilDiviner]) .SetValueFormat(OptionFormat.Seconds); + DivinationMaxCount = new IntegerOptionItem(Id + 11, "DivinationMaxCount", new(0, 15, 1), 1, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.EvilDiviner]) .SetValueFormat(OptionFormat.Times); + EdAbilityUseGainWithEachKill = new FloatOptionItem(Id + 12, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 0.3f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.EvilDiviner]) .SetValueFormat(OptionFormat.Times); @@ -52,6 +55,7 @@ namespace EHR.Impostor IsRitualist = Main.PlayerStates[playerId].MainRole == CustomRoles.Ritualist; playerId.SetAbilityUseLimit(IsRitualist ? Ritualist.RitualMaxCount.GetInt() : DivinationMaxCount.GetInt()); + if (IsRitualist) { KCD = Ritualist.KillCooldown.GetFloat(); @@ -78,10 +82,7 @@ namespace EHR.Impostor private static void SendRPC(byte playerId, byte targetId) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetEvilDiviner, SendOption.Reliable); writer.Write(playerId); @@ -125,10 +126,7 @@ namespace EHR.Impostor public override bool KnowRole(PlayerControl seer, PlayerControl target) { - if (base.KnowRole(seer, target)) - { - return true; - } + if (base.KnowRole(seer, target)) return true; return Main.PlayerStates[seer.PlayerId].Role is EvilDiviner ed && ed.DivinationTarget.Contains(target.PlayerId); } diff --git a/Roles/Impostor/EvilGuesser.cs b/Roles/Impostor/EvilGuesser.cs index 0d7c4a229..fa3d686b9 100644 --- a/Roles/Impostor/EvilGuesser.cs +++ b/Roles/Impostor/EvilGuesser.cs @@ -10,24 +10,24 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(1200, TabGroup.ImpostorRoles, CustomRoles.EvilGuesser); + EGCanGuessTime = new IntegerOptionItem(1205, "GuesserCanGuessTimes", new(1, 15, 1), 15, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.EvilGuesser]) .SetValueFormat(OptionFormat.Times); + EGCanGuessImp = new BooleanOptionItem(1206, "EGCanGuessImp", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.EvilGuesser]); + EGCanGuessAdt = new BooleanOptionItem(1207, "EGCanGuessAdt", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.EvilGuesser]); + EGTryHideMsg = new BooleanOptionItem(1209, "GuesserTryHideMsg", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.EvilGuesser]) .SetColor(Color.green); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Impostor/EvilTracker.cs b/Roles/Impostor/EvilTracker.cs index d3c973e81..34fad690d 100644 --- a/Roles/Impostor/EvilTracker.cs +++ b/Roles/Impostor/EvilTracker.cs @@ -45,10 +45,13 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.EvilTracker); + OptionCanSeeKillFlash = new BooleanOptionItem(Id + 10, "EvilTrackerCanSeeKillFlash", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.EvilTracker]); + OptionTargetMode = new StringOptionItem(Id + 11, "EvilTrackerTargetMode", TargetModeText, 2, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.EvilTracker]); + OptionCanSeeLastRoomInMeeting = new BooleanOptionItem(Id + 12, "EvilTrackerCanSeeLastRoomInMeeting", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.EvilTracker]); } @@ -75,19 +78,13 @@ namespace EHR.Impostor LateTask.New(() => { - foreach (byte id in ImpostorsId) - { - TargetArrow.Add(playerId, id); - } + foreach (byte id in ImpostorsId) TargetArrow.Add(playerId, id); }, 3f, "Add Evil Tracker Arrows"); } public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (RoleTypes != RoleTypes.Shapeshifter) - { - return; - } + if (RoleTypes != RoleTypes.Shapeshifter) return; AURoleOptions.ShapeshifterCooldown = CanTarget(playerId) ? 1f : 255f; AURoleOptions.ShapeshifterDuration = 1f; @@ -114,10 +111,7 @@ namespace EHR.Impostor public static bool KillFlashCheck(PlayerControl killer, PlayerControl target) { - if (!CanSeeKillFlash) - { - return false; - } + if (!CanSeeKillFlash) return false; PlayerControl realKiller = target.GetRealKiller() ?? killer; return realKiller.Is(CustomRoleTypes.Impostor) && realKiller != target; @@ -125,15 +119,9 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!CanTarget(shapeshifter.PlayerId) || !shapeshifting) - { - return false; - } + if (!CanTarget(shapeshifter.PlayerId) || !shapeshifting) return false; - if (target == null || target.Is(CustomRoleTypes.Impostor)) - { - return false; - } + if (target == null || target.Is(CustomRoleTypes.Impostor)) return false; SetTarget(shapeshifter.PlayerId, target.PlayerId); Logger.Info($"{shapeshifter.GetNameWithRole().RemoveHtmlTags()}'s target is now {target.GetNameWithRole().RemoveHtmlTags()}", "EvilTrackerTarget"); @@ -148,25 +136,18 @@ namespace EHR.Impostor { try { - if (CurrentTargetMode == TargetMode.EveryMeeting) - { - SetTarget(); - } + if (CurrentTargetMode == TargetMode.EveryMeeting) SetTarget(); foreach (byte playerId in PlayerIdList) { PlayerControl pc = Utils.GetPlayerById(playerId); PlayerControl target = Utils.GetPlayerById(Target); + try { - if (!pc.IsAlive() || !target.IsAlive()) - { - SetTarget(playerId); - } - } - catch (NullReferenceException) - { + if (!pc.IsAlive() || !target.IsAlive()) SetTarget(playerId); } + catch (NullReferenceException) { } pc?.SyncSettings(); pc?.RpcResetAbilityCooldown(); @@ -182,33 +163,20 @@ namespace EHR.Impostor public void SetTarget(byte trackerId = byte.MaxValue, byte targetId = byte.MaxValue) { if (trackerId == byte.MaxValue) - { CanSetTarget = true; - } else if (targetId == byte.MaxValue) - { Target = byte.MaxValue; - } else { Target = targetId; - if (CurrentTargetMode != TargetMode.Always) - { - CanSetTarget = false; - } + if (CurrentTargetMode != TargetMode.Always) CanSetTarget = false; TargetArrow.Add(trackerId, targetId); } - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetEvilTrackerTarget, SendOption.Reliable); writer.Write(trackerId); @@ -235,40 +203,26 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (!GameStates.IsInTask) - { - return string.Empty; - } + if (!GameStates.IsInTask) return string.Empty; byte trackerId = target.PlayerId; - if (seer.PlayerId != trackerId) - { - return string.Empty; - } + if (seer.PlayerId != trackerId) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is not EvilTracker et) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not EvilTracker et) return string.Empty; byte[] imps = et.ImpostorsId; - StringBuilder sb = new StringBuilder(80); + var sb = new StringBuilder(80); + if (imps.Length > 0) { sb.Append($""); - foreach (byte impostorId in imps) - { - sb.Append(TargetArrow.GetArrows(target, impostorId)); - } + foreach (byte impostorId in imps) sb.Append(TargetArrow.GetArrows(target, impostorId)); sb.Append(""); } byte targetId = et.Target; - if (targetId != byte.MaxValue) - { - sb.Append(Utils.ColorString(Color.white, TargetArrow.GetArrows(target, targetId))); - } + if (targetId != byte.MaxValue) sb.Append(Utils.ColorString(Color.white, TargetArrow.GetArrows(target, targetId))); return sb.ToString(); } @@ -277,14 +231,11 @@ namespace EHR.Impostor { string text = Utils.ColorString(Palette.ImpostorRed, TargetArrow.GetArrows(seer, target.PlayerId)); PlainShipRoom room = Main.PlayerStates[target.PlayerId].LastRoom; + if (room == null) - { text += Utils.ColorString(Color.gray, "@" + GetString("FailToTrack")); - } else - { text += Utils.ColorString(Palette.ImpostorRed, "@" + GetString(room.RoomId.ToString())); - } return text; } diff --git a/Roles/Impostor/FireWorks.cs b/Roles/Impostor/FireWorks.cs index 7b1a2de94..9bed85e75 100644 --- a/Roles/Impostor/FireWorks.cs +++ b/Roles/Impostor/FireWorks.cs @@ -41,17 +41,22 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.FireWorks); + FireWorksCountOpt = new IntegerOptionItem(Id + 10, "FireWorksMaxCount", new(1, 10, 1), 3, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.FireWorks]) .SetValueFormat(OptionFormat.Pieces); + FireWorksRadiusOpt = new FloatOptionItem(Id + 11, "FireWorksRadius", new(0.5f, 5f, 0.5f), 2f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.FireWorks]) .SetValueFormat(OptionFormat.Multiplier); + CanKill = new BooleanOptionItem(Id + 12, "CanKill", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.FireWorks]); + KillCooldown = new FloatOptionItem(Id + 13, "KillCooldown", new(0f, 180f, 0.5f), 30f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.FireWorks]) .SetValueFormat(OptionFormat.Seconds); + CanIgniteBeforePlacingAllFireworks = new BooleanOptionItem(Id + 14, "CanIgniteBeforePlacingAllFireworks", false, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.FireWorks]); } @@ -81,10 +86,7 @@ namespace EHR.Impostor private void SendRPC(byte playerId) { - if (!On || !Utils.DoRPC) - { - return; - } + if (!On || !Utils.DoRPC) return; Logger.Info($"Player{playerId}:SendRPC", "FireWorks"); MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SendFireWorksState, SendOption.Reliable); @@ -102,10 +104,7 @@ namespace EHR.Impostor public override bool CanUseKillButton(PlayerControl pc) { - if (pc == null || pc.Data.IsDead) - { - return false; - } + if (pc == null || pc.Data.IsDead) return false; try { @@ -120,17 +119,11 @@ namespace EHR.Impostor public override void OnPet(PlayerControl pc) { FireWorksState beforeState = state; - if (CanIgniteBeforePlacingAllFireworks.GetBool()) - { - state = FireWorksState.ReadyFire; - } + if (CanIgniteBeforePlacingAllFireworks.GetBool()) state = FireWorksState.ReadyFire; OnShapeshift(pc, null, true); - if (beforeState == FireWorksState.ReadyFire) - { - return; - } + if (beforeState == FireWorksState.ReadyFire) return; state = beforeState; } @@ -138,10 +131,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl pc, PlayerControl _, bool shapeshifting) { Logger.Info("FireWorks ShapeShift", "FireWorks"); - if (pc == null || pc.Data.IsDead || (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) || Pelican.IsEaten(pc.PlayerId)) - { - return false; - } + if (pc == null || pc.Data.IsDead || (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) || Pelican.IsEaten(pc.PlayerId)) return false; UseAbility(pc); @@ -151,10 +141,7 @@ namespace EHR.Impostor public override bool OnVanish(PlayerControl pc) { Logger.Info("FireWorks Vanish", "FireWorks"); - if (pc == null || pc.Data.IsDead || Pelican.IsEaten(pc.PlayerId)) - { - return false; - } + if (pc == null || pc.Data.IsDead || Pelican.IsEaten(pc.PlayerId)) return false; UseAbility(pc); @@ -170,41 +157,34 @@ namespace EHR.Impostor Logger.Info("Install Firework", "FireWorks"); fireWorksPosition.Add(pc.Pos()); nowFireWorksCount--; + state = nowFireWorksCount == 0 ? Main.AliveImpostorCount <= 1 ? FireWorksState.ReadyFire : FireWorksState.WaitTime : FireWorksState.SettingFireWorks; + break; case FireWorksState.ReadyFire: Logger.Info("Explode fireworks", "FireWorks"); - bool suicide = false; + var suicide = false; + foreach (PlayerControl target in Main.AllAlivePlayerControls) { foreach (Vector3 pos in fireWorksPosition) { float dis = Vector2.Distance(pos, target.transform.position); - if (dis > FireWorksRadius) - { - continue; - } + if (dis > FireWorksRadius) continue; if (target == pc) - { suicide = true; - } else - { target.Suicide(PlayerState.DeathReason.Bombed, pc); - } } } if (suicide) { int totalAlive = Main.AllAlivePlayerControls.Length; - if (totalAlive != 1) - { - pc.Suicide(); - } + if (totalAlive != 1) pc.Suicide(); } state = FireWorksState.FireEnd; @@ -217,16 +197,10 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - string retText = string.Empty; - if (seer == null || seer.Data.IsDead || seer.PlayerId != target.PlayerId) - { - return retText; - } + var retText = string.Empty; + if (seer == null || seer.Data.IsDead || seer.PlayerId != target.PlayerId) return retText; - if (Main.PlayerStates[seer.PlayerId].Role is not FireWorks fw) - { - return retText; - } + if (Main.PlayerStates[seer.PlayerId].Role is not FireWorks fw) return retText; if (fw.state == FireWorksState.WaitTime && Main.AliveImpostorCount <= 1) { diff --git a/Roles/Impostor/Framer.cs b/Roles/Impostor/Framer.cs index 409b352a2..4a50ca178 100644 --- a/Roles/Impostor/Framer.cs +++ b/Roles/Impostor/Framer.cs @@ -15,9 +15,11 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(647196, TabGroup.ImpostorRoles, CustomRoles.Framer); + AbilityUseLimit = new IntegerOptionItem(647198, "AbilityUseLimit", new(0, 5, 1), 0, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Framer]) .SetValueFormat(OptionFormat.Times); + FramerAbilityUseGainWithEachKill = new FloatOptionItem(647199, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 0.4f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Framer]) .SetValueFormat(OptionFormat.Times); @@ -37,10 +39,7 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.GetAbilityUseLimit() < 1f) - { - return true; - } + if (killer.GetAbilityUseLimit() < 1f) return true; return killer.CheckDoubleTrigger(target, () => { diff --git a/Roles/Impostor/Freezer.cs b/Roles/Impostor/Freezer.cs index e03a2a483..37b56cc31 100644 --- a/Roles/Impostor/Freezer.cs +++ b/Roles/Impostor/Freezer.cs @@ -14,9 +14,11 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Freezer); + FreezeCooldown = new FloatOptionItem(Id + 2, "FreezeCooldown", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Freezer]) .SetValueFormat(OptionFormat.Seconds); + FreezeDuration = new FloatOptionItem(Id + 3, "FreezeDuration", new(0f, 180f, 0.5f), 10f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Freezer]) .SetValueFormat(OptionFormat.Seconds); @@ -45,6 +47,7 @@ namespace EHR.Impostor float beforeSpeed = Main.AllPlayerSpeed[target.PlayerId]; Main.AllPlayerSpeed[target.PlayerId] = Main.MinSpeed; target.MarkDirtySettings(); + LateTask.New(() => { Main.AllPlayerSpeed[target.PlayerId] = beforeSpeed; diff --git a/Roles/Impostor/Gambler.cs b/Roles/Impostor/Gambler.cs index 9368efd65..a67c97c01 100644 --- a/Roles/Impostor/Gambler.cs +++ b/Roles/Impostor/Gambler.cs @@ -47,35 +47,49 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Gambler); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 60f, 2.5f), 25f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]) .SetValueFormat(OptionFormat.Seconds); + KillDelay = new IntegerOptionItem(Id + 11, "GamblerKillDelay", new(0, 10, 1), 3, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]) .SetValueFormat(OptionFormat.Seconds); + ShieldDur = new IntegerOptionItem(Id + 12, "GamblerShieldDur", new(1, 30, 1), 15, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]) .SetValueFormat(OptionFormat.Seconds); + FreezeDur = new IntegerOptionItem(Id + 13, "GamblerFreezeDur", new(1, 10, 1), 3, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]) .SetValueFormat(OptionFormat.Seconds); + LowVision = new FloatOptionItem(Id + 14, "GamblerLowVision", new(0f, 1f, 0.05f), 0.7f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]) .SetValueFormat(OptionFormat.Multiplier); + LowVisionDur = new IntegerOptionItem(Id + 15, "GamblerLowVisionDur", new(1, 30, 1), 10, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]) .SetValueFormat(OptionFormat.Seconds); + Speed = new FloatOptionItem(Id + 16, "GamblerSpeedup", new(0.1f, 3f, 0.05f), 1.5f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]) .SetValueFormat(OptionFormat.Multiplier); + SpeedDur = new IntegerOptionItem(Id + 17, "GamblerSpeedupDur", new(1, 20, 1), 5, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]) .SetValueFormat(OptionFormat.Seconds); + BsrDelay = new IntegerOptionItem(Id + 18, "GamblerBSRDelay", new(0, 10, 1), 2, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]) .SetValueFormat(OptionFormat.Seconds); + HighKCD = new FloatOptionItem(Id + 19, "GamblerHighKCD", new(10f, 60f, 2.5f), 30f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]) .SetValueFormat(OptionFormat.Seconds); + LowKCD = new FloatOptionItem(Id + 20, "GamblerLowKCD", new(10f, 60f, 2.5f), 17.5f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]) .SetValueFormat(OptionFormat.Seconds); + TPDelay = new IntegerOptionItem(Id + 21, "GamblerTPDelay", new(0, 10, 1), 2, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]) .SetValueFormat(OptionFormat.Seconds); + WhatToIgnore = new BooleanOptionItem(Id + 22, "GamblerWhatToIgnore", true, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]); IgnoreMedicShield = new BooleanOptionItem(Id + 23, "GamblerIgnoreMedicShield", true, TabGroup.ImpostorRoles).SetParent(WhatToIgnore); IgnoreCursedWolfAndJinx = new BooleanOptionItem(Id + 24, "GamblerIgnoreCursedWolfAndJinx", true, TabGroup.ImpostorRoles).SetParent(WhatToIgnore); IgnoreVeteranAlert = new BooleanOptionItem(Id + 25, "GamblerIgnoreVeteranAlert", false, TabGroup.ImpostorRoles).SetParent(WhatToIgnore); IgnorePestilence = new BooleanOptionItem(Id + 26, "GamblerIgnorePestilence", false, TabGroup.ImpostorRoles).SetParent(WhatToIgnore); + PositiveEffectChance = new IntegerOptionItem(Id + 27, "GamblerPositiveEffectChance", new(0, 100, 5), 70, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Gambler]) .SetValueFormat(OptionFormat.Percent); @@ -114,27 +128,19 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null) - { - return false; - } + if (killer == null) return false; - if (target == null) - { - return false; - } + if (target == null) return false; - if (EffectID != byte.MaxValue) - { - return true; - } + if (EffectID != byte.MaxValue) return true; - IRandom rd = IRandom.Instance; + var rd = IRandom.Instance; isPositiveEffect = rd.Next(1, 101) <= PositiveEffectChance.GetInt(); if (isPositiveEffect) { EffectID = (byte)rd.Next(1, 8); + switch (EffectID) { case 1: // Delayed kill @@ -147,14 +153,12 @@ namespace EHR.Impostor break; case 3: // No lunge (Swift kill) killer.Notify(GetString("GamblerGet.NoLunge")); - if (killer.RpcCheckAndMurder(target, true)) - { - target.Kill(target); - } + if (killer.RpcCheckAndMurder(target, true)) target.Kill(target); return false; case 4: // Swap with random player killer.Notify(GetString("GamblerGet.Swap")); + LateTask.New(() => { if (GameStates.IsInTask && killer.IsAlive()) @@ -163,9 +167,11 @@ namespace EHR.Impostor TP(killer.NetTransform, list.RandomElement().Pos()); } }, TPDelay.GetInt(), "Gambler Swap"); + break; case 5: // Ignore defense killer.Notify(GetString("GamblerGet.IgnoreDefense")); + if ((target.Is(CustomRoles.Pestilence) && IgnorePestilence.GetBool()) || (Veteran.VeteranInProtect.ContainsKey(target.PlayerId) && IgnoreVeteranAlert.GetBool()) || (Medic.InProtect(target.PlayerId) && IgnoreMedicShield.GetBool()) @@ -179,9 +185,7 @@ namespace EHR.Impostor || (Veteran.VeteranInProtect.ContainsKey(target.PlayerId) && !IgnoreVeteranAlert.GetBool()) || (Medic.InProtect(target.PlayerId) && !IgnoreMedicShield.GetBool()) || ((target.Is(CustomRoles.Jinx) || target.Is(CustomRoles.CursedWolf)) && !IgnoreCursedWolfAndJinx.GetBool())) - { break; - } killer.RpcCheckAndMurder(target); return false; @@ -203,22 +207,18 @@ namespace EHR.Impostor else { EffectID = (byte)rd.Next(1, 5); + switch (EffectID) { case 1: // BSR float delay = Math.Max(0.15f, BsrDelay.GetFloat()); - if (delay >= 1f) - { - killer.Notify(string.Format(GetString("GamblerGet.BSR"), BsrDelay.GetInt())); - } + if (delay >= 1f) killer.Notify(string.Format(GetString("GamblerGet.BSR"), BsrDelay.GetInt())); LateTask.New(() => { - if (GameStates.IsInTask) - { - killer.CmdReportDeadBody(target.Data); - } + if (GameStates.IsInTask) killer.CmdReportDeadBody(target.Data); }, delay, "Gambler Self Report"); + break; case 2: // Freeze killer.Notify(string.Format(GetString("GamblerGet.Freeze"), FreezeDur.GetInt())); @@ -248,16 +248,14 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl player) { - if (!GameStates.IsInTask || player == null || !player.Is(CustomRoles.Gambler) || (WaitingDelayedKills.Count == 0 && IsSpeedChange.Count == 0 && IsVisionChange.Count == 0 && IsShielded.Count == 0)) - { - return; - } + if (!GameStates.IsInTask || player == null || !player.Is(CustomRoles.Gambler) || (WaitingDelayedKills.Count == 0 && IsSpeedChange.Count == 0 && IsVisionChange.Count == 0 && IsShielded.Count == 0)) return; - bool sync = false; + var sync = false; foreach (KeyValuePair x in WaitingDelayedKills) { PlayerControl pc = GetPlayerById(x.Key); + if (!pc.IsAlive()) { WaitingDelayedKills.Remove(x.Key); @@ -284,15 +282,9 @@ namespace EHR.Impostor sync = true; } - if (IsShielded.TryGetValue(player.PlayerId, out long shielded) && shielded + ShieldDur.GetInt() < TimeStamp) - { - IsShielded.Remove(player.PlayerId); - } + if (IsShielded.TryGetValue(player.PlayerId, out long shielded) && shielded + ShieldDur.GetInt() < TimeStamp) IsShielded.Remove(player.PlayerId); - if (sync) - { - player.MarkDirtySettings(); - } + if (sync) player.MarkDirtySettings(); } public override void OnReportDeadBody() @@ -303,10 +295,7 @@ namespace EHR.Impostor foreach (byte playerId in WaitingDelayedKills.Keys.ToArray()) { PlayerControl pc = GetPlayerById(playerId); - if (pc.IsAlive()) - { - pc.Kill(pc); - } + if (pc.IsAlive()) pc.Kill(pc); } WaitingDelayedKills.Clear(); diff --git a/Roles/Impostor/Gangster.cs b/Roles/Impostor/Gangster.cs index ef6646659..cc5a681c0 100644 --- a/Roles/Impostor/Gangster.cs +++ b/Roles/Impostor/Gangster.cs @@ -23,9 +23,11 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Gangster); + KillCooldown = new FloatOptionItem(Id + 10, "GangsterRecruitCooldown", new(0f, 60f, 2.5f), 7.5f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Gangster]) .SetValueFormat(OptionFormat.Seconds); + RecruitLimitOpt = new IntegerOptionItem(Id + 12, "GangsterRecruitLimit", new(1, 5, 1), 1, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Gangster]) .SetValueFormat(OptionFormat.Times); @@ -67,17 +69,11 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.GetAbilityUseLimit() < 1) - { - return true; - } + if (killer.GetAbilityUseLimit() < 1) return true; if (CanBeMadmate(target)) { - if (!killer.GetCustomSubRoles().FindFirst(x => x.IsConverted(), out CustomRoles convertedAddon)) - { - convertedAddon = CustomRoles.Madmate; - } + if (!killer.GetCustomSubRoles().FindFirst(x => x.IsConverted(), out CustomRoles convertedAddon)) convertedAddon = CustomRoles.Madmate; killer.RpcRemoveAbilityUse(); target.RpcSetCustomRole(convertedAddon); @@ -94,18 +90,12 @@ namespace EHR.Impostor target.RpcGuardAndKill(target); Logger.Info($"SetRole: {target?.Data?.PlayerName} = {target.GetCustomRole()} + {convertedAddon}", $"Assign {convertedAddon}"); - if (killer.GetAbilityUseLimit() <= 0) - { - HudManager.Instance.KillButton.OverrideText($"{GetString("KillButtonText")}"); - } + if (killer.GetAbilityUseLimit() <= 0) HudManager.Instance.KillButton.OverrideText($"{GetString("KillButtonText")}"); return false; } - if (killer.GetAbilityUseLimit() < 0) - { - HudManager.Instance.KillButton.OverrideText($"{GetString("KillButtonText")}"); - } + if (killer.GetAbilityUseLimit() < 0) HudManager.Instance.KillButton.OverrideText($"{GetString("KillButtonText")}"); killer.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Gangster), GetString("GangsterRecruitmentFailure"))); return true; diff --git a/Roles/Impostor/Generator.cs b/Roles/Impostor/Generator.cs index ffb4d550d..490e40c0c 100644 --- a/Roles/Impostor/Generator.cs +++ b/Roles/Impostor/Generator.cs @@ -50,12 +50,16 @@ namespace EHR.Impostor { const int id = 11385; Options.SetupRoleOptions(id, TabGroup.ImpostorRoles, CustomRoles.Generator); + ChargesGainedPerSecond = new IntegerOptionItem(id + 2, "Generator.ChargesGainedEverySecond", new(1, 30, 1), 1, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Generator]); + StartingCharges = new IntegerOptionItem(id + 3, "Generator.StartingCharges", new(0, 100, 1), 0, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Generator]); + ChargesLostWhileShiftedPerSecond = new IntegerOptionItem(id + 4, "Generator.ChargesLostWhileShiftedPerSecond", new(1, 30, 1), 1, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Generator]); + MaxChargesStored = new IntegerOptionItem(id + 5, "Generator.MaxChargesStored", new(0, 200, 1), 100, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Generator]); @@ -63,6 +67,7 @@ namespace EHR.Impostor { OptionItem option = new IntegerOptionItem(id + 6 + (int)action, $"Generator.{action}.Cost", new(0, 100, 1), action.GetDefaultCost(), TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Generator]); + ActionCostSettings.Add(action, option); } } @@ -91,16 +96,10 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask || pc == null || !pc.IsAlive()) - { - return; - } + if (!GameStates.IsInTask || pc == null || !pc.IsAlive()) return; long now = Utils.TimeStamp; - if (now <= LastUpdate) - { - return; - } + if (now <= LastUpdate) return; LastUpdate = now; @@ -108,13 +107,9 @@ namespace EHR.Impostor bool shifted = pc.IsShifted(); if (shifted) - { Charges -= ChargesLostWhileShifted; - } else - { Charges += Gain; - } Charges = Math.Clamp(Charges, 0, MaxChargesStored.GetInt()); @@ -125,10 +120,7 @@ namespace EHR.Impostor pc.RpcResetAbilityCooldown(); } - if (beforeCharges != Charges) - { - pc.SetAbilityUseLimit(Charges, log: false); - } + if (beforeCharges != Charges) pc.SetAbilityUseLimit(Charges, log: false); } public override void OnCoEnterVent(PlayerPhysics physics, int ventId) @@ -142,6 +134,7 @@ namespace EHR.Impostor physics.RpcBootFromVent(ventId); physics.myPlayer.Notify(string.Format(Translator.GetString("Generator.Notify.NotEnoughCharges"), cost)); }, 0.5f, "Generator not enough charges to vent"); + return; } @@ -150,12 +143,10 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!base.OnCheckMurder(killer, target)) - { - return false; - } + if (!base.OnCheckMurder(killer, target)) return false; int cost = ActionCosts[Action.Kill]; + if (Charges < cost) { killer.Notify(string.Format(Translator.GetString("Generator.Notify.NotEnoughCharges"), cost)); @@ -172,10 +163,7 @@ namespace EHR.Impostor public override bool OnSabotage(PlayerControl pc) { - if (!pc.IsAlive()) - { - return true; - } + if (!pc.IsAlive()) return true; int cost = ActionCosts[Action.Sabotage]; @@ -191,10 +179,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting) - { - return true; - } + if (!shapeshifting) return true; int cost = ActionCosts[Action.Shapeshift]; diff --git a/Roles/Impostor/Godfather.cs b/Roles/Impostor/Godfather.cs index d71e718e4..b150142ba 100644 --- a/Roles/Impostor/Godfather.cs +++ b/Roles/Impostor/Godfather.cs @@ -24,10 +24,7 @@ public override bool OnVote(PlayerControl voter, PlayerControl target) { - if (voter == null || target == null || voter.PlayerId == target.PlayerId || Main.DontCancelVoteList.Contains(voter.PlayerId)) - { - return false; - } + if (voter == null || target == null || voter.PlayerId == target.PlayerId || Main.DontCancelVoteList.Contains(voter.PlayerId)) return false; GodfatherTarget = target.PlayerId; Main.DontCancelVoteList.Add(voter.PlayerId); diff --git a/Roles/Impostor/Greedier.cs b/Roles/Impostor/Greedier.cs index 6c96ed3a7..9683cc7c7 100644 --- a/Roles/Impostor/Greedier.cs +++ b/Roles/Impostor/Greedier.cs @@ -31,12 +31,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Greedier); + OddKillCooldown = new FloatOptionItem(Id + 10, "OddKillCooldown", new(0f, 60f, 2.5f), 27.5f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Greedier]) .SetValueFormat(OptionFormat.Seconds); + EvenKillCooldown = new FloatOptionItem(Id + 11, "EvenKillCooldown", new(0f, 30f, 2.5f), 15f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Greedier]) .SetValueFormat(OptionFormat.Seconds); + AfterMeetingKillCooldown = new FloatOptionItem(Id + 12, "AfterMeetingKillCooldown", new(0f, 30f, 2.5f), 25f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Greedier]) .SetValueFormat(OptionFormat.Seconds); @@ -53,6 +56,7 @@ namespace EHR.Impostor IsOdd = true; IsImitator = Main.PlayerStates[playerId].MainRole == CustomRoles.Imitator; + if (IsImitator) { OddKCD = Imitator.OddKillCooldown.GetFloat(); @@ -81,10 +85,7 @@ namespace EHR.Impostor private void SendRPC(byte playerId) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetGreedierOe, SendOption.Reliable); writer.Write(playerId); diff --git a/Roles/Impostor/Hacker.cs b/Roles/Impostor/Hacker.cs index 578350b04..19fc6045e 100644 --- a/Roles/Impostor/Hacker.cs +++ b/Roles/Impostor/Hacker.cs @@ -21,12 +21,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Hacker); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Hacker]) .SetValueFormat(OptionFormat.Seconds); + HackLimitOpt = new IntegerOptionItem(Id + 3, "HackLimit", new(0, 5, 1), 0, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Hacker]) .SetValueFormat(OptionFormat.Times); + HackerAbilityUseGainWithEachKill = new FloatOptionItem(Id + 4, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 0.2f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Hacker]) .SetValueFormat(OptionFormat.Times); @@ -71,50 +74,31 @@ namespace EHR.Impostor public static void AddDeadBody(PlayerControl target) { - if (target != null && !DeadBodyList.Contains(target.PlayerId)) - { - DeadBodyList.Add(target.PlayerId); - } + if (target != null && !DeadBodyList.Contains(target.PlayerId)) DeadBodyList.Add(target.PlayerId); } public override bool OnShapeshift(PlayerControl pc, PlayerControl ssTarget, bool shapeshifting) { - if (!shapeshifting || pc.GetAbilityUseLimit() < 1 || ssTarget == null || ssTarget.Is(CustomRoles.Needy) || ssTarget.Is(CustomRoles.Lazy)) - { - return false; - } + if (!shapeshifting || pc.GetAbilityUseLimit() < 1 || ssTarget == null || ssTarget.Is(CustomRoles.Needy) || ssTarget.Is(CustomRoles.Lazy)) return false; pc.RpcRemoveAbilityUse(); - byte targetId = byte.MaxValue; + var targetId = byte.MaxValue; foreach (byte db in DeadBodyList.ToArray()) { PlayerControl dp = Utils.GetPlayerById(db); - if (dp == null || dp.GetRealKiller() == null) - { - continue; - } + if (dp == null || dp.GetRealKiller() == null) continue; - if (dp.GetRealKiller().PlayerId == pc.PlayerId) - { - targetId = db; - } + if (dp.GetRealKiller().PlayerId == pc.PlayerId) targetId = db; } - if (targetId == byte.MaxValue && DeadBodyList.Count > 0) - { - targetId = DeadBodyList.RandomElement(); - } + if (targetId == byte.MaxValue && DeadBodyList.Count > 0) targetId = DeadBodyList.RandomElement(); if (targetId == byte.MaxValue) - { LateTask.New(() => ssTarget.NoCheckStartMeeting(ssTarget.Data), 0.15f, "Hacker Hacking Report Self"); - } else - { LateTask.New(() => ssTarget.NoCheckStartMeeting(Utils.GetPlayerById(targetId)?.Data), 0.15f, "Hacker Hacking Report"); - } return false; } diff --git a/Roles/Impostor/Hangman.cs b/Roles/Impostor/Hangman.cs index a5565855f..c87597b83 100644 --- a/Roles/Impostor/Hangman.cs +++ b/Roles/Impostor/Hangman.cs @@ -21,18 +21,23 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Hangman); + ShapeshiftCooldown = new FloatOptionItem(Id + 2, "ShapeshiftCooldown", new(1f, 60f, 1f), 30f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Hangman]) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftDuration = new FloatOptionItem(Id + 3, "ShapeshiftDuration", new(1f, 30f, 1f), 10f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Hangman]) .SetValueFormat(OptionFormat.Seconds); + KCD = new FloatOptionItem(Id + 4, "KillCooldownOnStrangle", new(1f, 90f, 1f), 40f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Hangman]) .SetValueFormat(OptionFormat.Seconds); + HangmanLimitOpt = new IntegerOptionItem(Id + 5, "AbilityUseLimit", new(0, 5, 1), 0, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Hangman]) .SetValueFormat(OptionFormat.Times); + HangmanAbilityUseGainWithEachKill = new FloatOptionItem(Id + 6, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 0.3f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Hangman]) .SetValueFormat(OptionFormat.Times); @@ -57,32 +62,17 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (Medic.ProtectList.Contains(target.PlayerId)) - { - return false; - } + if (Medic.ProtectList.Contains(target.PlayerId)) return false; - if (target.Is(CustomRoles.Madmate) && !ImpCanKillMadmate.GetBool()) - { - return false; - } + if (target.Is(CustomRoles.Madmate) && !ImpCanKillMadmate.GetBool()) return false; - if (killer.GetAbilityUseLimit() < 1 && killer.IsShifted()) - { - return false; - } + if (killer.GetAbilityUseLimit() < 1 && killer.IsShifted()) return false; if (killer.IsShifted()) { - if (target.Is(CustomRoles.Pestilence)) - { - return false; - } + if (target.Is(CustomRoles.Pestilence)) return false; - if (target.Is(CustomRoles.Veteran) && Veteran.VeteranInProtect.ContainsKey(target.PlayerId)) - { - return false; - } + if (target.Is(CustomRoles.Veteran) && Veteran.VeteranInProtect.ContainsKey(target.PlayerId)) return false; killer.RpcRemoveAbilityUse(); target.Data.IsDead = true; @@ -100,10 +90,7 @@ namespace EHR.Impostor public override void SetButtonTexts(HudManager hud, byte id) { - if (id.IsPlayerShifted()) - { - hud.KillButton?.OverrideText(Translator.GetString("HangmanKillButtonTextDuringSS")); - } + if (id.IsPlayerShifted()) hud.KillButton?.OverrideText(Translator.GetString("HangmanKillButtonTextDuringSS")); hud.AbilityButton?.SetUsesRemaining((int)id.GetAbilityUseLimit()); } diff --git a/Roles/Impostor/Hitman.cs b/Roles/Impostor/Hitman.cs index f5d2d03ae..2b145e490 100644 --- a/Roles/Impostor/Hitman.cs +++ b/Roles/Impostor/Hitman.cs @@ -24,10 +24,13 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Hitman); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 2.5f), 25f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Hitman]) .SetValueFormat(OptionFormat.Seconds); + SuccessKCD = new FloatOptionItem(Id + 11, "HitmanLowKCD", new(0f, 180f, 2.5f), 10f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Hitman]) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftCooldown = new FloatOptionItem(Id + 12, "ShapeshiftCooldown", new(0f, 180f, 2.5f), 10f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Hitman]) .SetValueFormat(OptionFormat.Seconds); } @@ -59,10 +62,7 @@ namespace EHR.Impostor private void SendRPC() { - if (!DoRPC) - { - return; - } + if (!DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetHitmanTarget, SendOption.Reliable); writer.Write(HitmanId); @@ -77,15 +77,9 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null) - { - return false; - } + if (killer == null) return false; - if (target == null) - { - return false; - } + if (target == null) return false; if (target.PlayerId == TargetId) { @@ -100,17 +94,14 @@ namespace EHR.Impostor public static void CheckAndResetTargets() { foreach (byte id in PlayerIdList) - { if (Main.PlayerStates[id].Role is Hitman { IsEnable: true } hm) - { hm.OnReportDeadBody(); - } - } } public override void OnReportDeadBody() { PlayerControl target = GetPlayerById(TargetId); + if (!target.IsAlive() || target.Data.Disconnected) { TargetId = byte.MaxValue; @@ -120,10 +111,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl hitman, PlayerControl target, bool shapeshifting) { - if (target == null || hitman == null || !shapeshifting || TargetId != byte.MaxValue || !target.IsAlive()) - { - return false; - } + if (target == null || hitman == null || !shapeshifting || TargetId != byte.MaxValue || !target.IsAlive()) return false; TargetId = target.PlayerId; SendRPC(); @@ -134,10 +122,7 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId) return string.Empty; byte id = (Main.PlayerStates[seer.PlayerId].Role as Hitman)?.TargetId ?? byte.MaxValue; return id == byte.MaxValue ? string.Empty : $"Target: {GetPlayerById(id).GetRealName().RemoveHtmlTags()}"; diff --git a/Roles/Impostor/Hypnotist.cs b/Roles/Impostor/Hypnotist.cs index 051dfeec8..18d01663b 100644 --- a/Roles/Impostor/Hypnotist.cs +++ b/Roles/Impostor/Hypnotist.cs @@ -73,21 +73,16 @@ namespace EHR.Impostor Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); Utils.SendRPC(CustomRPC.SyncRoleData, HypnotistId, ActivateTS); - if (DoReportAfterHypnosisEnds.GetBool()) - { - ReportDeadBodyPatch.CanReport.SetAllValues(false); - } + if (DoReportAfterHypnosisEnds.GetBool()) ReportDeadBodyPatch.CanReport.SetAllValues(false); } public override void OnFixedUpdate(PlayerControl pc) { - if (ActivateTS == 0) - { - return; - } + if (ActivateTS == 0) return; + + var notify = false; + var timeLeft = (int)(ActivateTS + AbilityDuration.GetInt() - Utils.TimeStamp); - bool notify = false; - int timeLeft = (int)(ActivateTS + AbilityDuration.GetInt() - Utils.TimeStamp); switch (timeLeft) { case <= 0: @@ -95,10 +90,7 @@ namespace EHR.Impostor notify = true; pc.RpcResetAbilityCooldown(); Utils.SendRPC(CustomRPC.SyncRoleData, HypnotistId, ActivateTS); - if (DoReportAfterHypnosisEnds.GetBool()) - { - ReportDeadBodyPatch.CanReport.SetAllValues(true); - } + if (DoReportAfterHypnosisEnds.GetBool()) ReportDeadBodyPatch.CanReport.SetAllValues(true); break; case <= 6 when Count++ >= 30: @@ -107,10 +99,7 @@ namespace EHR.Impostor break; } - if (notify) - { - Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - } + if (notify) Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); } public void ReceiveRPC(MessageReader reader) @@ -120,12 +109,9 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != HypnotistId || meeting || (seer.IsModClient() && !hud) || ActivateTS == 0) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != HypnotistId || meeting || (seer.IsModClient() && !hud) || ActivateTS == 0) return string.Empty; - int timeLeft = (int)(ActivateTS + AbilityDuration.GetInt() - Utils.TimeStamp); + var timeLeft = (int)(ActivateTS + AbilityDuration.GetInt() - Utils.TimeStamp); return timeLeft <= 5 ? $"\u25a9 ({timeLeft})" : "\u25a9"; } } diff --git a/Roles/Impostor/ImperiusCurse.cs b/Roles/Impostor/ImperiusCurse.cs index 3eeb8e174..7a193f811 100644 --- a/Roles/Impostor/ImperiusCurse.cs +++ b/Roles/Impostor/ImperiusCurse.cs @@ -11,9 +11,11 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(3700, TabGroup.ImpostorRoles, CustomRoles.ImperiusCurse); + ShapeImperiusCurseShapeshiftDuration = new FloatOptionItem(3710, "ShapeshiftDuration", new(2.5f, 300f, 2.5f), 20f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.ImperiusCurse]) .SetValueFormat(OptionFormat.Seconds); + ImperiusCurseShapeshiftCooldown = new FloatOptionItem(3711, "ShapeshiftCooldown", new(1f, 180f, 1f), 30f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.ImperiusCurse]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/Impostor/ImpostorVanillaRoles.cs b/Roles/Impostor/ImpostorVanillaRoles.cs index 3467d1a8f..fa960ae59 100644 --- a/Roles/Impostor/ImpostorVanillaRoles.cs +++ b/Roles/Impostor/ImpostorVanillaRoles.cs @@ -14,16 +14,21 @@ namespace EHR.Impostor { SetupRoleOptions(300, Tab, CustomRoles.ImpostorEHR); SetupRoleOptions(350, Tab, CustomRoles.PhantomEHR); + PhantomCooldown = new FloatOptionItem(352, "PhantomCooldown", new(1f, 180f, 1f), 30f, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.PhantomEHR]) .SetValueFormat(OptionFormat.Seconds); + PhantomDuration = new FloatOptionItem(353, "PhantomDuration", new(1f, 60f, 1f), 10f, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.PhantomEHR]) .SetValueFormat(OptionFormat.Seconds); + SetupRoleOptions(400, Tab, CustomRoles.ShapeshifterEHR); + ShapeshiftCD = new FloatOptionItem(402, "ShapeshiftCooldown", new(1f, 180f, 1f), 30f, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ShapeshifterEHR]) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftDur = new FloatOptionItem(403, "ShapeshiftDuration", new(1f, 60f, 1f), 10f, Tab) .SetParent(CustomRoleSpawnChances[CustomRoles.ShapeshifterEHR]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/Impostor/Inhibitor.cs b/Roles/Impostor/Inhibitor.cs index 72107abd8..d275685d8 100644 --- a/Roles/Impostor/Inhibitor.cs +++ b/Roles/Impostor/Inhibitor.cs @@ -12,9 +12,11 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(1500, TabGroup.ImpostorRoles, CustomRoles.Inhibitor); + InhibitorCD = new FloatOptionItem(1510, "KillCooldown", new(0f, 180f, 2.5f), 20f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Inhibitor]) .SetValueFormat(OptionFormat.Seconds); + InhibitorCDAfterMeetings = new FloatOptionItem(1511, "AfterMeetingKillCooldown", new(0f, 180f, 2.5f), 22.5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Inhibitor]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/Impostor/Kamikaze.cs b/Roles/Impostor/Kamikaze.cs index 484651391..f6858cb64 100644 --- a/Roles/Impostor/Kamikaze.cs +++ b/Roles/Impostor/Kamikaze.cs @@ -23,12 +23,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Kamikaze); + MarkCD = new FloatOptionItem(Id + 2, "KamikazeMarkCD", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Kamikaze]) .SetValueFormat(OptionFormat.Seconds); + KamikazeLimitOpt = new IntegerOptionItem(Id + 3, "AbilityUseLimit", new(0, 5, 1), 1, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Kamikaze]) .SetValueFormat(OptionFormat.Times); + KamikazeAbilityUseGainWithEachKill = new FloatOptionItem(Id + 4, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 0.5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Kamikaze]) .SetValueFormat(OptionFormat.Times); @@ -53,15 +56,9 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null) - { - return false; - } + if (killer == null || target == null) return false; - if (killer.GetAbilityUseLimit() < 1) - { - return true; - } + if (killer.GetAbilityUseLimit() < 1) return true; return killer.CheckDoubleTrigger(target, () => { @@ -73,34 +70,26 @@ namespace EHR.Impostor public override void OnGlobalFixedUpdate(PlayerControl pc, bool lowLoad) { - if (lowLoad || !On) - { - return; - } + if (lowLoad || !On) return; foreach (byte kkId in PlayerIdList) { if (Main.PlayerStates[kkId].Role is Kamikaze { IsEnable: true } kk) { PlayerControl kamikazePc = GetPlayerById(kk.KamikazeId); + if (kamikazePc == null) { LateTask.New(() => PlayerIdList.Remove(kkId), 0.001f, log: false); continue; } - if (kamikazePc.IsAlive() || kk.MarkedPlayers.Count == 0) - { - continue; - } + if (kamikazePc.IsAlive() || kk.MarkedPlayers.Count == 0) continue; foreach (byte id in kk.MarkedPlayers) { PlayerControl victim = GetPlayerById(id); - if (victim == null || !victim.IsAlive()) - { - continue; - } + if (victim == null || !victim.IsAlive()) continue; victim.Suicide(PlayerState.DeathReason.Kamikazed, kamikazePc); } diff --git a/Roles/Impostor/Kidnapper.cs b/Roles/Impostor/Kidnapper.cs index 8c8634e44..1dd673d6f 100644 --- a/Roles/Impostor/Kidnapper.cs +++ b/Roles/Impostor/Kidnapper.cs @@ -14,6 +14,7 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Kidnapper); + SSCD = new FloatOptionItem(Id + 2, "ShapeshiftCooldown", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Kidnapper]) .SetValueFormat(OptionFormat.Seconds); @@ -27,15 +28,9 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl kidnapper, PlayerControl target, bool shapeshifting) { - if (kidnapper == null || target == null || !shapeshifting) - { - return true; - } + if (kidnapper == null || target == null || !shapeshifting) return true; - if (!target.TP(kidnapper)) - { - kidnapper.Notify(Utils.ColorString(Color.yellow, Translator.GetString("TargetCannotBeTeleported"))); - } + if (!target.TP(kidnapper)) kidnapper.Notify(Utils.ColorString(Color.yellow, Translator.GetString("TargetCannotBeTeleported"))); return false; } diff --git a/Roles/Impostor/Librarian.cs b/Roles/Impostor/Librarian.cs index 15034020f..05a92e8cf 100644 --- a/Roles/Impostor/Librarian.cs +++ b/Roles/Impostor/Librarian.cs @@ -29,19 +29,25 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Librarian); + Radius = new FloatOptionItem(Id + 5, "LibrarianRadius", new(0.5f, 5f, 0.5f), 3f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Librarian]) .SetValueFormat(OptionFormat.Multiplier); + ShowSSAnimation = new BooleanOptionItem(Id + 6, "LibrarianShowSSAnimation", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Librarian]); + SSCD = new FloatOptionItem(Id + 7, "ShapeshiftCooldown", new(2.5f, 60f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(ShowSSAnimation) .SetValueFormat(OptionFormat.Seconds); + SSDur = new FloatOptionItem(Id + 8, "LibrarianSilenceDuration", new(2.5f, 60f, 2.5f), 10f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Librarian]) .SetValueFormat(OptionFormat.Seconds); + CanKillWhileShifted = new BooleanOptionItem(Id + 9, "CanKillWhileShifted", false, TabGroup.ImpostorRoles) .SetParent(ShowSSAnimation); + NameDuration = new IntegerOptionItem(Id + 10, "LibrarianNameNotifyDuration", new(1, 30, 1), 10, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Librarian]) .SetValueFormat(OptionFormat.Seconds); @@ -68,9 +74,7 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte id) { if (UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = SSCD.GetFloat(); - } else { AURoleOptions.ShapeshifterCooldown = SSCD.GetFloat(); @@ -80,10 +84,7 @@ namespace EHR.Impostor private static void SendRPC(byte playerId, bool isInSilenceMode) { - if (!DoRPC) - { - return; - } + if (!DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetLibrarianMode, SendOption.Reliable); writer.Write(playerId); @@ -96,59 +97,40 @@ namespace EHR.Impostor byte playerId = reader.ReadByte(); bool isInSilenceMode = reader.ReadBoolean(); - if (Main.PlayerStates[playerId].Role is not Librarian lr) - { - return; - } + if (Main.PlayerStates[playerId].Role is not Librarian lr) return; lr.IsInSilencingMode = (isInSilenceMode, TimeStamp); } public static bool OnAnyoneReport(PlayerControl reporter) { - if (reporter == null || PlayerIdList.Count == 0) - { - return true; - } + if (reporter == null || PlayerIdList.Count == 0) return true; PlayerControl librarian = null; float silenceRadius = Radius.GetFloat(); foreach (byte id in PlayerIdList) { - if (Main.PlayerStates[id].Role is not Librarian lr) - { - continue; - } + if (Main.PlayerStates[id].Role is not Librarian lr) continue; - if (!lr.IsInSilencingMode.SILENCING) - { - continue; - } + if (!lr.IsInSilencingMode.SILENCING) continue; PlayerControl pc = GetPlayerById(id); - if (pc == null || !pc.IsAlive()) - { - continue; - } + if (pc == null || !pc.IsAlive()) continue; - if (Vector2.Distance(pc.Pos(), reporter.Pos()) <= silenceRadius) - { - librarian = pc; - } + if (Vector2.Distance(pc.Pos(), reporter.Pos()) <= silenceRadius) librarian = pc; } - if (librarian == null) - { - return true; - } + if (librarian == null) return true; reporter.SetRealKiller(librarian); + if (librarian.RpcCheckAndMurder(reporter)) { Logger.Info(" Counter kill (report during and in range of silence)", "Librarian"); Sssh.Add(librarian.PlayerId); NotifyRoles(SpecifyTarget: librarian); + LateTask.New(() => { Sssh.Remove(librarian.PlayerId); @@ -161,15 +143,9 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl pc, PlayerControl target, bool shapeshifting) { - if (!IsEnable) - { - return false; - } + if (!IsEnable) return false; - if (pc == null) - { - return false; - } + if (pc == null) return false; ChangeSilencingMode(pc); @@ -178,15 +154,9 @@ namespace EHR.Impostor public override bool OnVanish(PlayerControl pc) { - if (!IsEnable) - { - return false; - } + if (!IsEnable) return false; - if (pc == null) - { - return false; - } + if (pc == null) return false; ChangeSilencingMode(pc); @@ -202,15 +172,9 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl pc) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - if (ShowSSAnimation.GetBool() && !UsePhantomBasis.GetBool() && !UseUnshiftTrigger.GetBool()) - { - return; - } + if (ShowSSAnimation.GetBool() && !UsePhantomBasis.GetBool() && !UseUnshiftTrigger.GetBool()) return; if (IsInSilencingMode.SILENCING && IsInSilencingMode.LAST_CHANGE + SSDur.GetInt() < TimeStamp) { @@ -222,10 +186,7 @@ namespace EHR.Impostor public override void OnReportDeadBody() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; IsInSilencingMode = (false, TimeStamp); Sssh.Clear(); @@ -233,26 +194,17 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - string result = string.Empty; - if (target.Is(CustomRoles.Librarian)) - { - result += GetNameTextForSuffix(target.PlayerId); - } + var result = string.Empty; + if (target.Is(CustomRoles.Librarian)) result += GetNameTextForSuffix(target.PlayerId); - if (hud || (seer.PlayerId == target.PlayerId && !seer.IsModClient())) - { - result += GetSelfSuffixAndHudText(target.PlayerId); - } + if (hud || (seer.PlayerId == target.PlayerId && !seer.IsModClient())) result += GetSelfSuffixAndHudText(target.PlayerId); return result; } private static string GetNameTextForSuffix(byte playerId) { - if (Main.PlayerStates[playerId].Role is not Librarian lr) - { - return string.Empty; - } + if (Main.PlayerStates[playerId].Role is not Librarian lr) return string.Empty; return lr.IsEnable && lr.IsInSilencingMode.SILENCING && Sssh.Contains(playerId) && GameStates.IsInTask ? GetString("LibrarianNameText") @@ -261,15 +213,9 @@ namespace EHR.Impostor private static string GetSelfSuffixAndHudText(byte playerId) { - if (Main.PlayerStates[playerId].Role is not Librarian lr) - { - return string.Empty; - } + if (Main.PlayerStates[playerId].Role is not Librarian lr) return string.Empty; - if (!lr.IsEnable || !GameStates.IsInTask) - { - return string.Empty; - } + if (!lr.IsEnable || !GameStates.IsInTask) return string.Empty; return string.Format(GetString("LibrarianModeText"), lr.IsInSilencingMode.SILENCING ? GetString("LibrarianSilenceMode") : GetString("LibrarianNormalMode")); } diff --git a/Roles/Impostor/Lurker.cs b/Roles/Impostor/Lurker.cs index 47ff6fc97..dab685567 100644 --- a/Roles/Impostor/Lurker.cs +++ b/Roles/Impostor/Lurker.cs @@ -16,9 +16,11 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Lurker); + DefaultKillCooldown = new FloatOptionItem(Id + 10, "SansDefaultKillCooldown", new(1f, 180f, 1f), 30f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Lurker]) .SetValueFormat(OptionFormat.Seconds); + ReduceKillCooldown = new FloatOptionItem(Id + 11, "SansReduceKillCooldown", new(0f, 10f, 1f), 1f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Lurker]) .SetValueFormat(OptionFormat.Seconds); @@ -41,16 +43,10 @@ namespace EHR.Impostor public override void OnEnterVent(PlayerControl pc, Vent vent) { - if (!pc.Is(CustomRoles.Lurker)) - { - return; - } + if (!pc.Is(CustomRoles.Lurker)) return; float newCd = Main.AllPlayerKillCooldown[pc.PlayerId] - ReduceKillCooldown.GetFloat(); - if (newCd <= 0) - { - return; - } + if (newCd <= 0) return; Main.AllPlayerKillCooldown[pc.PlayerId] = newCd; pc.SyncSettings(); diff --git a/Roles/Impostor/Mafia.cs b/Roles/Impostor/Mafia.cs index 94e9f1140..f04b5afb1 100644 --- a/Roles/Impostor/Mafia.cs +++ b/Roles/Impostor/Mafia.cs @@ -22,14 +22,18 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(3100, TabGroup.ImpostorRoles, CustomRoles.Mafia); + MafiaCanKillNum = new IntegerOptionItem(3200, "MafiaCanKillNum", new(0, 15, 1), 1, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mafia]) .SetValueFormat(OptionFormat.Players); + LegacyMafia = new BooleanOptionItem(3210, "LegacyMafia", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mafia]); + MafiaShapeshiftCD = new FloatOptionItem(3211, "ShapeshiftCooldown", new(1f, 180f, 1f), 30f, TabGroup.ImpostorRoles) .SetParent(LegacyMafia) .SetValueFormat(OptionFormat.Seconds); + MafiaShapeshiftDur = new FloatOptionItem(3212, "ShapeshiftDuration", new(1f, 180f, 1f), 15f, TabGroup.ImpostorRoles) .SetParent(LegacyMafia) .SetValueFormat(OptionFormat.Seconds); @@ -58,37 +62,21 @@ namespace EHR.Impostor public static bool MafiaMsgCheck(PlayerControl pc, string msg, bool isUI = false) { - if (!AmongUsClient.Instance.AmHost) - { - return false; - } + if (!AmongUsClient.Instance.AmHost) return false; - if (!GameStates.IsInGame || pc == null) - { - return false; - } + if (!GameStates.IsInGame || pc == null) return false; - if (!pc.Is(CustomRoles.Mafia)) - { - return false; - } + if (!pc.Is(CustomRoles.Mafia)) return false; msg = msg.Trim().ToLower().Replace(" ", string.Empty); - if (msg.Length < 3 || !msg.StartsWith("/rv")) - { - return false; - } + if (msg.Length < 3 || !msg.StartsWith("/rv")) return false; if (MafiaCanKillNum.GetInt() < 1) { if (!isUI) - { Utils.SendMessage(GetString("MafiaKillDisable"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("MafiaKillDisable")); - } return true; } @@ -113,19 +101,16 @@ namespace EHR.Impostor if (MafiaRevenged[pc.PlayerId] >= MafiaCanKillNum.GetInt()) { if (!isUI) - { Utils.SendMessage(GetString("MafiaKillMax"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("MafiaKillMax")); - } return true; } } PlayerControl target; + try { int targetId = int.Parse(msg.Replace("/rv", string.Empty)); @@ -134,13 +119,9 @@ namespace EHR.Impostor catch { if (!isUI) - { Utils.SendMessage(GetString("MafiaKillDead"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("MafiaKillDead")); - } return true; } @@ -148,13 +129,9 @@ namespace EHR.Impostor if (target == null || target.Data.IsDead) { if (!isUI) - { Utils.SendMessage(GetString("MafiaKillDead"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("MafiaKillDead")); - } return true; } @@ -162,13 +139,9 @@ namespace EHR.Impostor if (target.Is(CustomRoles.Pestilence)) { if (!isUI) - { Utils.SendMessage(GetString("PestilenceImmune"), pc.PlayerId); - } else - { pc.ShowPopUp(GetString("PestilenceImmune")); - } return true; } @@ -203,6 +176,7 @@ namespace EHR.Impostor LateTask.New(() => { Utils.SendMessage(string.Format(GetString("MafiaKillSucceed"), Name), 255, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Mafia), GetString("MafiaRevengeTitle"))); }, 0.6f, "Mafia Kill"); }, 0.2f, "Mafia Kill"); + return true; } @@ -223,19 +197,12 @@ namespace EHR.Impostor { Logger.Msg($"Click: ID {playerId}", "Mafia UI"); PlayerControl pc = Utils.GetPlayerById(playerId); - if (pc == null || !pc.IsAlive() || !GameStates.IsVoting) - { - return; - } + if (pc == null || !pc.IsAlive() || !GameStates.IsVoting) return; if (AmongUsClient.Instance.AmHost) - { MafiaMsgCheck(PlayerControl.LocalPlayer, $"/rv {playerId}", true); - } else - { SendRPC(playerId); - } } public static void CreateJudgeButton(MeetingHud __instance) @@ -243,18 +210,15 @@ namespace EHR.Impostor foreach (PlayerVoteArea pva in __instance.playerStates.ToArray()) { PlayerControl pc = Utils.GetPlayerById(pva.TargetPlayerId); - if (pc == null || !pc.IsAlive()) - { - continue; - } + if (pc == null || !pc.IsAlive()) continue; GameObject template = pva.Buttons.transform.Find("CancelButton").gameObject; GameObject targetBox = Object.Instantiate(template, pva.transform); targetBox.name = "ShootButton"; targetBox.transform.localPosition = new(-0.95f, 0.03f, -1.31f); - SpriteRenderer renderer = targetBox.GetComponent(); + var renderer = targetBox.GetComponent(); renderer.sprite = CustomButton.Get("MeetingKillButton"); - PassiveButton button = targetBox.GetComponent(); + var button = targetBox.GetComponent(); button.OnClick.RemoveAllListeners(); button.OnClick.AddListener((Action)(() => MafiaOnClick(pva.TargetPlayerId))); } @@ -265,10 +229,7 @@ namespace EHR.Impostor { public static void Postfix(MeetingHud __instance) { - if (PlayerControl.LocalPlayer.Is(CustomRoles.Mafia) && !PlayerControl.LocalPlayer.IsAlive()) - { - CreateJudgeButton(__instance); - } + if (PlayerControl.LocalPlayer.Is(CustomRoles.Mafia) && !PlayerControl.LocalPlayer.IsAlive()) CreateJudgeButton(__instance); } } } diff --git a/Roles/Impostor/Mafioso.cs b/Roles/Impostor/Mafioso.cs index a4fee4f65..0dc16c4f2 100644 --- a/Roles/Impostor/Mafioso.cs +++ b/Roles/Impostor/Mafioso.cs @@ -52,15 +52,20 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Mafioso); + Delay = new IntegerOptionItem(Id + 10, "MafiosoDelay", new(1, 10, 1), 3, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mafioso]) .SetValueFormat(OptionFormat.Seconds); + RewardForKilling = new IntegerOptionItem(Id + 11, "MafiosoRewardForKilling", new(0, 100, 5), 40, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mafioso]); + RewardForSabotaging = new IntegerOptionItem(Id + 12, "MafiosoRewardForSabotaging", new(0, 100, 5), 25, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mafioso]); + RewardForVenting = new IntegerOptionItem(Id + 13, "MafiosoRewardForVenting", new(0, 100, 5), 10, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mafioso]); + RewardForOtherPlayerEjected = new IntegerOptionItem(Id + 14, "MafiosoRewardForOtherPlayerEjected", new(0, 100, 5), 30, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mafioso]); } @@ -107,23 +112,17 @@ namespace EHR.Impostor private void SendRPC() { - if (!IsEnable || !DoRPC) - { - return; - } + if (!IsEnable || !DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncMafiosoData, SendOption.Reliable); writer.Write(MafiosoId); writer.Write(Tier); writer.Write(XP); writer.Write(PreviouslyUsedVents.Count); + if (PreviouslyUsedVents.Count > 0) - { foreach (int vent in PreviouslyUsedVents.ToArray()) - { writer.Write(vent); - } - } AmongUsClient.Instance.FinishRpcImmediately(writer); } @@ -134,21 +133,15 @@ namespace EHR.Impostor XP = reader.ReadInt32(); PreviouslyUsedVents.Clear(); int elements = reader.ReadInt32(); + if (elements > 0) - { - for (int i = 0; i < elements; i++) - { + for (var i = 0; i < elements; i++) PreviouslyUsedVents.Add(reader.ReadInt32()); - } - } } private void SendRPCSyncPistolCD() { - if (!IsEnable || !DoRPC) - { - return; - } + if (!IsEnable || !DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncMafiosoPistolCD, SendOption.Reliable); writer.Write(MafiosoId); @@ -167,10 +160,7 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask || !IsEnable || pc == null || !pc.IsAlive()) - { - return; - } + if (!GameStates.IsInTask || !IsEnable || pc == null || !pc.IsAlive()) return; if (XP >= 100 && Tier < 5) { @@ -183,47 +173,29 @@ namespace EHR.Impostor pc.Notify(GetString("MafiosoLevelUp")); } - if (lastUpdate >= TimeStamp) - { - return; - } + if (lastUpdate >= TimeStamp) return; lastUpdate = TimeStamp; int before1CD = Pistol1CD; int before2CD = Pistol2CD; - if (Pistol1CD > 0) - { - Pistol1CD--; - } + if (Pistol1CD > 0) Pistol1CD--; - if (Pistol2CD > 0) - { - Pistol2CD--; - } + if (Pistol2CD > 0) Pistol2CD--; if (before1CD != Pistol1CD || before2CD != Pistol2CD) { NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - if (pc.IsNonHostModClient()) - { - SendRPCSyncPistolCD(); - } + if (pc.IsNonHostModClient()) SendRPCSyncPistolCD(); } } public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!GameStates.IsInTask || target == null || killer == null || !killer.Is(CustomRoles.Mafioso) || Tier < 3 || !IsEnable) - { - return true; - } + if (!GameStates.IsInTask || target == null || killer == null || !killer.Is(CustomRoles.Mafioso) || Tier < 3 || !IsEnable) return true; - if (Pistol1CD > 0 && Pistol2CD > 0) - { - return false; - } + if (Pistol1CD > 0 && Pistol2CD > 0) return false; int KCD = Tier >= 4 ? (int)Math.Round(DefaultKillCooldown) : (int)Math.Round(DefaultKillCooldown * 1.5); KCD++; @@ -244,29 +216,20 @@ namespace EHR.Impostor LateTask.New(() => { // ReSharper disable once ConditionIsAlwaysTrueOrFalse ---- Can be null since it's a task that completes later - if (target != null && target.IsAlive() && GameStates.IsInTask) - { - target.Suicide(PlayerState.DeathReason.Kill, killer); - } + if (target != null && target.IsAlive() && GameStates.IsInTask) target.Suicide(PlayerState.DeathReason.Kill, killer); }, Delay.GetInt(), "Mafioso Tier 5 Kill Delay"); return false; } - if (Pistol1CD > 1 && Pistol2CD > 1) - { - LateTask.New(() => { killer.SetKillCooldown(Math.Min(Pistol1CD, Pistol2CD) - 1); }, 0.1f, "Mafioso SetKillCooldown"); - } + if (Pistol1CD > 1 && Pistol2CD > 1) LateTask.New(() => { killer.SetKillCooldown(Math.Min(Pistol1CD, Pistol2CD) - 1); }, 0.1f, "Mafioso SetKillCooldown"); return true; } public override void OnReportDeadBody() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; PreviouslyUsedVents.Clear(); int KCD = Tier >= 4 ? (int)Math.Round(DefaultKillCooldown) : (int)Math.Round(DefaultKillCooldown * 1.5); @@ -285,22 +248,16 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (!hud || Main.PlayerStates[seer.PlayerId].Role is not Mafioso { IsEnable: true } mo) - { - return string.Empty; - } + if (!hud || Main.PlayerStates[seer.PlayerId].Role is not Mafioso { IsEnable: true } mo) return string.Empty; if (mo.Tier >= 3) { string CD; + if (mo.Pistol1CD <= 0 && mo.Pistol2CD <= 0) - { CD = "Can Kill"; - } else - { CD = $"CD: {Math.Min(mo.Pistol1CD, mo.Pistol2CD)}s"; - } return string.Format(GetString("MafiosoHUDTextWithDualPistols"), mo.Tier, mo.XP, CD); } @@ -310,10 +267,7 @@ namespace EHR.Impostor public override void OnMurder(PlayerControl killer, PlayerControl target) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; XP += RewardForKilling.GetInt(); SendRPC(); @@ -321,15 +275,9 @@ namespace EHR.Impostor public override void OnEnterVent(PlayerControl pc, Vent vent) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - if (PreviouslyUsedVents.Contains(vent.Id)) - { - return; - } + if (PreviouslyUsedVents.Contains(vent.Id)) return; PreviouslyUsedVents.Add(vent.Id); XP += RewardForVenting.GetInt(); diff --git a/Roles/Impostor/Mastermind.cs b/Roles/Impostor/Mastermind.cs index 58ac5f198..d88900307 100644 --- a/Roles/Impostor/Mastermind.cs +++ b/Roles/Impostor/Mastermind.cs @@ -31,11 +31,14 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Mastermind); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 2.5f), 25f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Mastermind]) .SetValueFormat(OptionFormat.Seconds); + // Manipulation Cooldown = Kill Cooldown + Delay + Time Limit TimeLimit = new IntegerOptionItem(Id + 12, "MastermindTimeLimit", new(1, 60, 1), 20, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Mastermind]) .SetValueFormat(OptionFormat.Seconds); + Delay = new IntegerOptionItem(Id + 13, "MastermindDelay", new(0, 30, 1), 7, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Mastermind]) .SetValueFormat(OptionFormat.Seconds); } @@ -63,20 +66,11 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!IsEnable) - { - return false; - } + if (!IsEnable) return false; - if (killer == null) - { - return false; - } + if (killer == null) return false; - if (target == null) - { - return false; - } + if (target == null) return false; return killer.CheckDoubleTrigger(target, () => { @@ -88,10 +82,7 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl _) { - if (!IsEnable || GameStates.IsMeeting || (ManipulatedPlayers.Count == 0 && ManipulateDelays.Count == 0)) - { - return; - } + if (!IsEnable || GameStates.IsMeeting || (ManipulatedPlayers.Count == 0 && ManipulateDelays.Count == 0)) return; foreach (KeyValuePair x in ManipulateDelays) { @@ -114,9 +105,7 @@ namespace EHR.Impostor pc.SetKillCooldown(1f); } else - { pc.RpcChangeRoleBasis(CustomRoles.NSerialKiller); - } NotifyRoles(SpecifySeer: MastermindPC, SpecifyTarget: pc); } @@ -150,18 +139,12 @@ namespace EHR.Impostor public override void OnReportDeadBody() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; foreach (KeyValuePair x in ManipulatedPlayers) { PlayerControl pc = GetPlayerById(x.Key); - if (pc.IsAlive()) - { - pc.Suicide(realKiller: MastermindPC); - } + if (pc.IsAlive()) pc.Suicide(realKiller: MastermindPC); } ManipulateDelays.Clear(); @@ -171,22 +154,13 @@ namespace EHR.Impostor public static bool ForceKillForManipulatedPlayer(PlayerControl killer, PlayerControl target) { - if (killer == null) - { - return false; - } + if (killer == null) return false; - if (target == null) - { - return false; - } + if (target == null) return false; ManipulatedPlayers.Remove(killer.PlayerId); - foreach (byte id in PlayerIdList) - { - (Main.PlayerStates[id].Role as Mastermind)?.NotifyMastermindTargetSurvived(); - } + foreach (byte id in PlayerIdList) (Main.PlayerStates[id].Role as Mastermind)?.NotifyMastermindTargetSurvived(); if (target.Is(CustomRoles.Pestilence) || Veteran.VeteranInProtect.ContainsKey(target.PlayerId) || target.Is(CustomRoles.Mastermind)) { @@ -214,16 +188,10 @@ namespace EHR.Impostor private void NotifyMastermindTargetSurvived() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; MastermindPC.Notify(GetString("ManipulatedKilled")); - if (Main.KillTimers[MastermindId] > KillCooldown.GetFloat()) - { - MastermindPC.SetKillCooldown(KillCooldown.GetFloat()); - } + if (Main.KillTimers[MastermindId] > KillCooldown.GetFloat()) MastermindPC.SetKillCooldown(KillCooldown.GetFloat()); } } } \ No newline at end of file diff --git a/Roles/Impostor/Miner.cs b/Roles/Impostor/Miner.cs index 798be0fc2..cbbb51fff 100644 --- a/Roles/Impostor/Miner.cs +++ b/Roles/Impostor/Miner.cs @@ -10,6 +10,7 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(3800, TabGroup.ImpostorRoles, CustomRoles.Miner); + Options.MinerSSCD = new FloatOptionItem(3811, "ShapeshiftCooldown", new(1f, 180f, 1f), 5f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Miner]) .SetValueFormat(OptionFormat.Seconds); @@ -28,15 +29,10 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte playerId) { if (Options.UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = Options.MinerSSCD.GetFloat(); - } else { - if (Options.UsePets.GetBool()) - { - return; - } + if (Options.UsePets.GetBool()) return; AURoleOptions.ShapeshifterCooldown = Options.MinerSSCD.GetFloat(); AURoleOptions.ShapeshifterDuration = 1f; @@ -46,13 +42,9 @@ namespace EHR.Impostor public override void SetButtonTexts(HudManager hud, byte id) { if (Options.UsePets.GetBool()) - { hud.PetButton?.OverrideText(Translator.GetString("MinerTeleButtonText")); - } else - { hud.AbilityButton?.OverrideText(Translator.GetString("MinerTeleButtonText")); - } } public override void OnPet(PlayerControl pc) @@ -62,10 +54,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) return true; TeleportToVent(shapeshifter); diff --git a/Roles/Impostor/Minimalism.cs b/Roles/Impostor/Minimalism.cs index 6369f61c3..5a4f173b3 100644 --- a/Roles/Impostor/Minimalism.cs +++ b/Roles/Impostor/Minimalism.cs @@ -13,9 +13,11 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(16300, TabGroup.ImpostorRoles, CustomRoles.Minimalism); + MnKillCooldown = new FloatOptionItem(16310, "KillCooldown", new(2.5f, 180f, 2.5f), 10f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Minimalism]) .SetValueFormat(OptionFormat.Seconds); + BypassShields = new BooleanOptionItem(16311, "BypassShields", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Minimalism]); } @@ -54,10 +56,7 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!base.OnCheckMurder(killer, target)) - { - return false; - } + if (!base.OnCheckMurder(killer, target)) return false; if (BypassShields.GetBool()) { diff --git a/Roles/Impostor/Morphling.cs b/Roles/Impostor/Morphling.cs index 97946a7a3..ac47ebc64 100644 --- a/Roles/Impostor/Morphling.cs +++ b/Roles/Impostor/Morphling.cs @@ -18,12 +18,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Morphling); + KillCooldown = new FloatOptionItem(Id + 14, "KillCooldown", new(0f, 60f, 2.5f), 10f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Morphling]) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftCD = new FloatOptionItem(Id + 15, "ShapeshiftCooldown", new(1f, 60f, 1f), 20f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Morphling]) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftDur = new FloatOptionItem(Id + 16, "ShapeshiftDuration", new(1f, 30f, 1f), 10f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Morphling]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/Impostor/Nullifier.cs b/Roles/Impostor/Nullifier.cs index 6fcacf87f..ba2d8d87e 100644 --- a/Roles/Impostor/Nullifier.cs +++ b/Roles/Impostor/Nullifier.cs @@ -18,12 +18,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Nullifier); + NullCD = new FloatOptionItem(Id + 10, "NullCD", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Nullifier]) .SetValueFormat(OptionFormat.Seconds); + KCD = new FloatOptionItem(Id + 11, "KillCooldown", new(0f, 180f, 2.5f), 25f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Nullifier]) .SetValueFormat(OptionFormat.Seconds); + Delay = new IntegerOptionItem(Id + 12, "NullifierDelay", new(0, 90, 1), 5, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Nullifier]) .SetValueFormat(OptionFormat.Seconds); @@ -46,24 +49,19 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!IsEnable || killer == null || target == null) - { - return false; - } + if (!IsEnable || killer == null || target == null) return false; return killer.CheckDoubleTrigger(target, () => { killer.SetKillCooldown(NullCD.GetFloat()); killer.Notify(Translator.GetString("NullifierUseRemoved")); + LateTask.New(() => { switch (target.GetCustomRole()) { case CustomRoles.Cleanser: - if (Main.PlayerStates[target.PlayerId].Role is not Cleanser { IsEnable: true } cs) - { - return; - } + if (Main.PlayerStates[target.PlayerId].Role is not Cleanser { IsEnable: true } cs) return; cs.CleanserUses++; cs.SendRPC(target.PlayerId); @@ -75,16 +73,11 @@ namespace EHR.Impostor NiceHacker.SendRPC(target.PlayerId, NiceHacker.UseLimitSeconds[target.PlayerId]); } else - { NiceHacker.UseLimit[target.PlayerId]--; - } break; case CustomRoles.SabotageMaster: - if (Main.PlayerStates[target.PlayerId].Role is not SabotageMaster { IsEnable: true } sm) - { - return; - } + if (Main.PlayerStates[target.PlayerId].Role is not SabotageMaster { IsEnable: true } sm) return; sm.UsedSkillCount++; sm.SendRPC(); @@ -98,10 +91,7 @@ namespace EHR.Impostor break; } - if (GameStates.IsInTask) - { - Utils.NotifyRoles(SpecifySeer: target, SpecifyTarget: target); - } + if (GameStates.IsInTask) Utils.NotifyRoles(SpecifySeer: target, SpecifyTarget: target); }, Delay.GetInt(), "Nullifier Remove Ability Use"); }); } diff --git a/Roles/Impostor/OverKiller.cs b/Roles/Impostor/OverKiller.cs index f542a3c04..a24406f93 100644 --- a/Roles/Impostor/OverKiller.cs +++ b/Roles/Impostor/OverKiller.cs @@ -15,6 +15,7 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(16900, TabGroup.ImpostorRoles, CustomRoles.OverKiller); + KillCooldown = new FloatOptionItem(16902, "KillCooldown", new(0f, 180f, 0.5f), 30f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.OverKiller]) .SetValueFormat(OptionFormat.Seconds); @@ -42,27 +43,19 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!killer.RpcCheckAndMurder(target, true)) - { - return false; - } + if (!killer.RpcCheckAndMurder(target, true)) return false; if (killer.PlayerId != target.PlayerId) { Main.PlayerStates[target.PlayerId].deathReason = PlayerState.DeathReason.Dismembered; + LateTask.New(() => { - if (!OverDeadPlayerList.Contains(target.PlayerId)) - { - OverDeadPlayerList.Add(target.PlayerId); - } + if (!OverDeadPlayerList.Contains(target.PlayerId)) OverDeadPlayerList.Add(target.PlayerId); if (target.Is(CustomRoles.Avanger)) { - foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { - pc.Suicide(PlayerState.DeathReason.Revenge, target); - } + foreach (PlayerControl pc in Main.AllAlivePlayerControls) pc.Suicide(PlayerState.DeathReason.Revenge, target); CustomWinnerHolder.ResetAndSetWinner(CustomWinner.None); return; @@ -70,8 +63,9 @@ namespace EHR.Impostor Vector2 ops = target.Pos(); Vector2 originPos = killer.Pos(); - IRandom rd = IRandom.Instance; - for (int i = 0; i < 20; i++) + var rd = IRandom.Instance; + + for (var i = 0; i < 20; i++) { Vector2 location = new(ops.x + ((float)(rd.Next(0, 201) - 100) / 100), ops.y + ((float)(rd.Next(0, 201) - 100) / 100)); location += new Vector2(0, 0.3636f); diff --git a/Roles/Impostor/Overheat.cs b/Roles/Impostor/Overheat.cs index d9d23c905..c9f4b6c8f 100644 --- a/Roles/Impostor/Overheat.cs +++ b/Roles/Impostor/Overheat.cs @@ -25,18 +25,23 @@ namespace EHR.Impostor { const int id = 12332; Options.SetupRoleOptions(id, TabGroup.ImpostorRoles, CustomRoles.Overheat); + OverheatChanceIncrease = new FloatOptionItem(id + 2, "Overheat.ChanceIncrease", new(1f, 10f, 1f), 1f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Overheat]) .SetValueFormat(OptionFormat.Percent); + OverheatChanceIncreaseFrequency = new FloatOptionItem(id + 3, "Overheat.ChanceIncreaseFrequency", new(0.5f, 30f, 0.5f), 5f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Overheat]) .SetValueFormat(OptionFormat.Seconds); + OverheatRollChanceFrequency = new FloatOptionItem(id + 4, "Overheat.RollChanceFrequency", new(0.5f, 60f, 0.5f), 3f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Overheat]) .SetValueFormat(OptionFormat.Seconds); + CoolDownTime = new FloatOptionItem(id + 5, "Overheat.CoolDownTime", new(0.5f, 30f, 0.5f), 4f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Overheat]) .SetValueFormat(OptionFormat.Seconds); + KCDDecreasePerIncreasedTemperature = new FloatOptionItem(id + 6, "Overheat.KCDDecreasePerIncreasedTemperature", new(0.5f, 15f, 0.5f), 3f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Overheat]) .SetValueFormat(OptionFormat.Seconds); @@ -71,10 +76,7 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (Options.UsePets.GetBool()) - { - return; - } + if (Options.UsePets.GetBool()) return; AURoleOptions.ShapeshifterCooldown = 1f; AURoleOptions.ShapeshifterDuration = 1f; @@ -94,10 +96,7 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask || !pc.IsAlive() || ExileController.Instance != null) - { - return; - } + if (!GameStates.IsInTask || !pc.IsAlive() || ExileController.Instance != null) return; ChanceIncreaseTimer += Time.fixedDeltaTime; RollChanceTimer += Time.fixedDeltaTime; @@ -115,10 +114,7 @@ namespace EHR.Impostor if (RollChanceTimer >= OverheatRollChanceFrequency.GetFloat()) { RollChanceTimer = 0f; - if (IRandom.Instance.Next(100) < Temperature - StartingTemperature) - { - pc.Suicide(); - } + if (IRandom.Instance.Next(100) < Temperature - StartingTemperature) pc.Suicide(); } } @@ -152,15 +148,9 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (Main.PlayerStates[seer.PlayerId].Role is not Overheat oh) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not Overheat oh) return string.Empty; - if (seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId) return string.Empty; Color color = GetTemperatureColor(oh.Temperature); string str = Translator.GetString("Overheat.Suffix"); diff --git a/Roles/Impostor/Parasite.cs b/Roles/Impostor/Parasite.cs index 6ab3c7eea..a8df592de 100644 --- a/Roles/Impostor/Parasite.cs +++ b/Roles/Impostor/Parasite.cs @@ -18,12 +18,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupSingleRoleOptions(4900, TabGroup.ImpostorRoles, CustomRoles.Parasite); + ParasiteCD = new FloatOptionItem(4910, "KillCooldown", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Parasite]) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftCooldown = new FloatOptionItem(4911, "ShapeshiftCooldown", new(0f, 180f, 1f), 30f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Parasite]) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftDuration = new FloatOptionItem(4912, "ShapeshiftDuration", new(0f, 180f, 1f), 15f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Parasite]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/Impostor/Penguin.cs b/Roles/Impostor/Penguin.cs index 7cd430cea..ad1f29d65 100644 --- a/Roles/Impostor/Penguin.cs +++ b/Roles/Impostor/Penguin.cs @@ -43,12 +43,8 @@ namespace EHR.Impostor public static bool IsVictim(PlayerControl pc) { foreach (KeyValuePair state in Main.PlayerStates) - { if (state.Value.Role is Penguin { IsEnable: true, VictimCanUseAbilities: false } pg && pg.AbductVictim != null && pg.AbductVictim.PlayerId == pc.PlayerId) - { return true; - } - } return false; } @@ -56,14 +52,18 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Penguin); + OptionAbductTimerLimit = new FloatOptionItem(Id + 11, "PenguinAbductTimerLimit", new(1f, 20f, 1f), 10f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Penguin]) .SetValueFormat(OptionFormat.Seconds); + OptionMeetingKill = new BooleanOptionItem(Id + 12, "PenguinMeetingKill", false, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Penguin]); + OptionSpeedDuringDrag = new FloatOptionItem(Id + 13, "PenguinSpeedDuringDrag", new(0.1f, 3f, 0.1f), 1f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Penguin]) .SetValueFormat(OptionFormat.Multiplier); + OptionVictimCanUseAbilities = new BooleanOptionItem(Id + 14, "PenguinVictimCanUseAbilities", false, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Penguin]); } @@ -127,18 +127,12 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (IsGoose) - { - opt.SetVision(false); - } + if (IsGoose) opt.SetVision(false); } private void SendRPC() { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.PenguinSync, SendOption.Reliable); writer.Write(PenguinId); @@ -168,10 +162,7 @@ namespace EHR.Impostor private void AddVictim(PlayerControl target) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; AbductVictim = target; AbductTimer = AbductTimerLimit; @@ -184,10 +175,7 @@ namespace EHR.Impostor private void RemoveVictim(bool allowDelay = true) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; if (!allowDelay) { @@ -217,12 +205,10 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!IsEnable) - { - return true; - } + if (!IsEnable) return true; bool doKill = !IsGoose; + if (AbductVictim != null) { if (target.PlayerId != AbductVictim.PlayerId) @@ -241,19 +227,13 @@ namespace EHR.Impostor } else { - if (!IsGoose && !killer.RpcCheckAndMurder(target, true)) - { - return false; - } + if (!IsGoose && !killer.RpcCheckAndMurder(target, true)) return false; doKill = false; AddVictim(target); } - if (doKill) - { - killer.Kill(target); - } + if (doKill) killer.Kill(target); return false; } @@ -265,39 +245,25 @@ namespace EHR.Impostor public override void OnReportDeadBody() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; stopCount = true; + // If you meet a meeting with time running out, kill it even if you're on a ladder. if (AbductVictim != null && AbductTimer <= 0f) { - if (!IsGoose) - { - Penguin_.Kill(AbductVictim); - } + if (!IsGoose) Penguin_.Kill(AbductVictim); RemoveVictim(false); } if (MeetingKill) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; - if (AbductVictim == null) - { - return; - } + if (AbductVictim == null) return; - if (!IsGoose) - { - Penguin_.Kill(AbductVictim); - } + if (!IsGoose) Penguin_.Kill(AbductVictim); RemoveVictim(); } @@ -305,10 +271,7 @@ namespace EHR.Impostor public override void AfterMeetingTasks() { - if (Main.NormalOptions.MapId == 4) - { - return; - } + if (Main.NormalOptions.MapId == 4) return; //Maps other than Airship RestartAbduct(); @@ -317,51 +280,33 @@ namespace EHR.Impostor public static void OnSpawnAirship() { foreach (KeyValuePair state in Main.PlayerStates) - { if (state.Value.Role is Penguin { IsEnable: true } pg) - { pg.RestartAbduct(); - } - } } private void RestartAbduct() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - if (AbductVictim != null) - { - Penguin_.MarkDirtySettings(); - } + if (AbductVictim != null) Penguin_.MarkDirtySettings(); stopCount = false; } public override void OnFixedUpdate(PlayerControl pc) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; if (!stopCount) { AbductTimer -= Time.fixedDeltaTime; Count++; + if (Count >= 10) { Count = 0; @@ -396,31 +341,35 @@ namespace EHR.Impostor if (!AbductVictim.MyPhysics.Animations.IsPlayingAnyLadderAnimation()) { PlayerControl abductVictim = AbductVictim; + LateTask.New(() => { - if (IsGoose) - { - return; - } + if (IsGoose) return; int sId = abductVictim.NetTransform.lastSequenceId + 5; abductVictim.NetTransform.SnapTo(Penguin_.transform.position, (ushort)sId); Penguin_.Kill(abductVictim); - CustomRpcSender sender = CustomRpcSender.Create("PenguinMurder"); + var sender = CustomRpcSender.Create("PenguinMurder"); + { sender.AutoStartRpc(abductVictim.NetTransform.NetId, (byte)RpcCalls.SnapTo); + { NetHelpers.WriteVector2(Penguin_.transform.position, sender.stream); sender.Write(abductVictim.NetTransform.lastSequenceId); } + sender.EndRpc(); sender.AutoStartRpc(Penguin_.NetId, (byte)RpcCalls.MurderPlayer); + { sender.WriteNetObject(abductVictim); } + sender.EndRpc(); } + sender.SendMessage(); }, 0.3f, "PenguinMurder"); @@ -431,39 +380,26 @@ namespace EHR.Impostor else if (!AbductVictim.MyPhysics.Animations.IsPlayingAnyLadderAnimation()) { Vector3 position = Penguin_.transform.position; + if (!Penguin_.IsHost()) - { Utils.TP(AbductVictim.NetTransform, position, log: false); - } else { LateTask.New(() => { - if (AbductVictim != null) - { - Utils.TP(AbductVictim.NetTransform, position, log: false); - } + if (AbductVictim != null) Utils.TP(AbductVictim.NetTransform, position, log: false); }, 0.25f, log: false); } } } - else if (AbductTimer <= 100f) - { - AbductTimer = 255f; - } + else if (AbductTimer <= 100f) AbductTimer = 255f; } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer == null || seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud)) - { - return string.Empty; - } + if (seer == null || seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud)) return string.Empty; - if (!Main.PlayerStates.TryGetValue(seer.PlayerId, out PlayerState state) || state.Role is not Penguin pg || pg.AbductVictim == null) - { - return string.Empty; - } + if (!Main.PlayerStates.TryGetValue(seer.PlayerId, out PlayerState state) || state.Role is not Penguin pg || pg.AbductVictim == null) return string.Empty; return $"\u21b9 {(int)(pg.AbductTimer + 1f)}s"; } diff --git a/Roles/Impostor/Puppeteer.cs b/Roles/Impostor/Puppeteer.cs index f585b1957..0abfcf280 100644 --- a/Roles/Impostor/Puppeteer.cs +++ b/Roles/Impostor/Puppeteer.cs @@ -37,38 +37,52 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(3900, TabGroup.ImpostorRoles, CustomRoles.Puppeteer); + PuppeteerCD = new FloatOptionItem(3911, "PuppeteerCD", new(2.5f, 60f, 2.5f), 22.5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Puppeteer]) .SetValueFormat(OptionFormat.Seconds); + PuppeteerCanKillNormally = new BooleanOptionItem(3917, "PuppeteerCanKillNormally", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Puppeteer]); + PuppeteerKCD = new FloatOptionItem(3912, "PuppeteerKCD", new(2.5f, 60f, 2.5f), 25f, TabGroup.ImpostorRoles) .SetParent(PuppeteerCanKillNormally) .SetValueFormat(OptionFormat.Seconds); + PuppeteerMinDelay = new IntegerOptionItem(3913, "PuppeteerMinDelay", new(0, 90, 1), 3, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Puppeteer]) .SetValueFormat(OptionFormat.Seconds); + PuppeteerMaxDelay = new IntegerOptionItem(3914, "PuppeteerMaxDelay", new(0, 90, 1), 7, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Puppeteer]) .SetValueFormat(OptionFormat.Seconds); + PuppeteerManipulationEndsAfterFixedTime = new BooleanOptionItem(3915, "PuppeteerManipulationEndsAfterFixedTime", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Puppeteer]); + PuppeteerManipulationEndsAfterTime = new IntegerOptionItem(3916, "PuppeteerManipulationEndsAfterTime", new(0, 90, 1), 30, TabGroup.ImpostorRoles) .SetParent(PuppeteerManipulationEndsAfterFixedTime) .SetValueFormat(OptionFormat.Seconds); + PuppeteerManipulationBypassesLazy = new BooleanOptionItem(3918, "PuppeteerManipulationBypassesLazy", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Puppeteer]); + PuppeteerManipulationBypassesLazyGuy = new BooleanOptionItem(3922, "PuppeteerManipulationBypassesLazyGuy", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Puppeteer]); + PuppeteerPuppetCanKillImpostors = new BooleanOptionItem(3919, "PuppeteerPuppetCanKillImpostors", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Puppeteer]); + PuppeteerPuppetCanKillPuppeteer = new BooleanOptionItem(3920, "PuppeteerPuppetCanKillPuppeteer", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Puppeteer]); + PuppeteerMaxPuppetsOpt = new IntegerOptionItem(3921, "PuppeteerMaxPuppets", new(0, 30, 1), 5, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Puppeteer]) .SetValueFormat(OptionFormat.Times); + PuppeteerDiesAfterMaxPuppets = new BooleanOptionItem(3923, "PuppeteerDiesAfterMaxPuppets", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Puppeteer]); + PuppetDiesAlongWithVictim = new BooleanOptionItem(3924, "PuppetDiesAlongWithVictim", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Puppeteer]); } @@ -99,20 +113,11 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (target.Is(CustomRoles.Needy) && PuppeteerManipulationBypassesLazyGuy.GetBool()) - { - return false; - } + if (target.Is(CustomRoles.Needy) && PuppeteerManipulationBypassesLazyGuy.GetBool()) return false; - if (target.Is(CustomRoles.Lazy) && PuppeteerManipulationBypassesLazy.GetBool()) - { - return false; - } + if (target.Is(CustomRoles.Lazy) && PuppeteerManipulationBypassesLazy.GetBool()) return false; - if (Medic.ProtectList.Contains(target.PlayerId)) - { - return false; - } + if (Medic.ProtectList.Contains(target.PlayerId)) return false; if (!PuppeteerMaxPuppets.TryGetValue(killer.PlayerId, out int usesLeft)) { @@ -128,14 +133,11 @@ namespace EHR.Impostor PuppeteerDelayList[target.PlayerId] = Utils.TimeStamp; PuppeteerDelay[target.PlayerId] = IRandom.Instance.Next(PuppeteerMinDelay.GetInt(), PuppeteerMaxDelay.GetInt()); killer.SetKillCooldown(PuppeteerCD.GetFloat()); + if (usesLeft <= 1 && PuppeteerDiesAfterMaxPuppets.GetBool()) - { LateTask.New(() => { killer.Suicide(); }, 1.5f, "Puppeteer Max Uses Reached => Suicide"); - } else - { killer.Notify(string.Format(Translator.GetString("PuppeteerUsesRemaining"), usesLeft - 1)); - } PuppeteerMaxPuppets[killer.PlayerId]--; killer.RPCPlayCustomSound("Line"); @@ -147,14 +149,11 @@ namespace EHR.Impostor PuppeteerDelayList[target.PlayerId] = Utils.TimeStamp; PuppeteerDelay[target.PlayerId] = IRandom.Instance.Next(PuppeteerMinDelay.GetInt(), PuppeteerMaxDelay.GetInt()); killer.SetKillCooldown(); + if (usesLeft <= 1) - { LateTask.New(() => { killer.Suicide(); }, 1.5f, "Puppeteer Max Uses Reached => Suicide"); - } else - { killer.Notify(string.Format(Translator.GetString("PuppeteerUsesRemaining"), usesLeft - 1)); - } PuppeteerMaxPuppets[killer.PlayerId]--; killer.RPCPlayCustomSound("Line"); @@ -164,10 +163,7 @@ namespace EHR.Impostor public override void OnGlobalFixedUpdate(PlayerControl player, bool lowLoad) { - if (player == null || lowLoad) - { - return; - } + if (player == null || lowLoad) return; byte playerId = player.PlayerId; long now = Utils.TimeStamp; @@ -191,22 +187,14 @@ namespace EHR.Impostor { Vector2 puppeteerPos = player.transform.position; Dictionary targetDistance = []; + foreach (PlayerControl target in Main.AllAlivePlayerControls) { - if (target.PlayerId == playerId || target.Is(CustomRoles.Pestilence)) - { - continue; - } + if (target.PlayerId == playerId || target.Is(CustomRoles.Pestilence)) continue; - if (target.Is(CustomRoles.Puppeteer) && !PuppeteerPuppetCanKillPuppeteer.GetBool()) - { - continue; - } + if (target.Is(CustomRoles.Puppeteer) && !PuppeteerPuppetCanKillPuppeteer.GetBool()) continue; - if (target.Is(CustomRoleTypes.Impostor) && !PuppeteerPuppetCanKillImpostors.GetBool()) - { - continue; - } + if (target.Is(CustomRoleTypes.Impostor) && !PuppeteerPuppetCanKillImpostors.GetBool()) continue; float dis = Vector2.Distance(puppeteerPos, target.transform.position); targetDistance.Add(target.PlayerId, dis); @@ -217,6 +205,7 @@ namespace EHR.Impostor KeyValuePair min = targetDistance.OrderBy(c => c.Value).FirstOrDefault(); PlayerControl target = Utils.GetPlayerById(min.Key); float KillRange = NormalGameOptionsV08.KillDistances[Mathf.Clamp(Main.NormalOptions.KillDistance, 0, 2)]; + if (min.Value <= KillRange && player.CanMove && target.CanMove) { if (player.RpcCheckAndMurder(target, true)) @@ -226,10 +215,7 @@ namespace EHR.Impostor PlayerControl puppeteer = Utils.GetPlayerById(puppeteerId); target.SetRealKiller(puppeteer); player.Kill(target); - if (PuppetDiesAlongWithVictim.GetBool()) - { - player.Suicide(realKiller: puppeteer); - } + if (PuppetDiesAlongWithVictim.GetBool()) player.Suicide(realKiller: puppeteer); player.MarkDirtySettings(); target.MarkDirtySettings(); diff --git a/Roles/Impostor/QuickShooter.cs b/Roles/Impostor/QuickShooter.cs index 29f640d51..7d31e9097 100644 --- a/Roles/Impostor/QuickShooter.cs +++ b/Roles/Impostor/QuickShooter.cs @@ -22,12 +22,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.QuickShooter); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 2.5f), 25f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.QuickShooter]) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftCooldown = new FloatOptionItem(Id + 12, "QuickShooterShapeshiftCooldown", new(0f, 180f, 2.5f), 40f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.QuickShooter]) .SetValueFormat(OptionFormat.Seconds); + MeetingReserved = new IntegerOptionItem(Id + 14, "MeetingReserved", new(0, 15, 1), 1, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.QuickShooter]) .SetValueFormat(OptionFormat.Pieces); @@ -47,10 +50,7 @@ namespace EHR.Impostor private static void SendRPC(byte playerId) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetQuickShooterShotLimit, SendOption.Reliable); writer.Write(playerId); @@ -69,15 +69,10 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte playerId) { if (Options.UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = ShapeshiftCooldown.GetFloat(); - } else { - if (Options.UsePets.GetBool()) - { - return; - } + if (Options.UsePets.GetBool()) return; AURoleOptions.ShapeshifterCooldown = ShapeshiftCooldown.GetFloat(); AURoleOptions.ShapeshifterDuration = 1f; @@ -86,30 +81,21 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl pc, PlayerControl target, bool shapeshifting) { - if (Main.KillTimers[pc.PlayerId] <= 0 && (shapeshifting || Options.UseUnshiftTrigger.GetBool())) - { - Store(pc); - } + if (Main.KillTimers[pc.PlayerId] <= 0 && (shapeshifting || Options.UseUnshiftTrigger.GetBool())) Store(pc); return false; } public override bool OnVanish(PlayerControl pc) { - if (Main.KillTimers[pc.PlayerId] <= 0) - { - Store(pc); - } + if (Main.KillTimers[pc.PlayerId] <= 0) Store(pc); return false; } public override void OnPet(PlayerControl pc) { - if (Main.KillTimers[pc.PlayerId] <= 0) - { - Store(pc); - } + if (Main.KillTimers[pc.PlayerId] <= 0) Store(pc); } private static void Store(PlayerControl pc) @@ -130,10 +116,7 @@ namespace EHR.Impostor public override void OnReportDeadBody() { Dictionary NewSL = []; - foreach (KeyValuePair sl in ShotLimit) - { - NewSL.Add(sl.Key, Math.Clamp(sl.Value, 0, MeetingReserved.GetInt())); - } + foreach (KeyValuePair sl in ShotLimit) NewSL.Add(sl.Key, Math.Clamp(sl.Value, 0, MeetingReserved.GetInt())); foreach (KeyValuePair sl in NewSL) { @@ -145,10 +128,7 @@ namespace EHR.Impostor public override void OnMurder(PlayerControl killer, PlayerControl target) { ShotLimit.TryAdd(killer.PlayerId, 0); - if (ShotLimit[killer.PlayerId] > 0) - { - LateTask.New(() => killer.SetKillCooldown(0.01f), 0.01f, "QuickShooterKill: Set KCD to 0s"); - } + if (ShotLimit[killer.PlayerId] > 0) LateTask.New(() => killer.SetKillCooldown(0.01f), 0.01f, "QuickShooterKill: Set KCD to 0s"); ShotLimit[killer.PlayerId]--; ShotLimit[killer.PlayerId] = Math.Max(ShotLimit[killer.PlayerId], 0); @@ -163,9 +143,7 @@ namespace EHR.Impostor public override void SetButtonTexts(HudManager hud, byte id) { if (Options.UsePets.GetBool()) - { hud.PetButton?.OverrideText(Translator.GetString("QuickShooterShapeshiftText")); - } else { hud.AbilityButton?.OverrideText(Translator.GetString("QuickShooterShapeshiftText")); diff --git a/Roles/Impostor/Refugee.cs b/Roles/Impostor/Refugee.cs index e41dcd91b..49210de6a 100644 --- a/Roles/Impostor/Refugee.cs +++ b/Roles/Impostor/Refugee.cs @@ -7,9 +7,7 @@ namespace EHR.Impostor public static bool On; public override bool IsEnable => On; - public override void SetupCustomOption() - { - } + public override void SetupCustomOption() { } public override void Add(byte playerId) { diff --git a/Roles/Impostor/RiftMaker.cs b/Roles/Impostor/RiftMaker.cs index e1ca56676..34edbfe83 100644 --- a/Roles/Impostor/RiftMaker.cs +++ b/Roles/Impostor/RiftMaker.cs @@ -23,8 +23,10 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.RiftMaker); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 2.5f), 25f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.RiftMaker]) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftCooldown = new FloatOptionItem(Id + 11, "ShapeshiftCooldown", new(0f, 180f, 2.5f), 10f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.RiftMaker]) .SetValueFormat(OptionFormat.Seconds); } @@ -50,15 +52,10 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte playerId) { if (UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = ShapeshiftCooldown.GetFloat(); - } else { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.ShapeshifterCooldown = ShapeshiftCooldown.GetFloat(); AURoleOptions.ShapeshifterDuration = 1f; @@ -68,25 +65,13 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl player) { - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; - if (Pelican.IsEaten(player.PlayerId) || player.Data.IsDead) - { - return; - } + if (Pelican.IsEaten(player.PlayerId) || player.Data.IsDead) return; - if (!player.Is(CustomRoles.RiftMaker)) - { - return; - } + if (!player.Is(CustomRoles.RiftMaker)) return; - if (Marks.Count != 2) - { - return; - } + if (Marks.Count != 2) return; if (Vector2.Distance(Marks[0], Marks[1]) <= 4f) { @@ -95,23 +80,17 @@ namespace EHR.Impostor return; } - if (LastTP + 5 > TimeStamp) - { - return; - } + if (LastTP + 5 > TimeStamp) return; Vector2 position = player.transform.position; - bool isTP = false; + var isTP = false; Vector2 from = Marks[0]; foreach (Vector2 mark in Marks.ToArray()) { float dis = Vector2.Distance(mark, position); - if (dis > 2f) - { - continue; - } + if (dis > 2f) continue; isTP = true; from = mark; @@ -120,18 +99,13 @@ namespace EHR.Impostor if (isTP) { LastTP = TimeStamp; + if (from == Marks[0]) - { player.TP(Marks[1]); - } else if (from == Marks[1]) - { player.TP(Marks[0]); - } else - { Logger.Error($"Teleport failed - from: {from}", "RiftMakerTP"); - } } } @@ -150,20 +124,11 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl player, PlayerControl target, bool shapeshifting) { - if (player == null) - { - return false; - } + if (player == null) return false; - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; - if (Marks.Count >= 2) - { - return false; - } + if (Marks.Count >= 2) return false; Mark(player); @@ -172,15 +137,9 @@ namespace EHR.Impostor public override bool OnVanish(PlayerControl pc) { - if (pc == null) - { - return false; - } + if (pc == null) return false; - if (Marks.Count >= 2) - { - return false; - } + if (Marks.Count >= 2) return false; Mark(pc); @@ -189,15 +148,9 @@ namespace EHR.Impostor public override void OnPet(PlayerControl pc) { - if (pc == null) - { - return; - } + if (pc == null) return; - if (Marks.Count >= 2) - { - return; - } + if (Marks.Count >= 2) return; Mark(pc); } @@ -205,10 +158,7 @@ namespace EHR.Impostor private void Mark(PlayerControl player) { Marks.Add(player.transform.position); - if (Marks.Count == 2) - { - LastTP = TimeStamp; - } + if (Marks.Count == 2) LastTP = TimeStamp; player.Notify(GetString("MarkDone")); } diff --git a/Roles/Impostor/Saboteur.cs b/Roles/Impostor/Saboteur.cs index 0acecc99f..9a69cb0d9 100644 --- a/Roles/Impostor/Saboteur.cs +++ b/Roles/Impostor/Saboteur.cs @@ -12,9 +12,11 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(10005, TabGroup.ImpostorRoles, CustomRoles.Saboteur); + SaboteurCD = new FloatOptionItem(10015, "KillCooldown", new(0f, 180f, 2.5f), 17.5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Saboteur]) .SetValueFormat(OptionFormat.Seconds); + SaboteurCDAfterMeetings = new FloatOptionItem(10016, "AfterMeetingKillCooldown", new(0f, 180f, 2.5f), 25f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Saboteur]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/Impostor/Sans.cs b/Roles/Impostor/Sans.cs index 6d5e9e235..280b97f60 100644 --- a/Roles/Impostor/Sans.cs +++ b/Roles/Impostor/Sans.cs @@ -32,12 +32,16 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Sans); + DefaultKillCooldown = new FloatOptionItem(Id + 10, "SansDefaultKillCooldown", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Sans]) .SetValueFormat(OptionFormat.Seconds); + ReduceKillCooldown = new FloatOptionItem(Id + 11, "SansReduceKillCooldown", new(0f, 30f, 0.5f), 3.5f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Sans]) .SetValueFormat(OptionFormat.Seconds); + MinKillCooldown = new FloatOptionItem(Id + 12, "SansMinKillCooldown", new(0f, 30f, 2.5f), 10f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Sans]) .SetValueFormat(OptionFormat.Seconds); + BardChance = new IntegerOptionItem(Id + 13, "BardChance", new(0, 100, 5), 0, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sans]) .SetValueFormat(OptionFormat.Percent); @@ -110,10 +114,7 @@ namespace EHR.Impostor public override void OnReportDeadBody() { - if (!ResetKCDOnMeeting) - { - return; - } + if (!ResetKCDOnMeeting) return; NowCooldown = DefaultKCD; } diff --git a/Roles/Impostor/Sapper.cs b/Roles/Impostor/Sapper.cs index b3c564c8a..82f41e6d3 100644 --- a/Roles/Impostor/Sapper.cs +++ b/Roles/Impostor/Sapper.cs @@ -25,10 +25,13 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Sapper); + ShapeshiftCooldown = new FloatOptionItem(Id + 11, "SapperCD", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Sapper]) .SetValueFormat(OptionFormat.Seconds); + Delay = new IntegerOptionItem(Id + 12, "SapperDelay", new(1, 15, 1), 5, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Sapper]) .SetValueFormat(OptionFormat.Times); + Radius = new FloatOptionItem(Id + 13, "SapperRadius", new(0f, 10f, 0.25f), 3f, TabGroup.ImpostorRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Sapper]) .SetValueFormat(OptionFormat.Multiplier); } @@ -47,9 +50,7 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte id) { if (UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = ShapeshiftCooldown.GetFloat(); - } else { AURoleOptions.ShapeshifterCooldown = ShapeshiftCooldown.GetFloat(); @@ -64,10 +65,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; return PlaceBomb(shapeshifter); } @@ -94,15 +92,9 @@ namespace EHR.Impostor private static bool PlaceBomb(PlayerControl pc) { - if (pc == null) - { - return false; - } + if (pc == null) return false; - if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId)) - { - return false; - } + if (!pc.IsAlive() || Pelican.IsEaten(pc.PlayerId)) return false; Bombs.TryAdd(pc.Pos(), TimeStamp); @@ -111,15 +103,13 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl pc) { - if (pc == null || Bombs.Count == 0 || !GameStates.IsInTask || !pc.IsAlive()) - { - return; - } + if (pc == null || Bombs.Count == 0 || !GameStates.IsInTask || !pc.IsAlive()) return; foreach (KeyValuePair bomb in Bombs.Where(bomb => bomb.Value + Delay.GetInt() < TimeStamp)) { - bool b = false; + var b = false; IEnumerable players = GetPlayersInRadius(Radius.GetFloat(), bomb.Key); + foreach (PlayerControl tg in players.ToArray()) { if (tg.PlayerId == pc.PlayerId) @@ -133,23 +123,18 @@ namespace EHR.Impostor Bombs.Remove(bomb.Key); pc.Notify(GetString("MagicianBombExploded")); + if (b) { LateTask.New(() => { - if (!GameStates.IsEnded) - { - pc.Suicide(PlayerState.DeathReason.Bombed); - } + if (!GameStates.IsEnded) pc.Suicide(PlayerState.DeathReason.Bombed); }, 0.5f, "Sapper Bomb Suicide"); } } - StringBuilder sb = new StringBuilder(); - foreach (long x in Bombs.Values) - { - sb.Append(string.Format(GetString("MagicianBombExlodesIn"), Delay.GetInt() - (TimeStamp - x) + 1)); - } + var sb = new StringBuilder(); + foreach (long x in Bombs.Values) sb.Append(string.Format(GetString("MagicianBombExlodesIn"), Delay.GetInt() - (TimeStamp - x) + 1)); pc.Notify(sb.ToString(), overrideAll: true); } @@ -162,13 +147,9 @@ namespace EHR.Impostor public override void SetButtonTexts(HudManager hud, byte id) { if (UsePets.GetBool()) - { hud.PetButton?.OverrideText(GetString("BomberShapeshiftText")); - } else - { hud.AbilityButton?.OverrideText(GetString("BomberShapeshiftText")); - } } } } \ No newline at end of file diff --git a/Roles/Impostor/Scavenger.cs b/Roles/Impostor/Scavenger.cs index 1c4b4086c..bb82c1ac8 100644 --- a/Roles/Impostor/Scavenger.cs +++ b/Roles/Impostor/Scavenger.cs @@ -12,9 +12,11 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(4000, TabGroup.ImpostorRoles, CustomRoles.Scavenger); + ScavengerKillCooldown = new FloatOptionItem(4010, "KillCooldown", new(0f, 180f, 2.5f), 35f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Scavenger]) .SetValueFormat(OptionFormat.Seconds); + ScavengerKillDuration = new FloatOptionItem(4011, "ScavengerKillDuration", new(0f, 90f, 0.5f), 5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Scavenger]) .SetValueFormat(OptionFormat.Seconds); @@ -42,24 +44,20 @@ namespace EHR.Impostor float dur = ScavengerKillDuration.GetFloat(); killer.Notify("....", dur); killer.SetKillCooldown(dur + 0.5f); + LateTask.New(() => { - if (Vector2.Distance(killer.Pos(), target.Pos()) > 2f) - { - return; - } + if (Vector2.Distance(killer.Pos(), target.Pos()) > 2f) return; target.TP(Pelican.GetBlackRoomPS()); target.Suicide(PlayerState.DeathReason.Scavenged, killer); - if (target.Is(CustomRoles.Pelican)) - { - Pelican.OnPelicanDied(target.PlayerId); - } + if (target.Is(CustomRoles.Pelican)) Pelican.OnPelicanDied(target.PlayerId); killer.SetKillCooldown(); RPC.PlaySoundRPC(killer.PlayerId, Sounds.KillSound); target.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Scavenger), Translator.GetString("KilledByScavenger"))); }, dur, "Scavenger Kill"); + return false; } diff --git a/Roles/Impostor/SerialKiller.cs b/Roles/Impostor/SerialKiller.cs index 619c025d9..9b0b9cbe0 100644 --- a/Roles/Impostor/SerialKiller.cs +++ b/Roles/Impostor/SerialKiller.cs @@ -20,12 +20,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.SerialKiller); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SerialKiller]) .SetValueFormat(OptionFormat.Seconds); + TimeLimit = new FloatOptionItem(Id + 11, "SerialKillerLimit", new(5f, 180f, 5f), 40f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SerialKiller]) .SetValueFormat(OptionFormat.Seconds); + WaitFor1Kill = new BooleanOptionItem(Id + 12, "WaitFor1Kill", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SerialKiller]); } @@ -56,10 +59,7 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!killer.Is(CustomRoles.SerialKiller)) - { - return true; - } + if (!killer.Is(CustomRoles.SerialKiller)) return true; SuicideTimer = float.NaN; Timer = TimeLimit.GetInt(); @@ -75,10 +75,7 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl player) { - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; if (!HasKilled(player)) { @@ -87,10 +84,7 @@ namespace EHR.Impostor return; } - if (float.IsNaN(SuicideTimer)) - { - return; - } + if (float.IsNaN(SuicideTimer)) return; if (SuicideTimer >= TimeLimit.GetFloat()) { @@ -103,10 +97,7 @@ namespace EHR.Impostor SuicideTimer += Time.fixedDeltaTime; int tempTimer = Timer; Timer = TimeLimit.GetInt() - (int)SuicideTimer; - if (Timer != tempTimer && Timer <= 20 && !player.IsModClient()) - { - Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); - } + if (Timer != tempTimer && Timer <= 20 && !player.IsModClient()) Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); } } diff --git a/Roles/Impostor/Silencer.cs b/Roles/Impostor/Silencer.cs index 86180ba9a..98677850b 100644 --- a/Roles/Impostor/Silencer.cs +++ b/Roles/Impostor/Silencer.cs @@ -25,9 +25,11 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Silencer); + SkillCooldown = new FloatOptionItem(Id + 5, "SilencerSkillCooldown", new(2.5f, 60f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Silencer]) .SetValueFormat(OptionFormat.Seconds); + SilenceMode = new StringOptionItem(Id + 4, "SilenceMode", SilenceModes, 1, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Silencer]); } @@ -51,10 +53,7 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (SilenceMode.GetValue() == 1 || ForSilencer.Count >= 1) - { - return true; - } + if (SilenceMode.GetValue() == 1 || ForSilencer.Count >= 1) return true; return killer.CheckDoubleTrigger(target, () => { @@ -65,10 +64,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (SilenceMode.GetValue() == 1 && ForSilencer.Count == 0) - { - ForSilencer.Add(target.PlayerId); - } + if (SilenceMode.GetValue() == 1 && ForSilencer.Count == 0) ForSilencer.Add(target.PlayerId); return false; } diff --git a/Roles/Impostor/Sniper.cs b/Roles/Impostor/Sniper.cs index b9e938bfb..fcff407c7 100644 --- a/Roles/Impostor/Sniper.cs +++ b/Roles/Impostor/Sniper.cs @@ -42,17 +42,23 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Sniper); + SniperBulletCount = new IntegerOptionItem(Id + 10, "SniperBulletCount", new(1, 10, 1), 2, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Sniper]) .SetValueFormat(OptionFormat.Pieces); + SniperPrecisionShooting = new BooleanOptionItem(Id + 11, "SniperPrecisionShooting", false, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Sniper]); + SniperAimAssist = new BooleanOptionItem(Id + 12, "SniperAimAssist", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Sniper]); + SniperAimAssistOnshot = new BooleanOptionItem(Id + 13, "SniperAimAssistOneshot", false, TabGroup.ImpostorRoles) .SetParent(SniperAimAssist); + CanKillWithBullets = new BooleanOptionItem(Id + 14, "SniperCanKill", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Sniper]); + ShapeshiftDuration = new FloatOptionItem(Id + 15, "ShapeshiftDuration", new(1f, 30f, 1f), 10f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Sniper]) .SetValueFormat(OptionFormat.Seconds); @@ -102,18 +108,12 @@ namespace EHR.Impostor private void SendRPC(byte sniperId) { - if (!On || !Utils.DoRPC) - { - return; - } + if (!On || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SniperSync, SendOption.Reliable); writer.Write(sniperId); writer.Write(shotNotify.Count); - foreach (byte sn in shotNotify) - { - writer.Write(sn); - } + foreach (byte sn in shotNotify) writer.Write(sn); AmongUsClient.Instance.FinishRpcImmediately(writer); } @@ -122,6 +122,7 @@ namespace EHR.Impostor { shotNotify.Clear(); int count = msg.ReadInt32(); + while (count > 0) { shotNotify.Add(msg.ReadByte()); @@ -131,33 +132,21 @@ namespace EHR.Impostor public override bool CanUseKillButton(PlayerControl pc) { - if (!pc.IsAlive()) - { - return false; - } + if (!pc.IsAlive()) return false; - bool canUse = false; - if (pc.IsShifted()) - { - return false; - } + var canUse = false; + if (pc.IsShifted()) return false; - if (bulletCount <= 0) - { - canUse = true; - } + if (bulletCount <= 0) canUse = true; - if (CanKillWithBullets.GetBool()) - { - canUse = true; - } + if (CanKillWithBullets.GetBool()) canUse = true; return canUse; } private Dictionary GetSnipeTargets(PlayerControl sniper) { - Dictionary targets = new Dictionary(); + var targets = new Dictionary(); Vector3 snipeBasePos = snipeBasePosition; Vector3 snipePos = sniper.transform.position; Vector3 dir = (snipePos - snipeBasePos).normalized; @@ -166,31 +155,19 @@ namespace EHR.Impostor foreach (PlayerControl target in Main.AllAlivePlayerControls) { - if (target.PlayerId == sniper.PlayerId) - { - continue; - } + if (target.PlayerId == sniper.PlayerId) continue; Vector3 target_pos = target.transform.position - snipePos; - if (target_pos.magnitude < 1) - { - continue; - } + if (target_pos.magnitude < 1) continue; Vector3 target_dir = target_pos.normalized; float target_dot = Vector3.Dot(dir, target_dir); - if (target_dot < 0.995) - { - continue; - } + if (target_dot < 0.995) continue; if (PrecisionShooting) { float err = Vector3.Cross(dir, target_pos).magnitude; - if (err < 0.5) - { - targets.Add(target, err); - } + if (err < 0.5) targets.Add(target, err); } else { @@ -220,20 +197,14 @@ namespace EHR.Impostor private bool Snipe(PlayerControl sniper, bool shapeshifting, bool isPet = false) { - if (!IsThisRole(sniper.PlayerId) || !sniper.IsAlive()) - { - return true; - } + if (!IsThisRole(sniper.PlayerId) || !sniper.IsAlive()) return true; byte sniperId = sniper.PlayerId; if (bulletCount <= 0) { float CD = ShapeshiftDuration.GetFloat() + 1f; - if (Main.KillTimers[sniper.PlayerId] < CD && !isPet) - { - sniper.SetKillCooldown(CD); - } + if (Main.KillTimers[sniper.PlayerId] < CD && !isPet) sniper.SetKillCooldown(CD); return false; } @@ -262,10 +233,7 @@ namespace EHR.Impostor bulletCount--; - if (!AmongUsClient.Instance.AmHost || Pelican.IsEaten(sniperId) || Medic.ProtectList.Contains(sniperId)) - { - return false; - } + if (!AmongUsClient.Instance.AmHost || Pelican.IsEaten(sniperId) || Medic.ProtectList.Contains(sniperId)) return false; sniper.RPCPlayCustomSound("AWP"); @@ -282,6 +250,7 @@ namespace EHR.Impostor targets.Remove(snipedTarget); List snList = shotNotify; snList.Clear(); + foreach (PlayerControl otherPc in targets.Keys) { snList.Add(otherPc.PlayerId); @@ -289,13 +258,11 @@ namespace EHR.Impostor } SendRPC(sniperId); + LateTask.New(() => { snList.Clear(); - foreach (PlayerControl otherPc in targets.Keys) - { - Utils.NotifyRoles(SpecifySeer: otherPc); - } + foreach (PlayerControl otherPc in targets.Keys) Utils.NotifyRoles(SpecifySeer: otherPc); SendRPC(sniperId); }, 0.5f, "Sniper shot Notify"); @@ -307,50 +274,32 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte playerId) { if (Options.UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = bulletCount > 0 ? Options.DefaultKillCooldown : 255f; - } else { - if (Options.UsePets.GetBool()) - { - return; - } + if (Options.UsePets.GetBool()) return; try { if (bulletCount > 0) - { AURoleOptions.ShapeshifterDuration = ShapeshiftDuration.GetFloat(); - } else { AURoleOptions.ShapeshifterDuration = 1f; AURoleOptions.ShapeshifterCooldown = 255f; } } - catch - { - } + catch { } } } public override void OnFixedUpdate(PlayerControl sniper) { - if (!IsThisRole(sniper.PlayerId) || !sniper.IsAlive()) - { - return; - } + if (!IsThisRole(sniper.PlayerId) || !sniper.IsAlive()) return; - if (!AimAssist) - { - return; - } + if (!AimAssist) return; - if (!IsAim) - { - return; - } + if (!IsAim) return; if (!GameStates.IsInTask) { @@ -360,6 +309,7 @@ namespace EHR.Impostor } Vector3 pos = sniper.transform.position; + if (pos != LastPosition) { AimTime = 0f; @@ -398,33 +348,20 @@ namespace EHR.Impostor { if (AimAssist && IsThisRole(seerId)) { - if (Main.PlayerStates[seerId].Role is not Sniper sp) - { - return string.Empty; - } + if (Main.PlayerStates[seerId].Role is not Sniper sp) return string.Empty; if (0.5f < sp.AimTime && (!AimAssistOneshot || sp.AimTime < 1.0f)) - { if (sp.GetSnipeTargets(Utils.GetPlayerById(seerId)).Count > 0) - { return $"{Utils.ColorString(Palette.ImpostorRed, "◎")}"; - } - } } else { foreach (byte sniperId in PlayerIdList) { - if (Main.PlayerStates[sniperId].Role is not Sniper sp) - { - continue; - } + if (Main.PlayerStates[sniperId].Role is not Sniper sp) continue; List snList = sp.shotNotify; - if (snList.Count > 0 && snList.Contains(seerId)) - { - return $"{Utils.ColorString(Palette.ImpostorRed, "!")}"; - } + if (snList.Count > 0 && snList.Contains(seerId)) return $"{Utils.ColorString(Palette.ImpostorRed, "!")}"; } } @@ -434,15 +371,10 @@ namespace EHR.Impostor public override void SetButtonTexts(HudManager hud, byte id) { if (Options.UsePets.GetBool()) - { hud.PetButton.OverrideText(GetString(bulletCount <= 0 ? "DefaultShapeshiftText" : "SniperSnipeButtonText")); - } else { - if (IsThisRole(id)) - { - hud.AbilityButton.SetUsesRemaining(bulletCount); - } + if (IsThisRole(id)) hud.AbilityButton.SetUsesRemaining(bulletCount); hud.AbilityButton.OverrideText(GetString(bulletCount <= 0 ? "DefaultShapeshiftText" : "SniperSnipeButtonText")); } diff --git a/Roles/Impostor/Stealth.cs b/Roles/Impostor/Stealth.cs index d534a4e7c..96f8f3132 100644 --- a/Roles/Impostor/Stealth.cs +++ b/Roles/Impostor/Stealth.cs @@ -32,22 +32,17 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!base.OnCheckMurder(killer, target)) - { - return true; - } + if (!base.OnCheckMurder(killer, target)) return true; IEnumerable playersToDarken = FindPlayersInSameRoom(target); + if (playersToDarken == null) { Logger.Info("No players to darken"); return true; } - if (excludeImpostors) - { - playersToDarken = playersToDarken.Where(player => !player.Is(CustomRoles.Impostor)); - } + if (excludeImpostors) playersToDarken = playersToDarken.Where(player => !player.Is(CustomRoles.Impostor)); DarkenPlayers(playersToDarken); return true; @@ -56,10 +51,7 @@ namespace EHR.Impostor private IEnumerable FindPlayersInSameRoom(PlayerControl killedPlayer) { PlainShipRoom room = killedPlayer.GetPlainShipRoom(); - if (room == null) - { - return null; - } + if (room == null) return null; Collider2D roomArea = room.roomArea; SystemTypes roomName = room.RoomId; @@ -70,6 +62,7 @@ namespace EHR.Impostor private void DarkenPlayers(IEnumerable playersToDarken) { darkenedPlayers = playersToDarken.ToArray(); + foreach (PlayerControl player in darkenedPlayers) { Main.PlayerStates[player.PlayerId].IsBlackOut = true; @@ -92,27 +85,18 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl player) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; if (darkenedPlayers != null) { darkenTimer -= Time.fixedDeltaTime; - if (darkenTimer <= 0) - { - ResetDarkenState(); - } + if (darkenTimer <= 0) ResetDarkenState(); } } public override void OnReportDeadBody() { - if (AmongUsClient.Instance.AmHost) - { - ResetDarkenState(); - } + if (AmongUsClient.Instance.AmHost) ResetDarkenState(); } private void RpcDarken(SystemTypes? roomType) @@ -149,10 +133,7 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl seen, bool isForMeeting = false, bool isForHud = false) { seen ??= seer; - if (isForMeeting || seer != StealthPC || seen != StealthPC || !darkenedRoom.HasValue) - { - return base.GetSuffix(seer, seen, isForMeeting, isForHud); - } + if (isForMeeting || seer != StealthPC || seen != StealthPC || !darkenedRoom.HasValue) return base.GetSuffix(seer, seen, isForMeeting, isForHud); return string.Format(Translator.GetString("StealthDarkened"), DestroyableSingleton.Instance.GetString(darkenedRoom.Value)); } diff --git a/Roles/Impostor/Swapster.cs b/Roles/Impostor/Swapster.cs index 38197b795..f00da5f1c 100644 --- a/Roles/Impostor/Swapster.cs +++ b/Roles/Impostor/Swapster.cs @@ -25,6 +25,7 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Swapster); + SSCD = new FloatOptionItem(Id + 2, "ShapeshiftCooldown", new(0f, 180f, 2.5f), 30f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Swapster]) .SetValueFormat(OptionFormat.Seconds); @@ -38,10 +39,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl swapster, PlayerControl target, bool shapeshifting) { - if (swapster == null || target == null || swapster == target || !shapeshifting) - { - return true; - } + if (swapster == null || target == null || swapster == target || !shapeshifting) return true; if (FirstSwapTarget.TryGetValue(swapster.PlayerId, out byte firstTargetId)) { @@ -52,9 +50,7 @@ namespace EHR.Impostor FirstSwapTarget.Remove(swapster.PlayerId); } else - { FirstSwapTarget[swapster.PlayerId] = target.PlayerId; - } return false; } diff --git a/Roles/Impostor/Swiftclaw.cs b/Roles/Impostor/Swiftclaw.cs index a64e1a44e..b8a24291a 100644 --- a/Roles/Impostor/Swiftclaw.cs +++ b/Roles/Impostor/Swiftclaw.cs @@ -17,12 +17,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Swiftclaw); + DashCD = new FloatOptionItem(Id + 2, "SwiftclawDashCD", new(0f, 180f, 2.5f), 15f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Swiftclaw]) .SetValueFormat(OptionFormat.Seconds); + DashDuration = new IntegerOptionItem(Id + 3, "SwiftclawDashDur", new(0, 60, 1), 4, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Swiftclaw]) .SetValueFormat(OptionFormat.Seconds); + DashSpeed = new FloatOptionItem(Id + 4, "SwiftclawDashSpeed", new(0.05f, 3f, 0.05f), 2f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Swiftclaw]) .SetValueFormat(OptionFormat.Multiplier); @@ -41,15 +44,9 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (Options.UsePhantomBasis.GetBool()) - { - AURoleOptions.PhantomCooldown = DashCD.GetFloat() + DashDuration.GetFloat(); - } + if (Options.UsePhantomBasis.GetBool()) AURoleOptions.PhantomCooldown = DashCD.GetFloat() + DashDuration.GetFloat(); - if (Options.UseUnshiftTrigger.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = DashCD.GetFloat() + DashDuration.GetFloat(); - } + if (Options.UseUnshiftTrigger.GetBool()) AURoleOptions.ShapeshifterCooldown = DashCD.GetFloat() + DashDuration.GetFloat(); } public override void OnPet(PlayerControl pc) @@ -65,10 +62,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) return true; Dash(shapeshifter); return false; @@ -76,10 +70,7 @@ namespace EHR.Impostor private static void Dash(PlayerControl pc) { - if (pc == null || DashStart.ContainsKey(pc.PlayerId)) - { - return; - } + if (pc == null || DashStart.ContainsKey(pc.PlayerId)) return; DashStart[pc.PlayerId] = (Utils.TimeStamp, Main.AllPlayerSpeed[pc.PlayerId]); Main.AllPlayerSpeed[pc.PlayerId] = DashSpeed.GetFloat(); @@ -88,10 +79,7 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask || pc == null || !DashStart.TryGetValue(pc.PlayerId, out (long StartTimeStamp, float NormalSpeed) dashInfo) || dashInfo.StartTimeStamp + DashDuration.GetInt() > Utils.TimeStamp) - { - return; - } + if (!GameStates.IsInTask || pc == null || !DashStart.TryGetValue(pc.PlayerId, out (long StartTimeStamp, float NormalSpeed) dashInfo) || dashInfo.StartTimeStamp + DashDuration.GetInt() > Utils.TimeStamp) return; Main.AllPlayerSpeed[pc.PlayerId] = dashInfo.NormalSpeed; pc.MarkDirtySettings(); @@ -100,10 +88,7 @@ namespace EHR.Impostor public override void OnReportDeadBody() { - foreach (KeyValuePair item in DashStart) - { - Main.AllPlayerSpeed[item.Key] = item.Value.NormalSpeed; - } + foreach (KeyValuePair item in DashStart) Main.AllPlayerSpeed[item.Key] = item.Value.NormalSpeed; DashStart.Clear(); } diff --git a/Roles/Impostor/Swooper.cs b/Roles/Impostor/Swooper.cs index 031537fb0..e7ae08a53 100644 --- a/Roles/Impostor/Swooper.cs +++ b/Roles/Impostor/Swooper.cs @@ -46,17 +46,22 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Swooper); + SwooperCooldown = new FloatOptionItem(Id + 2, "SwooperCooldown", new(1f, 60f, 1f), 20f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Swooper]) .SetValueFormat(OptionFormat.Seconds); + SwooperDuration = new FloatOptionItem(Id + 3, "SwooperDuration", new(1f, 30f, 1f), 10f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Swooper]) .SetValueFormat(OptionFormat.Seconds); + SwooperVentNormallyOnCooldown = new BooleanOptionItem(Id + 4, "SwooperVentNormallyOnCooldown", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Swooper]); + SwooperLimitOpt = new IntegerOptionItem(Id + 5, "AbilityUseLimit", new(0, 5, 1), 1, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Swooper]) .SetValueFormat(OptionFormat.Times); + SwooperAbilityUseGainWithEachKill = new FloatOptionItem(Id + 6, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 0.5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Swooper]) .SetValueFormat(OptionFormat.Times); @@ -129,10 +134,7 @@ namespace EHR.Impostor private void SendRPC() { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetSwooperTimer, SendOption.Reliable); writer.Write(SwooperId); @@ -156,15 +158,9 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl player) { - if (!GameStates.IsInTask || !IsEnable || player == null) - { - return; - } + if (!GameStates.IsInTask || !IsEnable || player == null) return; - if (Count++ < 10) - { - return; - } + if (Count++ < 10) return; Count = 0; @@ -175,10 +171,7 @@ namespace EHR.Impostor if (!player.IsModClient()) { long cooldown = lastTime + (long)Cooldown - now; - if ((int)cooldown != CD) - { - player.Notify(string.Format(GetString("CDPT"), cooldown + 1), 1.1f, true); - } + if ((int)cooldown != CD) player.Notify(string.Format(GetString("CDPT"), cooldown + 1), 1.1f, true); CD = (int)cooldown; } @@ -186,10 +179,7 @@ namespace EHR.Impostor if (lastTime + (long)Cooldown < now) { lastTime = -10; - if (!player.IsModClient()) - { - player.Notify(GetString("SwooperCanVent"), 300f); - } + if (!player.IsModClient()) player.Notify(GetString("SwooperCanVent"), 300f); SendRPC(); CD = 0; @@ -199,8 +189,9 @@ namespace EHR.Impostor if (lastFixedTime != now && InvisTime != -10) { lastFixedTime = now; - bool refresh = false; + var refresh = false; long remainTime = InvisTime + (long)Duration - now; + switch (remainTime) { case < 0: @@ -218,25 +209,21 @@ namespace EHR.Impostor break; } - if (refresh) - { - SendRPC(); - } + if (refresh) SendRPC(); } } public override void OnCoEnterVent(PlayerPhysics __instance, int ventId) { - if (!AmongUsClient.Instance.AmHost || IsInvis) - { - return; - } + if (!AmongUsClient.Instance.AmHost || IsInvis) return; PlayerControl pc = __instance.myPlayer; + LateTask.New(() => { float limit = pc.GetAbilityUseLimit(); bool wraith = UsedRole == CustomRoles.Wraith; + if (CanGoInvis && (wraith || limit >= 1)) { ventedId = ventId; @@ -246,10 +233,7 @@ namespace EHR.Impostor AmongUsClient.Instance.FinishRpcImmediately(writer); InvisTime = Utils.TimeStamp; - if (!wraith) - { - pc.RpcRemoveAbilityUse(); - } + if (!wraith) pc.RpcRemoveAbilityUse(); SendRPC(); pc.Notify(GetString("SwooperInvisState"), Duration); @@ -264,10 +248,7 @@ namespace EHR.Impostor public override void OnEnterVent(PlayerControl pc, Vent vent) { - if (!IsInvis || InvisTime == Utils.TimeStamp) - { - return; - } + if (!IsInvis || InvisTime == Utils.TimeStamp) return; InvisTime = -10; lastTime = Utils.TimeStamp; @@ -279,17 +260,12 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (!hud || seer == null || !GameStates.IsInTask || !PlayerControl.LocalPlayer.IsAlive()) - { - return string.Empty; - } + if (!hud || seer == null || !GameStates.IsInTask || !PlayerControl.LocalPlayer.IsAlive()) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is not Swooper sw) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not Swooper sw) return string.Empty; + + var str = new StringBuilder(); - StringBuilder str = new StringBuilder(); if (sw.IsInvis) { long remainTime = sw.InvisTime + (long)sw.Duration - Utils.TimeStamp; @@ -301,29 +277,18 @@ namespace EHR.Impostor str.Append(string.Format(GetString("SwooperInvisCooldownRemain"), cooldown + 1)); } else - { str.Append(GetString("SwooperCanVent")); - } return str.ToString(); } public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (Medic.ProtectList.Contains(target.PlayerId)) - { - return false; - } + if (Medic.ProtectList.Contains(target.PlayerId)) return false; - if (target.Is(CustomRoles.Bait)) - { - return true; - } + if (target.Is(CustomRoles.Bait)) return true; - if (!IsInvis) - { - return true; - } + if (!IsInvis) return true; killer.SetKillCooldown(); target.SetRealKiller(killer); diff --git a/Roles/Impostor/TimeThief.cs b/Roles/Impostor/TimeThief.cs index eaca5d56e..f4473b257 100644 --- a/Roles/Impostor/TimeThief.cs +++ b/Roles/Impostor/TimeThief.cs @@ -17,15 +17,19 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.TimeThief); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 2.5f), 25f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.TimeThief]) .SetValueFormat(OptionFormat.Seconds); + DecreaseMeetingTime = new IntegerOptionItem(Id + 11, "TimeThiefDecreaseMeetingTime", new(0, 100, 1), 10, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.TimeThief]) .SetValueFormat(OptionFormat.Seconds); + LowerLimitVotingTime = new IntegerOptionItem(Id + 12, "TimeThiefLowerLimitVotingTime", new(0, 300, 5), 50, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.TimeThief]) .SetValueFormat(OptionFormat.Seconds); + ReturnStolenTimeUponDeath = new BooleanOptionItem(Id + 13, "TimeThiefReturnStolenTimeUponDeath", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.TimeThief]); } diff --git a/Roles/Impostor/Trickster.cs b/Roles/Impostor/Trickster.cs index 54e93bdf5..f81e7e0cf 100644 --- a/Roles/Impostor/Trickster.cs +++ b/Roles/Impostor/Trickster.cs @@ -9,12 +9,8 @@ Options.SetupRoleOptions(4300, TabGroup.ImpostorRoles, CustomRoles.Trickster); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Impostor/Twister.cs b/Roles/Impostor/Twister.cs index f42a5457b..7a712bab9 100644 --- a/Roles/Impostor/Twister.cs +++ b/Roles/Impostor/Twister.cs @@ -23,12 +23,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Twister); + ShapeshiftCooldown = new FloatOptionItem(Id + 10, "TwisterCooldown", new(1f, 60f, 1f), 15f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Twister]) .SetValueFormat(OptionFormat.Seconds); + TwisterLimitOpt = new IntegerOptionItem(Id + 11, "AbilityUseLimit", new(0, 5, 1), 0, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Twister]) .SetValueFormat(OptionFormat.Times); + TwisterAbilityUseGainWithEachKill = new FloatOptionItem(Id + 12, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 0.4f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Twister]) .SetValueFormat(OptionFormat.Times); @@ -48,9 +51,7 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte id) { if (UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = ShapeshiftCooldown.GetFloat(); - } else { AURoleOptions.ShapeshifterCooldown = ShapeshiftCooldown.GetFloat(); @@ -77,36 +78,21 @@ namespace EHR.Impostor private static void TwistPlayers(PlayerControl shapeshifter, bool shapeshifting) { - if (shapeshifter == null) - { - return; - } + if (shapeshifter == null) return; - if (shapeshifter.GetAbilityUseLimit() < 1) - { - return; - } + if (shapeshifter.GetAbilityUseLimit() < 1) return; - if (!shapeshifting) - { - return; - } + if (!shapeshifting) return; List changePositionPlayers = [shapeshifter.PlayerId]; shapeshifter.RpcRemoveAbilityUse(); foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (changePositionPlayers.Contains(pc.PlayerId) || Pelican.IsEaten(pc.PlayerId) || pc.onLadder || pc.inMovingPlat || pc.inVent || GameStates.IsMeeting) - { - continue; - } + if (changePositionPlayers.Contains(pc.PlayerId) || Pelican.IsEaten(pc.PlayerId) || pc.onLadder || pc.inMovingPlat || pc.inVent || GameStates.IsMeeting) continue; PlayerControl[] filtered = Main.AllAlivePlayerControls.Where(a => !a.inVent && !Pelican.IsEaten(a.PlayerId) && !a.onLadder && a.PlayerId != pc.PlayerId && !changePositionPlayers.Contains(a.PlayerId)).ToArray(); - if (filtered.Length == 0) - { - break; - } + if (filtered.Length == 0) break; PlayerControl target = filtered.RandomElement(); @@ -127,9 +113,7 @@ namespace EHR.Impostor public override void SetButtonTexts(HudManager hud, byte id) { if (UsePets.GetBool()) - { hud.PetButton?.OverrideText(GetString("TwisterButtonText")); - } else { hud.AbilityButton?.OverrideText(GetString("TwisterButtonText")); diff --git a/Roles/Impostor/Underdog.cs b/Roles/Impostor/Underdog.cs index 487cb74bb..d5832eabf 100644 --- a/Roles/Impostor/Underdog.cs +++ b/Roles/Impostor/Underdog.cs @@ -10,12 +10,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(10025, TabGroup.ImpostorRoles, CustomRoles.Underdog); + UnderdogMaximumPlayersNeededToKill = new IntegerOptionItem(10030, "UnderdogMaximumPlayersNeededToKill", new(1, 15, 1), 5, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Underdog]) .SetValueFormat(OptionFormat.Players); + UnderdogKillCooldown = new FloatOptionItem(10031, "KillCooldown", new(0f, 180f, 2.5f), 15f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Underdog]) .SetValueFormat(OptionFormat.Seconds); + UnderdogKillCooldownWithMorePlayersAlive = new FloatOptionItem(10032, "UnderdogKillCooldownWithMorePlayersAlive", new(0f, 180f, 2.5f), 35f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Underdog]) .SetValueFormat(OptionFormat.Seconds); diff --git a/Roles/Impostor/Undertaker.cs b/Roles/Impostor/Undertaker.cs index 9707feecb..b227d9800 100644 --- a/Roles/Impostor/Undertaker.cs +++ b/Roles/Impostor/Undertaker.cs @@ -14,22 +14,21 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id + 20, TabGroup.ImpostorRoles, CustomRoles.Undertaker); + UndertakerMarkCooldown = new FloatOptionItem(Id + 30, "UndertakerMarkCooldown", new(0f, 180f, 0.5f), 1f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Undertaker]) .SetValueFormat(OptionFormat.Seconds); + UndertakerAssassinateCooldown = new FloatOptionItem(Id + 31, "UndertakerAssassinateCooldown", new(0f, 180f, 0.5f), 18.5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Undertaker]) .SetValueFormat(OptionFormat.Seconds); + UndertakerCanKillAfterAssassinate = new BooleanOptionItem(Id + 32, "UndertakerCanKillAfterAssassinate", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Undertaker]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Impostor/Vampire.cs b/Roles/Impostor/Vampire.cs index 7625a3e41..179f425bc 100644 --- a/Roles/Impostor/Vampire.cs +++ b/Roles/Impostor/Vampire.cs @@ -29,12 +29,15 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Vampire); + Cooldown = new FloatOptionItem(Id + 9, "VampireKillCooldown", new(1f, 90f, 1f), 30f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Vampire]) .SetValueFormat(OptionFormat.Seconds); + OptionKillDelay = new FloatOptionItem(Id + 10, "VampireKillDelay", new(1f, 30f, 1f), 3f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Vampire]) .SetValueFormat(OptionFormat.Seconds); + OptionCanKillNormally = new BooleanOptionItem(Id + 11, "CanKillNormally", true, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Vampire]); } @@ -50,6 +53,7 @@ namespace EHR.Impostor PlayerIdList.Add(playerId); IsPoisoner = Main.PlayerStates[playerId].MainRole == CustomRoles.Poisoner; + if (!IsPoisoner) { KillCooldown = Cooldown.GetFloat(); @@ -83,45 +87,21 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!IsThisRole(killer.PlayerId)) - { - return true; - } + if (!IsThisRole(killer.PlayerId)) return true; - if (target.Is(CustomRoles.Bait)) - { - return true; - } + if (target.Is(CustomRoles.Bait)) return true; - if (target.Is(CustomRoles.Pestilence)) - { - return true; - } + if (target.Is(CustomRoles.Pestilence)) return true; - if (target.Is(CustomRoles.Guardian) && target.AllTasksCompleted()) - { - return true; - } + if (target.Is(CustomRoles.Guardian) && target.AllTasksCompleted()) return true; - if (target.Is(CustomRoles.Opportunist) && target.AllTasksCompleted() && Opportunist.OppoImmuneToAttacksWhenTasksDone.GetBool()) - { - return true; - } + if (target.Is(CustomRoles.Opportunist) && target.AllTasksCompleted() && Opportunist.OppoImmuneToAttacksWhenTasksDone.GetBool()) return true; - if (target.Is(CustomRoles.Veteran) && Veteran.VeteranInProtect.ContainsKey(target.PlayerId)) - { - return true; - } + if (target.Is(CustomRoles.Veteran) && Veteran.VeteranInProtect.ContainsKey(target.PlayerId)) return true; - if (Medic.ProtectList.Contains(target.PlayerId)) - { - return true; - } + if (Medic.ProtectList.Contains(target.PlayerId)) return true; - if (CanKillNormally) - { - return killer.CheckDoubleTrigger(target, Bite); - } + if (CanKillNormally) return killer.CheckDoubleTrigger(target, Bite); Bite(); return false; @@ -131,31 +111,23 @@ namespace EHR.Impostor killer.SetKillCooldown(KillCooldown + KillDelay); killer.RPCPlayCustomSound("Bite"); - if (!BittenPlayers.ContainsKey(target.PlayerId)) - { - BittenPlayers.Add(target.PlayerId, new(killer.PlayerId, 0f)); - } + if (!BittenPlayers.ContainsKey(target.PlayerId)) BittenPlayers.Add(target.PlayerId, new(killer.PlayerId, 0f)); } } public override void OnFixedUpdate(PlayerControl vampire) { - if (!AmongUsClient.Instance.AmHost || !GameStates.IsInTask || ExileController.Instance) - { - return; - } + if (!AmongUsClient.Instance.AmHost || !GameStates.IsInTask || ExileController.Instance) return; byte vampireID = vampire.PlayerId; - if (!IsThisRole(vampire.PlayerId)) - { - return; - } + if (!IsThisRole(vampire.PlayerId)) return; List targetList = [.. BittenPlayers.Where(b => b.Value.VampireId == vampireID).Select(b => b.Key)]; foreach (byte targetId in targetList.ToArray()) { BittenInfo bitten = BittenPlayers[targetId]; + if (bitten.KillTimer >= KillDelay) { PlayerControl target = Utils.GetPlayerById(targetId); @@ -172,21 +144,16 @@ namespace EHR.Impostor private void KillBitten(PlayerControl vampire, PlayerControl target, bool isButton = false) { - if (vampire == null || target == null || target.Data.Disconnected) - { - return; - } + if (vampire == null || target == null || target.Data.Disconnected) return; if (target.IsAlive()) { target.Suicide(IsPoisoner ? PlayerState.DeathReason.Poison : PlayerState.DeathReason.Bite, vampire); + if (!isButton && vampire.IsAlive()) { RPC.PlaySoundRPC(vampire.PlayerId, Sounds.KillSound); - if (target.Is(CustomRoles.Trapper)) - { - vampire.TrapperKilled(target); - } + if (target.Is(CustomRoles.Trapper)) vampire.TrapperKilled(target); vampire.Notify(GetString("VampireTargetDead")); } diff --git a/Roles/Impostor/Ventriloquist.cs b/Roles/Impostor/Ventriloquist.cs index 81001c0bf..f6b1367bc 100644 --- a/Roles/Impostor/Ventriloquist.cs +++ b/Roles/Impostor/Ventriloquist.cs @@ -13,9 +13,11 @@ public override void SetupCustomOption() { Options.SetupRoleOptions(649650, TabGroup.ImpostorRoles, CustomRoles.Ventriloquist); + UseLimit = new IntegerOptionItem(649652, "AbilityUseLimit", new(0, 5, 1), 0, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Ventriloquist]) .SetValueFormat(OptionFormat.Times); + VentriloquistAbilityUseGainWithEachKill = new FloatOptionItem(649653, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 1f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Ventriloquist]) .SetValueFormat(OptionFormat.Times); diff --git a/Roles/Impostor/Vindicator.cs b/Roles/Impostor/Vindicator.cs index 4b15f8f82..eb50eded6 100644 --- a/Roles/Impostor/Vindicator.cs +++ b/Roles/Impostor/Vindicator.cs @@ -9,19 +9,17 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(3400, TabGroup.ImpostorRoles, CustomRoles.Vindicator); + VindicatorAdditionalVote = new IntegerOptionItem(3410, "MayorAdditionalVote", new(1, 30, 1), 1, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Vindicator]) .SetValueFormat(OptionFormat.Votes); + VindicatorHideVote = new BooleanOptionItem(3411, "MayorHideVote", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Vindicator]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Impostor/Visionary.cs b/Roles/Impostor/Visionary.cs index a9e06bb46..c2a79ce1f 100644 --- a/Roles/Impostor/Visionary.cs +++ b/Roles/Impostor/Visionary.cs @@ -18,15 +18,19 @@ namespace EHR.Impostor public override void SetupCustomOption() { Options.SetupRoleOptions(16150, TabGroup.ImpostorRoles, CustomRoles.Visionary); + UseLimit = new IntegerOptionItem(16152, "AbilityUseLimit", new(0, 5, 1), 0, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Visionary]) .SetValueFormat(OptionFormat.Times); + VisionaryAbilityUseGainWithEachKill = new FloatOptionItem(16153, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 1f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Visionary]) .SetValueFormat(OptionFormat.Times); + ShapeshiftCooldown = new FloatOptionItem(16154, "ShapeshiftCooldown", new(1f, 60f, 1f), 15f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Visionary]) .SetValueFormat(OptionFormat.Seconds); + ChanceOfSeeingAllAlignmentsOnStart = new FloatOptionItem(16155, "ChanceOfSeeingAllAlignmentsOnStart", new(0f, 100f, 1f), 0f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Visionary]) .SetValueFormat(OptionFormat.Percent); @@ -60,15 +64,9 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting) - { - return true; - } + if (!shapeshifting) return true; - if (RevealedPlayerIds.Contains(target.PlayerId) || shapeshifter.GetAbilityUseLimit() < 1) - { - return false; - } + if (RevealedPlayerIds.Contains(target.PlayerId) || shapeshifter.GetAbilityUseLimit() < 1) return false; RevealedPlayerIds.Add(target.PlayerId); shapeshifter.RpcRemoveAbilityUse(); diff --git a/Roles/Impostor/Warlock.cs b/Roles/Impostor/Warlock.cs index 58d4e3a5f..81035ebf9 100644 --- a/Roles/Impostor/Warlock.cs +++ b/Roles/Impostor/Warlock.cs @@ -36,21 +36,28 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(4600, TabGroup.ImpostorRoles, CustomRoles.Warlock); + WarlockCanKillAllies = new BooleanOptionItem(4610, "CanKillAllies", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Warlock]); + WarlockCanKillSelf = new BooleanOptionItem(4611, "CanKillSelf", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Warlock]); + KillCooldown = new FloatOptionItem(4613, "KillCooldown", new(0f, 180f, 1f), 25f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Warlock]) .SetValueFormat(OptionFormat.Seconds); + CurseCooldown = new FloatOptionItem(4614, "CurseCooldown", new(0f, 180f, 1f), 15f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Warlock]) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftCooldown = new FloatOptionItem(4612, "ShapeshiftCooldown", new(0f, 180f, 1f), 30f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Warlock]) .SetValueFormat(OptionFormat.Seconds); + FreezeAfterCurseKill = new BooleanOptionItem(4615, "FreezeAfterCurseKill", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Warlock]); + FreezeDurationAfterCurseKill = new FloatOptionItem(4616, "FreezeDuration", new(0f, 60f, 1f), 4f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Warlock]) .SetValueFormat(OptionFormat.Seconds); @@ -76,23 +83,16 @@ namespace EHR.Impostor try { if (UsePhantomBasis.GetBool()) - { AURoleOptions.PhantomCooldown = IsCursed ? 1f : ShapeshiftCooldown.GetFloat(); - } else { - if (UsePets.GetBool()) - { - return; - } + if (UsePets.GetBool()) return; AURoleOptions.ShapeshifterCooldown = IsCursed ? 1f : ShapeshiftCooldown.GetFloat(); AURoleOptions.ShapeshifterDuration = 1f; } } - catch - { - } + catch { } } public override void SetKillCooldown(byte id) @@ -104,80 +104,49 @@ namespace EHR.Impostor { bool curse = IsCurseAndKill.TryGetValue(id, out bool wcs) && wcs; bool shapeshifting = id.IsPlayerShifted(); - if (!shapeshifting && !curse) - { - hud.KillButton?.OverrideText(Translator.GetString("WarlockCurseButtonText")); - } - else - { - hud.KillButton?.OverrideText(Translator.GetString("KillButtonText")); - } - if (!shapeshifting && curse) - { - hud.AbilityButton?.OverrideText(Translator.GetString("WarlockShapeshiftButtonText")); - } + if (!shapeshifting && !curse) + hud.KillButton?.OverrideText(Translator.GetString("WarlockCurseButtonText")); + else + hud.KillButton?.OverrideText(Translator.GetString("KillButtonText")); + + if (!shapeshifting && curse) hud.AbilityButton?.OverrideText(Translator.GetString("WarlockShapeshiftButtonText")); } private void ResetCooldowns(bool killCooldown = false, bool curseCooldown = false, bool shapeshiftCooldown = false, PlayerControl warlock = null) { - if (killCooldown) - { - KCD = KillCooldown.GetFloat(); - } + if (killCooldown) KCD = KillCooldown.GetFloat(); - if (curseCooldown) - { - CurseCD = CurseCooldown.GetFloat(); - } + if (curseCooldown) CurseCD = CurseCooldown.GetFloat(); - if (warlock == null) - { - return; - } + if (warlock == null) return; if (shapeshiftCooldown) { if (!UsePets.GetBool()) - { warlock.RpcResetAbilityCooldown(); - } else - { warlock.AddAbilityCD(); - } } - if (KCD > 0f && CurseCD > 0f) - { - LateTask.New(() => { warlock.SetKillCooldown(Math.Min(KCD, CurseCD) - 1f); }, 0.1f, log: false); - } + if (KCD > 0f && CurseCD > 0f) LateTask.New(() => { warlock.SetKillCooldown(Math.Min(KCD, CurseCD) - 1f); }, 0.1f, log: false); Utils.NotifyRoles(SpecifySeer: warlock, SpecifyTarget: warlock); } public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.IsShifted()) - { - return false; - } + if (killer.IsShifted()) return false; if (killer.CheckDoubleTrigger(target, () => { - if (CurseCD > 0f) - { - return; - } + if (CurseCD > 0f) return; IsCurseAndKill.TryAdd(killer.PlayerId, false); if (!killer.IsShifted() && !IsCurseAndKill[killer.PlayerId]) { - if (target.Is(CustomRoles.Needy) || target.Is(CustomRoles.Lazy)) - { - return; - } + if (target.Is(CustomRoles.Needy) || target.Is(CustomRoles.Lazy)) return; IsCursed = true; killer.SetKillCooldown(); @@ -192,16 +161,10 @@ namespace EHR.Impostor return; } - if (IsCurseAndKill[killer.PlayerId]) - { - killer.RpcGuardAndKill(target); - } + if (IsCurseAndKill[killer.PlayerId]) killer.RpcGuardAndKill(target); })) { - if (KCD > 0f) - { - return false; - } + if (KCD > 0f) return false; ResetCooldowns(true, true, true, killer); @@ -218,10 +181,7 @@ namespace EHR.Impostor public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; Curse(shapeshifter); @@ -237,6 +197,7 @@ namespace EHR.Impostor private void Curse(PlayerControl pc) { IsCurseAndKill.TryAdd(pc.PlayerId, false); + if (CursedPlayers[pc.PlayerId] != null) { if (!CursedPlayers[pc.PlayerId].Data.IsDead) @@ -244,32 +205,18 @@ namespace EHR.Impostor PlayerControl cp = CursedPlayers[pc.PlayerId]; Vector2 cppos = cp.Pos(); Dictionary cpdistance = []; + foreach (PlayerControl p in Main.AllAlivePlayerControls) { - if (p.PlayerId == cp.PlayerId) - { - continue; - } + if (p.PlayerId == cp.PlayerId) continue; - if (!WarlockCanKillSelf.GetBool() && p.PlayerId == pc.PlayerId) - { - continue; - } + if (!WarlockCanKillSelf.GetBool() && p.PlayerId == pc.PlayerId) continue; - if (!WarlockCanKillAllies.GetBool() && p.GetCustomRole().IsImpostor()) - { - continue; - } + if (!WarlockCanKillAllies.GetBool() && p.GetCustomRole().IsImpostor()) continue; - if (p.Is(CustomRoles.Pestilence)) - { - continue; - } + if (p.Is(CustomRoles.Pestilence)) continue; - if (Pelican.IsEaten(p.PlayerId) || Medic.ProtectList.Contains(p.PlayerId)) - { - continue; - } + if (Pelican.IsEaten(p.PlayerId) || Medic.ProtectList.Contains(p.PlayerId)) continue; float dis = Vector2.Distance(cppos, p.Pos()); cpdistance.Add(p, dis); @@ -280,6 +227,7 @@ namespace EHR.Impostor { KeyValuePair min = cpdistance.OrderBy(c => c.Value).FirstOrDefault(); PlayerControl targetw = min.Key; + if (cp.RpcCheckAndMurder(targetw, true)) { ResetCooldowns(true, true, true, pc); @@ -295,6 +243,7 @@ namespace EHR.Impostor float speed = Main.AllPlayerSpeed[pc.PlayerId]; Main.AllPlayerSpeed[pc.PlayerId] = Main.MinSpeed; pc.MarkDirtySettings(); + LateTask.New(() => { Main.AllPlayerSpeed[pc.PlayerId] = speed; @@ -303,15 +252,10 @@ namespace EHR.Impostor } } - if (!UsePets.GetBool()) - { - LateTask.New(() => { pc.RpcShapeshift(pc, false); }, 1.5f, "Warlock RpcRevertShapeshift"); - } + if (!UsePets.GetBool()) LateTask.New(() => { pc.RpcShapeshift(pc, false); }, 1.5f, "Warlock RpcRevertShapeshift"); } else - { pc.Notify(Translator.GetString("WarlockNoTarget")); - } IsCurseAndKill[pc.PlayerId] = false; } @@ -323,6 +267,7 @@ namespace EHR.Impostor public override void OnGlobalFixedUpdate(PlayerControl player, bool lowLoad) { byte playerId = player.PlayerId; + if (GameStates.IsInTask && WarlockTimer.ContainsKey(playerId)) { if (player.IsAlive()) @@ -335,38 +280,26 @@ namespace EHR.Impostor WarlockTimer.Remove(playerId); } else - { WarlockTimer[playerId] += Time.fixedDeltaTime; - } } else - { WarlockTimer.Remove(playerId); - } } } public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask || !pc.IsAlive() || pc.inVent) - { - return; - } + if (!GameStates.IsInTask || !pc.IsAlive() || pc.inVent) return; float beforeKCD = KCD; float beforeCCD = CurseCD; - if (KCD > 0f) - { - KCD -= Time.fixedDeltaTime; - } + if (KCD > 0f) KCD -= Time.fixedDeltaTime; - if (CurseCD > 0f) - { - CurseCD -= Time.fixedDeltaTime; - } + if (CurseCD > 0f) CurseCD -= Time.fixedDeltaTime; long now = Utils.TimeStamp; + if ((Math.Abs(KCD - beforeKCD) > 0.01f || Math.Abs(beforeCCD - CurseCD) > 0.01f) && LastNotify != now) { LastNotify = now; @@ -381,31 +314,16 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.IsModClient() && !hud) - { - return string.Empty; - } + if (seer.IsModClient() && !hud) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is not Warlock { IsEnable: true } wl) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not Warlock { IsEnable: true } wl) return string.Empty; - if (seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId) return string.Empty; - StringBuilder sb = new StringBuilder(); - if (wl.KCD > 0f) - { - sb.Append($"<#ffa500>{Translator.GetString("KillCooldown")}: <#ffffff>{(int)Math.Round(wl.KCD)}s"); - } + var sb = new StringBuilder(); + if (wl.KCD > 0f) sb.Append($"<#ffa500>{Translator.GetString("KillCooldown")}: <#ffffff>{(int)Math.Round(wl.KCD)}s"); - if (wl.CurseCD > 0f) - { - sb.Append($"{(sb.Length > 0 ? "\n" : string.Empty)}<#00ffa5>{Translator.GetString("CurseCooldown")}: <#ffffff>{(int)Math.Round(wl.CurseCD)}s"); - } + if (wl.CurseCD > 0f) sb.Append($"{(sb.Length > 0 ? "\n" : string.Empty)}<#00ffa5>{Translator.GetString("CurseCooldown")}: <#ffffff>{(int)Math.Round(wl.CurseCD)}s"); return hud ? sb.ToString() : $"{sb}"; } diff --git a/Roles/Impostor/Wasp.cs b/Roles/Impostor/Wasp.cs index b7cc7e202..07f99360c 100644 --- a/Roles/Impostor/Wasp.cs +++ b/Roles/Impostor/Wasp.cs @@ -70,10 +70,7 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (PestControlEnd == 0) - { - return; - } + if (PestControlEnd == 0) return; opt.SetVision(false); opt.SetFloat(FloatOptionNames.ImpostorLightMod, PestControlVision.GetFloat()); @@ -82,19 +79,12 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (DelayedKills.ContainsKey(target.PlayerId)) - { - return false; - } + if (DelayedKills.ContainsKey(target.PlayerId)) return false; if (target.HasKillButton()) - { DelayedKills[target.PlayerId] = Utils.TimeStamp + KillDelay.GetInt(); - } else - { MeetingKills.Add(target.PlayerId); - } killer.SetKillCooldown(StingCooldown.GetInt()); return false; @@ -102,26 +92,17 @@ namespace EHR.Impostor public override void OnGlobalFixedUpdate(PlayerControl pc, bool lowLoad) { - if (lowLoad || !GameStates.IsInTask || ExileController.Instance || !DelayedKills.TryGetValue(pc.PlayerId, out long ts) || ts > Utils.TimeStamp) - { - return; - } + if (lowLoad || !GameStates.IsInTask || ExileController.Instance || !DelayedKills.TryGetValue(pc.PlayerId, out long ts) || ts > Utils.TimeStamp) return; pc.Suicide(PlayerState.DeathReason.Stung, WaspPC); } public override void OnFixedUpdate(PlayerControl pc) { - if (SwarmModeEnd == 0 && PestControlEnd == 0) - { - return; - } + if (SwarmModeEnd == 0 && PestControlEnd == 0) return; long now = Utils.TimeStamp; - if (LastUpdate == now) - { - return; - } + if (LastUpdate == now) return; LastUpdate = now; @@ -133,9 +114,7 @@ namespace EHR.Impostor Utils.SendRPC(CustomRPC.SyncRoleData, WaspPC.PlayerId, SwarmModeEnd); if (WaspDiesAfterSwarmEnd.GetBool()) - { pc.Suicide(); - } else { pc.SyncSettings(); @@ -159,10 +138,7 @@ namespace EHR.Impostor foreach (byte id in DelayedKills.Keys) { PlayerControl player = id.GetPlayer(); - if (player == null || !player.IsAlive()) - { - continue; - } + if (player == null || !player.IsAlive()) continue; player.Suicide(PlayerState.DeathReason.Stung, WaspPC); } @@ -172,10 +148,7 @@ namespace EHR.Impostor public override bool OnCheckMurderAsTarget(PlayerControl killer, PlayerControl target) { - if (!EvadeKills.GetBool() || EvadedKillThisRound) - { - return true; - } + if (!EvadeKills.GetBool() || EvadedKillThisRound) return true; if (IRandom.Instance.Next(2) == 0) { @@ -223,23 +196,17 @@ namespace EHR.Impostor foreach (Wasp instance in Instances) { foreach (byte id in exileIds) - { if (id == instance.WaspPC.PlayerId) - { instance.MeetingKills.Clear(); - } - } } List waspDeathList = []; + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { foreach (Wasp instance in Instances) { - if (Main.AfterMeetingDeathPlayers.ContainsKey(pc.PlayerId)) - { - continue; - } + if (Main.AfterMeetingDeathPlayers.ContainsKey(pc.PlayerId)) continue; if (instance.MeetingKills.Contains(pc.PlayerId) && instance.WaspPC != null && instance.WaspPC.IsAlive()) { @@ -269,10 +236,7 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != WaspPC.PlayerId || seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud) || meeting || SwarmModeEnd == 0) - { - return string.Empty; - } + if (seer.PlayerId != WaspPC.PlayerId || seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud) || meeting || SwarmModeEnd == 0) return string.Empty; return string.Format(Translator.GetString("Wasp.SwarmModeSuffix"), SwarmModeEnd - Utils.TimeStamp); } diff --git a/Roles/Impostor/Wildling.cs b/Roles/Impostor/Wildling.cs index adb997101..13aa1d0ea 100644 --- a/Roles/Impostor/Wildling.cs +++ b/Roles/Impostor/Wildling.cs @@ -40,16 +40,21 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Wildling); + ProtectDurationOpt = new FloatOptionItem(Id + 14, "BKProtectDuration", new(1f, 30f, 1f), 15f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Wildling]) .SetValueFormat(OptionFormat.Seconds); + CanVentOpt = new BooleanOptionItem(Id + 15, "CanVent", true, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Wildling]); + CanShapeshiftOpt = new BooleanOptionItem(Id + 16, "CanShapeshift", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Wildling]); + ShapeshiftCDOpt = new FloatOptionItem(Id + 17, "ShapeshiftCooldown", new(1f, 60f, 1f), 30f, TabGroup.ImpostorRoles) .SetParent(CanShapeshiftOpt) .SetValueFormat(OptionFormat.Seconds); + ShapeshiftDurOpt = new FloatOptionItem(Id + 18, "ShapeshiftDuration", new(1f, 30f, 1f), 10f, TabGroup.ImpostorRoles) .SetParent(CanShapeshiftOpt) .SetValueFormat(OptionFormat.Seconds); @@ -99,6 +104,7 @@ namespace EHR.Impostor public override void ApplyGameOptions(IGameOptions opt, byte id) { opt.SetVision(HasImpostorVision); + if (CanShapeshift) { AURoleOptions.ShapeshifterCooldown = ShapeshiftCD; @@ -113,10 +119,7 @@ namespace EHR.Impostor private void SendRPC(byte playerId) { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetBkTimer, SendOption.Reliable); writer.Write(playerId); @@ -129,20 +132,14 @@ namespace EHR.Impostor byte PlayerId = reader.ReadByte(); string Time = reader.ReadString(); - if (Main.PlayerStates[PlayerId].Role is not Wildling wl) - { - return; - } + if (Main.PlayerStates[PlayerId].Role is not Wildling wl) return; wl.TimeStamp = long.Parse(Time); } public override void OnMurder(PlayerControl killer, PlayerControl target) { - if (killer.PlayerId == target.PlayerId) - { - return; - } + if (killer.PlayerId == target.PlayerId) return; TimeStamp = Utils.TimeStamp + (long)ProtectionDuration; SendRPC(killer.PlayerId); @@ -163,10 +160,7 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; if (TimeStamp < Utils.TimeStamp && TimeStamp != 0) { @@ -177,26 +171,19 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (!hud || seer == null || !GameStates.IsInTask || !PlayerControl.LocalPlayer.IsAlive()) - { - return string.Empty; - } + if (!hud || seer == null || !GameStates.IsInTask || !PlayerControl.LocalPlayer.IsAlive()) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is not Wildling wl) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not Wildling wl) return string.Empty; + + var str = new StringBuilder(); - StringBuilder str = new StringBuilder(); if (wl.InProtect) { long remainTime = wl.TimeStamp - Utils.GetTimeStamp(DateTime.Now); str.Append(string.Format(Translator.GetString("BKSkillTimeRemain"), remainTime)); } else - { str.Append(Translator.GetString("BKSkillNotice")); - } return str.ToString(); } diff --git a/Roles/Impostor/Witch.cs b/Roles/Impostor/Witch.cs index c3d3f7909..aa9095f0c 100644 --- a/Roles/Impostor/Witch.cs +++ b/Roles/Impostor/Witch.cs @@ -37,6 +37,7 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.Witch); + ModeSwitchAction = new StringOptionItem(Id + 10, "WitchModeSwitchAction", SwitchTriggerText, 2, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Witch]); } @@ -66,10 +67,7 @@ namespace EHR.Impostor private static void SendRPC(bool doSpell, byte witchId, byte target = 255, bool spellMode = false) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; if (doSpell) { @@ -90,35 +88,24 @@ namespace EHR.Impostor public static void ReceiveRPC(MessageReader reader, bool doSpell) { byte witch = reader.ReadByte(); - if (Main.PlayerStates[witch].Role is not Witch wc) - { - return; - } + if (Main.PlayerStates[witch].Role is not Witch wc) return; if (doSpell) { byte spelledId = reader.ReadByte(); + if (spelledId != 255) - { wc.SpelledPlayer.Add(spelledId); - } else - { wc.SpelledPlayer.Clear(); - } } else - { wc.SpellMode = reader.ReadBoolean(); - } } public override void OnPet(PlayerControl pc) { - if (NowSwitchTrigger == SwitchTrigger.DoubleTrigger) - { - return; - } + if (NowSwitchTrigger == SwitchTrigger.DoubleTrigger) return; SwitchMode(pc.PlayerId); } @@ -131,10 +118,8 @@ namespace EHR.Impostor SwitchTrigger.Vent => !kill, _ => false }; - if (needSwitch) - { - SwitchMode(playerId); - } + + if (needSwitch) SwitchMode(playerId); } private void SwitchMode(byte playerId) @@ -166,10 +151,7 @@ namespace EHR.Impostor { foreach (byte witch in PlayerIdList) { - if (Main.PlayerStates[witch].Role is not Witch wc) - { - continue; - } + if (Main.PlayerStates[witch].Role is not Witch wc) continue; wc.SpelledPlayer.Clear(); SendRPC(true, witch); @@ -178,15 +160,9 @@ namespace EHR.Impostor public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (Medic.ProtectList.Contains(target.PlayerId)) - { - return false; - } + if (Medic.ProtectList.Contains(target.PlayerId)) return false; - if (NowSwitchTrigger == SwitchTrigger.DoubleTrigger) - { - return killer.CheckDoubleTrigger(target, () => SetSpelled(killer, target)); - } + if (NowSwitchTrigger == SwitchTrigger.DoubleTrigger) return killer.CheckDoubleTrigger(target, () => SetSpelled(killer, target)); if (!SpellMode) { @@ -205,49 +181,37 @@ namespace EHR.Impostor { try { - if (deathReason != PlayerState.DeathReason.Vote) - { - return; - } + if (deathReason != PlayerState.DeathReason.Vote) return; foreach (byte id in exileIds) { if (PlayerIdList.Contains(id)) { - if (Main.PlayerStates[id].Role is not Witch wc) - { - continue; - } + if (Main.PlayerStates[id].Role is not Witch wc) continue; wc.SpelledPlayer.Clear(); } } - List spelledIdList = new List(); + var spelledIdList = new List(); + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { foreach (byte witchId in PlayerIdList) { - if (Main.AfterMeetingDeathPlayers.ContainsKey(pc.PlayerId)) - { - continue; - } + if (Main.AfterMeetingDeathPlayers.ContainsKey(pc.PlayerId)) continue; - if (Main.PlayerStates[witchId].Role is not Witch wc) - { - continue; - } + if (Main.PlayerStates[witchId].Role is not Witch wc) continue; PlayerControl witch = Utils.GetPlayerById(witchId); + if (wc.SpelledPlayer.Contains(pc.PlayerId) && witch != null && witch.IsAlive()) { pc.SetRealKiller(witch); spelledIdList.Add(pc.PlayerId); } else - { Main.AfterMeetingDeathPlayers.Remove(pc.PlayerId); - } } } @@ -262,48 +226,30 @@ namespace EHR.Impostor public static string GetSpelledMark(byte target, bool isMeeting) { - if (!isMeeting) - { - return string.Empty; - } + if (!isMeeting) return string.Empty; foreach (byte id in PlayerIdList) - { if (Main.PlayerStates[id].Role is Witch { IsEnable: true } wc && wc.IsSpelled(target)) - { return Utils.ColorString(wc.IsHM ? Utils.GetRoleColor(CustomRoles.HexMaster) : Palette.ImpostorRed, "†"); - } - } return string.Empty; } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer == null || meeting || seer.PlayerId != target.PlayerId || !seer.Is(CustomRoles.Witch) || (seer.IsModClient() && !hud)) - { - return string.Empty; - } + if (seer == null || meeting || seer.PlayerId != target.PlayerId || !seer.Is(CustomRoles.Witch) || (seer.IsModClient() && !hud)) return string.Empty; - StringBuilder str = new StringBuilder(); + var str = new StringBuilder(); if (hud) - { str.Append($"{GetString("WitchCurrentMode")}: "); - } else - { str.Append($"{GetString("Mode")}: "); - } if (NowSwitchTrigger == SwitchTrigger.DoubleTrigger) - { str.Append(GetString("WitchModeDouble")); - } else - { str.Append(SpellMode ? GetString("WitchModeSpell") : GetString("WitchModeKill")); - } return str.ToString(); } @@ -311,29 +257,18 @@ namespace EHR.Impostor public override void SetButtonTexts(HudManager hud, byte id) { if (SpellMode && NowSwitchTrigger != SwitchTrigger.DoubleTrigger) - { hud.KillButton.OverrideText(GetString("WitchSpellButtonText")); - } else - { hud.KillButton.OverrideText(GetString("KillButtonText")); - } } public override void OnEnterVent(PlayerControl pc, Vent vent) { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; if (PlayerIdList.Contains(pc.PlayerId)) - { if (NowSwitchTrigger is SwitchTrigger.Vent) - { SwitchSpellMode(pc.PlayerId, false); - } - } } private enum SwitchTrigger diff --git a/Roles/Impostor/YinYanger.cs b/Roles/Impostor/YinYanger.cs index 13cf592b0..1ef85245b 100644 --- a/Roles/Impostor/YinYanger.cs +++ b/Roles/Impostor/YinYanger.cs @@ -23,9 +23,11 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.ImpostorRoles, CustomRoles.YinYanger); + YinYangCD = new FloatOptionItem(Id + 5, "YinYangCD", new(0f, 60f, 2.5f), 12.5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.YinYanger]) .SetValueFormat(OptionFormat.Seconds); + KCD = new FloatOptionItem(Id + 6, "KillCooldown", new(0f, 60f, 2.5f), 25f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.YinYanger]) .SetValueFormat(OptionFormat.Seconds); @@ -50,18 +52,12 @@ namespace EHR.Impostor private void SendRPC(bool isClear, byte playerId = byte.MaxValue) { - if (!DoRPC) - { - return; - } + if (!DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncYinYanger, SendOption.Reliable); writer.Write(YinYangerId); writer.Write(isClear); - if (!isClear) - { - writer.Write(playerId); - } + if (!isClear) writer.Write(playerId); AmongUsClient.Instance.FinishRpcImmediately(writer); } @@ -69,44 +65,28 @@ namespace EHR.Impostor public static void ReceiveRPC(MessageReader reader) { byte yyId = reader.ReadByte(); - if (Main.PlayerStates[yyId].Role is not YinYanger yy) - { - return; - } + if (Main.PlayerStates[yyId].Role is not YinYanger yy) return; bool isClear = reader.ReadBoolean(); + if (!isClear) { byte playerId = reader.ReadByte(); yy.YinYangedPlayers.Add(playerId); } else - { yy.YinYangedPlayers.Clear(); - } } public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!IsEnable) - { - return false; - } + if (!IsEnable) return false; - if (killer == null || target == null || !killer.Is(CustomRoles.YinYanger)) - { - return false; - } + if (killer == null || target == null || !killer.Is(CustomRoles.YinYanger)) return false; - if (YinYangedPlayers.Count == 2) - { - return true; - } + if (YinYangedPlayers.Count == 2) return true; - if (YinYangedPlayers.Contains(target.PlayerId)) - { - return false; - } + if (YinYangedPlayers.Contains(target.PlayerId)) return false; YinYangedPlayers.Add(target.PlayerId); SendRPC(false, target.PlayerId); @@ -123,10 +103,7 @@ namespace EHR.Impostor public override void OnReportDeadBody() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; YinYangedPlayers.Clear(); YinYanger_?.ResetKillCooldown(); @@ -135,39 +112,25 @@ namespace EHR.Impostor public override void OnGlobalFixedUpdate(PlayerControl player, bool lowLoad) { - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; foreach (KeyValuePair state in Main.PlayerStates) { - if (state.Value.Role is not YinYanger { IsEnable: true, YinYangedPlayers.Count: 2 } yy) - { - continue; - } + if (state.Value.Role is not YinYanger { IsEnable: true, YinYangedPlayers.Count: 2 } yy) continue; PlayerControl yyPc = yy.YinYanger_; PlayerControl pc1 = GetPlayerById(yy.YinYangedPlayers[0]); PlayerControl pc2 = GetPlayerById(yy.YinYangedPlayers[1]); - if (pc1 == null || pc2 == null || yyPc == null) - { - return; - } + if (pc1 == null || pc2 == null || yyPc == null) return; - if (!pc1.IsAlive() || !pc2.IsAlive() || !yyPc.IsAlive()) - { - return; - } + if (!pc1.IsAlive() || !pc2.IsAlive() || !yyPc.IsAlive()) return; if (Vector2.Distance(pc1.Pos(), pc2.Pos()) <= 2f) { if (!yyPc.RpcCheckAndMurder(pc1, true) || !yyPc.RpcCheckAndMurder(pc2, true)) - { return; - } pc1.Suicide(PlayerState.DeathReason.YinYanged, yyPc); pc2.Suicide(PlayerState.DeathReason.YinYanged, yyPc); @@ -177,15 +140,9 @@ namespace EHR.Impostor public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.IsModClient() && !hud) - { - return string.Empty; - } + if (seer.IsModClient() && !hud) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is YinYanger { IsEnable: true } yy && seer.PlayerId == target.PlayerId) - { - return yy.YinYangedPlayers.Count == 2 ? $"{Translator.GetString("Mode")}: {Translator.GetString("YinYangModeNormal")}" : $"{Translator.GetString("Mode")}: {Translator.GetString("YinYangMode")} ({yy.YinYangedPlayers.Count}/2)"; - } + if (Main.PlayerStates[seer.PlayerId].Role is YinYanger { IsEnable: true } yy && seer.PlayerId == target.PlayerId) return yy.YinYangedPlayers.Count == 2 ? $"{Translator.GetString("Mode")}: {Translator.GetString("YinYangModeNormal")}" : $"{Translator.GetString("Mode")}: {Translator.GetString("YinYangMode")} ({yy.YinYangedPlayers.Count}/2)"; return string.Empty; } diff --git a/Roles/Impostor/Zombie.cs b/Roles/Impostor/Zombie.cs index eb8203085..3bad22bc7 100644 --- a/Roles/Impostor/Zombie.cs +++ b/Roles/Impostor/Zombie.cs @@ -20,18 +20,23 @@ namespace EHR.Impostor public override void SetupCustomOption() { SetupRoleOptions(16400, TabGroup.ImpostorRoles, CustomRoles.Zombie); + ZombieKillCooldown = new FloatOptionItem(16410, "KillCooldown", new(0f, 180f, 2.5f), 5f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Zombie]) .SetValueFormat(OptionFormat.Seconds); + ZombieSpeedReduce = new FloatOptionItem(16411, "ZombieSpeedReduce", new(0.0f, 1.0f, 0.1f), 0.1f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Zombie]) .SetValueFormat(OptionFormat.Multiplier); + ZombieSpeedReduceInterval = new FloatOptionItem(16412, "ZombieSpeedReduceInterval", new(0f, 180f, 1f), 10f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Zombie]) .SetValueFormat(OptionFormat.Seconds); + ZombieInitialSpeed = new FloatOptionItem(16413, "ZombieInitialSpeed", new(0.1f, 3f, 0.1f), 1f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Zombie]) .SetValueFormat(OptionFormat.Multiplier); + ZombieMinimumSpeed = new FloatOptionItem(16414, "ZombieMinimumSpeed", new(0.05f, 2f, 0.05f), 0.1f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Zombie]) .SetValueFormat(OptionFormat.Multiplier); @@ -61,12 +66,10 @@ namespace EHR.Impostor public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive() || !GameStates.IsInTask || Main.HasJustStarted) - { - return; - } + if (!pc.IsAlive() || !GameStates.IsInTask || Main.HasJustStarted) return; long now = Utils.TimeStamp; + if (now - LastReduce > ZombieSpeedReduceInterval.GetInt()) { LastReduce = now; diff --git a/Roles/Neutral/Agitater.cs b/Roles/Neutral/Agitater.cs index 5efb022b9..fbd618912 100644 --- a/Roles/Neutral/Agitater.cs +++ b/Roles/Neutral/Agitater.cs @@ -32,19 +32,25 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Agitater); + AgiTaterBombCooldown = new FloatOptionItem(Id + 10, "AgitaterBombCooldown", new(10f, 180f, 0.5f), 20f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Agitater]) .SetValueFormat(OptionFormat.Seconds); + PassCooldown = new FloatOptionItem(Id + 11, "AgitaterPassCooldown", new(0f, 5f, 0.25f), 2f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Agitater]) .SetValueFormat(OptionFormat.Seconds); + BombExplodeCooldown = new FloatOptionItem(Id + 12, "BombExplodeCooldown", new(1f, 60f, 1f), 15f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Agitater]) .SetValueFormat(OptionFormat.Seconds); + AgitaterCanGetBombed = new BooleanOptionItem(Id + 13, "AgitaterCanGetBombed", false, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Agitater]); + AgitaterAutoReportBait = new BooleanOptionItem(Id + 14, "AgitaterAutoReportBait", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Agitater]); + HasImpostorVision = new BooleanOptionItem(Id + 15, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Agitater]); } @@ -91,15 +97,9 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!IsEnable) - { - return false; - } + if (!IsEnable) return false; - if (AgitaterAutoReportBait.GetBool() && target.Is(CustomRoles.Bait)) - { - return true; - } + if (AgitaterAutoReportBait.GetBool() && target.Is(CustomRoles.Bait)) return true; if (target.Is(CustomRoles.Pestilence) || (target.Is(CustomRoles.Veteran) && Veteran.VeteranInProtect.ContainsKey(target.PlayerId))) { @@ -117,11 +117,13 @@ namespace EHR.Neutral AgitaterHasBombed = true; killer.ResetKillCooldown(); killer.SetKillCooldown(); + LateTask.New(() => { if (CurrentBombedPlayer != byte.MaxValue && GameStates.IsInTask) { PlayerControl pc = Utils.GetPlayerById(CurrentBombedPlayer); + // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (pc != null && pc.IsAlive() && killer != null) // Can be null since it's a late task { @@ -131,27 +133,19 @@ namespace EHR.Neutral } } }, BombExplodeCooldown.GetFloat(), "AgitaterBombKill"); + return false; } public override void OnReportDeadBody() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - if (CurrentBombedPlayer == byte.MaxValue) - { - return; - } + if (CurrentBombedPlayer == byte.MaxValue) return; PlayerControl target = Utils.GetPlayerById(CurrentBombedPlayer); PlayerControl killer = Utils.GetPlayerById(PlayerIdList[0]); - if (target == null || killer == null) - { - return; - } + if (target == null || killer == null) return; target.RpcExileV2(); target.SetRealKiller(killer); @@ -169,19 +163,15 @@ namespace EHR.Neutral if (!lowLoad && GameStates.IsInTask && IsEnable && AgitaterHasBombed && CurrentBombedPlayer == playerId) { if (!player.IsAlive()) - { ResetBomb(); - } else { Vector2 agitaterPos = player.transform.position; Dictionary targetDistance = []; + foreach (PlayerControl target in PlayerControl.AllPlayerControls) { - if (!target.IsAlive()) - { - continue; - } + if (!target.IsAlive()) continue; if (target.PlayerId != playerId && target.PlayerId != LastBombedPlayer && !target.Data.IsDead) { @@ -195,10 +185,7 @@ namespace EHR.Neutral KeyValuePair min = targetDistance.OrderBy(c => c.Value).FirstOrDefault(); PlayerControl target = Utils.GetPlayerById(min.Key); float KillRange = GameOptionsData.KillDistances[Mathf.Clamp(GameOptionsManager.Instance.currentNormalGameOptions.KillDistance, 0, 2)]; - if (min.Value <= KillRange && player.CanMove && target.CanMove) - { - PassBomb(player, target); - } + if (min.Value <= KillRange && player.CanMove && target.CanMove) PassBomb(player, target); } } } @@ -206,36 +193,18 @@ namespace EHR.Neutral private void PassBomb(PlayerControl player, PlayerControl target /*, bool IsAgitater = false*/) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - if (!AgitaterHasBombed) - { - return; - } + if (!AgitaterHasBombed) return; - if (target.Data.IsDead) - { - return; - } + if (target.Data.IsDead) return; long now = Utils.TimeStamp; - if (now - CurrentBombedPlayerTime < PassCooldown.GetFloat()) - { - return; - } + if (now - CurrentBombedPlayerTime < PassCooldown.GetFloat()) return; - if (target.PlayerId == LastBombedPlayer) - { - return; - } + if (target.PlayerId == LastBombedPlayer) return; - if (!AgitaterCanGetBombed.GetBool() && target.Is(CustomRoles.Agitater)) - { - return; - } + if (!AgitaterCanGetBombed.GetBool() && target.Is(CustomRoles.Agitater)) return; if (target.Is(CustomRoles.Pestilence) || (target.Is(CustomRoles.Veteran) && Veteran.VeteranInProtect.ContainsKey(target.PlayerId))) @@ -271,10 +240,7 @@ namespace EHR.Neutral public static void ReceiveRPC(MessageReader reader) { byte agitaterId = reader.ReadByte(); - if (Main.PlayerStates[agitaterId].Role is not Agitater at) - { - return; - } + if (Main.PlayerStates[agitaterId].Role is not Agitater at) return; at.CurrentBombedPlayer = reader.ReadByte(); at.LastBombedPlayer = reader.ReadByte(); diff --git a/Roles/Neutral/Amnesiac.cs b/Roles/Neutral/Amnesiac.cs index c28cfeaa0..30949f89b 100644 --- a/Roles/Neutral/Amnesiac.cs +++ b/Roles/Neutral/Amnesiac.cs @@ -41,20 +41,27 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Amnesiac); + RememberMode = new StringOptionItem(Id + 9, "RememberMode", RememberModes, 0, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Amnesiac]); + RememberCooldown = new FloatOptionItem(Id + 10, "RememberCooldown", new(0f, 180f, 0.5f), 5f, TabGroup.NeutralRoles) .SetParent(RememberMode) .SetValueFormat(OptionFormat.Seconds); + CanRememberCrewPower = new BooleanOptionItem(Id + 11, "CanRememberCrewPower", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Amnesiac]); + IncompatibleNeutralMode = new StringOptionItem(Id + 12, "IncompatibleNeutralMode", AmnesiacIncompatibleNeutralMode.Select(x => x.ToColoredString()).ToArray(), 0, TabGroup.NeutralRoles, noTranslation: true) .SetParent(CustomRoleSpawnChances[CustomRoles.Amnesiac]); + CanVent = new BooleanOptionItem(Id + 13, "CanVent", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Amnesiac]); + VentCooldown = new FloatOptionItem(Id + 14, "VentCooldown", new(0f, 180f, 0.5f), 5f, TabGroup.NeutralRoles) .SetParent(CanVent) .SetValueFormat(OptionFormat.Seconds); + VentDuration = new FloatOptionItem(Id + 15, "MaxInVentTime", new(0f, 180f, 0.5f), 5f, TabGroup.NeutralRoles) .SetParent(CanVent) .SetValueFormat(OptionFormat.Seconds); @@ -85,6 +92,7 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte playerId) { opt.SetVision(false); + if (CanVent.GetBool()) { AURoleOptions.EngineerCooldown = VentCooldown.GetFloat(); @@ -107,10 +115,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (RememberMode.GetValue() == 1) - { - RememberRole(killer, target); - } + if (RememberMode.GetValue() == 1) RememberRole(killer, target); return false; } @@ -130,7 +135,7 @@ namespace EHR.Neutral { CustomRoles? RememberedRole = null; - string amneNotifyString = string.Empty; + var amneNotifyString = string.Empty; CustomRoles targetRole = target.GetCustomRole(); int loversAlive = Main.LoversPlayers.Count(x => x.IsAlive()); @@ -215,15 +220,9 @@ namespace EHR.Neutral target.RpcGuardAndKill(amnesiac); target.RpcGuardAndKill(target); - if (role.IsRecruitingRole()) - { - amnesiac.SetAbilityUseLimit(0); - } + if (role.IsRecruitingRole()) amnesiac.SetAbilityUseLimit(0); - if (role.GetRoleTypes() == RoleTypes.Engineer) - { - WasAmnesiac.Add(amnesiac.PlayerId); - } + if (role.GetRoleTypes() == RoleTypes.Engineer) WasAmnesiac.Add(amnesiac.PlayerId); } public override void OnReportDeadBody() @@ -233,15 +232,9 @@ namespace EHR.Neutral public override bool KnowRole(PlayerControl player, PlayerControl target) { - if (base.KnowRole(player, target)) - { - return true; - } + if (base.KnowRole(player, target)) return true; - if (player.Is(CustomRoles.Refugee) && target.Is(CustomRoleTypes.Impostor)) - { - return true; - } + if (player.Is(CustomRoles.Refugee) && target.Is(CustomRoleTypes.Impostor)) return true; return player.Is(CustomRoleTypes.Impostor) && target.Is(CustomRoles.Refugee); } @@ -254,10 +247,7 @@ namespace EHR.Neutral public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != AmnesiacId || meeting || hud) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != AmnesiacId || meeting || hud) return string.Empty; return LocateArrow.GetArrows(seer); } diff --git a/Roles/Neutral/Arsonist.cs b/Roles/Neutral/Arsonist.cs index 5c3b1b3f6..affd5f41d 100644 --- a/Roles/Neutral/Arsonist.cs +++ b/Roles/Neutral/Arsonist.cs @@ -19,18 +19,24 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(10400, TabGroup.NeutralRoles, CustomRoles.Arsonist); + ArsonistDouseTime = new FloatOptionItem(10410, "ArsonistDouseTime", new(0f, 90f, 0.5f), 3f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Arsonist]) .SetValueFormat(OptionFormat.Seconds); + ArsonistCooldown = new FloatOptionItem(10411, "Cooldown", new(0f, 60f, 0.5f), 10f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Arsonist]) .SetValueFormat(OptionFormat.Seconds); + ArsonistCanIgniteAnytime = new BooleanOptionItem(10413, "ArsonistCanIgniteAnytime", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Arsonist]); + ArsonistMinPlayersToIgnite = new IntegerOptionItem(10414, "ArsonistMinPlayersToIgnite", new(1, 14, 1), 1, TabGroup.NeutralRoles) .SetParent(ArsonistCanIgniteAnytime); + ArsonistMaxPlayersToIgnite = new IntegerOptionItem(10415, "ArsonistMaxPlayersToIgnite", new(1, 14, 1), 3, TabGroup.NeutralRoles) .SetParent(ArsonistCanIgniteAnytime); + ArsonistKeepsGameGoing = new BooleanOptionItem(10412, "ArsonistKeepsGameGoing", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Arsonist]); } @@ -38,10 +44,7 @@ namespace EHR.Neutral public override void Add(byte playerId) { On = true; - foreach (PlayerControl ar in Main.AllPlayerControls) - { - IsDoused.Add((playerId, ar.PlayerId), false); - } + foreach (PlayerControl ar in Main.AllPlayerControls) IsDoused.Add((playerId, ar.PlayerId), false); } public override void Init() @@ -78,6 +81,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { killer.SetKillCooldown(ArsonistDouseTime.GetFloat()); + if (!IsDoused[(killer.PlayerId, target.PlayerId)] && !ArsonistTimer.ContainsKey(killer.PlayerId)) { ArsonistTimer.Add(killer.PlayerId, (target, 0f)); @@ -95,10 +99,7 @@ namespace EHR.Neutral public override void OnCoEnterVent(PlayerPhysics physics, int ventId) { - if (AmongUsClient.Instance.IsGameStarted) - { - Ignite(physics); - } + if (AmongUsClient.Instance.IsGameStarted) Ignite(physics); } private static void Ignite(PlayerPhysics physics) @@ -106,18 +107,12 @@ namespace EHR.Neutral if (physics.myPlayer.IsDouseDone()) { CustomSoundsManager.RPCPlayCustomSoundAll("Boom"); - foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { - if (pc != physics.myPlayer) - { - pc.Suicide(PlayerState.DeathReason.Torched, physics.myPlayer); - } - } - foreach (PlayerControl pc in Main.AllPlayerControls) - { - pc.KillFlash(); - } + foreach (PlayerControl pc in Main.AllAlivePlayerControls) + if (pc != physics.myPlayer) + pc.Suicide(PlayerState.DeathReason.Torched, physics.myPlayer); + + foreach (PlayerControl pc in Main.AllPlayerControls) pc.KillFlash(); CustomWinnerHolder.ShiftWinnerAndSetWinner(CustomWinner.Arsonist); CustomWinnerHolder.WinnerIds.Add(physics.myPlayer.PlayerId); @@ -127,19 +122,14 @@ namespace EHR.Neutral if (ArsonistCanIgniteAnytime.GetBool()) { int douseCount = Utils.GetDousedPlayerCount(physics.myPlayer.PlayerId).Item1; + if (douseCount >= ArsonistMinPlayersToIgnite.GetInt()) // Don't check for max, since the player would not be able to ignite at all if they somehow get more players doused than the max { - if (douseCount > ArsonistMaxPlayersToIgnite.GetInt()) - { - Logger.Warn("Arsonist Ignited with more players doused than the maximum amount in the settings", "Arsonist Ignite"); - } + if (douseCount > ArsonistMaxPlayersToIgnite.GetInt()) Logger.Warn("Arsonist Ignited with more players doused than the maximum amount in the settings", "Arsonist Ignite"); foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (!physics.myPlayer.IsDousedPlayer(pc)) - { - continue; - } + if (!physics.myPlayer.IsDousedPlayer(pc)) continue; pc.Suicide(PlayerState.DeathReason.Torched, physics.myPlayer); } @@ -147,6 +137,7 @@ namespace EHR.Neutral physics.myPlayer.KillFlash(); int apc = Main.AllAlivePlayerControls.Length; + switch (apc) { case 1: @@ -169,9 +160,11 @@ namespace EHR.Neutral public override void OnGlobalFixedUpdate(PlayerControl player, bool lowLoad) { byte playerId = player.PlayerId; + if (GameStates.IsInTask && ArsonistTimer.ContainsKey(playerId)) { PlayerControl arTarget = ArsonistTimer[playerId].Player; + if (!player.IsAlive() || Pelican.IsEaten(playerId)) { ArsonistTimer.Remove(playerId); @@ -182,10 +175,9 @@ namespace EHR.Neutral { PlayerControl ar_target = ArsonistTimer[playerId].Player; float ar_time = ArsonistTimer[playerId].Timer; + if (!ar_target.IsAlive()) - { ArsonistTimer.Remove(playerId); - } else if (ar_time >= ArsonistDouseTime.GetFloat()) { player.SetKillCooldown(); @@ -199,10 +191,9 @@ namespace EHR.Neutral { float range = NormalGameOptionsV08.KillDistances[Mathf.Clamp(player.Is(CustomRoles.Reach) ? 2 : Main.NormalOptions.KillDistance, 0, 2)] + 0.5f; float dis = Vector2.Distance(player.transform.position, ar_target.transform.position); + if (dis <= range) - { ArsonistTimer[playerId] = (ar_target, ar_time + Time.fixedDeltaTime); - } else { player.SetKillCooldown(0.01f); diff --git a/Roles/Neutral/Backstabber.cs b/Roles/Neutral/Backstabber.cs index b0cca44e0..5d6cfe45a 100644 --- a/Roles/Neutral/Backstabber.cs +++ b/Roles/Neutral/Backstabber.cs @@ -17,15 +17,19 @@ namespace EHR.Neutral public override void SetupCustomOption() { - int id = 649150; + var id = 649150; Options.SetupRoleOptions(id++, TabGroup.NeutralRoles, CustomRoles.Backstabber); + KillCooldown = new FloatOptionItem(++id, "KillCooldown", new(0f, 180f, 0.5f), 15f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Backstabber]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(++id, "CanVent", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Backstabber]); + HasImpostorVision = new BooleanOptionItem(++id, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Backstabber]); + RevealAfterKilling = new BooleanOptionItem(++id, "Backstabber.RevealAfterKilling", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Backstabber]); } @@ -65,6 +69,7 @@ namespace EHR.Neutral public override void OnMurder(PlayerControl killer, PlayerControl target) { Team targetTeam = target.GetTeam(); + Team = targetTeam switch { EHR.Team.Impostor => WinningTeam.NK, diff --git a/Roles/Neutral/Bandit.cs b/Roles/Neutral/Bandit.cs index 7bb105728..8cc58a389 100644 --- a/Roles/Neutral/Bandit.cs +++ b/Roles/Neutral/Bandit.cs @@ -34,19 +34,26 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Bandit); + MaxSteals = new IntegerOptionItem(Id + 10, "BanditMaxSteals", new(1, 20, 1), 3, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bandit]); + KillCooldown = new FloatOptionItem(Id + 11, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bandit]) .SetValueFormat(OptionFormat.Seconds); + StealMode = new StringOptionItem(Id + 12, "BanditStealMode", BanditStealModeOpt, 0, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bandit]); + CanStealBetrayalAddon = new BooleanOptionItem(Id + 13, "BanditCanStealBetrayalAddon", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bandit]); + CanStealImpOnlyAddon = new BooleanOptionItem(Id + 14, "BanditCanStealImpOnlyAddon", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bandit]); + CanVent = new BooleanOptionItem(Id + 16, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bandit]); + HasImpostorVision = new BooleanOptionItem(Id + 17, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bandit]); } @@ -77,10 +84,7 @@ namespace EHR.Neutral private static void SendRPC(byte playerId /*, bool isTargetList = false*/) { - if (!On || !Utils.DoRPC) - { - return; - } + if (!On || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetBanditStealLimit, SendOption.Reliable); writer.Write(playerId); @@ -92,10 +96,7 @@ namespace EHR.Neutral { byte PlayerId = reader.ReadByte(); int Limit = reader.ReadInt32(); - if (!TotalSteals.TryAdd(PlayerId, 0)) - { - TotalSteals[PlayerId] = Limit; - } + if (!TotalSteals.TryAdd(PlayerId, 0)) TotalSteals[PlayerId] = Limit; } public override void SetKillCooldown(byte id) @@ -105,15 +106,14 @@ namespace EHR.Neutral private static CustomRoles? SelectRandomAddon(PlayerControl Target) { - if (!AmongUsClient.Instance.AmHost) - { - return null; - } + if (!AmongUsClient.Instance.AmHost) return null; List AllSubRoles = Main.PlayerStates[Target.PlayerId].SubRoles; - for (int i = 0; i < AllSubRoles.Count; i++) + + for (var i = 0; i < AllSubRoles.Count; i++) { CustomRoles role = AllSubRoles[i]; + if (IsBlacklistedAddon(role)) { Logger.Info($"Removed {role} from stealable addons", "Bandit"); @@ -138,15 +138,9 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!On) - { - return true; - } + if (!On) return true; - if (!target.HasSubRole()) - { - return true; - } + if (!target.HasSubRole()) return true; if (TotalSteals[killer.PlayerId] >= MaxSteals.GetInt()) { @@ -156,10 +150,7 @@ namespace EHR.Neutral } CustomRoles? SelectedAddOn = SelectRandomAddon(target); - if (SelectedAddOn == null) - { - return true; // no stealable addons found on the target. - } + if (SelectedAddOn == null) return true; // no stealable addons found on the target. killer.ResetKillCooldown(); @@ -182,10 +173,7 @@ namespace EHR.Neutral SendRPC(killer.PlayerId); Utils.NotifyRoles(SpecifySeer: killer, SpecifyTarget: target, ForceLoop: true); Utils.NotifyRoles(SpecifySeer: target, SpecifyTarget: killer, ForceLoop: true); - if (!DisableShieldAnimations.GetBool()) - { - killer.RpcGuardAndKill(target); - } + if (!DisableShieldAnimations.GetBool()) killer.RpcGuardAndKill(target); killer.ResetKillCooldown(); killer.SetKillCooldown(); @@ -194,35 +182,24 @@ namespace EHR.Neutral public override void OnReportDeadBody() { - if (!On) - { - return; - } + if (!On) return; - if (StealMode.GetValue() == 1) - { - return; - } + if (StealMode.GetValue() == 1) return; foreach (KeyValuePair> kvp1 in Targets) { byte banditId = kvp1.Key; PlayerControl banditpc = Utils.GetPlayerById(banditId); - if (banditpc == null || !banditpc.IsAlive()) - { - continue; - } + if (banditpc == null || !banditpc.IsAlive()) continue; Dictionary innerDictionary = kvp1.Value; Utils.NotifyRoles(SpecifySeer: banditpc); + foreach (KeyValuePair kvp2 in innerDictionary) { byte targetId = kvp2.Key; PlayerControl target = Utils.GetPlayerById(banditId); - if (target == null) - { - continue; - } + if (target == null) continue; CustomRoles role = kvp2.Value; Main.PlayerStates[targetId].RemoveSubRole(role); diff --git a/Roles/Neutral/Bargainer.cs b/Roles/Neutral/Bargainer.cs index 9eab4827b..6b998db0f 100644 --- a/Roles/Neutral/Bargainer.cs +++ b/Roles/Neutral/Bargainer.cs @@ -75,7 +75,7 @@ namespace EHR.Neutral { get { - string mapName = Main.CurrentMap.ToString(); + var mapName = Main.CurrentMap.ToString(); IEnumerable> devices = DisableDevice.DevicePos.SkipWhile(x => !x.Key.StartsWith(mapName)).TakeWhile(x => x.Key.StartsWith(mapName)); return devices.Select(x => x.Value); } @@ -85,7 +85,7 @@ namespace EHR.Neutral public override void SetupCustomOption() { - int id = 14870; + var id = 14870; const TabGroup tab = TabGroup.NeutralRoles; SetupRoleOptions(id++, tab, CustomRoles.Bargainer); @@ -93,10 +93,13 @@ namespace EHR.Neutral KillCooldown = new FloatOptionItem(++id, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Bargainer]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(++id, "CanVent", true, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Bargainer]); + HasImpostorVision = new BooleanOptionItem(++id, "ImpostorVision", true, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Bargainer]); + StartingMoney = new IntegerOptionItem(++id, "Bargainer.StartingMoney", new(0, 100, 5), 0, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Bargainer]); @@ -104,6 +107,7 @@ namespace EHR.Neutral { OptionItem boolOpt = new BooleanOptionItem(++id, $"Bargainer.{action}.Enabled", true, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Bargainer]); + OptionItem intOpt = new IntegerOptionItem(++id, $"Bargainer.{action}.Amount", new(0, 100, 5), GetDefaultValue(), tab) .SetParent(boolOpt); @@ -125,15 +129,14 @@ namespace EHR.Neutral foreach (Item item in Enum.GetValues()) { - if (item == Item.None) - { - continue; - } + if (item == Item.None) continue; OptionItem boolOpt = new BooleanOptionItem(++id, $"Bargainer.{item}.Enabled", true, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Bargainer]); + OptionItem intOpt = new IntegerOptionItem(++id, $"Bargainer.{item}.Cost", new(0, 200, 5), GetDefaultValue(), tab) .SetParent(boolOpt); + SetupExtraSettings(); ItemSettings[item] = (boolOpt, intOpt); @@ -158,21 +161,26 @@ namespace EHR.Neutral case Item.BandAid: ShieldDuration = new StringOptionItem(++id, $"Bargainer.{item}.DurationSwitch", Enum.GetNames(), 0, tab) .SetParent(boolOpt); + ShieldTime = new IntegerOptionItem(++id, $"Bargainer.{item}.Duration", new(0, 60, 1), 20, tab) .SetParent(ShieldDuration) .SetValueFormat(OptionFormat.Seconds); + break; case Item.EnergyDrink: ReducedKillCooldown = new FloatOptionItem(++id, $"Bargainer.{item}.ReducedKCD", new(0f, 180f, 0.5f), 17.5f, tab) .SetParent(boolOpt) .SetValueFormat(OptionFormat.Seconds); + break; case Item.LensOfTruth: AlignmentVisible = new StringOptionItem(++id, $"Bargainer.{item}.DurationSwitch", Enum.GetNames(), (int)AlignmentVisibleOptions.UntilNextReveal, tab) .SetParent(boolOpt); + AlignmentVisibleDuration = new IntegerOptionItem(++id, $"Bargainer.{item}.Duration", new(1, 30, 1), 10, tab) .SetParent(AlignmentVisible) .SetValueFormat(OptionFormat.Seconds); + break; } } @@ -184,22 +192,16 @@ namespace EHR.Neutral On = false; Gains = []; + foreach (KeyValuePair kvp in MoneySettings) - { if (kvp.Value.Enabled.GetBool()) - { Gains[kvp.Key] = kvp.Value.Amount.GetInt(); - } - } Costs = []; + foreach (KeyValuePair kvp in ItemSettings) - { if (kvp.Value.Enabled.GetBool()) - { Costs[kvp.Key] = kvp.Value.Cost.GetInt(); - } - } Costs[Item.None] = 0; } @@ -235,15 +237,9 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte id) { opt.SetVision(HasImpostorVision.GetBool()); - if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) - { - AURoleOptions.PhantomCooldown = 1f; - } + if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) AURoleOptions.PhantomCooldown = 1f; - if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = 1f; - } + if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) AURoleOptions.ShapeshifterCooldown = 1f; } private void Update() @@ -297,10 +293,7 @@ namespace EHR.Neutral public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; CycleItem(shapeshifter); return false; @@ -354,10 +347,7 @@ namespace EHR.Neutral case Item.EnergyDrink: pc.ResetKillCooldown(); pc.SyncSettings(); - if (Main.KillTimers[pc.PlayerId] > ReducedKillCooldown.GetFloat()) - { - pc.SetKillCooldown(ReducedKillCooldown.GetFloat()); - } + if (Main.KillTimers[pc.PlayerId] > ReducedKillCooldown.GetFloat()) pc.SetKillCooldown(ReducedKillCooldown.GetFloat()); break; case Item.LensOfTruth: @@ -394,13 +384,11 @@ namespace EHR.Neutral } int rc = ActiveItems.RemoveAll(x => x.Item == Item.None); - if (rc > 0) - { - Utils.SendRPC(CustomRPC.SyncBargainer, pc.PlayerId, 6); - } + if (rc > 0) Utils.SendRPC(CustomRPC.SyncBargainer, pc.PlayerId, 6); (Item Item, long ActivateTimeStamp, int Duration, byte Target)[] array = ActiveItems.Where(x => x.Duration != int.MaxValue && x.ActivateTimeStamp + x.Duration < Utils.TimeStamp).ToArray(); - for (int i = 0; i < array.Length; i++) + + for (var i = 0; i < array.Length; i++) { (Item Item, long ActivateTimeStamp, int Duration, byte Target) item = array[i]; ActiveItems.Remove(item); @@ -418,15 +406,12 @@ namespace EHR.Neutral { List indexesToRemove = []; - for (int i = 0; i < ActiveItems.Count; i++) + for (var i = 0; i < ActiveItems.Count; i++) { switch (ActiveItems[i].Item) { case Item.LensOfTruth: - if ((AlignmentVisibleOptions)AlignmentVisible.GetValue() is AlignmentVisibleOptions.ForSpecifiedTime or AlignmentVisibleOptions.UntilNextMeeting) - { - indexesToRemove.Add(i); - } + if ((AlignmentVisibleOptions)AlignmentVisible.GetValue() is AlignmentVisibleOptions.ForSpecifiedTime or AlignmentVisibleOptions.UntilNextMeeting) indexesToRemove.Add(i); break; default: @@ -446,10 +431,7 @@ namespace EHR.Neutral public override bool KnowRole(PlayerControl seer, PlayerControl target) { - if (base.KnowRole(seer, target)) - { - return true; - } + if (base.KnowRole(seer, target)) return true; return Main.PlayerStates[seer.PlayerId].Role is Bargainer bg && bg.ActiveItems.Any(x => x.Target == target.PlayerId); } @@ -457,10 +439,7 @@ namespace EHR.Neutral public static void ReceiveRPC(MessageReader reader) { byte playerId = reader.ReadByte(); - if (Main.PlayerStates[playerId].Role is not Bargainer bg) - { - return; - } + if (Main.PlayerStates[playerId].Role is not Bargainer bg) return; switch (reader.ReadPackedInt32()) { @@ -487,17 +466,11 @@ namespace EHR.Neutral public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is not Bargainer bg) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not Bargainer bg) return string.Empty; - string result = string.Empty; + var result = string.Empty; if (bg.InShop) { @@ -505,29 +478,22 @@ namespace EHR.Neutral Translator.GetString("Bargainer.Suffix.InShop"), Translator.GetString($"Bargainer.{bg.SelectedItem}"), Utils.ColorString(bg.Money >= Costs[bg.SelectedItem] ? Color.white : Color.red, $"{Costs[bg.SelectedItem]}")); + result += "\n"; } - if (seer.IsModClient()) - { - result += ""; - } + if (seer.IsModClient()) result += ""; result += string.Join(' ', bg.ActiveItems.Select(x => { long timeLeft = x.Duration - (Utils.TimeStamp - x.ActivateTimeStamp) + 1; string icon = Icons[x.Item]; - if (x.Item == Item.LensOfTruth && x.Target != byte.MaxValue) - { - icon = Utils.ColorString(Main.PlayerColors[x.Target], icon); - } + if (x.Item == Item.LensOfTruth && x.Target != byte.MaxValue) icon = Utils.ColorString(Main.PlayerColors[x.Target], icon); return seer.IsModClient() && timeLeft < 10 ? $"{icon} ({timeLeft}s)" : icon; })); - if (seer.IsModClient()) - { - result += ""; - } + + if (seer.IsModClient()) result += ""; return result; } diff --git a/Roles/Neutral/Beehive.cs b/Roles/Neutral/Beehive.cs index ceb5f50c6..cbe93398d 100644 --- a/Roles/Neutral/Beehive.cs +++ b/Roles/Neutral/Beehive.cs @@ -26,23 +26,30 @@ namespace EHR.Neutral public override void SetupCustomOption() { - int id = 647350; + var id = 647350; Options.SetupRoleOptions(id++, TabGroup.NeutralRoles, CustomRoles.Beehive); + Distance = new FloatOptionItem(++id, "Beehive.Distance", new(0f, 20f, 0.5f), 15f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Beehive]); + Time = new FloatOptionItem(++id, "Beehive.Time", new(0f, 30f, 0.5f), 10f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Beehive]) .SetValueFormat(OptionFormat.Seconds); + StingCooldown = new FloatOptionItem(++id, "Beehive.StingCooldown", new(0f, 180f, 0.5f), 5f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Beehive]) .SetValueFormat(OptionFormat.Seconds); + StungPlayersDieOnMeeting = new BooleanOptionItem(++id, "Beehive.StungPlayersDieOnMeeting", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Beehive]); + KillCooldown = new FloatOptionItem(++id, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Beehive]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(++id, "CanVent", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Beehive]); + HasImpostorVision = new BooleanOptionItem(++id, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Beehive]); } @@ -76,10 +83,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!base.OnCheckMurder(killer, target)) - { - return false; - } + if (!base.OnCheckMurder(killer, target)) return false; return killer.CheckDoubleTrigger(target, () => { @@ -94,10 +98,7 @@ namespace EHR.Neutral public override void OnGlobalFixedUpdate(PlayerControl pc, bool lowLoad) { - if (lowLoad || !pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) - { - return; - } + if (lowLoad || !pc.IsAlive() || !GameStates.IsInTask || ExileController.Instance) return; if (StungPlayers.TryGetValue(pc.PlayerId, out (long TimeStamp, Vector2 InitialPosition) sp)) { @@ -105,10 +106,7 @@ namespace EHR.Neutral { StungPlayers.Remove(pc.PlayerId); Utils.SendRPC(CustomRPC.SyncRoleData, BeehiveId, 2, pc.PlayerId); - if (Vector2.Distance(pc.Pos(), sp.InitialPosition) < Distance.GetFloat()) - { - pc.Suicide(realKiller: Utils.GetPlayerById(BeehiveId)); - } + if (Vector2.Distance(pc.Pos(), sp.InitialPosition) < Distance.GetFloat()) pc.Suicide(realKiller: Utils.GetPlayerById(BeehiveId)); } Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); @@ -142,10 +140,7 @@ namespace EHR.Neutral public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || meeting || hud || !StungPlayers.TryGetValue(seer.PlayerId, out (long TimeStamp, Vector2 InitialPosition) sp)) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || meeting || hud || !StungPlayers.TryGetValue(seer.PlayerId, out (long TimeStamp, Vector2 InitialPosition) sp)) return string.Empty; double walked = Math.Round(Vector2.Distance(seer.Pos(), sp.InitialPosition), 1); double distance = Math.Round(Distance.GetFloat(), 1); diff --git a/Roles/Neutral/BloodKnight.cs b/Roles/Neutral/BloodKnight.cs index 0942ef1de..89e577274 100644 --- a/Roles/Neutral/BloodKnight.cs +++ b/Roles/Neutral/BloodKnight.cs @@ -16,20 +16,19 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.BloodKnight); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.BloodKnight]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 11, "CanVent", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.BloodKnight]); HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.BloodKnight]); + ProtectDuration = new FloatOptionItem(Id + 14, "BKProtectDuration", new(1f, 30f, 1f), 15f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.BloodKnight]) .SetValueFormat(OptionFormat.Seconds); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Neutral/Bubble.cs b/Roles/Neutral/Bubble.cs index b301ddcfd..636fac8c8 100644 --- a/Roles/Neutral/Bubble.cs +++ b/Roles/Neutral/Bubble.cs @@ -30,22 +30,29 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Bubble); + KillCooldown = new FloatOptionItem(Id + 2, "BubbleCD", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bubble]) .SetValueFormat(OptionFormat.Seconds); + HasImpostorVision = new BooleanOptionItem(Id + 6, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bubble]); + NotifyDelay = new IntegerOptionItem(Id + 3, "BubbleTargetNotifyDelay", new(0, 60, 1), 3, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bubble]) .SetValueFormat(OptionFormat.Seconds); + ExplodeDelay = new IntegerOptionItem(Id + 4, "BubbleExplosionDelay", new(0, 60, 1), 10, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bubble]) .SetValueFormat(OptionFormat.Seconds); + BubbleDiesIfInRange = new BooleanOptionItem(Id + 5, "BubbleDiesIfInRange", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bubble]); + ExplosionRadius = new FloatOptionItem(Id + 7, "BubbleExplosionRadius", new(0.1f, 5f, 0.1f), 3f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bubble]) .SetValueFormat(OptionFormat.Multiplier); + CanVent = new BooleanOptionItem(Id + 8, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Bubble]); } @@ -79,10 +86,7 @@ namespace EHR.Neutral private void SendRPC(byte id = byte.MaxValue, bool remove = false, bool clear = false) { - if (!IsEnable || !DoRPC) - { - return; - } + if (!IsEnable || !DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncBubble, SendOption.Reliable); writer.Write(remove); @@ -96,26 +100,18 @@ namespace EHR.Neutral bool remove = reader.ReadBoolean(); bool clear = reader.ReadBoolean(); byte id = reader.ReadByte(); + if (clear) - { EncasedPlayers.Clear(); - } else if (remove) - { EncasedPlayers.Remove(id); - } else - { EncasedPlayers.Add(id, TimeStamp); - } } public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!IsEnable || target == null) - { - return false; - } + if (!IsEnable || target == null) return false; EncasedPlayers.Add(target.PlayerId, TimeStamp); SendRPC(target.PlayerId); @@ -125,10 +121,7 @@ namespace EHR.Neutral public override void OnGlobalFixedUpdate(PlayerControl encasedPc, bool lowLoad) { - if (lowLoad || !IsEnable || !GameStates.IsInTask || !EncasedPlayers.TryGetValue(encasedPc.PlayerId, out long ts)) - { - return; - } + if (lowLoad || !IsEnable || !GameStates.IsInTask || !EncasedPlayers.TryGetValue(encasedPc.PlayerId, out long ts)) return; long now = TimeStamp; byte id = encasedPc.PlayerId; @@ -143,12 +136,10 @@ namespace EHR.Neutral } IEnumerable players = GetPlayersInRadius(ExplosionRadius.GetFloat(), encasedPc.Pos()); + foreach (PlayerControl pc in players) { - if (pc == null) - { - continue; - } + if (pc == null) continue; if (pc.PlayerId == BubbleId) { @@ -156,10 +147,7 @@ namespace EHR.Neutral { LateTask.New(() => { - if (GameStates.IsInTask) - { - pc.Suicide(PlayerState.DeathReason.Bombed); - } + if (GameStates.IsInTask) pc.Suicide(PlayerState.DeathReason.Bombed); }, 0.5f, log: false); } @@ -186,15 +174,9 @@ namespace EHR.Neutral public override void OnReportDeadBody() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - foreach (PlayerControl pc in EncasedPlayers.Keys.Select(x => GetPlayerById(x)).Where(x => x != null && x.IsAlive())) - { - pc.Suicide(PlayerState.DeathReason.Bombed, BubblePC); - } + foreach (PlayerControl pc in EncasedPlayers.Keys.Select(x => GetPlayerById(x)).Where(x => x != null && x.IsAlive())) pc.Suicide(PlayerState.DeathReason.Bombed, BubblePC); EncasedPlayers.Clear(); SendRPC(clear: true); @@ -202,10 +184,7 @@ namespace EHR.Neutral public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (target == null || !EncasedPlayers.TryGetValue(target.PlayerId, out long ts) || (ts + NotifyDelay.GetInt() >= TimeStamp && !seer.Is(CustomRoles.Bubble))) - { - return string.Empty; - } + if (target == null || !EncasedPlayers.TryGetValue(target.PlayerId, out long ts) || (ts + NotifyDelay.GetInt() >= TimeStamp && !seer.Is(CustomRoles.Bubble))) return string.Empty; return ColorString(GetRoleColor(CustomRoles.Bubble), $"⚠ {ExplodeDelay.GetInt() - (TimeStamp - ts) + 1}"); } diff --git a/Roles/Neutral/Chemist.cs b/Roles/Neutral/Chemist.cs index 3f76cc879..6aca9287e 100644 --- a/Roles/Neutral/Chemist.cs +++ b/Roles/Neutral/Chemist.cs @@ -111,7 +111,7 @@ namespace EHR.Neutral public override void SetupCustomOption() { - int id = 17670; + var id = 17670; const TabGroup tab = TabGroup.NeutralRoles; SetupRoleOptions(id++, tab, CustomRoles.Chemist); @@ -119,18 +119,22 @@ namespace EHR.Neutral KillCooldown = new FloatOptionItem(++id, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Chemist]) .SetValueFormat(OptionFormat.Seconds); + HasImpostorVision = new BooleanOptionItem(++id, "ImpostorVision", true, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Chemist]); AirGainedPerSecond = new IntegerOptionItem(++id, "Chemist.AirGainedPerSecond", new(5, 100, 5), 10, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Chemist]) .SetValueFormat(OptionFormat.Times); + WaterGainedPerSecond = new IntegerOptionItem(++id, "Chemist.WaterGainedPerSecond", new(5, 100, 5), 10, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Chemist]) .SetValueFormat(OptionFormat.Times); + CoalGainedPerVent = new IntegerOptionItem(++id, "Chemist.CoalGainedPerVent", new(1, 10, 1), 1, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Chemist]) .SetValueFormat(OptionFormat.Times); + IronOreGainedPerVent = new IntegerOptionItem(++id, "Chemist.IronOreGainedPerVent", new(1, 50, 1), 4, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Chemist]) .SetValueFormat(OptionFormat.Times); @@ -143,15 +147,19 @@ namespace EHR.Neutral AcidPlayersDie = new StringOptionItem(++id, "Chemist.AcidPlayersDie", Enum.GetNames(), 0, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Chemist]); + AcidPlayersDieAfterTime = new IntegerOptionItem(++id, "Chemist.AcidPlayersDieAfterTime", new(1, 60, 1), 15, tab) .SetParent(AcidPlayersDie) .SetValueFormat(OptionFormat.Seconds); + BlindDuration = new IntegerOptionItem(++id, "Chemist.BlindDuration", new(1, 60, 1), 10, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Chemist]) .SetValueFormat(OptionFormat.Seconds); + GrenadeExplodeDelay = new IntegerOptionItem(++id, "Chemist.GrenadeExplodeDelay", new(1, 60, 1), 5, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Chemist]) .SetValueFormat(OptionFormat.Seconds); + GrenadeExplodeRadius = new FloatOptionItem(++id, "Chemist.GrenadeExplodeRadius", new(0.25f, 10f, 0.25f), 4f, tab) .SetParent(CustomRoleSpawnChances[CustomRoles.Chemist]) .SetValueFormat(OptionFormat.Multiplier); @@ -177,6 +185,7 @@ namespace EHR.Neutral Instances = []; FactoryLocations = []; + LateTask.New(() => { FactoryLocations = ShipStatus.Instance.AllRooms @@ -225,15 +234,9 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte id) { opt.SetVision(HasImpostorVision.GetBool()); - if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) - { - AURoleOptions.PhantomCooldown = 1f; - } + if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) AURoleOptions.PhantomCooldown = 1f; - if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = 1f; - } + if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) AURoleOptions.ShapeshifterCooldown = 1f; } private static ItemType GetItemType(Item item) @@ -311,20 +314,14 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!base.OnCheckMurder(killer, target)) - { - return false; - } + if (!base.OnCheckMurder(killer, target)) return false; int need = FinalProductUsageAmounts[Item.SulfuricAcid].GetInt(); int need2 = FinalProductUsageAmounts[Item.Grenade].GetInt(); bool canUseAcid = ItemCounts[Item.SulfuricAcid] >= need && !AcidPlayers.ContainsKey(target.PlayerId) && !AcidPlayers.Any(x => x.Value.OtherAcidPlayers.Contains(target.PlayerId)); bool canUseGrenade = ItemCounts[Item.Grenade] >= need2; - if (!canUseAcid && !canUseGrenade) - { - return true; - } + if (!canUseAcid && !canUseGrenade) return true; return killer.CheckDoubleTrigger(target, () => { @@ -349,6 +346,7 @@ namespace EHR.Neutral public override void OnMurder(PlayerControl killer, PlayerControl target) { int need = FinalProductUsageAmounts[Item.Explosive].GetInt(); + if (ItemCounts[Item.Explosive] >= need) { ItemCounts[Item.Explosive] -= need; @@ -359,10 +357,7 @@ namespace EHR.Neutral public override void OnGlobalFixedUpdate(PlayerControl pc, bool lowLoad) { - if (!GameStates.IsInTask || !pc.IsAlive()) - { - return; - } + if (!GameStates.IsInTask || !pc.IsAlive()) return; Vector2 pos = pc.Pos(); @@ -379,6 +374,7 @@ namespace EHR.Neutral Grenades.Remove(pc.PlayerId); float radius = GrenadeExplodeRadius.GetFloat(); + Main.AllAlivePlayerControls .Where(x => x.PlayerId != ChemistPC.PlayerId && Vector2.Distance(x.Pos(), pos) < radius && ChemistPC.RpcCheckAndMurder(x, true)) .Do(x => x.Suicide(realKiller: ChemistPC)); @@ -387,12 +383,10 @@ namespace EHR.Neutral public override void OnEnterVent(PlayerControl pc, Vent vent) { - if (IsBlinding) - { - return; - } + if (IsBlinding) return; int need = FinalProductUsageAmounts[Item.MethylamineGas].GetInt(); + if (ItemCounts[Item.MethylamineGas] >= need) { ItemCounts[Item.MethylamineGas] -= need; @@ -401,6 +395,7 @@ namespace EHR.Neutral IsBlinding = true; Utils.MarkEveryoneDirtySettings(); + LateTask.New(() => { if (IsBlinding) @@ -426,10 +421,7 @@ namespace EHR.Neutral { if (BombedBodies.Contains(target.PlayerId)) { - if (ChemistPC.RpcCheckAndMurder(reporter, true)) - { - reporter.Suicide(realKiller: ChemistPC); - } + if (ChemistPC.RpcCheckAndMurder(reporter, true)) reporter.Suicide(realKiller: ChemistPC); return false; } @@ -451,18 +443,12 @@ namespace EHR.Neutral if (force || kvp.Value.TimeStamp + AcidPlayersDieAfterTime.GetInt() <= Utils.TimeStamp) { PlayerControl srcPlayer = Utils.GetPlayerById(kvp.Key); - if (srcPlayer != null && srcPlayer.IsAlive() && ChemistPC.RpcCheckAndMurder(srcPlayer, true)) - { - srcPlayer.Suicide(realKiller: ChemistPC); - } + if (srcPlayer != null && srcPlayer.IsAlive() && ChemistPC.RpcCheckAndMurder(srcPlayer, true)) srcPlayer.Suicide(realKiller: ChemistPC); foreach (byte id in kvp.Value.OtherAcidPlayers) { PlayerControl player = Utils.GetPlayerById(id); - if (player == null || !player.IsAlive() || !ChemistPC.RpcCheckAndMurder(player, true)) - { - continue; - } + if (player == null || !player.IsAlive() || !ChemistPC.RpcCheckAndMurder(player, true)) continue; player.Suicide(realKiller: ChemistPC); } @@ -472,10 +458,7 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask || !pc.IsAlive() || LastUpdate >= Utils.TimeStamp) - { - return; - } + if (!GameStates.IsInTask || !pc.IsAlive() || LastUpdate >= Utils.TimeStamp) return; LastUpdate = Utils.TimeStamp; @@ -511,20 +494,14 @@ namespace EHR.Neutral } } - if ((AcidPlayersDieOptions)AcidPlayersDie.GetValue() == AcidPlayersDieOptions.AfterTime) - { - CheckAndKillAcidPlayers(); - } + if ((AcidPlayersDieOptions)AcidPlayersDie.GetValue() == AcidPlayersDieOptions.AfterTime) CheckAndKillAcidPlayers(); Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); } public override bool OnSabotage(PlayerControl pc) { - if (SortedAvailableProcesses.Count == 0) - { - return false; - } + if (SortedAvailableProcesses.Count == 0) return false; Cycle(pc); @@ -533,10 +510,7 @@ namespace EHR.Neutral public override bool OnVanish(PlayerControl pc) { - if (SortedAvailableProcesses.Count == 0) - { - return false; - } + if (SortedAvailableProcesses.Count == 0) return false; Cycle(pc); @@ -545,15 +519,9 @@ namespace EHR.Neutral public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; - if (SortedAvailableProcesses.Count == 0) - { - return false; - } + if (SortedAvailableProcesses.Count == 0) return false; Cycle(shapeshifter); @@ -571,23 +539,18 @@ namespace EHR.Neutral public override void OnPet(PlayerControl pc) { - if (SelectedProcess == string.Empty) - { - return; - } + if (SelectedProcess == string.Empty) return; (List<(int Count, Item Item)> Ingredients, List<(int Count, Item Item)> Results) = Processes[CurrentFactory][SelectedProcess]; - if (!Ingredients.TrueForAll(x => ItemCounts[x.Item] >= x.Count)) - { - return; - } + if (!Ingredients.TrueForAll(x => ItemCounts[x.Item] >= x.Count)) return; Ingredients.ForEach(x => { ItemCounts[x.Item] -= x.Count; Utils.SendRPC(CustomRPC.SyncRoleData, pc.PlayerId, 1, (int)x.Item, -x.Count); }); + Results.ForEach(x => { ItemCounts[x.Item] += x.Count; @@ -602,7 +565,7 @@ namespace EHR.Neutral switch (reader.ReadPackedInt32()) { case 1: - Item item = (Item)reader.ReadPackedInt32(); + var item = (Item)reader.ReadPackedInt32(); ItemCounts.TryAdd(item, 0); ItemCounts[item] += reader.ReadPackedInt32(); break; @@ -620,21 +583,12 @@ namespace EHR.Neutral public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is not Chemist cm) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not Chemist cm) return string.Empty; bool self = seer.PlayerId == target.PlayerId; - if (self && seer.IsModClient() && !hud) - { - return string.Empty; - } + if (self && seer.IsModClient() && !hud) return string.Empty; StringBuilder sb = new StringBuilder().Append(""); @@ -648,26 +602,17 @@ namespace EHR.Neutral foreach ((ItemType type, Dictionary items) in grouped) { - if (items.Count == 0) - { - continue; - } + if (items.Count == 0) continue; sb.Append($"{type.ToString()[0]}: "); - foreach ((Item item, int count) in items) - { - sb.Append(Utils.ColorString(GetItemColor(item), $"{Utils.ColorString(FinalProductUsageAmounts.TryGetValue(item, out OptionItem opt) && opt.GetInt() <= count ? Color.green : Color.white, $"{count}")} {GetChemicalForm(item)}") + ", "); - } + foreach ((Item item, int count) in items) sb.Append(Utils.ColorString(GetItemColor(item), $"{Utils.ColorString(FinalProductUsageAmounts.TryGetValue(item, out OptionItem opt) && opt.GetInt() <= count ? Color.green : Color.white, $"{count}")} {GetChemicalForm(item)}") + ", "); sb.Length -= 2; sb.AppendLine(); } - if (cm.SelectedProcess == string.Empty) - { - return sb.ToString().TrimEnd(); - } + if (cm.SelectedProcess == string.Empty) return sb.ToString().TrimEnd(); (List<(int Count, Item Item)> Ingredients, List<(int Count, Item Item)> Results) = Processes[cm.CurrentFactory][cm.SelectedProcess]; @@ -681,6 +626,7 @@ namespace EHR.Neutral { int time = AcidPlayersDieAfterTime.GetInt(); long now = Utils.TimeStamp; + foreach (KeyValuePair OtherAcidPlayers, long TimeStamp)> kvp in cm.AcidPlayers) { if (kvp.Key == target.PlayerId || kvp.Value.OtherAcidPlayers.Contains(target.PlayerId)) diff --git a/Roles/Neutral/Cherokious.cs b/Roles/Neutral/Cherokious.cs index 521438cab..3140e3d2f 100644 --- a/Roles/Neutral/Cherokious.cs +++ b/Roles/Neutral/Cherokious.cs @@ -14,9 +14,11 @@ namespace EHR.Neutral { const int id = 13860; Options.SetupRoleOptions(id, TabGroup.NeutralRoles, CustomRoles.Cherokious); + KillCooldown = new IntegerOptionItem(id + 2, "KillCooldown", new(0, 60, 1), 15, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Cherokious]) .SetValueFormat(OptionFormat.Seconds); + Tasks = Options.OverrideTasksData.Create(id + 3, TabGroup.NeutralRoles, CustomRoles.Cherokious); } @@ -38,16 +40,10 @@ namespace EHR.Neutral public override void OnPet(PlayerControl pc) { - if (pc.GetAbilityUseLimit() < 1) - { - return; - } + if (pc.GetAbilityUseLimit() < 1) return; PlayerControl target = ExternalRpcPetPatch.SelectKillButtonTarget(pc); - if (target != null && pc.RpcCheckAndMurder(target)) - { - pc.RpcRemoveAbilityUse(); - } + if (target != null && pc.RpcCheckAndMurder(target)) pc.RpcRemoveAbilityUse(); } public override bool CanUseKillButton(PlayerControl pc) diff --git a/Roles/Neutral/Collector.cs b/Roles/Neutral/Collector.cs index 85f6666cf..4340bd2e4 100644 --- a/Roles/Neutral/Collector.cs +++ b/Roles/Neutral/Collector.cs @@ -19,6 +19,7 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Collector); + CollectorCollectAmount = new IntegerOptionItem(Id + 13, "CollectorCollectAmount", new(1, 60, 1), 30, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Collector]) .SetValueFormat(OptionFormat.Votes); @@ -39,10 +40,7 @@ namespace EHR.Neutral private static void SendRPC(byte playerId) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetCollectorVotes, SendOption.Reliable); writer.Write(playerId); @@ -60,10 +58,7 @@ namespace EHR.Neutral public override string GetProgressText(byte playerId, bool comms) { - if (!CollectVote.TryGetValue(playerId, out int VoteAmount)) - { - return string.Empty; - } + if (!CollectVote.TryGetValue(playerId, out int VoteAmount)) return string.Empty; int CollectNum = CollectorCollectAmount.GetInt(); return Utils.ColorString(Utils.GetRoleColor(CustomRoles.Collector).ShadeColor(0.25f), $"({VoteAmount}/{CollectNum})"); @@ -72,18 +67,13 @@ namespace EHR.Neutral public static bool CollectorWin(bool check = true) { PlayerControl[] pc = Main.AllPlayerControls.Where(x => x.Is(CustomRoles.Collector) && x.IsAlive() && CollectDone(x)).ToArray(); + if (pc.Length > 0) { - if (check) - { - return true; - } + if (check) return true; CustomWinnerHolder.ResetAndSetWinner(CustomWinner.Collector); - foreach (PlayerControl winner in pc) - { - CustomWinnerHolder.WinnerIds.Add(winner.PlayerId); - } + foreach (PlayerControl winner in pc) CustomWinnerHolder.WinnerIds.Add(winner.PlayerId); return true; } @@ -98,10 +88,7 @@ namespace EHR.Neutral byte pcid = player.PlayerId; int VoteAmount = CollectVote[pcid]; int CollectNum = CollectorCollectAmount.GetInt(); - if (VoteAmount >= CollectNum) - { - return true; - } + if (VoteAmount >= CollectNum) return true; } return false; @@ -109,26 +96,17 @@ namespace EHR.Neutral public static void CollectorVotes(PlayerControl target, PlayerVoteArea ps) //集票者投票给谁 { - if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Collector)) - { - CollectorVoteFor.TryAdd(target.PlayerId, ps.TargetPlayerId); - } + if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Collector)) CollectorVoteFor.TryAdd(target.PlayerId, ps.TargetPlayerId); } public static void CollectAmount(Dictionary VotingData, MeetingHud __instance) //得到集票者收集到的票 { foreach (PlayerVoteArea pva in __instance.playerStates.ToArray()) { - if (pva == null) - { - continue; - } + if (pva == null) continue; PlayerControl pc = Utils.GetPlayerById(pva.TargetPlayerId); - if (pc == null) - { - continue; - } + if (pc == null) continue; foreach ((byte key, int value) in VotingData) { diff --git a/Roles/Neutral/DarkHide.cs b/Roles/Neutral/DarkHide.cs index 83d5e3acf..f70e68a74 100644 --- a/Roles/Neutral/DarkHide.cs +++ b/Roles/Neutral/DarkHide.cs @@ -26,15 +26,20 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.DarkHide); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 30f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.DarkHide]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 14, "CanVent", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.DarkHide]); + HasImpostorVision = new BooleanOptionItem(Id + 11, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.DarkHide]); + CanCountNeutralKiller = new BooleanOptionItem(Id + 12, "CanCountNeutralKiller", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.DarkHide]); + SnatchesWin = new BooleanOptionItem(Id + 13, "SnatchesWin", false, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.DarkHide]); } @@ -58,10 +63,7 @@ namespace EHR.Neutral public static void ReceiveRPC(MessageReader msg) { byte DarkHiderId = msg.ReadByte(); - if (Main.PlayerStates[DarkHiderId].Role is not DarkHide { IsEnable: true } dh) - { - return; - } + if (Main.PlayerStates[DarkHiderId].Role is not DarkHide { IsEnable: true } dh) return; bool IsKillerKill = msg.ReadBoolean(); dh.IsWinKill = IsKillerKill; @@ -69,10 +71,7 @@ namespace EHR.Neutral private void DRpcSetKillCount(PlayerControl player) { - if (!IsEnable || !Utils.DoRPC || !AmongUsClient.Instance.AmHost) - { - return; - } + if (!IsEnable || !Utils.DoRPC || !AmongUsClient.Instance.AmHost) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetDarkHiderKillCount, SendOption.Reliable); writer.Write(player.PlayerId); @@ -104,15 +103,9 @@ namespace EHR.Neutral { CustomRoles targetRole = Ktarget.GetCustomRole(); bool succeeded = targetRole.IsImpostor(); - if (CanCountNeutralKiller.GetBool() && !Ktarget.Is(CustomRoles.Arsonist) && !Ktarget.Is(CustomRoles.Revolutionist)) - { - succeeded = succeeded || Ktarget.IsNeutralKiller(); - } + if (CanCountNeutralKiller.GetBool() && !Ktarget.Is(CustomRoles.Arsonist) && !Ktarget.Is(CustomRoles.Revolutionist)) succeeded = succeeded || Ktarget.IsNeutralKiller(); - if (succeeded && SnatchesWin.GetBool()) - { - IsWinKill = true; - } + if (succeeded && SnatchesWin.GetBool()) IsWinKill = true; DRpcSetKillCount(killer); MessageWriter SabotageFixWriter = AmongUsClient.Instance.StartRpcImmediately(ShipStatus.Instance.NetId, (byte)RpcCalls.UpdateSystem, SendOption.Reliable, killer.GetClientId()); @@ -122,10 +115,7 @@ namespace EHR.Neutral foreach (PlayerControl target in Main.AllPlayerControls) { - if (target.PlayerId == killer.PlayerId || target.Data.Disconnected) - { - continue; - } + if (target.PlayerId == killer.PlayerId || target.Data.Disconnected) continue; SabotageFixWriter = AmongUsClient.Instance.StartRpcImmediately(ShipStatus.Instance.NetId, (byte)RpcCalls.UpdateSystem, SendOption.Reliable, target.GetClientId()); SabotageFixWriter.Write((byte)SystemTypes.Electrical); diff --git a/Roles/Neutral/Doomsayer.cs b/Roles/Neutral/Doomsayer.cs index f8ece31f3..727a16294 100644 --- a/Roles/Neutral/Doomsayer.cs +++ b/Roles/Neutral/Doomsayer.cs @@ -33,26 +33,35 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Doomsayer); + DoomsayerAmountOfGuessesToWin = new IntegerOptionItem(Id + 10, "DoomsayerAmountOfGuessesToWin", new(1, 10, 1), 3, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Doomsayer]) .SetValueFormat(OptionFormat.Times); + DCanGuessImpostors = new BooleanOptionItem(Id + 12, "DCanGuessImpostors", true, TabGroup.NeutralRoles, true) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Doomsayer]); + DCanGuessCrewmates = new BooleanOptionItem(Id + 13, "DCanGuessCrewmates", true, TabGroup.NeutralRoles, true) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Doomsayer]); + DCanGuessNeutrals = new BooleanOptionItem(Id + 14, "DCanGuessNeutrals", true, TabGroup.NeutralRoles, true) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Doomsayer]); + DCanGuessAdt = new BooleanOptionItem(Id + 15, "DCanGuessAdt", false, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Doomsayer]); AdvancedSettings = new BooleanOptionItem(Id + 16, "DoomsayerAdvancedSettings", true, TabGroup.NeutralRoles, true) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Doomsayer]); + MaxNumberOfGuessesPerMeeting = new IntegerOptionItem(Id + 17, "DoomsayerMaxNumberOfGuessesPerMeeting", new(1, 10, 1), 2, TabGroup.NeutralRoles) .SetParent(AdvancedSettings); + KillCorrectlyGuessedPlayers = new BooleanOptionItem(Id + 18, "DoomsayerKillCorrectlyGuessedPlayers", true, TabGroup.NeutralRoles, true) .SetParent(AdvancedSettings); + DoesNotSuicideWhenMisguessing = new BooleanOptionItem(Id + 19, "DoomsayerDoesNotSuicideWhenMisguessing", true, TabGroup.NeutralRoles) .SetParent(AdvancedSettings); + MisguessRolePrevGuessRoleUntilNextMeeting = new BooleanOptionItem(Id + 20, "DoomsayerMisguessRolePrevGuessRoleUntilNextMeeting", true, TabGroup.NeutralRoles, true) .SetParent(DoesNotSuicideWhenMisguessing); @@ -83,10 +92,7 @@ namespace EHR.Neutral public static void SendRPC(PlayerControl player) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetDoomsayerProgress, SendOption.Reliable); writer.Write(player.PlayerId); @@ -101,10 +107,7 @@ namespace EHR.Neutral public static void CheckCountGuess(PlayerControl doomsayer) { - if (!(GuessingToWin[doomsayer.PlayerId] >= DoomsayerAmountOfGuessesToWin.GetInt())) - { - return; - } + if (!(GuessingToWin[doomsayer.PlayerId] >= DoomsayerAmountOfGuessesToWin.GetInt())) return; GuessingToWin[doomsayer.PlayerId] = DoomsayerAmountOfGuessesToWin.GetInt(); GuessesCount = DoomsayerAmountOfGuessesToWin.GetInt(); @@ -114,10 +117,7 @@ namespace EHR.Neutral public override void OnReportDeadBody() { - if (!(IsEnable && AdvancedSettings.GetBool())) - { - return; - } + if (!(IsEnable && AdvancedSettings.GetBool())) return; CantGuess = false; GuessesCountPerMeeting = 0; diff --git a/Roles/Neutral/Doppelganger.cs b/Roles/Neutral/Doppelganger.cs index 2f0cd18e6..ad20fc35e 100644 --- a/Roles/Neutral/Doppelganger.cs +++ b/Roles/Neutral/Doppelganger.cs @@ -42,17 +42,23 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Doppelganger); + MaxSteals = new IntegerOptionItem(Id + 10, "DoppelMaxSteals", new(1, 14, 1), 9, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Doppelganger]); + KillCooldown = new FloatOptionItem(Id + 11, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Doppelganger]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 14, "CanVent", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Doppelganger]); + ImpostorVision = new BooleanOptionItem(Id + 15, "ImpostorVision", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Doppelganger]); + ResetMode = new StringOptionItem(Id + 12, "DGResetMode", ResetModes, 0, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Doppelganger]); + ResetTimer = new FloatOptionItem(Id + 13, "DGResetTimer", new(0f, 60f, 1f), 30f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Doppelganger]) .SetValueFormat(OptionFormat.Seconds); @@ -75,14 +81,11 @@ namespace EHR.Neutral DGId = playerId; TotalSteals.Add(playerId, 0); PlayerControl pc = Utils.GetPlayerById(playerId); + if (playerId == PlayerControl.LocalPlayer.PlayerId && Main.NickName.Length != 0) - { DoppelVictim[playerId] = Main.NickName; - } else - { DoppelVictim[playerId] = pc.Data.PlayerName; - } DoppelDefaultSkin[playerId] = pc.CurrentOutfit; StealTimeStamp = 0; @@ -90,10 +93,7 @@ namespace EHR.Neutral private void SendRPC(byte playerId) { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetDoppelgangerStealLimit, SendOption.Reliable); writer.Write(playerId); @@ -105,10 +105,7 @@ namespace EHR.Neutral { byte PlayerId = reader.ReadByte(); int Limit = reader.ReadInt32(); - if (!TotalSteals.TryAdd(PlayerId, 0)) - { - TotalSteals[PlayerId] = Limit; - } + if (!TotalSteals.TryAdd(PlayerId, 0)) TotalSteals[PlayerId] = Limit; } public override void SetKillCooldown(byte id) @@ -140,9 +137,10 @@ namespace EHR.Neutral private static void RpcChangeSkin(PlayerControl pc, NetworkedPlayerInfo.PlayerOutfit newOutfit) { - CustomRpcSender sender = CustomRpcSender.Create($"Doppelganger.RpcChangeSkin({pc.Data.PlayerName})"); + var sender = CustomRpcSender.Create($"Doppelganger.RpcChangeSkin({pc.Data.PlayerName})"); pc.SetName(newOutfit.PlayerName); + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetName) .Write(pc.Data.NetId) .Write(newOutfit.PlayerName) @@ -151,6 +149,7 @@ namespace EHR.Neutral Main.AllPlayerNames[pc.PlayerId] = newOutfit.PlayerName; pc.SetColor(newOutfit.ColorId); + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetColor) .Write(pc.Data.NetId) .Write((byte)newOutfit.ColorId) @@ -158,6 +157,7 @@ namespace EHR.Neutral pc.SetHat(newOutfit.HatId, newOutfit.ColorId); pc.Data.DefaultOutfit.HatSequenceId += 10; + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetHatStr) .Write(newOutfit.HatId) .Write(pc.GetNextRpcSequenceId(RpcCalls.SetHatStr)) @@ -165,6 +165,7 @@ namespace EHR.Neutral pc.SetSkin(newOutfit.SkinId, newOutfit.ColorId); pc.Data.DefaultOutfit.SkinSequenceId += 10; + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetSkinStr) .Write(newOutfit.SkinId) .Write(pc.GetNextRpcSequenceId(RpcCalls.SetSkinStr)) @@ -172,6 +173,7 @@ namespace EHR.Neutral pc.SetVisor(newOutfit.VisorId, newOutfit.ColorId); pc.Data.DefaultOutfit.VisorSequenceId += 10; + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetVisorStr) .Write(newOutfit.VisorId) .Write(pc.GetNextRpcSequenceId(RpcCalls.SetVisorStr)) @@ -179,6 +181,7 @@ namespace EHR.Neutral pc.SetPet(newOutfit.PetId); pc.Data.DefaultOutfit.PetSequenceId += 10; + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetPetStr) .Write(newOutfit.PetId) .Write(pc.GetNextRpcSequenceId(RpcCalls.SetPetStr)) @@ -186,6 +189,7 @@ namespace EHR.Neutral pc.SetNamePlate(newOutfit.NamePlateId); pc.Data.DefaultOutfit.NamePlateSequenceId += 10; + sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.SetNamePlateStr) .Write(newOutfit.NamePlateId) .Write(pc.GetNextRpcSequenceId(RpcCalls.SetNamePlateStr)) @@ -197,10 +201,7 @@ namespace EHR.Neutral public static void OnCheckMurderEnd(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null || Camouflage.IsCamouflage || Camouflager.IsActive || Main.PlayerStates[killer.PlayerId].Role is not Doppelganger { IsEnable: true } dg) - { - return; - } + if (killer == null || target == null || Camouflage.IsCamouflage || Camouflager.IsActive || Main.PlayerStates[killer.PlayerId].Role is not Doppelganger { IsEnable: true } dg) return; if (target.IsShifted()) { @@ -219,24 +220,18 @@ namespace EHR.Neutral dg.StealTimeStamp = Utils.TimeStamp; string kname; + if (killer.PlayerId == PlayerControl.LocalPlayer.PlayerId && Main.NickName.Length != 0) - { kname = Main.NickName; - } else - { kname = killer.Data.PlayerName; - } string tname; + if (target.PlayerId == PlayerControl.LocalPlayer.PlayerId && Main.NickName.Length != 0) - { tname = Main.NickName; - } else - { tname = target.Data.PlayerName; - } NetworkedPlayerInfo.PlayerOutfit killerSkin = Set(new(), kname, killer.CurrentOutfit.ColorId, killer.CurrentOutfit.HatId, killer.CurrentOutfit.SkinId, killer.CurrentOutfit.VisorId, killer.CurrentOutfit.PetId, killer.CurrentOutfit.NamePlateId); @@ -265,12 +260,10 @@ namespace EHR.Neutral if (ResetMode.GetValue() == 1 && TotalSteals[DGId] > 0) { PlayerControl pc = Utils.GetPlayerById(DGId); - if (pc == null) - { - return; - } + if (pc == null) return; PlayerControl currentTarget = Main.AllPlayerControls.FirstOrDefault(x => x?.GetRealName() == DoppelVictim[pc.PlayerId]); + if (currentTarget != null) { RpcChangeSkin(currentTarget, DoppelPresentSkin[currentTarget.PlayerId]); @@ -290,16 +283,14 @@ namespace EHR.Neutral if (ResetMode.GetValue() == 2 && TotalSteals[pc.PlayerId] > 0 && Utils.TimeStamp - StealTimeStamp > ResetTimer.GetInt()) { PlayerControl currentTarget = Main.AllPlayerControls.FirstOrDefault(x => x.GetRealName() == DoppelVictim[pc.PlayerId]); + if (currentTarget != null) { RpcChangeSkin(currentTarget, DoppelPresentSkin[currentTarget.PlayerId]); RpcChangeSkin(pc, DoppelDefaultSkin[pc.PlayerId]); DoppelVictim[pc.PlayerId] = string.Empty; - if (GameStates.IsInTask) - { - Utils.NotifyRoles(); - } + if (GameStates.IsInTask) Utils.NotifyRoles(); } } } diff --git a/Roles/Neutral/Eclipse.cs b/Roles/Neutral/Eclipse.cs index c9665c83a..bc440d3b5 100644 --- a/Roles/Neutral/Eclipse.cs +++ b/Roles/Neutral/Eclipse.cs @@ -23,17 +23,22 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Eclipse); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Eclipse]) .SetValueFormat(OptionFormat.Seconds); + StartVision = new FloatOptionItem(Id + 11, "EclipseStartVision", new(0.1f, 5f, 0.1f), 0.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Eclipse]) .SetValueFormat(OptionFormat.Multiplier); + VisionIncrease = new FloatOptionItem(Id + 12, "EclipseVisionIncrease", new(0.05f, 5f, 0.05f), 0.1f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Eclipse]) .SetValueFormat(OptionFormat.Multiplier); + MaxVision = new FloatOptionItem(Id + 13, "EclipseMaxVision", new(0.25f, 5f, 0.25f), 1.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Eclipse]) .SetValueFormat(OptionFormat.Multiplier); + CanVent = new BooleanOptionItem(Id + 14, "CanVent", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Eclipse]); } @@ -67,22 +72,13 @@ namespace EHR.Neutral public override void OnMurder(PlayerControl pc, PlayerControl target) { - if (pc == null) - { - return; - } + if (pc == null) return; float currentVision = Vision; Vision += VisionIncrease.GetFloat(); - if (Vision > MaxVision.GetFloat()) - { - Vision = MaxVision.GetFloat(); - } + if (Vision > MaxVision.GetFloat()) Vision = MaxVision.GetFloat(); - if (Math.Abs(Vision - currentVision) > 0.1f) - { - pc.MarkDirtySettings(); - } + if (Math.Abs(Vision - currentVision) > 0.1f) pc.MarkDirtySettings(); } } } \ No newline at end of file diff --git a/Roles/Neutral/Enderman.cs b/Roles/Neutral/Enderman.cs index 7cbf5b4d9..31a764746 100644 --- a/Roles/Neutral/Enderman.cs +++ b/Roles/Neutral/Enderman.cs @@ -22,11 +22,14 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Enderman); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Enderman]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 3, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Enderman]); + Time = new IntegerOptionItem(Id + 4, "EndermanSecondsBeforeTP", new(1, 60, 1), 7, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Enderman]) .SetValueFormat(OptionFormat.Seconds); @@ -62,15 +65,9 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte id) { opt.SetVision(true); - if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) - { - AURoleOptions.PhantomCooldown = Time.GetInt() + 2f; - } + if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) AURoleOptions.PhantomCooldown = Time.GetInt() + 2f; - if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = Time.GetInt() + 2f; - } + if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) AURoleOptions.ShapeshifterCooldown = Time.GetInt() + 2f; } @@ -93,10 +90,7 @@ namespace EHR.Neutral public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; MarkPosition(); return false; @@ -104,10 +98,7 @@ namespace EHR.Neutral private void MarkPosition() { - if (!IsEnable || EndermanPC.HasAbilityCD()) - { - return; - } + if (!IsEnable || EndermanPC.HasAbilityCD()) return; EndermanPC.AddAbilityCD(Time.GetInt() + 2); MarkedPosition.MarkTimeStamp = TimeStamp; @@ -118,10 +109,7 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl pc) { - if (!IsEnable || !GameStates.IsInTask || !MarkedPosition.TP || !EndermanPC.IsAlive() || MarkedPosition.MarkTimeStamp + Time.GetInt() >= TimeStamp) - { - return; - } + if (!IsEnable || !GameStates.IsInTask || !MarkedPosition.TP || !EndermanPC.IsAlive() || MarkedPosition.MarkTimeStamp + Time.GetInt() >= TimeStamp) return; EndermanPC.TP(MarkedPosition.Position); MarkedPosition.TP = false; @@ -129,10 +117,7 @@ namespace EHR.Neutral public override void OnReportDeadBody() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; MarkedPosition.TP = false; } diff --git a/Roles/Neutral/Evolver.cs b/Roles/Neutral/Evolver.cs index 4e9dc6c6e..f41968b73 100644 --- a/Roles/Neutral/Evolver.cs +++ b/Roles/Neutral/Evolver.cs @@ -29,6 +29,7 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Evolver); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 0.5f), 30f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Evolver]) .SetValueFormat(OptionFormat.Seconds); @@ -49,6 +50,7 @@ namespace EHR.Neutral SelectedUpgradeIndex = -1; OptionBackupData opts = Main.RealOptionsData; + Stats = ( KillCooldown.GetFloat(), false, @@ -114,10 +116,7 @@ namespace EHR.Neutral public override void AfterMeetingTasks() { - if (!EvolverPC.IsAlive()) - { - return; - } + if (!EvolverPC.IsAlive()) return; Upgrades = Enum.GetValues().Except(GetBannedUpgradeList()).Shuffle().GetRange(0, 3); SelectedUpgradeIndex = 0; @@ -130,31 +129,16 @@ namespace EHR.Neutral private IEnumerable GetBannedUpgradeList() { - List banned = new List(); - if (Stats.KillCooldown <= Limits.MinKillCooldown) - { - banned.Add(Upgrade.DecreaseKillCooldown); - } + var banned = new List(); + if (Stats.KillCooldown <= Limits.MinKillCooldown) banned.Add(Upgrade.DecreaseKillCooldown); - if (Stats.ImpostorVision) - { - banned.Add(Upgrade.GainImpostorVision); - } + if (Stats.ImpostorVision) banned.Add(Upgrade.GainImpostorVision); - if (Stats.Vision >= Limits.MaxVision) - { - banned.Add(Upgrade.IncreaseVision); - } + if (Stats.Vision >= Limits.MaxVision) banned.Add(Upgrade.IncreaseVision); - if (Stats.Speed >= Limits.MaxSpeed) - { - banned.Add(Upgrade.IncreaseSpeed); - } + if (Stats.Speed >= Limits.MaxSpeed) banned.Add(Upgrade.IncreaseSpeed); - if (Stats.KillDistance >= Limits.MaxKillDistance) - { - banned.Add(Upgrade.IncreaseKillDistance); - } + if (Stats.KillDistance >= Limits.MaxKillDistance) banned.Add(Upgrade.IncreaseKillDistance); banned.Add(Stats.CanVent ? Upgrade.GainVent : Upgrade.IncreaseVentUseLimit); banned.Add(Stats.CanSabotage ? Upgrade.GainSabotage : Upgrade.IncreaseSabotageUseLimit); @@ -163,20 +147,14 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask || !pc.IsAlive() || ChooseTimer == 0 || SelectedUpgradeIndex == -1 || Upgrades.Count == 0 || LastUpdate == Utils.TimeStamp) - { - return; - } + if (!GameStates.IsInTask || !pc.IsAlive() || ChooseTimer == 0 || SelectedUpgradeIndex == -1 || Upgrades.Count == 0 || LastUpdate == Utils.TimeStamp) return; LastUpdate = Utils.TimeStamp; ChooseTimer--; Utils.SendRPC(CustomRPC.SyncRoleData, EvolverPC.PlayerId, 3, ChooseTimer); - if (ChooseTimer == 0) - { - ApplySelectedUpgradeAndReset(); - } + if (ChooseTimer == 0) ApplySelectedUpgradeAndReset(); Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); } @@ -220,19 +198,14 @@ namespace EHR.Neutral } EnsureStatLimits(); + if (GameStates.IsInTask) { EvolverPC.ResetKillCooldown(); EvolverPC.SyncSettings(); - if (Main.KillTimers[EvolverPC.PlayerId] > Stats.KillCooldown) - { - EvolverPC.SetKillCooldown(); - } + if (Main.KillTimers[EvolverPC.PlayerId] > Stats.KillCooldown) EvolverPC.SetKillCooldown(); - if (PlayerControl.LocalPlayer.PlayerId == EvolverPC.PlayerId) - { - HudManager.Instance.SetHudActive(EvolverPC, EvolverPC.Data.Role, true); - } + if (PlayerControl.LocalPlayer.PlayerId == EvolverPC.PlayerId) HudManager.Instance.SetHudActive(EvolverPC, EvolverPC.Data.Role, true); } Upgrades = []; @@ -255,10 +228,7 @@ namespace EHR.Neutral public override void OnPet(PlayerControl pc) { - if (Upgrades.Count == 0 || SelectedUpgradeIndex == -1) - { - return; - } + if (Upgrades.Count == 0 || SelectedUpgradeIndex == -1) return; SelectedUpgradeIndex = (SelectedUpgradeIndex + 1) % Upgrades.Count; ChooseTimer = 8; @@ -283,18 +253,12 @@ namespace EHR.Neutral { case 1: Upgrades = []; - for (int i = 0; i < Upgrades.Count; i++) - { - Upgrades.Add((Upgrade)reader.ReadPackedInt32()); - } + for (var i = 0; i < Upgrades.Count; i++) Upgrades.Add((Upgrade)reader.ReadPackedInt32()); break; case 2: SelectedUpgradeIndex = reader.ReadPackedInt32(); - if (SelectedUpgradeIndex == -1) - { - Upgrades = []; - } + if (SelectedUpgradeIndex == -1) Upgrades = []; break; case 3: @@ -305,27 +269,18 @@ namespace EHR.Neutral public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != EvolverPC.PlayerId || (seer.IsModClient() && !hud) || meeting || ChooseTimer == 0 || Upgrades.Count == 0 || SelectedUpgradeIndex == -1) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != EvolverPC.PlayerId || (seer.IsModClient() && !hud) || meeting || ChooseTimer == 0 || Upgrades.Count == 0 || SelectedUpgradeIndex == -1) return string.Empty; return string.Format(Translator.GetString("EvolverSuffix"), ChooseTimer, Translator.GetString($"EvolverUpgrade.{Upgrades[SelectedUpgradeIndex]}"), string.Join(", ", Upgrades.ConvertAll(x => Translator.GetString($"EvolverUpgrade.{x}")))); } public override string GetProgressText(byte playerId, bool comms) { - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); - if (Stats.CanVent) - { - sb.Append(string.Format(Translator.GetString("EvolverProgress.Vent"), Stats.VentUseLimit)); - } + if (Stats.CanVent) sb.Append(string.Format(Translator.GetString("EvolverProgress.Vent"), Stats.VentUseLimit)); - if (Stats.CanSabotage) - { - sb.Append(string.Format(Translator.GetString("EvolverProgress.Sabotage"), Stats.SabotageUseLimit)); - } + if (Stats.CanSabotage) sb.Append(string.Format(Translator.GetString("EvolverProgress.Sabotage"), Stats.SabotageUseLimit)); if (sb.Length > 0) { diff --git a/Roles/Neutral/Executioner.cs b/Roles/Neutral/Executioner.cs index 75894a7fb..e985be461 100644 --- a/Roles/Neutral/Executioner.cs +++ b/Roles/Neutral/Executioner.cs @@ -67,10 +67,7 @@ namespace EHR.Neutral List targetList = []; targetList.AddRange(from target in Main.AllPlayerControls where playerId != target.PlayerId where CanTargetImpostor.GetBool() || !target.Is(CustomRoleTypes.Impostor) where CanTargetNeutralKiller.GetBool() || !target.IsNeutralKiller() where CanTargetNeutralBenign.GetBool() || !target.IsNeutralBenign() where CanTargetNeutralEvil.GetBool() || !target.IsNeutralEvil() where target.GetCustomRole() is not (CustomRoles.GM or CustomRoles.SuperStar) where Main.LoversPlayers.TrueForAll(x => x.PlayerId != playerId) select target); targetList.AddRange(Main.AllPlayerControls.Where(x => x.IsCrewmate())); - if (!CanTargetNeutralBenign.GetBool() && !CanTargetNeutralEvil.GetBool() && !CanTargetNeutralKiller.GetBool()) - { - targetList.RemoveAll(x => x.GetCustomRole().IsNeutral() || x.Is(CustomRoles.Bloodlust)); - } + if (!CanTargetNeutralBenign.GetBool() && !CanTargetNeutralEvil.GetBool() && !CanTargetNeutralKiller.GetBool()) targetList.RemoveAll(x => x.GetCustomRole().IsNeutral() || x.Is(CustomRoles.Bloodlust)); if (targetList.Count == 0) { @@ -92,12 +89,10 @@ namespace EHR.Neutral public static void SendRPC(byte executionerId, byte targetId = 0x73, string Progress = "") { - if (!AmongUsClient.Instance.AmHost || !Utils.DoRPC) - { - return; - } + if (!AmongUsClient.Instance.AmHost || !Utils.DoRPC) return; MessageWriter writer; + switch (Progress) { case "SetTarget": @@ -107,10 +102,7 @@ namespace EHR.Neutral AmongUsClient.Instance.FinishRpcImmediately(writer); break; case "": - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.RemoveExecutionerTarget, SendOption.Reliable); writer.Write(executionerId); @@ -128,9 +120,7 @@ namespace EHR.Neutral Target[ExecutionerId] = TargetId; } else - { Target.Remove(reader.ReadByte()); - } } public static void ChangeRoleByTarget(PlayerControl target) @@ -159,15 +149,9 @@ namespace EHR.Neutral public override bool KnowRole(PlayerControl player, PlayerControl target) { - if (base.KnowRole(player, target)) - { - return true; - } + if (base.KnowRole(player, target)) return true; - if (!KnowTargetRole.GetBool()) - { - return false; - } + if (!KnowTargetRole.GetBool()) return false; return player.Is(CustomRoles.Executioner) && Target.TryGetValue(player.PlayerId, out byte tar) && tar == target.PlayerId; } @@ -183,15 +167,9 @@ namespace EHR.Neutral foreach (KeyValuePair kvp in Target.Where(x => x.Value == exiled.PlayerId)) { PlayerControl executioner = Utils.GetPlayerById(kvp.Key); - if (executioner == null || !executioner.IsAlive() || executioner.Data.Disconnected) - { - continue; - } + if (executioner == null || !executioner.IsAlive() || executioner.Data.Disconnected) continue; - if (!Check) - { - ExeWin(kvp.Key); - } + if (!Check) ExeWin(kvp.Key); return true; } diff --git a/Roles/Neutral/FFF.cs b/Roles/Neutral/FFF.cs index ca50769fb..4784eeae5 100644 --- a/Roles/Neutral/FFF.cs +++ b/Roles/Neutral/FFF.cs @@ -84,25 +84,16 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null) - { - return false; - } + if (killer == null || target == null) return false; - if (killer.PlayerId == target.PlayerId) - { - return true; - } + if (killer.PlayerId == target.PlayerId) return true; if (target.GetCustomSubRoles().Any(x => x.IsConverted() || x == CustomRoles.Madmate) || IsConvertedMainRole(target.GetCustomRole())) { if (!ChooseConverted.GetBool()) { - if (killer.RpcCheckAndMurder(target)) - { - IsWon = true; - } + if (killer.RpcCheckAndMurder(target)) IsWon = true; Logger.Info($"{killer.GetRealName()} killed right target case 1", "FFF"); return false; @@ -120,10 +111,7 @@ namespace EHR.Neutral || ((target.Is(CustomRoles.Contagious) || target.Is(CustomRoles.Virus)) && CanKillContagious.GetBool()) ) { - if (killer.RpcCheckAndMurder(target)) - { - IsWon = true; - } + if (killer.RpcCheckAndMurder(target)) IsWon = true; Logger.Info($"{killer.GetRealName()} killed right target case 2", "FFF"); return false; @@ -161,10 +149,7 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive()) - { - return; - } + if (!pc.IsAlive()) return; if (ChangeRoleWhenCantWin.GetBool() && !IsWon && Main.AllAlivePlayerControls.All(x => Main.LoversPlayers.TrueForAll(l => l.PlayerId != x.PlayerId) && !x.GetCustomRole().IsRecruitingRole() && !x.GetCustomSubRoles().Any(p => p.IsConverted()))) { diff --git a/Roles/Neutral/Gamer.cs b/Roles/Neutral/Gamer.cs index d1295f2a9..637b2b1ba 100644 --- a/Roles/Neutral/Gamer.cs +++ b/Roles/Neutral/Gamer.cs @@ -28,22 +28,29 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Gamer); + KillCooldown = new FloatOptionItem(Id + 10, "GamerKillCooldown", new(1f, 180f, 1f), 2f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Gamer]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 11, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Gamer]); + HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Gamer]); + HealthMax = new IntegerOptionItem(Id + 15, "GamerHealthMax", new(5, 300, 5), 100, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Gamer]) .SetValueFormat(OptionFormat.Health); + Damage = new IntegerOptionItem(Id + 16, "GamerDamage", new(1, 100, 1), 15, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Gamer]) .SetValueFormat(OptionFormat.Health); + SelfHealthMax = new IntegerOptionItem(Id + 17, "GamerSelfHealthMax", new(100, 100, 5), 100, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Gamer]) .SetValueFormat(OptionFormat.Health); + SelfDamage = new IntegerOptionItem(Id + 18, "GamerSelfDamage", new(1, 100, 1), 35, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Gamer]) .SetValueFormat(OptionFormat.Health); @@ -60,10 +67,7 @@ namespace EHR.Neutral { PlayerIdList.Add(playerId); GamerHealth[playerId] = SelfHealthMax.GetInt(); - foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { - PlayerHealth[pc.PlayerId] = HealthMax.GetInt(); - } + foreach (PlayerControl pc in Main.AllAlivePlayerControls) PlayerHealth[pc.PlayerId] = HealthMax.GetInt(); } public override void SetKillCooldown(byte id) @@ -83,10 +87,7 @@ namespace EHR.Neutral private void SendRPC(byte playerId) { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetGamerHealth, SendOption.Reliable); writer.Write(playerId); @@ -98,22 +99,16 @@ namespace EHR.Neutral { byte PlayerId = reader.ReadByte(); int Health = reader.ReadInt32(); + if (GamerHealth.ContainsKey(PlayerId)) - { GamerHealth[PlayerId] = Health; - } else - { PlayerHealth[PlayerId] = Health; - } } public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null || target.Is(CustomRoles.Gamer) || !PlayerHealth.ContainsKey(target.PlayerId)) - { - return false; - } + if (killer == null || target == null || target.Is(CustomRoles.Gamer) || !PlayerHealth.ContainsKey(target.PlayerId)) return false; killer.SetKillCooldown(); @@ -142,10 +137,7 @@ namespace EHR.Neutral public override bool OnCheckMurderAsTarget(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null || killer.Is(CustomRoles.Gamer)) - { - return true; - } + if (killer == null || target == null || killer.Is(CustomRoles.Gamer)) return true; if (GamerHealth[target.PlayerId] - SelfDamage.GetInt() < 1) { @@ -167,10 +159,7 @@ namespace EHR.Neutral public static string TargetMark(PlayerControl seer, PlayerControl target) { - if (!seer.IsAlive() || !PlayerIdList.Contains(seer.PlayerId)) - { - return string.Empty; - } + if (!seer.IsAlive() || !PlayerIdList.Contains(seer.PlayerId)) return string.Empty; if (seer.PlayerId == target.PlayerId) { @@ -186,18 +175,15 @@ namespace EHR.Neutral private static Color32 GetColor(float Health, bool self = false) { - int x = (int)(Health / (self ? SelfHealthMax.GetInt() : HealthMax.GetInt()) * 10 * 50); - int R = 255; - int G = 255; - int B = 0; + var x = (int)(Health / (self ? SelfHealthMax.GetInt() : HealthMax.GetInt()) * 10 * 50); + var R = 255; + var G = 255; + var B = 0; + if (x > 255) - { R -= x - 255; - } else - { G = x; - } return new((byte)R, (byte)G, (byte)B, byte.MaxValue); } diff --git a/Roles/Neutral/Gaslighter.cs b/Roles/Neutral/Gaslighter.cs index 490d35292..e19dbc92f 100644 --- a/Roles/Neutral/Gaslighter.cs +++ b/Roles/Neutral/Gaslighter.cs @@ -81,25 +81,20 @@ namespace EHR.Neutral foreach (Gaslighter instance in Instances) { foreach (byte id in exileIds) - { if (id == instance.GaslighterId) - { instance.CursedPlayers.Clear(); - } - } } List curseDeathList = []; + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { foreach (Gaslighter instance in Instances) { - if (Main.AfterMeetingDeathPlayers.ContainsKey(pc.PlayerId)) - { - continue; - } + if (Main.AfterMeetingDeathPlayers.ContainsKey(pc.PlayerId)) continue; PlayerControl gaslighter = instance.GaslighterId.GetPlayer(); + if (instance.CursedPlayers.Contains(pc.PlayerId) && gaslighter != null && gaslighter.IsAlive()) { pc.SetRealKiller(gaslighter); @@ -126,10 +121,7 @@ namespace EHR.Neutral CycleFinished = true; CurrentRound = Round.Kill; } - else if (!CycleFinished || CycleRepeats.GetBool()) - { - CurrentRound++; - } + else if (!CycleFinished || CycleRepeats.GetBool()) CurrentRound++; float limit = CurrentRound switch { @@ -137,6 +129,7 @@ namespace EHR.Neutral Round.Shield => Medic.SkillLimit, _ => 0 }; + GaslighterId.SetAbilityUseLimit(limit); PlayerControl pc = GaslighterId.GetPlayer(); @@ -196,16 +189,10 @@ namespace EHR.Neutral public static string GetMark(PlayerControl seer, PlayerControl target, bool meeting = false) { bool seerIsGaslighter = seer.Is(CustomRoles.Gaslighter); - StringBuilder sb = new StringBuilder(); - if (IsShielded(target) && (seerIsGaslighter || seer.PlayerId == target.PlayerId)) - { - sb.Append($" ●"); - } + var sb = new StringBuilder(); + if (IsShielded(target) && (seerIsGaslighter || seer.PlayerId == target.PlayerId)) sb.Append($" ●"); - if (IsCursed(target) && (meeting || seerIsGaslighter)) - { - sb.Append(Utils.ColorString(Palette.ImpostorRed, "†")); - } + if (IsCursed(target) && (meeting || seerIsGaslighter)) sb.Append(Utils.ColorString(Palette.ImpostorRed, "†")); return sb.ToString(); } diff --git a/Roles/Neutral/Glitch.cs b/Roles/Neutral/Glitch.cs index 71032be5b..fa2e76091 100644 --- a/Roles/Neutral/Glitch.cs +++ b/Roles/Neutral/Glitch.cs @@ -41,16 +41,22 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Glitch); + KillCooldown = new IntegerOptionItem(Id + 10, "KillCooldown", new(0, 180, 1), 25, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Glitch]) .SetValueFormat(OptionFormat.Seconds); + HackCooldown = new IntegerOptionItem(Id + 11, "HackCooldown", new(0, 180, 1), 20, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Glitch]) .SetValueFormat(OptionFormat.Seconds); + HackDuration = new FloatOptionItem(Id + 14, "HackDuration", new(0f, 60f, 1f), 15f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Glitch]) .SetValueFormat(OptionFormat.Seconds); + MimicCooldown = new IntegerOptionItem(Id + 15, "MimicCooldown", new(0, 180, 1), 30, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Glitch]) .SetValueFormat(OptionFormat.Seconds); + MimicDuration = new FloatOptionItem(Id + 16, "MimicDuration", new(0f, 60f, 1f), 10f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Glitch]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 12, "CanVent", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Glitch]); CanVote = new BooleanOptionItem(Id + 17, "CanVote", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Glitch]); HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Glitch]); @@ -103,10 +109,7 @@ namespace EHR.Neutral private void SendRPCSyncTimers() { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncGlitchTimers, SendOption.Reliable); writer.Write(GlitchId); @@ -120,10 +123,7 @@ namespace EHR.Neutral public static void ReceiveRPCSyncTimers(MessageReader reader) { byte id = reader.ReadByte(); - if (Main.PlayerStates[id].Role is not Glitch gc) - { - return; - } + if (Main.PlayerStates[id].Role is not Glitch gc) return; gc.MimicCDTimer = reader.ReadInt32(); gc.MimicDurTimer = reader.ReadInt32(); @@ -143,10 +143,7 @@ namespace EHR.Neutral private void Mimic(PlayerControl pc) { - if (pc == null || !pc.Is(CustomRoles.Glitch) || !pc.IsAlive() || MimicCDTimer > 0 || IsShifted) - { - return; - } + if (pc == null || !pc.Is(CustomRoles.Glitch) || !pc.IsAlive() || MimicCDTimer > 0 || IsShifted) return; PlayerControl[] playerlist = Main.AllAlivePlayerControls.Where(a => a.PlayerId != pc.PlayerId).ToArray(); @@ -180,10 +177,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null || (KCDTimer > 0 && HackCDTimer > 0)) - { - return false; - } + if (killer == null || target == null || (KCDTimer > 0 && HackCDTimer > 0)) return false; if (killer.CheckDoubleTrigger(target, () => { @@ -197,10 +191,7 @@ namespace EHR.Neutral } })) { - if (KCDTimer > 0) - { - return false; - } + if (KCDTimer > 0) return false; LastKill = Utils.TimeStamp; KCDTimer = KillCooldown.GetInt(); @@ -214,37 +205,19 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl player) { long now = Utils.TimeStamp; - if (LastUpdate == now) - { - return; - } + if (LastUpdate == now) return; LastUpdate = now; - if (HackCDTimer is > 180 or < 0) - { - HackCDTimer = 0; - } + if (HackCDTimer is > 180 or < 0) HackCDTimer = 0; - if (KCDTimer is > 180 or < 0) - { - KCDTimer = 0; - } + if (KCDTimer is > 180 or < 0) KCDTimer = 0; - if (MimicCDTimer is > 180 or < 0) - { - MimicCDTimer = 0; - } + if (MimicCDTimer is > 180 or < 0) MimicCDTimer = 0; - if (MimicDurTimer is > 180 or < 0) - { - MimicDurTimer = 0; - } + if (MimicDurTimer is > 180 or < 0) MimicDurTimer = 0; - if (player == null) - { - return; - } + if (player == null) return; if (!player.IsAlive()) { @@ -266,10 +239,7 @@ namespace EHR.Neutral MimicDurTimer = 0; } - if (MimicDurTimer > 180) - { - MimicDurTimer = 0; - } + if (MimicDurTimer > 180) MimicDurTimer = 0; } if ((MimicDurTimer <= 0 || !GameStates.IsInTask) && IsShifted) @@ -284,16 +254,10 @@ namespace EHR.Neutral Logger.Error(ex.ToString(), "Glitch.Mimic.RpcRevertShapeshift"); } - if (!GameStates.IsInTask) - { - MimicDurTimer = 0; - } + if (!GameStates.IsInTask) MimicDurTimer = 0; } - if (HackCDTimer <= 0 && KCDTimer <= 0 && MimicCDTimer <= 0 && MimicDurTimer <= 0) - { - return; - } + if (HackCDTimer <= 0 && KCDTimer <= 0 && MimicCDTimer <= 0 && MimicDurTimer <= 0) return; try { @@ -304,10 +268,7 @@ namespace EHR.Neutral HackCDTimer = 0; } - if (HackCDTimer is > 180 or < 0) - { - HackCDTimer = 0; - } + if (HackCDTimer is > 180 or < 0) HackCDTimer = 0; try { @@ -318,10 +279,7 @@ namespace EHR.Neutral KCDTimer = 0; } - if (KCDTimer is > 180 or < 0) - { - KCDTimer = 0; - } + if (KCDTimer is > 180 or < 0) KCDTimer = 0; try { @@ -332,82 +290,43 @@ namespace EHR.Neutral MimicCDTimer = 0; } - if (MimicCDTimer is > 180 or < 0) - { - MimicCDTimer = 0; - } + if (MimicCDTimer is > 180 or < 0) MimicCDTimer = 0; if (!player.IsModClient()) { - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); - if (MimicDurTimer > 0) - { - sb.Append($"\n{string.Format(Translator.GetString("MimicDur"), MimicDurTimer)}"); - } + if (MimicDurTimer > 0) sb.Append($"\n{string.Format(Translator.GetString("MimicDur"), MimicDurTimer)}"); - if (MimicCDTimer > 0 && MimicDurTimer <= 0) - { - sb.Append($"\n{string.Format(Translator.GetString("MimicCD"), MimicCDTimer)}"); - } + if (MimicCDTimer > 0 && MimicDurTimer <= 0) sb.Append($"\n{string.Format(Translator.GetString("MimicCD"), MimicCDTimer)}"); - if (HackCDTimer > 0) - { - sb.Append($"\n{string.Format(Translator.GetString("HackCD"), HackCDTimer)}"); - } + if (HackCDTimer > 0) sb.Append($"\n{string.Format(Translator.GetString("HackCD"), HackCDTimer)}"); - if (KCDTimer > 0) - { - sb.Append($"\n{string.Format(Translator.GetString("KCD"), KCDTimer)}"); - } + if (KCDTimer > 0) sb.Append($"\n{string.Format(Translator.GetString("KCD"), KCDTimer)}"); - string ns = sb.ToString(); + var ns = sb.ToString(); - if ((!NameNotifyManager.GetNameNotify(player, out string a) || a != ns) && ns != string.Empty) - { - player.Notify(ns, 1.1f); - } + if ((!NameNotifyManager.GetNameNotify(player, out string a) || a != ns) && ns != string.Empty) player.Notify(ns, 1.1f); } - if (player.IsNonHostModClient()) - { - SendRPCSyncTimers(); - } + if (player.IsNonHostModClient()) SendRPCSyncTimers(); } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (!hud || seer == null || !seer.IsAlive() || meeting) - { - return string.Empty; - } + if (!hud || seer == null || !seer.IsAlive() || meeting) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is not Glitch gc) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not Glitch gc) return string.Empty; - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); - if (gc.MimicDurTimer > 0) - { - sb.Append($"{string.Format(Translator.GetString("MimicDur"), gc.MimicDurTimer)}\n"); - } + if (gc.MimicDurTimer > 0) sb.Append($"{string.Format(Translator.GetString("MimicDur"), gc.MimicDurTimer)}\n"); - if (gc.MimicCDTimer > 0 && gc.MimicDurTimer <= 0) - { - sb.Append($"{string.Format(Translator.GetString("MimicCD"), gc.MimicCDTimer)}\n"); - } + if (gc.MimicCDTimer > 0 && gc.MimicDurTimer <= 0) sb.Append($"{string.Format(Translator.GetString("MimicCD"), gc.MimicCDTimer)}\n"); - if (gc.HackCDTimer > 0) - { - sb.Append($"{string.Format(Translator.GetString("HackCD"), gc.HackCDTimer)}\n"); - } + if (gc.HackCDTimer > 0) sb.Append($"{string.Format(Translator.GetString("HackCD"), gc.HackCDTimer)}\n"); - if (gc.KCDTimer > 0) - { - sb.Append($"{string.Format(Translator.GetString("KCD"), gc.KCDTimer)}\n"); - } + if (gc.KCDTimer > 0) sb.Append($"{string.Format(Translator.GetString("KCD"), gc.KCDTimer)}\n"); return sb.ToString(); } diff --git a/Roles/Neutral/God.cs b/Roles/Neutral/God.cs index eb39c0058..5d630c87e 100644 --- a/Roles/Neutral/God.cs +++ b/Roles/Neutral/God.cs @@ -20,20 +20,19 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(18200, TabGroup.NeutralRoles, CustomRoles.God); + NotifyGodAlive = new BooleanOptionItem(18210, "NotifyGodAlive", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.God]); + GodCanGuess = new BooleanOptionItem(18211, "CanGuess", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.God]); + KnowInfo = new StringOptionItem(18212, "God.KnowInfo", KnowInfoMode, 2, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.God]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Neutral/HeadHunter.cs b/Roles/Neutral/HeadHunter.cs index d77e85875..55d867834 100644 --- a/Roles/Neutral/HeadHunter.cs +++ b/Roles/Neutral/HeadHunter.cs @@ -31,19 +31,26 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.HeadHunter); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 27.5f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.HeadHunter]) .SetValueFormat(OptionFormat.Seconds); + SuccessKillCooldown = new FloatOptionItem(Id + 11, "HHSuccessKCDDecrease", new(0f, 180f, 0.5f), 3f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.HeadHunter]) .SetValueFormat(OptionFormat.Seconds); + FailureKillCooldown = new FloatOptionItem(Id + 12, "HHFailureKCDIncrease", new(0f, 180f, 0.5f), 10f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.HeadHunter]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 13, "CanVent", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.HeadHunter]); HasImpostorVision = new BooleanOptionItem(Id + 14, "ImpostorVision", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.HeadHunter]); + NumOfTargets = new IntegerOptionItem(Id + 15, "HHNumOfTargets", new(0, 10, 1), 3, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.HeadHunter]) .SetValueFormat(OptionFormat.Times); + MaxKCD = new FloatOptionItem(Id + 16, "HHMaxKCD", new(0f, 180f, 0.5f), 40f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.HeadHunter]) .SetValueFormat(OptionFormat.Seconds); + MinKCD = new FloatOptionItem(Id + 17, "HHMinKCD", new(0f, 180f, 0.5f), 10f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.HeadHunter]) .SetValueFormat(OptionFormat.Seconds); } @@ -69,10 +76,7 @@ namespace EHR.Neutral MessageWriter writer = Utils.CreateRPC(CustomRPC.SyncHeadHunter); writer.Write(HeadHunterId); writer.Write(Targets.Count); - foreach (byte target in Targets.ToArray()) - { - writer.Write(target); - } + foreach (byte target in Targets.ToArray()) writer.Write(target); Utils.EndRPC(writer); } @@ -80,17 +84,11 @@ namespace EHR.Neutral public static void ReceiveRPC(MessageReader reader) { byte playerId = reader.ReadByte(); - if (Main.PlayerStates[playerId].Role is not HeadHunter hh) - { - return; - } + if (Main.PlayerStates[playerId].Role is not HeadHunter hh) return; hh.Targets.Clear(); int count = reader.ReadInt32(); - for (int i = 0; i < count; i++) - { - hh.Targets.Add(reader.ReadByte()); - } + for (var i = 0; i < count; i++) hh.Targets.Add(reader.ReadByte()); } public override void ApplyGameOptions(IGameOptions opt, byte id) @@ -116,14 +114,11 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { float tempkcd = KCD; + if (Targets.Contains(target.PlayerId)) - { Math.Clamp(KCD -= SuccessKillCooldown.GetFloat(), MinKCD.GetFloat(), MaxKCD.GetFloat()); - } else - { Math.Clamp(KCD += FailureKillCooldown.GetFloat(), MinKCD.GetFloat(), MaxKCD.GetFloat()); - } if (Math.Abs(KCD - tempkcd) > 0.1f) { @@ -141,25 +136,16 @@ namespace EHR.Neutral public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (!hud) - { - return string.Empty; - } + if (!hud) return string.Empty; byte targetId = seer.PlayerId; - string output = string.Empty; - if (Main.PlayerStates[targetId].Role is not HeadHunter hh) - { - return output; - } + var output = string.Empty; + if (Main.PlayerStates[targetId].Role is not HeadHunter hh) return output; - for (int i = 0; i < hh.Targets.Count; i++) + for (var i = 0; i < hh.Targets.Count; i++) { byte playerId = hh.Targets[i]; - if (i != 0) - { - output += ", "; - } + if (i != 0) output += ", "; output += playerId.ColoredPlayerName(); } @@ -169,21 +155,16 @@ namespace EHR.Neutral private void ResetTargets() { - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; Targets.Clear(); - for (int i = 0; i < NumOfTargets.GetInt(); i++) + + for (var i = 0; i < NumOfTargets.GetInt(); i++) { try { - List cTargets = new List(Main.AllAlivePlayerControls.Where(pc => !Targets.Contains(pc.PlayerId) && pc.GetCustomRole() != CustomRoles.HeadHunter)); - if (cTargets.Count == 0) - { - break; - } + var cTargets = new List(Main.AllAlivePlayerControls.Where(pc => !Targets.Contains(pc.PlayerId) && pc.GetCustomRole() != CustomRoles.HeadHunter)); + if (cTargets.Count == 0) break; PlayerControl target = cTargets.RandomElement(); Targets.Add(target.PlayerId); diff --git a/Roles/Neutral/HexMaster.cs b/Roles/Neutral/HexMaster.cs index 2923f9cc5..414476a6c 100644 --- a/Roles/Neutral/HexMaster.cs +++ b/Roles/Neutral/HexMaster.cs @@ -13,16 +13,13 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.HexMaster); + ModeSwitchAction = new StringOptionItem(Id + 10, "WitchModeSwitchAction", Witch.SwitchTriggerText, 2, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.HexMaster]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Neutral/Hookshot.cs b/Roles/Neutral/Hookshot.cs index 73a8e9988..2f74c9cfd 100644 --- a/Roles/Neutral/Hookshot.cs +++ b/Roles/Neutral/Hookshot.cs @@ -25,11 +25,14 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Hookshot); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Hookshot]) .SetValueFormat(OptionFormat.Seconds); + HasImpostorVision = new BooleanOptionItem(Id + 3, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Hookshot]); + CanVent = new BooleanOptionItem(Id + 4, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Hookshot]); } @@ -65,23 +68,14 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte id) { opt.SetVision(HasImpostorVision.GetBool()); - if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) - { - AURoleOptions.PhantomCooldown = 1f; - } + if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) AURoleOptions.PhantomCooldown = 1f; - if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = 1f; - } + if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) AURoleOptions.ShapeshifterCooldown = 1f; } private void SendRPC() { - if (!IsEnable || !DoRPC) - { - return; - } + if (!IsEnable || !DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncHookshot, SendOption.Reliable); writer.Write(HookshotId); @@ -93,10 +87,7 @@ namespace EHR.Neutral public static void ReceiveRPC(MessageReader reader) { byte playerId = reader.ReadByte(); - if (Main.PlayerStates[playerId].Role is not Hookshot hs) - { - return; - } + if (Main.PlayerStates[playerId].Role is not Hookshot hs) return; hs.ToTargetTP = reader.ReadBoolean(); hs.MarkedPlayerId = reader.ReadByte(); @@ -121,10 +112,7 @@ namespace EHR.Neutral public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; ExecuteAction(); return false; @@ -132,12 +120,10 @@ namespace EHR.Neutral private void ExecuteAction() { - if (MarkedPlayerId == byte.MaxValue) - { - return; - } + if (MarkedPlayerId == byte.MaxValue) return; PlayerControl markedPlayer = GetPlayerById(MarkedPlayerId); + if (markedPlayer == null) { MarkedPlayerId = byte.MaxValue; @@ -163,10 +149,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (target == null) - { - return false; - } + if (target == null) return false; return HookshotPC.CheckDoubleTrigger(target, () => { diff --git a/Roles/Neutral/Imitator.cs b/Roles/Neutral/Imitator.cs index 8e1815ed8..24f7e82bb 100644 --- a/Roles/Neutral/Imitator.cs +++ b/Roles/Neutral/Imitator.cs @@ -16,22 +16,22 @@ public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Imitator); + OddKillCooldown = new FloatOptionItem(Id + 10, "OddKillCooldown", new(0f, 60f, 0.5f), 27.5f, TabGroup.NeutralRoles).SetParent(Options.CustomRoleSpawnChances[CustomRoles.Imitator]) .SetValueFormat(OptionFormat.Seconds); + EvenKillCooldown = new FloatOptionItem(Id + 11, "EvenKillCooldown", new(0f, 30f, 0.5f), 15f, TabGroup.NeutralRoles).SetParent(Options.CustomRoleSpawnChances[CustomRoles.Imitator]) .SetValueFormat(OptionFormat.Seconds); + AfterMeetingKillCooldown = new FloatOptionItem(Id + 12, "AfterMeetingKillCooldown", new(0f, 30f, 0.5f), 22.5f, TabGroup.NeutralRoles).SetParent(Options.CustomRoleSpawnChances[CustomRoles.Imitator]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 13, "CanVent", true, TabGroup.NeutralRoles).SetParent(Options.CustomRoleSpawnChances[CustomRoles.Imitator]); HasImpostorVision = new BooleanOptionItem(Id + 14, "ImpostorVision", true, TabGroup.NeutralRoles).SetParent(Options.CustomRoleSpawnChances[CustomRoles.Imitator]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Neutral/Impartial.cs b/Roles/Neutral/Impartial.cs index 9bf87d210..fb6a383f1 100644 --- a/Roles/Neutral/Impartial.cs +++ b/Roles/Neutral/Impartial.cs @@ -33,10 +33,7 @@ namespace EHR.Neutral { get { - if (CanWinWhenKillingMore.GetBool()) - { - return ImpKillCount.Killed >= ImpKillCount.Limit && NeutralKillCount.Killed >= NeutralKillCount.Limit && CrewKillCount.Killed >= CrewKillCount.Limit; - } + if (CanWinWhenKillingMore.GetBool()) return ImpKillCount.Killed >= ImpKillCount.Limit && NeutralKillCount.Killed >= NeutralKillCount.Limit && CrewKillCount.Killed >= CrewKillCount.Limit; return ImpKillCount.Killed == ImpKillCount.Limit && NeutralKillCount.Killed == NeutralKillCount.Limit && CrewKillCount.Killed == CrewKillCount.Limit; } @@ -52,14 +49,19 @@ namespace EHR.Neutral NeutralMaxOpt = CreateSetting(id + 5, false, "Neutral"); CrewMinOpt = CreateSetting(id + 6, true, "Crew"); CrewMaxOpt = CreateSetting(id + 7, false, "Crew"); + CanVent = new BooleanOptionItem(id + 8, "CanVent", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Impartial]); + CanVentAfterWinning = new BooleanOptionItem(id + 9, "EvenAfterWinning", false, TabGroup.NeutralRoles) .SetParent(CanVent); + HasImpVision = new BooleanOptionItem(id + 10, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Impartial]); + HasImpVisionAfterWinning = new BooleanOptionItem(id + 11, "EvenAfterWinning", false, TabGroup.NeutralRoles) .SetParent(HasImpVision); + CanWinWhenKillingMore = new BooleanOptionItem(id + 12, "ImpartialCanWinWhenKillingMore", false, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Impartial]); } @@ -68,6 +70,7 @@ namespace EHR.Neutral { OptionItem opt = new IntegerOptionItem(id, $"Impartial{roleType}{(min ? "min" : "max")}", new(0, 14, 1), 1, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Impartial]); + opt.ReplacementDictionary = ReplacementDictionary; return opt; } @@ -75,7 +78,7 @@ namespace EHR.Neutral public override void Add(byte playerId) { On = true; - IRandom r = IRandom.Instance; + var r = IRandom.Instance; ImpKillCount = (0, r.Next(ImpMinOpt.GetInt(), ImpMaxOpt.GetInt() + 1)); NeutralKillCount = (0, r.Next(NeutralMinOpt.GetInt(), NeutralMaxOpt.GetInt() + 1)); CrewKillCount = (0, r.Next(CrewMinOpt.GetInt(), CrewMaxOpt.GetInt() + 1)); @@ -145,12 +148,9 @@ namespace EHR.Neutral public override string GetProgressText(byte playerId, bool comms) { - if (IsWon) - { - return " \u2713"; - } + if (IsWon) return " \u2713"; - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.Append($" <{Main.ImpostorColor}>{ImpKillCount.Killed}/{ImpKillCount.Limit}"); sb.Append($" <{Main.NeutralColor}>{NeutralKillCount.Killed}/{NeutralKillCount.Limit}"); sb.Append($" <{Main.CrewmateColor}>{CrewKillCount.Killed}/{CrewKillCount.Limit}"); diff --git a/Roles/Neutral/Innocent.cs b/Roles/Neutral/Innocent.cs index b8f3ebbe2..2ca786140 100644 --- a/Roles/Neutral/Innocent.cs +++ b/Roles/Neutral/Innocent.cs @@ -10,6 +10,7 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(10800, TabGroup.NeutralRoles, CustomRoles.Innocent); + Options.InnocentCanWinByImp = new BooleanOptionItem(10810, "InnocentCanWinByImp", false, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Innocent]); } diff --git a/Roles/Neutral/Jackal.cs b/Roles/Neutral/Jackal.cs index 95fde99f5..0ae1ee76f 100644 --- a/Roles/Neutral/Jackal.cs +++ b/Roles/Neutral/Jackal.cs @@ -37,45 +37,64 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Jackal); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Jackal]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 3, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Jackal]); + CanSabotage = new BooleanOptionItem(Id + 4, "CanSabotage", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Jackal]); + HasImpostorVision = new BooleanOptionItem(Id + 6, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Jackal]); + ResetKillCooldownWhenSbGetKilled = new BooleanOptionItem(Id + 7, "ResetKillCooldownWhenPlayerGetKilled", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Jackal]); + ResetKillCooldownOn = new FloatOptionItem(Id + 8, "ResetKillCooldownOn", new(0f, 180f, 2.5f), 15f, TabGroup.NeutralRoles) .SetParent(ResetKillCooldownWhenSbGetKilled) .SetValueFormat(OptionFormat.Seconds); + OptionItem SKOpts = new BooleanOptionItem(Id + 9, "SidekickSettings", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Jackal]); + CanRecruitImpostors = new BooleanOptionItem(Id + 10, "JackalCanRecruitImpostors", true, TabGroup.NeutralRoles) .SetParent(SKOpts); + CanRecruitMadmates = new BooleanOptionItem(Id + 11, "JackalCanRecruitMadmates", true, TabGroup.NeutralRoles) .SetParent(CanRecruitImpostors); + JackalCanKillSidekick = new BooleanOptionItem(Id + 12, "JackalCanKillSidekick", false, TabGroup.NeutralRoles) .SetParent(SKOpts); + SKCanKill = new BooleanOptionItem(Id + 13, "SKCanKill", true, TabGroup.NeutralRoles) .SetParent(SKOpts); + KillCooldownSK = new FloatOptionItem(Id + 14, "KillCooldown", new(0f, 180f, 2.5f), 20f, TabGroup.NeutralRoles) .SetParent(SKCanKill) .SetValueFormat(OptionFormat.Seconds); + SidekickCanKillJackal = new BooleanOptionItem(Id + 15, "SidekickCanKillJackal", false, TabGroup.NeutralRoles) .SetParent(SKCanKill); + SidekickCanKillSidekick = new BooleanOptionItem(Id + 16, "SidekickCanKillSidekick", false, TabGroup.NeutralRoles) .SetParent(SKCanKill); + CanVentSK = new BooleanOptionItem(Id + 17, "CanVent", true, TabGroup.NeutralRoles) .SetParent(SKOpts); + CanSabotageSK = new BooleanOptionItem(Id + 18, "CanSabotage", true, TabGroup.NeutralRoles) .SetParent(SKOpts); + SKPromotesToJackal = new BooleanOptionItem(Id + 19, "SKPromotesToJackal", true, TabGroup.NeutralRoles) .SetParent(SKOpts); + PromotedSKCanRecruit = new BooleanOptionItem(Id + 20, "PromotedSKCanRecruit", true, TabGroup.NeutralRoles) .SetParent(SKPromotesToJackal); + SidekickCountMode = new StringOptionItem(Id + 21, "SidekickCountMode", Options.SidekickCountMode, 0, TabGroup.NeutralRoles) .SetParent(SKOpts); } @@ -122,10 +141,7 @@ namespace EHR.Neutral public static void AfterPlayerDiedTask(PlayerControl target) { - if (target.Is(CustomRoles.Jackal)) - { - return; - } + if (target.Is(CustomRoles.Jackal)) return; Main.AllAlivePlayerControls .Where(x => x.Is(CustomRoles.Jackal)) @@ -134,10 +150,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.GetAbilityUseLimit() < 1 || !CanBeSidekick(target)) - { - return true; - } + if (killer.GetAbilityUseLimit() < 1 || !CanBeSidekick(target)) return true; killer.RpcRemoveAbilityUse(); target.RpcSetCustomRole(CustomRoles.Sidekick); @@ -162,25 +175,16 @@ namespace EHR.Neutral private static bool CanBeSidekick(PlayerControl pc) { - if (!CanRecruitImpostors.GetBool() && pc.Is(CustomRoleTypes.Impostor)) - { - return false; - } + if (!CanRecruitImpostors.GetBool() && pc.Is(CustomRoleTypes.Impostor)) return false; - if (!CanRecruitMadmates.GetBool() && pc.IsMadmate()) - { - return false; - } + if (!CanRecruitMadmates.GetBool() && pc.IsMadmate()) return false; return pc != null && !pc.Is(CustomRoles.Sidekick) && !pc.Is(CustomRoles.Loyal) && !pc.IsConverted() && pc.GetCustomRole().IsAbleToBeSidekicked(); } public override void OnFixedUpdate(PlayerControl pc) { - if (pc.IsAlive()) - { - return; - } + if (pc.IsAlive()) return; PromoteSidekick(); } @@ -189,22 +193,13 @@ namespace EHR.Neutral { try { - if (!SKPromotesToJackal.GetBool()) - { - return; - } + if (!SKPromotesToJackal.GetBool()) return; PlayerControl sk = SidekickId.GetPlayer(); - if (sk == null || !sk.Is(CustomRoles.Sidekick)) - { - return; - } + if (sk == null || !sk.Is(CustomRoles.Sidekick)) return; sk.RpcSetCustomRole(CustomRoles.Jackal); - if (!PromotedSKCanRecruit.GetBool()) - { - sk.SetAbilityUseLimit(0); - } + if (!PromotedSKCanRecruit.GetBool()) sk.SetAbilityUseLimit(0); } catch (Exception e) { @@ -219,9 +214,7 @@ namespace EHR.Neutral public override bool IsEnable => PlayerIdList.Count > 0; - public override void SetupCustomOption() - { - } + public override void SetupCustomOption() { } public override void Init() { diff --git a/Roles/Neutral/Jester.cs b/Roles/Neutral/Jester.cs index c1b5fff0d..d94f0c97b 100644 --- a/Roles/Neutral/Jester.cs +++ b/Roles/Neutral/Jester.cs @@ -19,20 +19,27 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(10900, TabGroup.NeutralRoles, CustomRoles.Jester); + JesterCanUseButton = new BooleanOptionItem(10910, "JesterCanUseButton", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Jester]); + JesterCanVent = new BooleanOptionItem(10911, "CanVent", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Jester]); + VentCooldown = new FloatOptionItem(10913, "VentCooldown", new(0f, 60f, 0.5f), 0f, TabGroup.NeutralRoles) .SetParent(JesterCanVent) .SetValueFormat(OptionFormat.Seconds); + MaxInVentTime = new FloatOptionItem(10914, "MaxInVentTime", new(0f, 60f, 0.5f), 30f, TabGroup.NeutralRoles) .SetParent(JesterCanVent) .SetValueFormat(OptionFormat.Seconds); + BlockVentMovement = new BooleanOptionItem(10916, "BlockVentMovement", false, TabGroup.NeutralRoles) .SetParent(JesterCanVent); + JesterHasImpostorVision = new BooleanOptionItem(10912, "ImpostorVision", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Jester]); + SunnyboyChance = new IntegerOptionItem(10915, "SunnyboyChance", new(0, 100, 5), 0, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Jester]) .SetValueFormat(OptionFormat.Percent); diff --git a/Roles/Neutral/Jinx.cs b/Roles/Neutral/Jinx.cs index c7b835ea8..c3eba1735 100644 --- a/Roles/Neutral/Jinx.cs +++ b/Roles/Neutral/Jinx.cs @@ -17,22 +17,22 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Jinx); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Jinx]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 11, "CanVent", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Jinx]); HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Jinx]); + JinxSpellTimes = new IntegerOptionItem(Id + 14, "JinxSpellTimes", new(0, 15, 1), 1, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Jinx]) .SetValueFormat(OptionFormat.Times); + KillAttacker = new BooleanOptionItem(Id + 12, "killAttacker", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Jinx]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Neutral/Juggernaut.cs b/Roles/Neutral/Juggernaut.cs index a29266fed..4ffe3e7c8 100644 --- a/Roles/Neutral/Juggernaut.cs +++ b/Roles/Neutral/Juggernaut.cs @@ -17,22 +17,22 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Juggernaut); + DefaultKillCooldown = new FloatOptionItem(Id + 10, "SansDefaultKillCooldown", new(0f, 180f, 0.5f), 30f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Juggernaut]) .SetValueFormat(OptionFormat.Seconds); + ReduceKillCooldown = new FloatOptionItem(Id + 11, "SansReduceKillCooldown", new(0f, 30f, 0.5f), 4f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Juggernaut]) .SetValueFormat(OptionFormat.Seconds); + MinKillCooldown = new FloatOptionItem(Id + 12, "SansMinKillCooldown", new(0f, 30f, 0.5f), 10f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Juggernaut]) .SetValueFormat(OptionFormat.Seconds); + HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Juggernaut]); CanVent = new BooleanOptionItem(Id + 14, "CanVent", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Juggernaut]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Neutral/Lawyer.cs b/Roles/Neutral/Lawyer.cs index c5b587e69..07673b603 100644 --- a/Roles/Neutral/Lawyer.cs +++ b/Roles/Neutral/Lawyer.cs @@ -90,12 +90,10 @@ namespace EHR.Neutral public static void SendRPC(byte lawyerId, byte targetId = 0x73, string Progress = "") { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer; + switch (Progress) { case "SetTarget": @@ -105,10 +103,7 @@ namespace EHR.Neutral AmongUsClient.Instance.FinishRpcImmediately(writer); break; case "": - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.RemoveLawyerTarget, SendOption.Reliable); writer.Write(lawyerId); @@ -126,21 +121,18 @@ namespace EHR.Neutral Target[LawyerId] = TargetId; } else - { Target.Remove(reader.ReadByte()); - } } public static void ChangeRoleByTarget(PlayerControl target) { byte Lawyer = 0x73; + Target.Do(x => { - if (x.Value == target.PlayerId) - { - Lawyer = x.Key; - } + if (x.Value == target.PlayerId) Lawyer = x.Key; }); + PlayerControl lawyer = Utils.GetPlayerById(Lawyer); CustomRoles newRole = CRoleChangeRoles[ChangeRolesAfterTargetKilled.GetValue()]; lawyer.RpcChangeRoleBasis(newRole); @@ -154,15 +146,9 @@ namespace EHR.Neutral public override bool KnowRole(PlayerControl player, PlayerControl target) { - if (base.KnowRole(player, target)) - { - return true; - } + if (base.KnowRole(player, target)) return true; - if (!KnowTargetRole.GetBool()) - { - return false; - } + if (!KnowTargetRole.GetBool()) return false; return player.Is(CustomRoles.Lawyer) && Target.TryGetValue(player.PlayerId, out byte tar) && tar == target.PlayerId; } @@ -171,10 +157,7 @@ namespace EHR.Neutral { if (!seer.Is(CustomRoles.Lawyer)) { - if (!TargetKnowsLawyer.GetBool()) - { - return string.Empty; - } + if (!TargetKnowsLawyer.GetBool()) return string.Empty; return Target.TryGetValue(target.PlayerId, out byte x) && seer.PlayerId == x ? Utils.ColorString(Utils.GetRoleColor(CustomRoles.Lawyer), "§") : string.Empty; } @@ -200,10 +183,7 @@ namespace EHR.Neutral public override void OnReportDeadBody() { - if (MeetingStates.FirstMeeting && TargetKnowsLawyer.GetBool() && Target.TryGetValue(LawyerId, out byte target)) - { - LateTask.New(() => Utils.SendMessage("\n", target, string.Format(Translator.GetString("YourLawyerIsNotify"), LawyerId.ColoredPlayerName())), 10f, log: false); - } + if (MeetingStates.FirstMeeting && TargetKnowsLawyer.GetBool() && Target.TryGetValue(LawyerId, out byte target)) LateTask.New(() => Utils.SendMessage("\n", target, string.Format(Translator.GetString("YourLawyerIsNotify"), LawyerId.ColoredPlayerName())), 10f, log: false); } } } \ No newline at end of file diff --git a/Roles/Neutral/Magician.cs b/Roles/Neutral/Magician.cs index bfc77bddd..0ae716ffd 100644 --- a/Roles/Neutral/Magician.cs +++ b/Roles/Neutral/Magician.cs @@ -49,27 +49,39 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupSingleRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Magician); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Magician]) .SetValueFormat(OptionFormat.Seconds); + SlownessValue = new FloatOptionItem(Id + 11, "MagicianSlownessValue", new(0f, 1f, 0.05f), 1f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Magician]) .SetValueFormat(OptionFormat.Multiplier); + SlownessRadius = new FloatOptionItem(Id + 12, "MagicianSlownessRadius", new(0f, 10f, 0.25f), 3f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Magician]) .SetValueFormat(OptionFormat.Multiplier); + SlownessDur = new IntegerOptionItem(Id + 13, "MagicianSlownessDur", new(1, 30, 1), 10, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Magician]) .SetValueFormat(OptionFormat.Seconds); + Speed = new FloatOptionItem(Id + 14, "MagicianSpeedup", new(0.1f, 3f, 0.05f), 1.5f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Magician]) .SetValueFormat(OptionFormat.Multiplier); + SpeedDur = new IntegerOptionItem(Id + 15, "MagicianSpeedupDur", new(1, 20, 1), 10, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Magician]) .SetValueFormat(OptionFormat.Seconds); + LowKCD = new FloatOptionItem(Id + 16, "MagicianLowKCD", new(1f, 20f, 1f), 5f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Magician]) .SetValueFormat(OptionFormat.Seconds); + BlindDur = new IntegerOptionItem(Id + 17, "MagicianBlindDur", new(1, 20, 1), 5, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Magician]) .SetValueFormat(OptionFormat.Seconds); + BlindRadius = new FloatOptionItem(Id + 18, "MagicianBlindRadius", new(0f, 10f, 0.25f), 3f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Magician]) .SetValueFormat(OptionFormat.Multiplier); + ClearPortalAfterMeeting = new BooleanOptionItem(Id + 19, "MagicianClearPortalAfterMeeting", false, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Magician]); + BombRadius = new FloatOptionItem(Id + 20, "MagicianBombRadius", new(0f, 10f, 0.25f), 3f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Magician]) .SetValueFormat(OptionFormat.Multiplier); + BombDelay = new IntegerOptionItem(Id + 21, "MagicianBombDelay", new(0, 10, 1), 3, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Magician]) .SetValueFormat(OptionFormat.Seconds); @@ -118,27 +130,18 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte id) { opt.SetVision(HasImpostorVision.GetBool()); - if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) - { - AURoleOptions.PhantomCooldown = 1f; - } + if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) AURoleOptions.PhantomCooldown = 1f; - if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = 1f; - } + if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) AURoleOptions.ShapeshifterCooldown = 1f; } public override void OnMurder(PlayerControl killer, PlayerControl target) { - if (killer == null) - { - return; - } + if (killer == null) return; CardId = (byte)IRandom.Instance.Next(1, 11); - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.Append("\n\n"); sb.AppendLine(ColorString(GetRoleColor(CustomRoles.Magician), $"Card name: {GetString($"Magician-GetIdToName-{CardId}")}")); @@ -167,15 +170,9 @@ namespace EHR.Neutral public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (shapeshifter == null) - { - return false; - } + if (shapeshifter == null) return false; - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return false; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return false; UseCard(shapeshifter); return false; @@ -183,33 +180,22 @@ namespace EHR.Neutral public static void UseCard(PlayerControl pc) { - if (pc == null) - { - return; - } + if (pc == null) return; - if (CardId == byte.MaxValue) - { - return; - } + if (CardId == byte.MaxValue) return; - bool sync = false; + var sync = false; switch (CardId) { case 1: // Slowness for everyone nearby - if (TempSpeeds.Count > 0) - { - RevertSpeedChanges(true); - } + if (TempSpeeds.Count > 0) RevertSpeedChanges(true); IEnumerable list = GetPlayersInRadius(SlownessRadius.GetFloat(), pc.Pos()); + foreach (PlayerControl x in list) { - if (x.PlayerId == pc.PlayerId) - { - continue; - } + if (x.PlayerId == pc.PlayerId) continue; TempSpeeds.TryAdd(x.PlayerId, Main.AllPlayerSpeed[x.PlayerId]); SlowPpl.TryAdd(x.PlayerId, TimeStamp); @@ -229,16 +215,10 @@ namespace EHR.Neutral CardId = byte.MaxValue; break; case 4: // Create Rift Maker portal - if (PortalMarks.Count == 2) - { - PortalMarks.Clear(); - } + if (PortalMarks.Count == 2) PortalMarks.Clear(); PortalMarks.Add(pc.Pos()); - if (PortalMarks.Count == 2) - { - CardId = byte.MaxValue; - } + if (PortalMarks.Count == 2) CardId = byte.MaxValue; break; case 5: // Snipe @@ -254,10 +234,7 @@ namespace EHR.Neutral CardId = byte.MaxValue; pc.Notify(GetString("MagicianCardUsed")); - if (!AmongUsClient.Instance.AmHost || Pelican.IsEaten(pc.PlayerId) || Medic.ProtectList.Contains(pc.PlayerId)) - { - return; - } + if (!AmongUsClient.Instance.AmHost || Pelican.IsEaten(pc.PlayerId) || Medic.ProtectList.Contains(pc.PlayerId)) return; pc.RPCPlayCustomSound("AWP"); @@ -272,29 +249,21 @@ namespace EHR.Neutral targets.Remove(snipedTarget); PlayerControl[] list1 = [.. targets.Keys]; - foreach (PlayerControl x in list1) - { - NotifyRoles(SpecifySeer: x); - } + foreach (PlayerControl x in list1) NotifyRoles(SpecifySeer: x); LateTask.New(() => { - foreach (PlayerControl x in list1) - { - NotifyRoles(SpecifySeer: x); - } + foreach (PlayerControl x in list1) NotifyRoles(SpecifySeer: x); }, 0.5f, "Sniper shot Notify"); } break; case 6: // Blind everyone nearby IEnumerable players = GetPlayersInRadius(BlindRadius.GetFloat(), pc.Pos()); + foreach (PlayerControl x in players) { - if (x.PlayerId == pc.PlayerId) - { - continue; - } + if (x.PlayerId == pc.PlayerId) continue; BlindPpl.TryAdd(x.PlayerId, TimeStamp); x.MarkDirtySettings(); @@ -312,12 +281,14 @@ namespace EHR.Neutral Main.AllPlayerSpeed[pc.PlayerId] = Speed.GetFloat(); IsSpeedup = true; sync = true; + LateTask.New(() => { Main.AllPlayerSpeed[pc.PlayerId] = OriginalSpeed; pc.MarkDirtySettings(); IsSpeedup = false; }, SpeedDur.GetInt(), "Revert Magician Speed"); + CardId = byte.MaxValue; break; case 9: // Call meeting @@ -326,11 +297,8 @@ namespace EHR.Neutral break; case 10: // Admin map Dictionary rooms = GetAllPlayerLocationsCount(); - StringBuilder sb = new StringBuilder(); - foreach (KeyValuePair location in rooms) - { - sb.Append($"\n{location.Key}: {location.Value}"); - } + var sb = new StringBuilder(); + foreach (KeyValuePair location in rooms) sb.Append($"\n{location.Key}: {location.Value}"); pc.Notify(sb.ToString(), 10f); break; @@ -339,33 +307,18 @@ namespace EHR.Neutral break; } - if (sync) - { - pc.MarkDirtySettings(); - } + if (sync) pc.MarkDirtySettings(); } public override void OnFixedUpdate(PlayerControl pc) { - if (pc == null) - { - return; - } + if (pc == null) return; - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; - if (Pelican.IsEaten(pc.PlayerId) || pc.Data.IsDead) - { - return; - } + if (Pelican.IsEaten(pc.PlayerId) || pc.Data.IsDead) return; - if (TempSpeeds.Count > 0) - { - RevertSpeedChanges(false); - } + if (TempSpeeds.Count > 0) RevertSpeedChanges(false); if (PortalMarks.Count == 2 && LastTP + 5 < TimeStamp) { @@ -378,16 +331,13 @@ namespace EHR.Neutral { Vector2 position = pc.Pos(); - bool isTP = false; + var isTP = false; Vector2 from = PortalMarks[0]; foreach (Vector2 mark in PortalMarks.ToArray()) { float dis = Vector2.Distance(mark, position); - if (dis > 2f) - { - continue; - } + if (dis > 2f) continue; isTP = true; from = mark; @@ -396,18 +346,13 @@ namespace EHR.Neutral if (isTP) { LastTP = TimeStamp; + if (from == PortalMarks[0]) - { pc.TP(PortalMarks[1]); - } else if (from == PortalMarks[1]) - { pc.TP(PortalMarks[0]); - } else - { Logger.Error($"Teleport failed - from: {from}", "MagicianTP"); - } } } } @@ -425,8 +370,9 @@ namespace EHR.Neutral { foreach (KeyValuePair bomb in Bombs.Where(bomb => bomb.Value + BombDelay.GetInt() < TimeStamp)) { - bool b = false; + var b = false; IEnumerable players = GetPlayersInRadius(BombRadius.GetFloat(), bomb.Key); + foreach (PlayerControl tg in players) { if (tg.PlayerId == pc.PlayerId) @@ -440,24 +386,19 @@ namespace EHR.Neutral Bombs.Remove(bomb.Key); pc.Notify(GetString("MagicianBombExploded")); + if (b) { LateTask.New(() => { - if (!GameStates.IsEnded) - { - pc.Suicide(PlayerState.DeathReason.Bombed); - } + if (!GameStates.IsEnded) pc.Suicide(PlayerState.DeathReason.Bombed); }, 0.5f, "Magician Bomb Suicide"); } } - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); long[] list = [.. Bombs.Values]; - foreach (long x in list) - { - sb.Append(string.Format(GetString("MagicianBombExlodesIn"), BombDelay.GetInt() - (TimeStamp - x) + 1)); - } + foreach (long x in list) sb.Append(string.Format(GetString("MagicianBombExlodesIn"), BombDelay.GetInt() - (TimeStamp - x) + 1)); pc.Notify(sb.ToString()); } @@ -469,10 +410,7 @@ namespace EHR.Neutral BlindPpl.Clear(); Bombs.Clear(); IsSniping = false; - if (ClearPortalAfterMeeting.GetBool()) - { - PortalMarks.Clear(); - } + if (ClearPortalAfterMeeting.GetBool()) PortalMarks.Clear(); if (IsSpeedup) { @@ -494,7 +432,7 @@ namespace EHR.Neutral private static Dictionary GetSnipeTargets(PlayerControl sniper) { - Dictionary targets = new Dictionary(); + var targets = new Dictionary(); Vector3 snipeBasePos = SnipeBasePosition; Vector3 snipePos = sniper.transform.position; Vector3 dir = (snipePos - snipeBasePos).normalized; @@ -503,24 +441,15 @@ namespace EHR.Neutral foreach (PlayerControl target in Main.AllAlivePlayerControls) { - if (target.PlayerId == sniper.PlayerId) - { - continue; - } + if (target.PlayerId == sniper.PlayerId) continue; Vector3 target_pos = target.transform.position - snipePos; - if (target_pos.magnitude < 1) - { - continue; - } + if (target_pos.magnitude < 1) continue; Vector3 target_dir = target_pos.normalized; float target_dot = Vector3.Dot(dir, target_dir); - if (target_dot < 0.995) - { - continue; - } + if (target_dot < 0.995) continue; float err = target_pos.magnitude; targets.Add(target, err); diff --git a/Roles/Neutral/Mario.cs b/Roles/Neutral/Mario.cs index d4d3fdc7a..c219c1ebf 100644 --- a/Roles/Neutral/Mario.cs +++ b/Roles/Neutral/Mario.cs @@ -15,9 +15,11 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(18300, TabGroup.NeutralRoles, CustomRoles.Mario); + MarioVentNumWin = new IntegerOptionItem(18310, "MarioVentNumWin", new(0, 900, 5), 80, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mario]) .SetValueFormat(OptionFormat.Times); + MarioVentCD = new FloatOptionItem(18311, "VentCooldown", new(0f, 180f, 1f), 0f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mario]) .SetValueFormat(OptionFormat.Seconds); @@ -54,6 +56,7 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl pc) { byte playerId = pc.PlayerId; + if (MarioVentCount[playerId] > MarioVentNumWin.GetInt() && GameStates.IsInTask) { MarioVentCount[playerId] = MarioVentNumWin.GetInt(); diff --git a/Roles/Neutral/Maverick.cs b/Roles/Neutral/Maverick.cs index 745d2c5ae..94029267c 100644 --- a/Roles/Neutral/Maverick.cs +++ b/Roles/Neutral/Maverick.cs @@ -21,13 +21,17 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Maverick); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 35f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Maverick]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 11, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Maverick]); + HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Maverick]); + MinKillsToWin = new IntegerOptionItem(Id + 12, "DQNumOfKillsNeeded", new(0, 14, 1), 2, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Maverick]); } @@ -71,10 +75,7 @@ namespace EHR.Neutral public override string GetProgressText(byte playerId, bool comms) { - if (Main.PlayerStates[playerId].Role is not Maverick mr) - { - return string.Empty; - } + if (Main.PlayerStates[playerId].Role is not Maverick mr) return string.Empty; int kills = mr.NumOfKills; int min = MinKillsToWin.GetInt(); diff --git a/Roles/Neutral/Medusa.cs b/Roles/Neutral/Medusa.cs index 416923fd8..8c064bad7 100644 --- a/Roles/Neutral/Medusa.cs +++ b/Roles/Neutral/Medusa.cs @@ -17,26 +17,27 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Medusa); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 30f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Medusa]) .SetValueFormat(OptionFormat.Seconds); + KillCooldownAfterStoneGazing = new FloatOptionItem(Id + 14, "KillCooldownAfterStoneGazing", new(0f, 180f, 0.5f), 60f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Medusa]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 11, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Medusa]); + HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Medusa]); + CannotStoneGazeWhenKCDIsntUp = new BooleanOptionItem(Id + 12, "CannotStoneGazeWhenKCDIsntUp", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Medusa]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Neutral/Mycologist.cs b/Roles/Neutral/Mycologist.cs index cd3b1e157..8f0a02600 100644 --- a/Roles/Neutral/Mycologist.cs +++ b/Roles/Neutral/Mycologist.cs @@ -38,19 +38,25 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Mycologist); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mycologist]) .SetValueFormat(OptionFormat.Seconds); + HasImpostorVision = new BooleanOptionItem(Id + 7, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mycologist]); + SpreadAction = new StringOptionItem(Id + 3, "MycologistAction", SpreadMode, 1, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mycologist]); + CD = new IntegerOptionItem(Id + 4, "AbilityCooldown", new(1, 90, 1), 15, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mycologist]) .SetValueFormat(OptionFormat.Seconds); + InfectRadius = new FloatOptionItem(Id + 5, "InfectRadius", new(0.1f, 5f, 0.1f), 3f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mycologist]) .SetValueFormat(OptionFormat.Multiplier); + InfectTime = new IntegerOptionItem(Id + 6, "InfectDelay", new(0, 60, 1), 5, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Mycologist]) .SetValueFormat(OptionFormat.Seconds); @@ -76,34 +82,22 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte id) { opt.SetVision(HasImpostorVision.GetBool()); - if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) - { - AURoleOptions.PhantomCooldown = CD.GetInt(); - } + if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) AURoleOptions.PhantomCooldown = CD.GetInt(); - if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = CD.GetInt(); - } + if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) AURoleOptions.ShapeshifterCooldown = CD.GetInt(); } private void SendRPC() { - if (!IsEnable || !DoRPC) - { - return; - } + if (!IsEnable || !DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncMycologist, SendOption.Reliable); writer.Write(MycologistId); writer.Write(InfectedPlayers.Count); + if (InfectedPlayers.Count > 0) - { foreach (byte x in InfectedPlayers) - { writer.Write(x); - } - } AmongUsClient.Instance.FinishRpcImmediately(writer); } @@ -111,84 +105,59 @@ namespace EHR.Neutral public static void ReceiveRPC(MessageReader reader) { byte playerId = reader.ReadByte(); - if (Main.PlayerStates[playerId].Role is not Mycologist mg) - { - return; - } + if (Main.PlayerStates[playerId].Role is not Mycologist mg) return; mg.InfectedPlayers.Clear(); int length = reader.ReadInt32(); - for (int i = 0; i < length; i++) - { - mg.InfectedPlayers.Add(reader.ReadByte()); - } + for (var i = 0; i < length; i++) mg.InfectedPlayers.Add(reader.ReadByte()); } public override void OnPet(PlayerControl pc) { - if (SpreadAction.GetValue() == 2) - { - SpreadSpores(); - } + if (SpreadAction.GetValue() == 2) SpreadSpores(); } public override bool OnSabotage(PlayerControl pc) { - if (SpreadAction.GetValue() == 1) - { - SpreadSpores(); - } + if (SpreadAction.GetValue() == 1) SpreadSpores(); return false; } public override void OnEnterVent(PlayerControl pc, Vent vent) { - if (SpreadAction.GetValue() == 0 || (SpreadAction.GetValue() == 2 && !UsePets.GetBool())) - { - SpreadSpores(); - } + if (SpreadAction.GetValue() == 0 || (SpreadAction.GetValue() == 2 && !UsePets.GetBool())) SpreadSpores(); } public override bool OnVanish(PlayerControl pc) { - if (SpreadAction.GetValue() == 3) - { - SpreadSpores(); - } + if (SpreadAction.GetValue() == 3) SpreadSpores(); return false; } public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; - if (SpreadAction.GetValue() == 4) - { - SpreadSpores(); - } + if (SpreadAction.GetValue() == 4) SpreadSpores(); return false; } private void SpreadSpores() { - if (!IsEnable || MycologistPC.HasAbilityCD()) - { - return; - } + if (!IsEnable || MycologistPC.HasAbilityCD()) return; MycologistPC.AddAbilityCD(CD.GetInt()); + LateTask.New(() => { InfectedPlayers.AddRange(GetPlayersInRadius(InfectRadius.GetFloat(), MycologistPC.Pos()).Select(x => x.PlayerId)); SendRPC(); NotifyRoles(SpecifySeer: MycologistPC); }, InfectTime.GetFloat(), "Mycologist Infect Time"); + MycologistPC.Notify(GetString("MycologistNotify")); } diff --git a/Roles/Neutral/NSerialKiller.cs b/Roles/Neutral/NSerialKiller.cs index 487a3c562..bb3ff1a08 100644 --- a/Roles/Neutral/NSerialKiller.cs +++ b/Roles/Neutral/NSerialKiller.cs @@ -16,11 +16,14 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.NSerialKiller); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.NSerialKiller]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 3, "CanVent", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.NSerialKiller]); + HasImpostorVision = new BooleanOptionItem(Id + 4, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.NSerialKiller]); } diff --git a/Roles/Neutral/Necromancer.cs b/Roles/Neutral/Necromancer.cs index 4b49b8df5..81e6e6a13 100644 --- a/Roles/Neutral/Necromancer.cs +++ b/Roles/Neutral/Necromancer.cs @@ -30,14 +30,18 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupSingleRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Necromancer); + CD = new FloatOptionItem(Id + 2, "NecromancerCD", new(0f, 180f, 0.5f), 30f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Necromancer]) .SetValueFormat(OptionFormat.Seconds); + Dkcd = new FloatOptionItem(Id + 10, "DKCD", new(0f, 180f, 2.5f), 30f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Necromancer]) .SetValueFormat(OptionFormat.Seconds); + KnowTargetRole = new BooleanOptionItem(Id + 13, "NecromancerKnowTargetRole", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Necromancer]); + UndeadCountMode = new StringOptionItem(Id + 15, "UndeadCountMode", UndeadCountModeStrings, 0, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Necromancer]); } @@ -127,10 +131,7 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask || !IsEnable || NecromancerPC.IsAlive() || !Deathknight.DeathknightPC.IsAlive()) - { - return; - } + if (!GameStates.IsInTask || !IsEnable || NecromancerPC.IsAlive() || !Deathknight.DeathknightPC.IsAlive()) return; Deathknight.DeathknightPC.RpcSetCustomRole(CustomRoles.Necromancer); Add(Deathknight.DeathknightId); @@ -141,25 +142,13 @@ namespace EHR.Neutral public override bool KnowRole(PlayerControl player, PlayerControl target) { - if (base.KnowRole(player, target)) - { - return true; - } + if (base.KnowRole(player, target)) return true; - if (player.Is(CustomRoles.Undead) && (target.Is(CustomRoles.Necromancer) || target.Is(CustomRoles.Deathknight))) - { - return true; - } + if (player.Is(CustomRoles.Undead) && (target.Is(CustomRoles.Necromancer) || target.Is(CustomRoles.Deathknight))) return true; - if (KnowTargetRole.GetBool() && (player.Is(CustomRoles.Necromancer) || player.Is(CustomRoles.Deathknight)) && target.Is(CustomRoles.Undead)) - { - return true; - } + if (KnowTargetRole.GetBool() && (player.Is(CustomRoles.Necromancer) || player.Is(CustomRoles.Deathknight)) && target.Is(CustomRoles.Undead)) return true; - if (player.Is(CustomRoles.Deathknight) && target.Is(CustomRoles.Necromancer)) - { - return true; - } + if (player.Is(CustomRoles.Deathknight) && target.Is(CustomRoles.Necromancer)) return true; return player.Is(CustomRoles.Necromancer) && target.Is(CustomRoles.Deathknight); } @@ -177,9 +166,7 @@ namespace EHR.Neutral public override bool IsEnable => DeathknightId != byte.MaxValue; - public override void SetupCustomOption() - { - } + public override void SetupCustomOption() { } public override void Init() { diff --git a/Roles/Neutral/Nonplus.cs b/Roles/Neutral/Nonplus.cs index 669e66ce5..6742a33f3 100644 --- a/Roles/Neutral/Nonplus.cs +++ b/Roles/Neutral/Nonplus.cs @@ -17,15 +17,19 @@ const CustomRoles role = CustomRoles.Nonplus; Options.SetupRoleOptions(id, tab, role); + BlindCooldown = new IntegerOptionItem(id + 2, "Nonplus.BlindCooldown", new(0, 60, 1), 30, tab) .SetParent(Options.CustomRoleSpawnChances[role]) .SetValueFormat(OptionFormat.Seconds); + BlindDuration = new IntegerOptionItem(id + 3, "Nonplus.BlindDuration", new(0, 60, 1), 10, tab) .SetParent(Options.CustomRoleSpawnChances[role]) .SetValueFormat(OptionFormat.Seconds); + UseLimit = new IntegerOptionItem(id + 4, "AbilityUseLimit", new(0, 5, 1), 0, tab) .SetParent(Options.CustomRoleSpawnChances[role]) .SetValueFormat(OptionFormat.Times); + NonplusAbilityUseGainWithEachKill = new FloatOptionItem(id + 5, "AbilityUseGainWithEachKill", new(0f, 5f, 0.1f), 1f, tab) .SetParent(Options.CustomRoleSpawnChances[role]) .SetValueFormat(OptionFormat.Times); @@ -54,20 +58,14 @@ public override void OnEnterVent(PlayerControl pc, Vent vent) { - if (Options.UsePets.GetBool()) - { - return; - } + if (Options.UsePets.GetBool()) return; Blind(pc); } private static void Blind(PlayerControl pc) { - if (pc.GetAbilityUseLimit() < 1) - { - return; - } + if (pc.GetAbilityUseLimit() < 1) return; pc.RpcRemoveAbilityUse(); diff --git a/Roles/Neutral/Opportunist.cs b/Roles/Neutral/Opportunist.cs index f88aad5e2..a049efd3b 100644 --- a/Roles/Neutral/Opportunist.cs +++ b/Roles/Neutral/Opportunist.cs @@ -24,10 +24,7 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (!CanVent.GetBool()) - { - return; - } + if (!CanVent.GetBool()) return; AURoleOptions.EngineerCooldown = VentCooldown.GetFloat(); AURoleOptions.EngineerInVentMaxTime = MaxInVentTime.GetFloat(); @@ -41,16 +38,21 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(10100, TabGroup.NeutralRoles, CustomRoles.Opportunist); + OppoImmuneToAttacksWhenTasksDone = new BooleanOptionItem(10110, "ImmuneToAttacksWhenTasksDone", false, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Opportunist]); + CanVent = new BooleanOptionItem(10111, "CanVent", false, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Opportunist]); + VentCooldown = new FloatOptionItem(10112, "VentCooldown", new(0f, 120f, 0.5f), 30f, TabGroup.NeutralRoles) .SetParent(CanVent) .SetValueFormat(OptionFormat.Seconds); + MaxInVentTime = new FloatOptionItem(10113, "MaxInVentTime", new(0f, 120f, 0.5f), 15f, TabGroup.NeutralRoles) .SetParent(CanVent) .SetValueFormat(OptionFormat.Seconds); + Options.OverrideTasksData.Create(10114, TabGroup.NeutralRoles, CustomRoles.Opportunist); } } diff --git a/Roles/Neutral/Patroller.cs b/Roles/Neutral/Patroller.cs index 93de01e7a..3cd471520 100644 --- a/Roles/Neutral/Patroller.cs +++ b/Roles/Neutral/Patroller.cs @@ -25,12 +25,15 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Patroller); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Patroller]) .SetValueFormat(OptionFormat.Seconds); + DecreasedKillCooldown = new FloatOptionItem(Id + 3, "DecreasedKillCooldown", new(0f, 180f, 0.5f), 15f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Patroller]) .SetValueFormat(OptionFormat.Seconds); + IncreasedSpeed = new FloatOptionItem(Id + 4, "GamblerSpeedup", new(0.05f, 5f, 0.05f), 1.75f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Patroller]) .SetValueFormat(OptionFormat.Multiplier); @@ -47,6 +50,7 @@ namespace EHR.Neutral PatrollerId = playerId; LastRoom = null; + RoomBoosts = ShipStatus.Instance.AllRooms .Shuffle() .Zip(Enum.GetValues()) @@ -72,21 +76,12 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte id) { - if (Options.UsePhantomBasis.GetBool() && Options.UsePhantomBasisForNKs.GetBool()) - { - AURoleOptions.PhantomCooldown = 1f; - } + if (Options.UsePhantomBasis.GetBool() && Options.UsePhantomBasisForNKs.GetBool()) AURoleOptions.PhantomCooldown = 1f; - if (Options.UseUnshiftTrigger.GetBool() && Options.UseUnshiftTriggerForNKs.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = 1f; - } + if (Options.UseUnshiftTrigger.GetBool() && Options.UseUnshiftTriggerForNKs.GetBool()) AURoleOptions.ShapeshifterCooldown = 1f; PlainShipRoom room = Utils.GetPlayerById(id)?.GetPlainShipRoom(); - if (room == null) - { - return; - } + if (room == null) return; opt.SetVision(room == RoomBoosts[Boost.Vision]); opt.SetInt(Int32OptionNames.KillDistance, room == RoomBoosts[Boost.Range] ? 2 : 0); @@ -95,30 +90,22 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive() || !GameStates.IsInTask) - { - return; - } + if (!pc.IsAlive() || !GameStates.IsInTask) return; Count++; - if (Count < 20) - { - return; - } + if (Count < 20) return; Count = 0; PlainShipRoom room = pc.GetPlainShipRoom(); - if ((LastRoom != null && room != null && room == LastRoom) || (LastRoom == null && room == null)) - { - return; - } + if ((LastRoom != null && room != null && room == LastRoom) || (LastRoom == null && room == null)) return; LastRoom = room; if (room != null) { string roomName = Translator.GetString(room.RoomId.ToString()); + pc.Notify(RoomBoosts.Any(x => x.Value == room) ? string.Format(Translator.GetString("PatrollerNotify"), roomName, Translator.GetString($"PatrollerBoost.{RoomBoosts.First(x => x.Value == room).Key}")) : string.Format(Translator.GetString("PatrollerNotifyNoBoost"), roomName), 300f); @@ -126,18 +113,12 @@ namespace EHR.Neutral pc.MarkDirtySettings(); - if (pc.PlayerId == PlayerControl.LocalPlayer.PlayerId) - { - HudManager.Instance.SetHudActive(pc, pc.Data.Role, true); - } + if (pc.PlayerId == PlayerControl.LocalPlayer.PlayerId) HudManager.Instance.SetHudActive(pc, pc.Data.Role, true); } public override void OnEnterVent(PlayerControl pc, Vent vent) { - if (pc.GetPlainShipRoom() == RoomBoosts[Boost.Vent]) - { - return; - } + if (pc.GetPlainShipRoom() == RoomBoosts[Boost.Vent]) return; pc.RpcRemoveAbilityUse(); } @@ -161,10 +142,7 @@ namespace EHR.Neutral public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) return true; OnPet(shapeshifter); return false; diff --git a/Roles/Neutral/Pelican.cs b/Roles/Neutral/Pelican.cs index f2c871c5e..e1864c868 100644 --- a/Roles/Neutral/Pelican.cs +++ b/Roles/Neutral/Pelican.cs @@ -25,11 +25,14 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Pelican); + KillCooldown = new FloatOptionItem(Id + 10, "PelicanKillCooldown", new(0f, 180f, 0.5f), 30f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Pelican]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 11, "CanVent", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Pelican]); + ImpostorVision = new BooleanOptionItem(Id + 12, "ImpostorVision", false, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Pelican]); } @@ -63,28 +66,20 @@ namespace EHR.Neutral private static void SyncEatenList( /*byte playerId*/) { SendRPC(byte.MaxValue); - foreach (KeyValuePair> el in EatenList) - { - SendRPC(el.Key); - } + foreach (KeyValuePair> el in EatenList) SendRPC(el.Key); } private static void SendRPC(byte playerId) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetPelicanEtenNum, SendOption.Reliable); writer.Write(playerId); + if (playerId != byte.MaxValue) { writer.Write(EatenList[playerId].Count); - foreach (byte el in EatenList[playerId].ToArray()) - { - writer.Write(el); - } + foreach (byte el in EatenList[playerId].ToArray()) writer.Write(el); } AmongUsClient.Instance.FinishRpcImmediately(writer); @@ -93,19 +88,15 @@ namespace EHR.Neutral public static void ReceiveRPC(MessageReader reader) { byte playerId = reader.ReadByte(); + if (playerId == byte.MaxValue) - { EatenList.Clear(); - } else { int eatenNum = reader.ReadInt32(); EatenList.Remove(playerId); List list = []; - for (int i = 0; i < eatenNum; i++) - { - list.Add(reader.ReadByte()); - } + for (var i = 0; i < eatenNum; i++) list.Add(reader.ReadByte()); EatenList.Add(playerId, list); } @@ -119,22 +110,15 @@ namespace EHR.Neutral public static bool IsEaten(byte id) { foreach (KeyValuePair> el in EatenList) - { if (el.Value.Contains(id)) - { return true; - } - } return false; } public static bool CanEat(PlayerControl pc, byte id) { - if (!pc.Is(CustomRoles.Pelican) || GameStates.IsMeeting) - { - return false; - } + if (!pc.Is(CustomRoles.Pelican) || GameStates.IsMeeting) return false; PlayerControl target = Utils.GetPlayerById(id); return target != null && target.IsAlive() && !target.inVent && !Medic.ProtectList.Contains(target.PlayerId) && !target.Is(CustomRoles.GM) && !IsEaten(pc, id) && !IsEaten(id); @@ -157,31 +141,19 @@ namespace EHR.Neutral public override string GetProgressText(byte playerId, bool comms) { PlayerControl player = Utils.GetPlayerById(playerId); - if (player == null) - { - return "Invalid"; - } + if (player == null) return "Invalid"; - int eatenNum = 0; - if (EatenList.TryGetValue(playerId, out List value)) - { - eatenNum = value.Count; - } + var eatenNum = 0; + if (EatenList.TryGetValue(playerId, out List value)) eatenNum = value.Count; return Utils.ColorString(eatenNum < 1 ? Color.gray : Utils.GetRoleColor(CustomRoles.Pelican), $"({eatenNum})"); } public static void EatPlayer(PlayerControl pc, PlayerControl target) { - if (pc == null || target == null || !CanEat(pc, target.PlayerId)) - { - return; - } + if (pc == null || target == null || !CanEat(pc, target.PlayerId)) return; - if (!EatenList.ContainsKey(pc.PlayerId)) - { - EatenList.Add(pc.PlayerId, []); - } + if (!EatenList.ContainsKey(pc.PlayerId)) EatenList.Add(pc.PlayerId, []); EatenList[pc.PlayerId].Add(target.PlayerId); @@ -208,10 +180,7 @@ namespace EHR.Neutral { PlayerControl target = Utils.GetPlayerById(tar); PlayerControl killer = Utils.GetPlayerById(pc.Key); - if (killer == null || target == null) - { - continue; - } + if (killer == null || target == null) continue; Main.AllPlayerSpeed[tar] = Main.AllPlayerSpeed[tar] - 0.5f + OriginalSpeed[tar]; ReportDeadBodyPatch.CanReport[tar] = true; @@ -230,19 +199,13 @@ namespace EHR.Neutral public static void OnPelicanDied(byte pc) { - if (!EatenList.TryGetValue(pc, out List value)) - { - return; - } + if (!EatenList.TryGetValue(pc, out List value)) return; foreach (byte tar in value) { PlayerControl target = Utils.GetPlayerById(tar); PlayerControl player = Utils.GetPlayerById(pc); - if (player == null || target == null) - { - continue; - } + if (player == null || target == null) continue; target.TP(player); Main.AllPlayerSpeed[tar] = Main.AllPlayerSpeed[tar] - 0.5f + OriginalSpeed[tar]; @@ -270,38 +233,23 @@ namespace EHR.Neutral return; } - if (!IsEnable) - { - return; - } + if (!IsEnable) return; Count--; - if (Count > 0) - { - return; - } + if (Count > 0) return; Count = 20; - if (!EatenList.TryGetValue(pc.PlayerId, out List list)) - { - return; - } + if (!EatenList.TryGetValue(pc.PlayerId, out List list)) return; foreach (byte tar in list) { PlayerControl target = Utils.GetPlayerById(tar); - if (target == null) - { - continue; - } + if (target == null) continue; Vector2 pos = GetBlackRoomPS(); float dis = Vector2.Distance(pos, target.Pos()); - if (dis < 2f) - { - continue; - } + if (dis < 2f) continue; target.TP(pos, log: false); Utils.NotifyRoles(SpecifySeer: target, SpecifyTarget: pc); diff --git a/Roles/Neutral/Phantasm.cs b/Roles/Neutral/Phantasm.cs index 9ee2f627f..a515536b7 100644 --- a/Roles/Neutral/Phantasm.cs +++ b/Roles/Neutral/Phantasm.cs @@ -9,21 +9,21 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(11400, TabGroup.NeutralRoles, CustomRoles.Phantasm); + PhantomCanVent = new BooleanOptionItem(11410, "CanVent", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Phantasm]); + PhantomSnatchesWin = new BooleanOptionItem(11411, "SnatchesWin", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Phantasm]); + PhantomCanGuess = new BooleanOptionItem(11412, "CanGuess", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Phantasm]); + OverrideTasksData.Create(11413, TabGroup.NeutralRoles, CustomRoles.Phantasm); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Neutral/Pickpocket.cs b/Roles/Neutral/Pickpocket.cs index 3dcb5dc5a..145bd4eae 100644 --- a/Roles/Neutral/Pickpocket.cs +++ b/Roles/Neutral/Pickpocket.cs @@ -19,13 +19,17 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Pickpocket); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Pickpocket]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 11, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Pickpocket]); + HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Pickpocket]); + VotesPerKill = new FloatOptionItem(Id + 12, "VotesPerKill", new(0.1f, 10f, 0.1f), 0.3f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Pickpocket]); } diff --git a/Roles/Neutral/PlagueBearer.cs b/Roles/Neutral/PlagueBearer.cs index bd59f09b6..ebcc4d191 100644 --- a/Roles/Neutral/PlagueBearer.cs +++ b/Roles/Neutral/PlagueBearer.cs @@ -25,14 +25,18 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.PlagueBearer); + PlagueBearerCDOpt = new FloatOptionItem(Id + 10, "PlagueBearerCD", new(0f, 180f, 0.5f), 17.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.PlagueBearer]) .SetValueFormat(OptionFormat.Seconds); + PestilenceCDOpt = new FloatOptionItem(Id + 11, "PestilenceCD", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.PlagueBearer]) .SetValueFormat(OptionFormat.Seconds); + PestilenceCanVent = new BooleanOptionItem(Id + 12, "PestilenceCanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.PlagueBearer]); + PestilenceHasImpostorVision = new BooleanOptionItem(Id + 13, "PestilenceHasImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.PlagueBearer]); } @@ -69,10 +73,7 @@ namespace EHR.Neutral public static void SendRPC(PlayerControl player, PlayerControl target) { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetPlaguedPlayer, SendOption.Reliable); //RPCによる同期 writer.Write(player.PlayerId); @@ -90,18 +91,13 @@ namespace EHR.Neutral public static (int Plagued, int All) PlaguedPlayerCount(byte playerId) { int plagued = 0, all = 0; + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (pc.PlayerId == playerId) - { - continue; - } + if (pc.PlayerId == playerId) continue; all++; - if (IsPlagued(playerId, pc.PlayerId)) - { - plagued++; - } + if (IsPlagued(playerId, pc.PlayerId)) plagued++; } return (plagued, all); @@ -109,10 +105,7 @@ namespace EHR.Neutral public static bool IsPlaguedAll(PlayerControl player) { - if (!player.Is(CustomRoles.PlagueBearer)) - { - return false; - } + if (!player.Is(CustomRoles.PlagueBearer)) return false; (int plagued, int all) = PlaguedPlayerCount(player.PlayerId); return plagued >= all; @@ -145,9 +138,7 @@ namespace EHR.Neutral public static bool On; public override bool IsEnable => On; - public override void SetupCustomOption() - { - } + public override void SetupCustomOption() { } public override void Add(byte playerId) { @@ -176,20 +167,14 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (base.OnCheckMurder(killer, target)) - { - killer.Kill(target); - } + if (base.OnCheckMurder(killer, target)) killer.Kill(target); return false; } public override bool OnCheckMurderAsTarget(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null) - { - return false; - } + if (killer == null || target == null) return false; killer.SetRealKiller(target); target.Kill(killer); diff --git a/Roles/Neutral/PlagueDoctor.cs b/Roles/Neutral/PlagueDoctor.cs index 0e67ed7c3..858e45a90 100644 --- a/Roles/Neutral/PlagueDoctor.cs +++ b/Roles/Neutral/PlagueDoctor.cs @@ -39,21 +39,28 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.PlagueDoctor); + OptionInfectLimit = new IntegerOptionItem(Id + 10, "PlagueDoctorInfectLimit", new(1, 3, 1), 1, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.PlagueDoctor]) .SetValueFormat(OptionFormat.Times); + OptionInfectWhenKilled = new BooleanOptionItem(Id + 11, "PlagueDoctorInfectWhenKilled", false, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.PlagueDoctor]); + OptionInfectTime = new FloatOptionItem(Id + 12, "PlagueDoctorInfectTime", new(3f, 20f, 1f), 8f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.PlagueDoctor]) .SetValueFormat(OptionFormat.Seconds); + OptionInfectDistance = new FloatOptionItem(Id + 13, "PlagueDoctorInfectDistance", new(0.5f, 2f, 0.25f), 1.5f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.PlagueDoctor]); + OptionInfectInactiveTime = new FloatOptionItem(Id + 14, "PlagueDoctorInfectInactiveTime", new(0.5f, 10f, 0.5f), 5f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.PlagueDoctor]) .SetValueFormat(OptionFormat.Seconds); + OptionInfectCanInfectSelf = new BooleanOptionItem(Id + 15, "PlagueDoctorCanInfectSelf", false, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.PlagueDoctor]); + OptionInfectCanInfectVent = new BooleanOptionItem(Id + 16, "PlagueDoctorCanInfectVent", false, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.PlagueDoctor]); } @@ -77,11 +84,10 @@ namespace EHR.Neutral playerId.SetAbilityUseLimit(InfectLimit); InfectActive = true; + if (Main.NormalOptions.MapId == 4) // Fixed airship respawn selection delay - { InfectInactiveTime += 5f; - } PlayerIdList.Add(playerId); } @@ -113,10 +119,7 @@ namespace EHR.Neutral private bool CanInfect(PlayerControl player) { - if (!IsEnable) - { - return false; - } + if (!IsEnable) return false; // Not a plague doctor, or capable of self-infection and infected person created return player.PlayerId != PlayerIdList[0] || (CanInfectSelf && player.GetAbilityUseLimit() == 0); @@ -124,10 +127,7 @@ namespace EHR.Neutral private void SendRPC(byte targetId, float rate) { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncPlagueDoctor, SendOption.Reliable); writer.Write(targetId); @@ -156,10 +156,7 @@ namespace EHR.Neutral public static void OnPDdeath(PlayerControl killer, PlayerControl target) { - if (Main.PlayerStates[target.PlayerId].Role is not PlagueDoctor { IsEnable: true } pd) - { - return; - } + if (Main.PlayerStates[target.PlayerId].Role is not PlagueDoctor { IsEnable: true } pd) return; if (InfectWhenKilled && target.GetAbilityUseLimit() > 0) { @@ -181,20 +178,11 @@ namespace EHR.Neutral public override void OnCheckPlayerPosition(PlayerControl player) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; if (LateCheckWin) { @@ -203,48 +191,35 @@ namespace EHR.Neutral CheckWin(); } - if (!player.IsAlive() || !InfectActive) - { - return; - } + if (!player.IsAlive() || !InfectActive) return; if (InfectInfos.TryGetValue(player.PlayerId, out float rate) && rate >= 100) { // In case of an infected person - bool changed = false; + var changed = false; bool inVent = player.inVent; List updates = []; + foreach (PlayerControl target in Main.AllAlivePlayerControls) { // Plague doctors are excluded if they cannot infect themselves. - if (!CanInfect(target)) - { - continue; - } + if (!CanInfect(target)) continue; // Excluded if inside or outside the vent - if (!CanInfectVent && target.inVent != inVent) - { - continue; - } + if (!CanInfectVent && target.inVent != inVent) continue; InfectInfos.TryGetValue(target.PlayerId, out float oldRate); // Exclude infected people - if (oldRate >= 100) - { - continue; - } + if (oldRate >= 100) continue; // Exclude players outside the range float distance = Vector3.Distance(player.transform.position, target.transform.position); - if (distance > InfectDistance) - { - continue; - } + if (distance > InfectDistance) continue; float newRate = oldRate + (Time.fixedDeltaTime / InfectTime * 100); newRate = Math.Clamp(newRate, 0, 100); InfectInfos[target.PlayerId] = newRate; + if ((oldRate < 50 && newRate >= 50) || newRate >= 100) { changed = true; @@ -258,10 +233,7 @@ namespace EHR.Neutral { //If someone is infected CheckWin(); - foreach (PlayerControl x in updates) - { - Utils.NotifyRoles(SpecifyTarget: x); - } + foreach (PlayerControl x in updates) Utils.NotifyRoles(SpecifyTarget: x); } } } @@ -281,55 +253,31 @@ namespace EHR.Neutral public static string GetMarkOthers(PlayerControl seer, PlayerControl seen = null) { - if (Main.PlayerStates[seer.PlayerId].Role is not PlagueDoctor { IsEnable: true } pd) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not PlagueDoctor { IsEnable: true } pd) return string.Empty; seen ??= seer; - if (!pd.CanInfect(seen)) - { - return string.Empty; - } + if (!pd.CanInfect(seen)) return string.Empty; - if (!seer.Is(CustomRoles.PlagueDoctor) && seer.IsAlive()) - { - return string.Empty; - } + if (!seer.Is(CustomRoles.PlagueDoctor) && seer.IsAlive()) return string.Empty; return Utils.ColorString(Utils.GetRoleColor(CustomRoles.PlagueDoctor), GetInfectRateCharactor(seen, pd)); } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId && seer.IsAlive()) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId && seer.IsAlive()) return string.Empty; - if (!seer.Is(CustomRoles.PlagueDoctor) && seer.IsAlive()) - { - return string.Empty; - } + if (!seer.Is(CustomRoles.PlagueDoctor) && seer.IsAlive()) return string.Empty; - if (!hud && seer.IsModClient()) - { - return string.Empty; - } + if (!hud && seer.IsModClient()) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is not PlagueDoctor { IsEnable: true } pd) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not PlagueDoctor { IsEnable: true } pd) return string.Empty; + + var str = new StringBuilder(40); - StringBuilder str = new StringBuilder(40); foreach (PlayerControl player in Main.AllAlivePlayerControls) - { if (!player.Is(CustomRoles.PlagueDoctor)) - { str.Append(GetInfectRateCharactor(player, pd)); - } - } return Utils.ColorString(Utils.GetRoleColor(CustomRoles.PlagueDoctor), str.ToString()); } @@ -342,20 +290,11 @@ namespace EHR.Neutral public static string GetInfectRateCharactor(PlayerControl player, PlagueDoctor pd) { - if (!pd.IsEnable) - { - return string.Empty; - } + if (!pd.IsEnable) return string.Empty; - if (!pd.CanInfect(player) || !player.IsAlive()) - { - return string.Empty; - } + if (!pd.CanInfect(player) || !player.IsAlive()) return string.Empty; - if (!InfectInfos.TryGetValue(player.PlayerId, out float rate)) - { - return string.Empty; - } + if (!InfectInfos.TryGetValue(player.PlayerId, out float rate)) return string.Empty; return rate switch { @@ -368,10 +307,7 @@ namespace EHR.Neutral private void DirectInfect(PlayerControl player) { - if (PlayerIdList.Count == 0 || player == null) - { - return; - } + if (PlayerIdList.Count == 0 || player == null) return; Logger.Info($"InfectRate [{player.GetNameWithRole()}]: 100%", "PlagueDoctor"); InfectInfos[player.PlayerId] = 100; @@ -383,42 +319,28 @@ namespace EHR.Neutral private void CheckWin() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - if (!AmongUsClient.Instance.AmHost) - { - return; - } + if (!AmongUsClient.Instance.AmHost) return; // Invalid if someone's victory is being processed - if (CustomWinnerHolder.WinnerTeam != CustomWinner.Default) - { - return; - } + if (CustomWinnerHolder.WinnerTeam != CustomWinner.Default) return; if (Main.AllAlivePlayerControls.All(p => p.Is(CustomRoles.PlagueDoctor) || IsInfected(p.PlayerId))) { InfectActive = false; PlayerControl pd = Main.AllPlayerControls.FirstOrDefault(x => x.Is(CustomRoles.PlagueDoctor)); + foreach (PlayerControl player in Main.AllAlivePlayerControls) { - if (player.Is(CustomRoles.PlagueDoctor)) - { - continue; - } + if (player.Is(CustomRoles.PlagueDoctor)) continue; player.Suicide(PlayerState.DeathReason.Curse, pd); } CustomWinnerHolder.ResetAndSetWinner(CustomWinner.PlagueDoctor); - foreach (PlayerControl plagueDoctor in Main.AllPlayerControls.Where(p => p.Is(CustomRoles.PlagueDoctor)).ToArray()) - { - CustomWinnerHolder.WinnerIds.Add(plagueDoctor.PlayerId); - } + foreach (PlayerControl plagueDoctor in Main.AllPlayerControls.Where(p => p.Is(CustomRoles.PlagueDoctor)).ToArray()) CustomWinnerHolder.WinnerIds.Add(plagueDoctor.PlayerId); } } diff --git a/Roles/Neutral/Poisoner.cs b/Roles/Neutral/Poisoner.cs index 4b9c16ece..a0ab4067d 100644 --- a/Roles/Neutral/Poisoner.cs +++ b/Roles/Neutral/Poisoner.cs @@ -13,24 +13,24 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Poisoner); + KillCooldown = new FloatOptionItem(Id + 10, "PoisonCooldown", new(0f, 180f, 0.5f), 25f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Poisoner]) .SetValueFormat(OptionFormat.Seconds); + OptionKillDelay = new FloatOptionItem(Id + 11, "PoisonerKillDelay", new(1f, 30f, 1f), 3f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Poisoner]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 12, "CanVent", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Poisoner]); + CanKillNormally = new BooleanOptionItem(Id + 13, "CanKillNormally", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Poisoner]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Neutral/Postman.cs b/Roles/Neutral/Postman.cs index 71e233b3e..c7a549594 100644 --- a/Roles/Neutral/Postman.cs +++ b/Roles/Neutral/Postman.cs @@ -27,8 +27,10 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Postman); + KillCooldown = new FloatOptionItem(Id + 10, "DeliverCooldown", new(0f, 180f, 0.5f), 10f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Postman]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 11, "CanVent", false, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Postman]); HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", false, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Postman]); DieWhenTargetDies = new BooleanOptionItem(Id + 12, "PostmanDiesWhenTargetDies", false, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Postman]); @@ -78,24 +80,16 @@ namespace EHR.Neutral foreach (byte id in PlayerIdList) { PlayerControl pc = Utils.GetPlayerById(id); - if (pc == null || !pc.IsAlive()) - { - continue; - } + if (pc == null || !pc.IsAlive()) continue; if (Main.PlayerStates[id].Role is Postman { IsEnable: true } pm && pm.Target == deadPc.PlayerId) { if (isDeath && DieWhenTargetDies.GetBool()) - { pc.Suicide(); - } else { pm.SetNewTarget(); - if (!isDeath) - { - continue; - } + if (!isDeath) continue; pm.NotifyPostman(Utils.GetPlayerById(id), GetString("PostmanTargetDied")); } @@ -105,19 +99,13 @@ namespace EHR.Neutral private void SetNewTarget() { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - byte tempTarget = byte.MaxValue; + var tempTarget = byte.MaxValue; foreach (PlayerControl pc in Main.AllAlivePlayerControls) { - if (wereTargets.Contains(pc.PlayerId) || pc.Is(CustomRoles.Postman)) - { - continue; - } + if (wereTargets.Contains(pc.PlayerId) || pc.Is(CustomRoles.Postman)) continue; tempTarget = pc.PlayerId; break; @@ -143,25 +131,13 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!IsEnable) - { - return false; - } + if (!IsEnable) return false; - if (killer == null) - { - return false; - } + if (killer == null) return false; - if (target == null) - { - return false; - } + if (target == null) return false; - if (IsFinished) - { - return false; - } + if (IsFinished) return false; if (Target == byte.MaxValue) { @@ -176,21 +152,16 @@ namespace EHR.Neutral NotifyPostman(killer, GetString("PostmanCorrectDeliver")); } else - { killer.Suicide(); - } return false; } private void NotifyPostman(PlayerControl pc, string baseText) { - if (!IsEnable) - { - return; - } + if (!IsEnable) return; - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.Append("\r\n\r\n"); sb.AppendLine(baseText); @@ -201,25 +172,16 @@ namespace EHR.Neutral private static string GetHudText(PlayerControl pc) { - if (Main.PlayerStates[pc.PlayerId].Role is not Postman { IsEnable: true } pm) - { - return string.Empty; - } + if (Main.PlayerStates[pc.PlayerId].Role is not Postman { IsEnable: true } pm) return string.Empty; return !pm.IsFinished ? string.Format(GetString("PostmanTarget"), Utils.GetPlayerById(pm.Target).GetRealName()) : GetString("PostmanDone"); } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (hud) - { - return GetHudText(seer); - } + if (hud) return GetHudText(seer); - if (seer.IsModClient() || seer.PlayerId != target.PlayerId || Main.PlayerStates[seer.PlayerId].Role is not Postman { IsEnable: true } pm) - { - return string.Empty; - } + if (seer.IsModClient() || seer.PlayerId != target.PlayerId || Main.PlayerStates[seer.PlayerId].Role is not Postman { IsEnable: true } pm) return string.Empty; return !pm.IsFinished ? string.Format(GetString("PostmanTarget"), Utils.GetPlayerById(pm.Target).GetRealName()) : "✓"; } diff --git a/Roles/Neutral/Predator.cs b/Roles/Neutral/Predator.cs index 4415c32ce..31b8d7f19 100644 --- a/Roles/Neutral/Predator.cs +++ b/Roles/Neutral/Predator.cs @@ -25,15 +25,20 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Predator); + NumOfRolesToKill = new IntegerOptionItem(Id + 2, "NumOfRolesToKill", new(1, 10, 1), 3, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Predator]); + MaxImpRolePicks = new IntegerOptionItem(Id + 3, "MaxImpRolePicks", new(1, 10, 1), 1, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Predator]); + KillCooldown = new FloatOptionItem(Id + 4, "KillCooldown", new(0f, 180f, 0.5f), 15f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Predator]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 5, "CanVent", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Predator]); + HasImpVision = new BooleanOptionItem(Id + 6, "ImpostorVision", false, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Predator]); } @@ -50,10 +55,10 @@ namespace EHR.Neutral List allRoles = Enum.GetValues().ToList(); allRoles.RemoveAll(x => x == CustomRoles.Predator || x >= CustomRoles.NotAssigned || !x.RoleExist(true)); - IRandom r = IRandom.Instance; - int impRoles = 0; + var r = IRandom.Instance; + var impRoles = 0; - for (int i = 0; i < NumOfRolesToKill.GetInt(); i++) + for (var i = 0; i < NumOfRolesToKill.GetInt(); i++) { int index = r.Next(allRoles.Count); CustomRoles role = allRoles[index]; @@ -78,10 +83,7 @@ namespace EHR.Neutral MessageWriter w = Utils.CreateRPC(CustomRPC.SyncRoleData); w.WritePacked(1); w.WritePacked(RolesToKill.Count); - foreach (CustomRoles role in RolesToKill) - { - w.WritePacked((int)role); - } + foreach (CustomRoles role in RolesToKill) w.WritePacked((int)role); Utils.EndRPC(w); Utils.SendRPC(CustomRPC.SyncRoleData, playerId, 2, IsWon); @@ -95,10 +97,7 @@ namespace EHR.Neutral case 1: RolesToKill = []; int count = reader.ReadPackedInt32(); - for (int i = 0; i < count; i++) - { - RolesToKill.Add((CustomRoles)reader.ReadPackedInt32()); - } + for (var i = 0; i < count; i++) RolesToKill.Add((CustomRoles)reader.ReadPackedInt32()); break; case 2: @@ -134,19 +133,14 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (IsWon) - { - return false; - } + if (IsWon) return false; CustomRoles targetRole = target.GetCustomRole(); + if (RolesToKill.Contains(targetRole)) { IsWon = true; - if (!killer.IsModClient()) - { - killer.Notify(string.Format(Translator.GetString("PredatorCorrectKill"), Translator.GetString($"{targetRole}"))); - } + if (!killer.IsModClient()) killer.Notify(string.Format(Translator.GetString("PredatorCorrectKill"), Translator.GetString($"{targetRole}"))); return true; } @@ -157,25 +151,13 @@ namespace EHR.Neutral public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId) return string.Empty; - if (seer.IsModClient() && !hud) - { - return string.Empty; - } + if (seer.IsModClient() && !hud) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is not Predator { IsEnable: true } pt) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not Predator { IsEnable: true } pt) return string.Empty; - if (pt.IsWon) - { - return !hud ? "<#00ff00>\u2713" : Translator.GetString("PredatorDone"); - } + if (pt.IsWon) return !hud ? "<#00ff00>\u2713" : Translator.GetString("PredatorDone"); string text = pt.RolesToKill.Join(x => x.ToColoredString()); return hud ? text : $"{text}"; diff --git a/Roles/Neutral/Pursuer.cs b/Roles/Neutral/Pursuer.cs index 0af434701..d0ed3a35b 100644 --- a/Roles/Neutral/Pursuer.cs +++ b/Roles/Neutral/Pursuer.cs @@ -19,9 +19,11 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Pursuer); + PursuerSkillCooldown = new FloatOptionItem(Id + 10, "PursuerSkillCooldown", new(0.5f, 60f, 0.5f), 15f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Pursuer]) .SetValueFormat(OptionFormat.Seconds); + PursuerSkillLimitTimes = new IntegerOptionItem(Id + 11, "PursuerSkillLimitTimes", new(1, 99, 1), 2, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Pursuer]) .SetValueFormat(OptionFormat.Times); @@ -64,20 +66,14 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (CanBeClient(target) && CanSeel(killer.PlayerId)) - { - SeelToClient(killer, target); - } + if (CanBeClient(target) && CanSeel(killer.PlayerId)) SeelToClient(killer, target); return false; } private void SeelToClient(PlayerControl pc, PlayerControl target) { - if (pc == null || target == null || !pc.Is(CustomRoles.Pursuer)) - { - return; - } + if (pc == null || target == null || !pc.Is(CustomRoles.Pursuer)) return; pc.RpcRemoveAbilityUse(); clientList.Add(target.PlayerId); @@ -91,20 +87,11 @@ namespace EHR.Neutral { foreach (byte id in PlayerIdList) { - if (!Main.PlayerStates.TryGetValue(id, out PlayerState state)) - { - continue; - } + if (!Main.PlayerStates.TryGetValue(id, out PlayerState state)) continue; - if (state.Role is not Pursuer { IsEnable: true } ps) - { - continue; - } + if (state.Role is not Pursuer { IsEnable: true } ps) continue; - if (!ps.clientList.Contains(pc.PlayerId) || NotActiveList.Contains(pc.PlayerId)) - { - continue; - } + if (!ps.clientList.Contains(pc.PlayerId) || NotActiveList.Contains(pc.PlayerId)) continue; // Get rid of this nonsense of killing the player for no reason // Just reset their KCD instead diff --git a/Roles/Neutral/Pyromaniac.cs b/Roles/Neutral/Pyromaniac.cs index 697794408..9362b861a 100644 --- a/Roles/Neutral/Pyromaniac.cs +++ b/Roles/Neutral/Pyromaniac.cs @@ -22,12 +22,16 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Pyromaniac); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Pyromaniac]) .SetValueFormat(OptionFormat.Seconds); + DouseCooldown = new FloatOptionItem(Id + 11, "PyroDouseCooldown", new(0f, 180f, 2.5f), 20f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Pyromaniac]) .SetValueFormat(OptionFormat.Seconds); + BurnCooldown = new FloatOptionItem(Id + 12, "PyroBurnCooldown", new(0f, 180f, 2.5f), 5f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Pyromaniac]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 13, "CanVent", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Pyromaniac]); HasImpostorVision = new BooleanOptionItem(Id + 14, "ImpostorVision", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Pyromaniac]); } @@ -61,15 +65,9 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null) - { - return true; - } + if (killer == null) return true; - if (target == null) - { - return true; - } + if (target == null) return true; if (DousedList.Contains(target.PlayerId)) { diff --git a/Roles/Neutral/QuizMaster.cs b/Roles/Neutral/QuizMaster.cs index db6a10043..778510f81 100644 --- a/Roles/Neutral/QuizMaster.cs +++ b/Roles/Neutral/QuizMaster.cs @@ -52,20 +52,27 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.QuizMaster); + MarkCooldown = new FloatOptionItem(Id + 2, "QuizMaster.MarkCooldown", new(0f, 180f, 1f), 1f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.QuizMaster]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 3, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.QuizMaster]); + HasImpostorVision = new BooleanOptionItem(Id + 4, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.QuizMaster]); + CanKillWithDoubleClick = new BooleanOptionItem(Id + 5, "CanKillWithDoubleClick", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.QuizMaster]); + KillCooldown = new FloatOptionItem(Id + 6, "KillCooldown", new(0f, 60f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CanKillWithDoubleClick) .SetValueFormat(OptionFormat.Seconds); + EnableCustomQuestionsOpt = new BooleanOptionItem(Id + 7, "QuizMaster.EnableCustomQuestions", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.QuizMaster]); + CustomQuestionChance = new FloatOptionItem(Id + 8, "QuizMaster.CustomQuestionChance", new(0f, 100f, 5f), 50f, TabGroup.NeutralRoles) .SetParent(EnableCustomQuestionsOpt) .SetValueFormat(OptionFormat.Percent); @@ -82,6 +89,7 @@ namespace EHR.Neutral Data = ((string.Empty, null), string.Empty, default, string.Empty, 0, string.Empty, 0, 0, 0, 0, 0); AllColors = []; + LateTask.New(() => { foreach (PlayerControl pc in Main.AllPlayerControls) @@ -97,6 +105,7 @@ namespace EHR.Neutral if (EnableCustomQuestions) { string[] lines = File.ReadAllLines("./EHR_DATA/QuizMasterQuestions.txt"); + IEnumerable questions = lines.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => { try @@ -155,10 +164,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!base.OnCheckMurder(killer, target)) - { - return false; - } + if (!base.OnCheckMurder(killer, target)) return false; if (!CanKillWithDoubleClick.GetBool()) { @@ -178,7 +184,7 @@ namespace EHR.Neutral List allowedIndexes = []; List allowedABCIndexes = []; - for (int i = 1; i <= 14; i++) + for (var i = 1; i <= 14; i++) { switch (i) { @@ -196,7 +202,7 @@ namespace EHR.Neutral } } - for (int i = 1; i <= 6; i++) + for (var i = 1; i <= 6; i++) { switch (i) { @@ -207,12 +213,9 @@ namespace EHR.Neutral } } - IRandom random = IRandom.Instance; + var random = IRandom.Instance; - if (EnableCustomQuestions && random.Next(100) < CustomQuestionChance.GetInt()) - { - return CustomQuestions.RandomElement(); - } + if (EnableCustomQuestions && random.Next(100) < CustomQuestionChance.GetInt()) return CustomQuestions.RandomElement(); bool abc = random.Next(4) == 0; List indexes = abc ? allowedABCIndexes : allowedIndexes; @@ -272,10 +275,7 @@ namespace EHR.Neutral public override void OnReportDeadBody() { - if (Target == byte.MaxValue) - { - return; - } + if (Target == byte.MaxValue) return; CurrentQuestion = GetQuestion(); @@ -297,10 +297,7 @@ namespace EHR.Neutral index = answer[0] - 'A'; string name = Utils.GetPlayerById(Target)?.GetNameWithRole(); - if (index != -1) - { - Logger.Info($"Player {name} answered {CurrentQuestion.Answers[index]}", "QuizMaster"); - } + if (index != -1) Logger.Info($"Player {name} answered {CurrentQuestion.Answers[index]}", "QuizMaster"); if (CurrentQuestion.CorrectAnswerIndex == index) { @@ -321,18 +318,13 @@ namespace EHR.Neutral Logger.Info($"Player {name} was killed for answering incorrectly", "QuizMaster"); } } - catch (IndexOutOfRangeException) - { - } + catch (IndexOutOfRangeException) { } catch (Exception e) { Utils.ThrowException(e); } - if (index == -1) - { - return; - } + if (index == -1) return; CurrentQuestion = default; Target = byte.MaxValue; diff --git a/Roles/Neutral/Reckless.cs b/Roles/Neutral/Reckless.cs index 4b49e93bf..ce7f56b8f 100644 --- a/Roles/Neutral/Reckless.cs +++ b/Roles/Neutral/Reckless.cs @@ -17,22 +17,22 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Reckless); + DefaultKillCooldown = new FloatOptionItem(Id + 10, "SansDefaultKillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Reckless]) .SetValueFormat(OptionFormat.Seconds); + ReduceKillCooldown = new FloatOptionItem(Id + 11, "SansReduceKillCooldown", new(0f, 30f, 0.5f), 5f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Reckless]) .SetValueFormat(OptionFormat.Seconds); + MinKillCooldown = new FloatOptionItem(Id + 12, "SansMinKillCooldown", new(0f, 30f, 0.5f), 10f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Reckless]) .SetValueFormat(OptionFormat.Seconds); + HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Reckless]); CanVent = new BooleanOptionItem(Id + 14, "CanVent", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Reckless]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Neutral/Revolutionist.cs b/Roles/Neutral/Revolutionist.cs index d26c1cc30..2afbb313d 100644 --- a/Roles/Neutral/Revolutionist.cs +++ b/Roles/Neutral/Revolutionist.cs @@ -22,18 +22,23 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(18400, TabGroup.NeutralRoles, CustomRoles.Revolutionist); + RevolutionistDrawTime = new FloatOptionItem(18410, "RevolutionistDrawTime", new(0f, 90f, 1f), 3f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Revolutionist]) .SetValueFormat(OptionFormat.Seconds); + RevolutionistCooldown = new FloatOptionItem(18411, "RevolutionistCooldown", new(0f, 100f, 1f), 10f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Revolutionist]) .SetValueFormat(OptionFormat.Seconds); + RevolutionistDrawCount = new IntegerOptionItem(18412, "RevolutionistDrawCount", new(0, 14, 1), 6, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Revolutionist]) .SetValueFormat(OptionFormat.Players); + RevolutionistKillProbability = new IntegerOptionItem(18413, "RevolutionistKillProbability", new(0, 100, 5), 15, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Revolutionist]) .SetValueFormat(OptionFormat.Percent); + RevolutionistVentCountDown = new FloatOptionItem(18414, "RevolutionistVentCountDown", new(0f, 180f, 1f), 15f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Revolutionist]) .SetValueFormat(OptionFormat.Seconds); @@ -43,10 +48,7 @@ namespace EHR.Neutral public override void Add(byte playerId) { On = true; - foreach (PlayerControl ar in Main.AllPlayerControls) - { - IsDraw.Add((playerId, ar.PlayerId), false); - } + foreach (PlayerControl ar in Main.AllPlayerControls) IsDraw.Add((playerId, ar.PlayerId), false); } public override void Init() @@ -98,6 +100,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { killer.SetKillCooldown(RevolutionistDrawTime.GetFloat()); + if (!IsDraw[(killer.PlayerId, target.PlayerId)] && !RevolutionistTimer.ContainsKey(killer.PlayerId)) { RevolutionistTimer.TryAdd(killer.PlayerId, (target, 0f)); @@ -113,10 +116,7 @@ namespace EHR.Neutral foreach (KeyValuePair x in RevolutionistStart) { PlayerControl tar = Utils.GetPlayerById(x.Key); - if (tar == null) - { - continue; - } + if (tar == null) continue; tar.Data.IsDead = true; Main.PlayerStates[tar.PlayerId].deathReason = PlayerState.DeathReason.Sacrifice; @@ -136,6 +136,7 @@ namespace EHR.Neutral if (GameStates.IsInTask && RevolutionistTimer.ContainsKey(playerId)) { PlayerControl rvTarget = RevolutionistTimer[playerId].PLAYER; + if (!player.IsAlive() || Pelican.IsEaten(playerId)) { RevolutionistTimer.Remove(playerId); @@ -146,10 +147,9 @@ namespace EHR.Neutral { PlayerControl rv_target = RevolutionistTimer[playerId].PLAYER; float rv_time = RevolutionistTimer[playerId].TIMER; + if (!rv_target.IsAlive()) - { RevolutionistTimer.Remove(playerId); - } else if (rv_time >= RevolutionistDrawTime.GetFloat()) { player.SetKillCooldown(); @@ -158,6 +158,7 @@ namespace EHR.Neutral player.RpcSetDrawPlayer(rv_target, true); Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: rv_target, ForceLoop: true); RPC.ResetCurrentDrawTarget(playerId); + if (IRandom.Instance.Next(1, 100) <= RevolutionistKillProbability.GetInt()) { rv_target.SetRealKiller(player); @@ -171,10 +172,9 @@ namespace EHR.Neutral { float range = NormalGameOptionsV08.KillDistances[Mathf.Clamp(player.Is(CustomRoles.Reach) ? 2 : Main.NormalOptions.KillDistance, 0, 2)] + 0.5f; float dis = Vector2.Distance(player.transform.position, rv_target.transform.position); + if (dis <= range) - { RevolutionistTimer[playerId] = (rv_target, rv_time + Time.fixedDeltaTime); - } else { RevolutionistTimer.Remove(playerId); @@ -195,12 +195,14 @@ namespace EHR.Neutral { long nowtime = Utils.TimeStamp; RevolutionistLastTime[playerId] = nowtime; - int time = (int)(RevolutionistLastTime[playerId] - RevolutionistStart[playerId]); + var time = (int)(RevolutionistLastTime[playerId] - RevolutionistStart[playerId]); int countdown = RevolutionistVentCountDown.GetInt() - time; RevolutionistCountdown.Clear(); + if (countdown <= 0) { Utils.GetDrawPlayerCount(playerId, out List y); + foreach (PlayerControl pc in y.Where(x => x != null && x.IsAlive())) { pc.Suicide(PlayerState.DeathReason.Sacrifice); @@ -210,19 +212,13 @@ namespace EHR.Neutral player.Suicide(PlayerState.DeathReason.Sacrifice); } else - { RevolutionistCountdown.Add(playerId, countdown); - } } else - { RevolutionistLastTime.TryAdd(playerId, RevolutionistStart[playerId]); - } } else - { RevolutionistStart.TryAdd(playerId, Utils.TimeStamp); - } } } @@ -233,10 +229,7 @@ namespace EHR.Neutral CustomWinnerHolder.ResetAndSetWinner(CustomWinner.Revolutionist); Utils.GetDrawPlayerCount(physics.myPlayer.PlayerId, out List x); CustomWinnerHolder.WinnerIds.Add(physics.myPlayer.PlayerId); - foreach (PlayerControl apc in x) - { - CustomWinnerHolder.WinnerIds.Add(apc.PlayerId); - } + foreach (PlayerControl apc in x) CustomWinnerHolder.WinnerIds.Add(apc.PlayerId); } } } diff --git a/Roles/Neutral/Ritualist.cs b/Roles/Neutral/Ritualist.cs index 962c6dc28..0cbe1df7e 100644 --- a/Roles/Neutral/Ritualist.cs +++ b/Roles/Neutral/Ritualist.cs @@ -16,24 +16,24 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Ritualist); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ritualist]) .SetValueFormat(OptionFormat.Seconds); + RitualMaxCount = new IntegerOptionItem(Id + 11, "RitualMaxCount", new(0, 15, 1), 1, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ritualist]) .SetValueFormat(OptionFormat.Times); + CanVent = new BooleanOptionItem(Id + 12, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ritualist]); + HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Ritualist]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Neutral/Rogue.cs b/Roles/Neutral/Rogue.cs index 2bf1471ac..4b3dddc06 100644 --- a/Roles/Neutral/Rogue.cs +++ b/Roles/Neutral/Rogue.cs @@ -35,9 +35,11 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Rogue); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Rogue]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 3, "CanVent", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Rogue]); } @@ -105,10 +107,7 @@ namespace EHR.Neutral public override void OnMurder(PlayerControl killer, PlayerControl target) { - if (MeetingStates.FirstMeeting || CurrentTask.Data == null) - { - return; - } + if (MeetingStates.FirstMeeting || CurrentTask.Data == null) return; switch (CurrentTask.Objective) { @@ -117,10 +116,7 @@ namespace EHR.Neutral break; case Objective.KillXTimes: CurrentTask.Data = (int)CurrentTask.Data - 1; - if ((int)CurrentTask.Data <= 0) - { - SetTaskCompleted(); - } + if ((int)CurrentTask.Data <= 0) SetTaskCompleted(); break; case Objective.KillInSpecificRoom when Translator.GetString(target.GetPlainShipRoom().RoomId.ToString()) == (string)CurrentTask.Data: @@ -134,25 +130,16 @@ namespace EHR.Neutral if (CurrentTask.Objective == Objective.VentXTimes) { CurrentTask.Data = (int)CurrentTask.Data - 1; - if ((int)CurrentTask.Data <= 0) - { - SetTaskCompleted(); - } + if ((int)CurrentTask.Data <= 0) SetTaskCompleted(); } } public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive() || !GameStates.IsInTask) - { - return; - } + if (!pc.IsAlive() || !GameStates.IsInTask) return; Count++; - if (Count < 30) - { - return; - } + if (Count < 30) return; Count = 0; @@ -166,10 +153,7 @@ namespace EHR.Neutral Moving = Vector2.Distance(pc.Pos(), LastPos.Value) >= 0.1f; LastPos = pc.Pos(); - if (!Moving) - { - pc.Notify(Utils.ColorString(Color.red, "x")); - } + if (!Moving) pc.Notify(Utils.ColorString(Color.red, "x")); } if (MorphCooldown > 0) @@ -178,27 +162,18 @@ namespace EHR.Neutral Utils.SendRPC(CustomRPC.SyncRoleData, pc.PlayerId, 2, MorphCooldown); Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); - if (pc.IsShifted() && MorphCooldown <= Main.RealOptionsData.GetFloat(FloatOptionNames.KillCooldown)) - { - pc.RpcShapeshift(pc, !Options.DisableAllShapeshiftAnimations.GetBool()); - } + if (pc.IsShifted() && MorphCooldown <= Main.RealOptionsData.GetFloat(FloatOptionNames.KillCooldown)) pc.RpcShapeshift(pc, !Options.DisableAllShapeshiftAnimations.GetBool()); } } public void OnButtonPressed() { - if (CurrentTask.Objective == Objective.CallEmergencyMeeting) - { - SetTaskCompleted(true); - } + if (CurrentTask.Objective == Objective.CallEmergencyMeeting) SetTaskCompleted(true); } public void OnFixSabotage() { - if (CurrentTask.Objective == Objective.FixSabotage) - { - SetTaskCompleted(); - } + if (CurrentTask.Objective == Objective.FixSabotage) SetTaskCompleted(); } private void SetTaskCompleted(bool chatMessage = false) @@ -207,33 +182,23 @@ namespace EHR.Neutral SendRPC(); if (chatMessage) - { LateTask.New(() => Utils.SendMessage("\n", RoguePC.PlayerId, Translator.GetString("Rogue.TaskCompleted")), 8f, log: false); - } else - { Utils.NotifyRoles(SpecifySeer: RoguePC, SpecifyTarget: RoguePC); - } } public override void OnReportDeadBody() { DoCheck = false; - if (CurrentTask.Objective == Objective.DontStopWalking && Moving) - { - SetTaskCompleted(true); - } + if (CurrentTask.Objective == Objective.DontStopWalking && Moving) SetTaskCompleted(true); } public override void AfterMeetingTasks() { try { - if (AllTasksCompleted || !RoguePC.IsAlive()) - { - return; - } + if (AllTasksCompleted || !RoguePC.IsAlive()) return; if (CurrentTask.IsCompleted) { @@ -259,6 +224,7 @@ namespace EHR.Neutral Objective objective = Enum.GetValues().Except(GotObjectives).Shuffle()[0]; Reward reward = Enum.GetValues().Except(GotRewards).Shuffle()[0]; + object data = objective switch { Objective.KillInSpecificRoom => Translator.GetString(ShipStatus.Instance.AllRooms.RandomElement().RoomId.ToString()), @@ -316,10 +282,11 @@ namespace EHR.Neutral { if (reader.ReadPackedInt32() == 1) { - Objective objective = (Objective)reader.ReadPackedInt32(); - Reward reward = (Reward)reader.ReadPackedInt32(); + var objective = (Objective)reader.ReadPackedInt32(); + var reward = (Reward)reader.ReadPackedInt32(); bool isCompleted = reader.ReadBoolean(); AllTasksCompleted = reader.ReadBoolean(); + object data = reader.ReadPackedInt32() switch { 0 => reader.ReadString(), @@ -328,32 +295,23 @@ namespace EHR.Neutral 3 => null, _ => default }; + CurrentTask = (objective, reward, data, isCompleted); } else - { MorphCooldown = reader.ReadPackedInt32(); - } } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != RoguePC.PlayerId || seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud) || MeetingStates.FirstMeeting) - { - return string.Empty; - } + if (seer.PlayerId != RoguePC.PlayerId || seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud) || MeetingStates.FirstMeeting) return string.Empty; - if (AllTasksCompleted) - { - return Translator.GetString("Rogue.AllTasksCompleted"); - } + if (AllTasksCompleted) return Translator.GetString("Rogue.AllTasksCompleted"); - if (CurrentTask.IsCompleted) - { - return Translator.GetString("Rogue.TaskCompleted"); - } + if (CurrentTask.IsCompleted) return Translator.GetString("Rogue.TaskCompleted"); float d = Main.RealOptionsData.GetFloat(FloatOptionNames.KillCooldown); + string c = GotRewards.Contains(Reward.Morph) && MorphCooldown > 0 ? MorphCooldown <= d ? string.Format(Translator.GetString("CDPT"), MorphCooldown) + "\n" @@ -361,10 +319,7 @@ namespace EHR.Neutral : string.Empty; string o = Translator.GetString("Rogue.Objective." + CurrentTask.Objective); - if (CurrentTask.Objective is Objective.KillInSpecificRoom or Objective.VentXTimes or Objective.KillSpecificPlayer or Objective.KillXTimes) - { - o = string.Format(o, CurrentTask.Data is byte id ? Utils.ColorString(Main.PlayerColors.GetValueOrDefault(id, Color.white), Utils.GetPlayerById(id).GetRealName()) : CurrentTask.Data); - } + if (CurrentTask.Objective is Objective.KillInSpecificRoom or Objective.VentXTimes or Objective.KillSpecificPlayer or Objective.KillXTimes) o = string.Format(o, CurrentTask.Data is byte id ? Utils.ColorString(Main.PlayerColors.GetValueOrDefault(id, Color.white), Utils.GetPlayerById(id).GetRealName()) : CurrentTask.Data); string r = Translator.GetString("Rogue.Reward." + CurrentTask.Reward); string s = string.Format(Translator.GetString("Rogue.Task"), o, r); diff --git a/Roles/Neutral/Romantic.cs b/Roles/Neutral/Romantic.cs index f81ce8b39..2c1623397 100644 --- a/Roles/Neutral/Romantic.cs +++ b/Roles/Neutral/Romantic.cs @@ -51,37 +51,51 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupSingleRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Romantic); + BetCooldown = new FloatOptionItem(Id + 10, "RomanticBetCooldown", new(0f, 60f, 1f), 7f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]) .SetValueFormat(OptionFormat.Seconds); + ProtectCooldown = new FloatOptionItem(Id + 11, "RomanticProtectCooldown", new(0f, 60f, 2.5f), 25f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]) .SetValueFormat(OptionFormat.Seconds); + ProtectDuration = new FloatOptionItem(Id + 12, "RomanticProtectDuration", new(0f, 60f, 2.5f), 10f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]) .SetValueFormat(OptionFormat.Seconds); + KnowTargetRole = new BooleanOptionItem(Id + 13, "RomanticKnowTargetRole", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]); + BetTargetKnowRomantic = new BooleanOptionItem(Id + 14, "RomanticBetTargetKnowRomantic", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]); + RomanticGetsPartnerConvertedAddons = new BooleanOptionItem(Id + 15, "RomanticGetsPartnerConvertedAddons", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]); + Arrows = new BooleanOptionItem(Id + 16, "RomanticArrows", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]); + PartnerHasArrows = new BooleanOptionItem(Id + 17, "RomanticPartnerHasArrows", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]); + VengefulKCD = new FloatOptionItem(Id + 18, "VengefulKCD", new(0f, 60f, 2.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]) .SetValueFormat(OptionFormat.Seconds); + VengefulCanVent = new BooleanOptionItem(Id + 19, "VengefulCanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]); + VengefulHasImpVision = new BooleanOptionItem(Id + 20, "VengefulHasImpVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]); + RuthlessKCD = new FloatOptionItem(Id + 21, "RuthlessKCD", new(0f, 60f, 2.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]) .SetValueFormat(OptionFormat.Seconds); + RuthlessCanVent = new BooleanOptionItem(Id + 22, "RuthlessCanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]); + RuthlessHasImpVision = new BooleanOptionItem(Id + 23, "RuthlessHasImpVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Romantic]); } @@ -106,10 +120,7 @@ namespace EHR.Neutral private static void SendRPC() { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncRomanticTarget, SendOption.Reliable); writer.Write(PartnerId); @@ -127,41 +138,25 @@ namespace EHR.Neutral float beforeCD = Main.AllPlayerKillCooldown.GetValueOrDefault(RomanticId, 0f); if (HasPickedPartner) - { Main.AllPlayerKillCooldown[RomanticId] = ProtectCooldown.GetFloat(); - } else - { Main.AllPlayerKillCooldown[RomanticId] = BetCooldown.GetFloat(); - } - if (Math.Abs(beforeCD - Main.AllPlayerKillCooldown[RomanticId]) > 0.5f) - { - RomanticPC?.SyncSettings(); - } + if (Math.Abs(beforeCD - Main.AllPlayerKillCooldown[RomanticId]) > 0.5f) RomanticPC?.SyncSettings(); } public override bool KnowRole(PlayerControl player, PlayerControl target) { - if (base.KnowRole(player, target)) - { - return true; - } + if (base.KnowRole(player, target)) return true; - if (!KnowTargetRole.GetBool()) - { - return false; - } + if (!KnowTargetRole.GetBool()) return false; return (player.Is(CustomRoles.Romantic) && PartnerId == target.PlayerId) || (BetTargetKnowRomantic.GetBool() && target.Is(CustomRoles.Romantic) && player.PlayerId == PartnerId); } public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null || target == null || killer.PlayerId == target.PlayerId || killer.PlayerId != RomanticId) - { - return true; - } + if (killer == null || target == null || killer.PlayerId == target.PlayerId || killer.PlayerId != RomanticId) return true; if (!HasPickedPartner) { @@ -175,23 +170,14 @@ namespace EHR.Neutral RomanticPC.RPCPlayCustomSound("Bet"); RomanticPC.Notify(GetString("RomanticBetPlayer")); - if (BetTargetKnowRomantic.GetBool()) - { - target.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Romantic), GetString("RomanticBetOnYou"))); - } + if (BetTargetKnowRomantic.GetBool()) target.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Romantic), GetString("RomanticBetOnYou"))); - if (RomanticGetsPartnerConvertedAddons.GetBool() && Partner.IsConverted()) - { - Partner.GetCustomSubRoles().DoIf(x => x.IsConverted() && !RomanticPC.Is(x), x => RomanticPC.RpcSetCustomRole(x)); - } + if (RomanticGetsPartnerConvertedAddons.GetBool() && Partner.IsConverted()) Partner.GetCustomSubRoles().DoIf(x => x.IsConverted() && !RomanticPC.Is(x), x => RomanticPC.RpcSetCustomRole(x)); if (Arrows.GetBool()) { TargetArrow.Add(RomanticId, PartnerId); - if (PartnerHasArrows.GetBool() && BetTargetKnowRomantic.GetBool()) - { - TargetArrow.Add(PartnerId, RomanticId); - } + if (PartnerHasArrows.GetBool() && BetTargetKnowRomantic.GetBool()) TargetArrow.Add(PartnerId, RomanticId); } Logger.Info($"Partner picked: {RomanticPC.GetNameWithRole().RemoveHtmlTags()} => {target.GetNameWithRole().RemoveHtmlTags()}", "Romantic"); @@ -209,17 +195,11 @@ namespace EHR.Neutral LateTask.New(() => { - if (!Partner.IsAlive()) - { - return; - } + if (!Partner.IsAlive()) return; IsPartnerProtected = false; - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; RomanticPC.Notify(GetString("ProtectingOver")); Partner.Notify(GetString("ProtectingOver")); @@ -233,20 +213,14 @@ namespace EHR.Neutral public override void OnGlobalFixedUpdate(PlayerControl pc, bool lowLoad) { - if (!lowLoad && (Partner == null || Partner.Data == null || Partner.Data.Disconnected || !Partner.IsAlive()) && RomanticPC.IsAlive() && RomanticPC.Is(CustomRoles.Romantic)) - { - ChangeRole(); - } + if (!lowLoad && (Partner == null || Partner.Data == null || Partner.Data.Disconnected || !Partner.IsAlive()) && RomanticPC.IsAlive() && RomanticPC.Is(CustomRoles.Romantic)) ChangeRole(); } public static string TargetMark(PlayerControl seer, PlayerControl target) { if (!seer.Is(CustomRoles.Romantic)) { - if (!BetTargetKnowRomantic.GetBool()) - { - return string.Empty; - } + if (!BetTargetKnowRomantic.GetBool()) return string.Empty; return target.Is(CustomRoles.Romantic) && RomanticId == target.PlayerId && PartnerId == seer.PlayerId ? Utils.ColorString(Utils.GetRoleColor(CustomRoles.Romantic), "♥") @@ -260,27 +234,15 @@ namespace EHR.Neutral public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId) return string.Empty; - if (seer.PlayerId == PartnerId && HasPickedPartner) - { - return TargetArrow.GetArrows(seer, RomanticId); - } + if (seer.PlayerId == PartnerId && HasPickedPartner) return TargetArrow.GetArrows(seer, RomanticId); - if (seer.PlayerId != RomanticId || !seer.Is(CustomRoles.Romantic)) - { - return string.Empty; - } + if (seer.PlayerId != RomanticId || !seer.Is(CustomRoles.Romantic)) return string.Empty; Color color = !HasPickedPartner ? Color.white : Utils.GetRoleColor(CustomRoles.Romantic); string text = !HasPickedPartner ? "PICK PARTNER" : "♥"; - if (Arrows.GetBool()) - { - text += TargetArrow.GetArrows(seer, PartnerId); - } + if (Arrows.GetBool()) text += TargetArrow.GetArrows(seer, PartnerId); return Utils.ColorString(color, text); } @@ -302,20 +264,14 @@ namespace EHR.Neutral private static void ChangeRole() { - if (Partner == null || RomanticPC == null || !RomanticPC.Is(CustomRoles.Romantic)) - { - return; - } + if (Partner == null || RomanticPC == null || !RomanticPC.Is(CustomRoles.Romantic)) return; CustomRoles partnerRole = Partner.GetCustomRole(); PlayerControl killer = Partner.GetRealKiller(); if (killer?.PlayerId == RomanticId) // If the Romantic killed their Partner, they also die { - if (!RomanticPC.IsAlive()) - { - return; - } + if (!RomanticPC.IsAlive()) return; Logger.Info("Romantic killed their own Partner, Romantic suicides", "Romantic"); RomanticPC.Suicide(PlayerState.DeathReason.FollowingSuicide, Partner); @@ -330,10 +286,7 @@ namespace EHR.Neutral else if (ConvertingRolesAndAddons.TryGetValue(partnerRole, out CustomRoles convertedRole)) { RomanticPC.RpcSetCustomRole(convertedRole); - if (convertedRole.IsAdditionRole()) - { - RomanticPC.RpcSetCustomRole(CustomRoles.RuthlessRomantic); - } + if (convertedRole.IsAdditionRole()) RomanticPC.RpcSetCustomRole(CustomRoles.RuthlessRomantic); Logger.Info($"Converting Romantic Partner Died ({Partner.GetNameWithRole()}) => Romantic becomes their ally ({RomanticPC.GetNameWithRole()})", "Romantic"); } @@ -365,10 +318,7 @@ namespace EHR.Neutral VengefulRomantic.SendRPC(); } - if (RomanticGetsPartnerConvertedAddons.GetBool() && Partner.IsConverted()) - { - Partner.GetCustomSubRoles().DoIf(x => x.IsConverted() && !RomanticPC.Is(x), x => RomanticPC.RpcSetCustomRole(x)); - } + if (RomanticGetsPartnerConvertedAddons.GetBool() && Partner.IsConverted()) Partner.GetCustomSubRoles().DoIf(x => x.IsConverted() && !RomanticPC.Is(x), x => RomanticPC.RpcSetCustomRole(x)); RomanticPC.SetKillCooldown(); } @@ -388,9 +338,7 @@ namespace EHR.Neutral public override bool IsEnable => VengefulRomanticId != byte.MaxValue; - public override void SetupCustomOption() - { - } + public override void SetupCustomOption() { } public override void Init() { @@ -422,10 +370,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.PlayerId == target.PlayerId || killer.PlayerId != VengefulRomanticId || target.PlayerId == Target) - { - return true; - } + if (killer.PlayerId == target.PlayerId || killer.PlayerId != VengefulRomanticId || target.PlayerId == Target) return true; killer.Suicide(PlayerState.DeathReason.Misfire); return false; @@ -433,28 +378,19 @@ namespace EHR.Neutral public override void OnMurder(PlayerControl killer, PlayerControl target) { - if (target.PlayerId == Target) - { - HasKilledKiller = true; - } + if (target.PlayerId == Target) HasKilledKiller = true; } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != VengefulRomanticId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != VengefulRomanticId) return string.Empty; return seer == null ? string.Empty : Utils.ColorString(HasKilledKiller ? Color.green : Utils.GetRoleColor(CustomRoles.VengefulRomantic), $"{(HasKilledKiller ? "✓" : "☹")}"); } public static void SendRPC() { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncVengefulRomanticTarget, SendOption.Reliable); writer.Write(Target); @@ -484,9 +420,7 @@ namespace EHR.Neutral public override bool IsEnable => PlayerIdList.Count > 0; - public override void SetupCustomOption() - { - } + public override void SetupCustomOption() { } public override void Init() { diff --git a/Roles/Neutral/RouleteGrandeur.cs b/Roles/Neutral/RouleteGrandeur.cs index 174528134..1256b2008 100644 --- a/Roles/Neutral/RouleteGrandeur.cs +++ b/Roles/Neutral/RouleteGrandeur.cs @@ -29,11 +29,14 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.RouleteGrandeur); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.RouleteGrandeur]) .SetValueFormat(OptionFormat.Seconds); + HasImpostorVision = new BooleanOptionItem(Id + 3, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.RouleteGrandeur]); + KCDReduction = new FloatOptionItem(Id + 4, "KCDReduction", new(0f, 100f, 0.5f), 3.5f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.RouleteGrandeur]) .SetValueFormat(OptionFormat.Seconds); @@ -71,15 +74,9 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte id) { opt.SetVision(HasImpostorVision.GetBool()); - if (Options.UsePhantomBasis.GetBool() && Options.UsePhantomBasisForNKs.GetBool()) - { - AURoleOptions.PhantomCooldown = 1f; - } + if (Options.UsePhantomBasis.GetBool() && Options.UsePhantomBasisForNKs.GetBool()) AURoleOptions.PhantomCooldown = 1f; - if (Options.UseUnshiftTrigger.GetBool() && Options.UseUnshiftTriggerForNKs.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = 1f; - } + if (Options.UseUnshiftTrigger.GetBool() && Options.UseUnshiftTriggerForNKs.GetBool()) AURoleOptions.ShapeshifterCooldown = 1f; } public override void OnExitVent(PlayerControl pc, Vent vent) @@ -108,10 +105,7 @@ namespace EHR.Neutral public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) return true; Roll(shapeshifter); return false; @@ -120,10 +114,7 @@ namespace EHR.Neutral private void Roll(PlayerControl pc) { long now = Utils.TimeStamp; - if (now - LastRoll < 5) - { - return; - } + if (now - LastRoll < 5) return; LastRoll = now; Utils.SendRPC(CustomRPC.SyncRoleData, pc.PlayerId, 1, LastRoll); @@ -131,13 +122,14 @@ namespace EHR.Neutral string result = new(NoHitIcon, BulletCount); result = $"<#ffffff>{result}"; HashSet takenSlots = []; - for (int i = 0; i < Bullets; i++) + + for (var i = 0; i < Bullets; i++) { int slot; + do - { slot = IRandom.Instance.Next(BulletCount); - } while (!takenSlots.Add(slot)); + while (!takenSlots.Add(slot)); result = result.Remove(slot, 1).Insert(slot, HitIcon.ToString()); } @@ -149,6 +141,7 @@ namespace EHR.Neutral bool hit = icon == HitIcon; string str; + if (hit) { pc.Suicide(PlayerState.DeathReason.BadLuck); @@ -156,7 +149,7 @@ namespace EHR.Neutral } else { - float reduction = (float)Math.Round(Bullets * KCDReduction.GetFloat(), 1); + var reduction = (float)Math.Round(Bullets * KCDReduction.GetFloat(), 1); str = string.Format(Translator.GetString("RG.NoHit"), Bullets, reduction); KCD -= reduction; pc.ResetKillCooldown(); @@ -181,10 +174,7 @@ namespace EHR.Neutral public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != RouleteGrandeurId || meeting || (seer.IsModClient() && !hud) || (!hud && Utils.TimeStamp - LastRoll < 15)) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != RouleteGrandeurId || meeting || (seer.IsModClient() && !hud) || (!hud && Utils.TimeStamp - LastRoll < 15)) return string.Empty; return string.Format(Translator.GetString("RG.Suffix"), Bullets); } diff --git a/Roles/Neutral/Samurai.cs b/Roles/Neutral/Samurai.cs index b2ebf36d7..9c4c33eaf 100644 --- a/Roles/Neutral/Samurai.cs +++ b/Roles/Neutral/Samurai.cs @@ -26,19 +26,25 @@ namespace EHR.Neutral { const int id = 16880; SetupRoleOptions(id, TabGroup.NeutralRoles, CustomRoles.Samurai); + KillCooldown = new FloatOptionItem(id + 2, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Samurai]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(id + 3, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Samurai]); + HasImpostorVision = new BooleanOptionItem(id + 4, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Samurai]); + NearbyDuration = new FloatOptionItem(id + 5, "Samurai.NearbyDuration", new(0f, 30f, 0.5f), 3f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Samurai]) .SetValueFormat(OptionFormat.Seconds); + SuccessKCD = new FloatOptionItem(id + 6, "Samurai.SuccessKCD", new(0f, 180f, 0.5f), 17.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Samurai]) .SetValueFormat(OptionFormat.Seconds); + KillDelay = new FloatOptionItem(id + 7, "Samurai.KillDelay", new(0f, 60f, 0.5f), 5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Samurai]) .SetValueFormat(OptionFormat.Seconds); @@ -79,10 +85,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (Target.Id != byte.MaxValue) - { - return false; - } + if (Target.Id != byte.MaxValue) return false; Target = (target.PlayerId, Utils.TimeStamp); return false; @@ -90,40 +93,24 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask || ExileController.Instance != null) - { - return; - } + if (!GameStates.IsInTask || ExileController.Instance != null) return; long now = Utils.TimeStamp; foreach (KeyValuePair kvp in Delays) { PlayerControl player = Utils.GetPlayerById(kvp.Key); - if (player == null || !player.IsAlive()) - { - continue; - } + if (player == null || !player.IsAlive()) continue; if (kvp.Value + KillDelay.GetInt() <= now) - { if (pc.RpcCheckAndMurder(player, true)) - { player.Suicide(realKiller: pc); - } - } } - if (Target.Id == byte.MaxValue || !pc.IsAlive()) - { - return; - } + if (Target.Id == byte.MaxValue || !pc.IsAlive()) return; PlayerControl target = Utils.GetPlayerById(Target.Id); - if (target == null) - { - return; - } + if (target == null) return; if (Vector2.Distance(target.Pos(), pc.Pos()) > NormalGameOptionsV08.KillDistances[Mathf.Clamp(pc.Is(CustomRoles.Reach) ? 2 : Main.NormalOptions.KillDistance, 0, 2)] + 0.5f) { @@ -145,15 +132,9 @@ namespace EHR.Neutral foreach (byte id in Delays.Keys) { PlayerControl player = Utils.GetPlayerById(id); - if (player == null || !player.IsAlive()) - { - continue; - } + if (player == null || !player.IsAlive()) continue; - if (SamuraiPC.RpcCheckAndMurder(player, true)) - { - player.Suicide(realKiller: SamuraiPC); - } + if (SamuraiPC.RpcCheckAndMurder(player, true)) player.Suicide(realKiller: SamuraiPC); } Delays.Clear(); diff --git a/Roles/Neutral/SchrodingersCat.cs b/Roles/Neutral/SchrodingersCat.cs index 6c142168c..edd698a8a 100644 --- a/Roles/Neutral/SchrodingersCat.cs +++ b/Roles/Neutral/SchrodingersCat.cs @@ -11,6 +11,7 @@ { const int id = 13840; Options.SetupRoleOptions(id, TabGroup.NeutralRoles, CustomRoles.SchrodingersCat); + WinsWithCrewIfNotAttacked = new BooleanOptionItem(id + 2, "SchrodingersCat.WinsWithCrewIfNotAttacked", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.SchrodingersCat]); } @@ -28,20 +29,11 @@ public override bool OnCheckMurderAsTarget(PlayerControl killer, PlayerControl target) { CustomRoles killerRole = killer.GetCustomRole(); - if (killerRole.IsImpostor() || killerRole.IsMadmate()) - { - killerRole = CustomRoles.Refugee; - } + if (killerRole.IsImpostor() || killerRole.IsMadmate()) killerRole = CustomRoles.Refugee; - if (killerRole == CustomRoles.Jackal) - { - killerRole = CustomRoles.Sidekick; - } + if (killerRole == CustomRoles.Jackal) killerRole = CustomRoles.Sidekick; - if (Options.SingleRoles.Contains(killerRole)) - { - killerRole = CustomRoles.Amnesiac; - } + if (Options.SingleRoles.Contains(killerRole)) killerRole = CustomRoles.Amnesiac; target.RpcSetCustomRole(killerRole); target.RpcChangeRoleBasis(killerRole); diff --git a/Roles/Neutral/Shifter.cs b/Roles/Neutral/Shifter.cs index 11959db39..13aa3634d 100644 --- a/Roles/Neutral/Shifter.cs +++ b/Roles/Neutral/Shifter.cs @@ -22,21 +22,21 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Shifter); + KillCooldown = new FloatOptionItem(Id + 2, "AbilityCooldown", new(0f, 180f, 0.5f), 15f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Shifter]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 3, "CanVent", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Shifter]); + HasImpostorVision = new BooleanOptionItem(Id + 4, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Shifter]); } public override void Init() { - if (GameStates.InGame && !Main.HasJustStarted) - { - return; - } + if (GameStates.InGame && !Main.HasJustStarted) return; On = false; @@ -48,10 +48,7 @@ namespace EHR.Neutral On = true; PlayerControl pc = playerId.GetPlayer(); - if (pc == null) - { - return; - } + if (pc == null) return; pc.AddAbilityCD(); pc.ResetKillCooldown(); @@ -81,12 +78,10 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!base.OnCheckMurder(killer, target)) - { - return false; - } + if (!base.OnCheckMurder(killer, target)) return false; CustomRoles targetRole = target.GetCustomRole(); + switch (targetRole) { case CustomRoles.Enigma: @@ -112,10 +107,7 @@ namespace EHR.Neutral killer.SetAbilityUseLimit(target.GetAbilityUseLimit()); TaskState taskState = target.GetTaskState(); - if (taskState.HasTasks) - { - Main.PlayerStates[killer.PlayerId].TaskState = taskState; - } + if (taskState.HasTasks) Main.PlayerStates[killer.PlayerId].TaskState = taskState; killer.RemoveAbilityCD(); killer.SyncSettings(); diff --git a/Roles/Neutral/Simon.cs b/Roles/Neutral/Simon.cs index 0d82e8839..8b5f53c3f 100644 --- a/Roles/Neutral/Simon.cs +++ b/Roles/Neutral/Simon.cs @@ -34,9 +34,11 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Simon); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Simon]) .SetValueFormat(OptionFormat.Seconds); + HasImpostorVision = new BooleanOptionItem(Id + 4, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Simon]); } @@ -76,23 +78,14 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte id) { opt.SetVision(HasImpostorVision.GetBool()); - if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) - { - AURoleOptions.PhantomCooldown = 1f; - } + if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) AURoleOptions.PhantomCooldown = 1f; - if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = 1f; - } + if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) AURoleOptions.ShapeshifterCooldown = 1f; } public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!base.OnCheckMurder(killer, target)) - { - return false; - } + if (!base.OnCheckMurder(killer, target)) return false; return killer.CheckDoubleTrigger(target, () => { @@ -104,26 +97,18 @@ namespace EHR.Neutral public override void OnCoEnterVent(PlayerPhysics physics, int ventId) { - if (Executed || MarkedPlayers.Count == 0) - { - return; - } + if (Executed || MarkedPlayers.Count == 0) return; int size = MarkedPlayers.Count; MarkedPlayers.Where(x => x.Value.Instruction == Instruction.None).ToList().ForEach(x => MarkedPlayers.Remove(x.Key)); - if (size != MarkedPlayers.Count) - { - Utils.SendRPC(CustomRPC.SyncRoleData, physics.myPlayer.PlayerId, 2); - } + if (size != MarkedPlayers.Count) Utils.SendRPC(CustomRPC.SyncRoleData, physics.myPlayer.PlayerId, 2); Executed = true; + foreach (KeyValuePair kvp in MarkedPlayers) { PlayerControl pc = Utils.GetPlayerById(kvp.Key); - if (pc == null || !pc.IsAlive()) - { - continue; - } + if (pc == null || !pc.IsAlive()) continue; pc.Notify(Translator.GetString(GetNotify(kvp.Value.Instruction, kvp.Value.DoAction, false)), 300f); } @@ -135,10 +120,7 @@ namespace EHR.Neutral { if (!forSimon) { - if (instruction == Instruction.Kill) - { - return doAction ? "SimonKill" : "SimonDontKill"; - } + if (instruction == Instruction.Kill) return doAction ? "SimonKill" : "SimonDontKill"; return doAction ? "SimonTask" : "SimonDontTask"; } @@ -167,10 +149,7 @@ namespace EHR.Neutral public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; OnPet(shapeshifter); return false; @@ -181,18 +160,13 @@ namespace EHR.Neutral if (Executed) { Executed = false; + foreach (KeyValuePair kvp in MarkedPlayers) { - if (!kvp.Value.DoAction || kvp.Value.Instruction == Instruction.None) - { - continue; - } + if (!kvp.Value.DoAction || kvp.Value.Instruction == Instruction.None) continue; PlayerControl pc = Utils.GetPlayerById(kvp.Key); - if (pc == null || !pc.IsAlive()) - { - continue; - } + if (pc == null || !pc.IsAlive()) continue; pc.Suicide(); } @@ -226,26 +200,14 @@ namespace EHR.Neutral public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (Main.PlayerStates[seer.PlayerId].Role is not Simon simon) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not Simon simon) return string.Empty; bool self = seer.PlayerId == target.PlayerId; - if (seer.IsModClient() && !hud && self) - { - return string.Empty; - } + if (seer.IsModClient() && !hud && self) return string.Empty; - if (self) - { - return Translator.GetString(simon.DoMode ? "SimonDoMode" : "SimonDontMode"); - } + if (self) return Translator.GetString(simon.DoMode ? "SimonDoMode" : "SimonDontMode"); - if (simon.MarkedPlayers.TryGetValue(target.PlayerId, out (bool DoAction, Instruction Instruction) value)) - { - return Translator.GetString(GetNotify(value.Instruction, value.DoAction, true)); - } + if (simon.MarkedPlayers.TryGetValue(target.PlayerId, out (bool DoAction, Instruction Instruction) value)) return Translator.GetString(GetNotify(value.Instruction, value.DoAction, true)); return string.Empty; } @@ -254,26 +216,16 @@ namespace EHR.Neutral { foreach (Simon simon in Instances) { - if (!simon.Executed) - { - continue; - } + if (!simon.Executed) continue; if (simon.MarkedPlayers.TryGetValue(pc.PlayerId, out (bool DoAction, Instruction Instruction) value)) { - if (value.Instruction != instruction) - { - continue; - } + if (value.Instruction != instruction) continue; if (value.DoAction) - { pc.Notify(Utils.ColorString(Color.green, "\u2713")); - } else - { pc.Suicide(); - } simon.MarkedPlayers.Remove(pc.PlayerId); Utils.SendRPC(CustomRPC.SyncRoleData, simon.SimonId, 4, pc.PlayerId); diff --git a/Roles/Neutral/SoulHunter.cs b/Roles/Neutral/SoulHunter.cs index 90406a109..631207234 100644 --- a/Roles/Neutral/SoulHunter.cs +++ b/Roles/Neutral/SoulHunter.cs @@ -33,18 +33,24 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.SoulHunter); + CanVent = new BooleanOptionItem(Id + 3, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.SoulHunter]); + HasImpostorVision = new BooleanOptionItem(Id + 4, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.SoulHunter]); + NumOfSoulsToWin = new IntegerOptionItem(Id + 5, "SoulHunterNumOfSoulsToWin", new(1, 14, 1), 3, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.SoulHunter]); + WaitingTimeAfterMeeting = new IntegerOptionItem(Id + 6, "SoulHunterFreezeTimeAfterMeeting", new(0, 90, 1), 3, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.SoulHunter]) .SetValueFormat(OptionFormat.Seconds); + TimeToKillTarget = new IntegerOptionItem(Id + 7, "SoulHunterTimeToKillTarget", new(1, 90, 1), 30, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.SoulHunter]) .SetValueFormat(OptionFormat.Seconds); + GetSoulForSuicide = new BooleanOptionItem(Id + 8, "SoulHunterGetSoulForSuicide", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.SoulHunter]); } @@ -108,10 +114,7 @@ namespace EHR.Neutral public static void ReceiveRPC(MessageReader reader) { byte id = reader.ReadByte(); - if (Main.PlayerStates[id].Role is not SoulHunter sh) - { - return; - } + if (Main.PlayerStates[id].Role is not SoulHunter sh) return; sh.Souls = reader.ReadInt32(); sh.CurrentTarget.ID = reader.ReadByte(); @@ -121,10 +124,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (SoulHunter_ == null || target == null) - { - return false; - } + if (SoulHunter_ == null || target == null) return false; if (CurrentTarget.ID == byte.MaxValue || CurrentTarget.START_TIMESTAMP == 0) { @@ -161,10 +161,7 @@ namespace EHR.Neutral public override void AfterMeetingTasks() { - if (!IsEnable || CurrentTarget.ID == byte.MaxValue) - { - return; - } + if (!IsEnable || CurrentTarget.ID == byte.MaxValue) return; long now = TimeStamp; @@ -178,10 +175,7 @@ namespace EHR.Neutral PlayerControl target = GetPlayerById(CurrentTarget.ID); int waitingTime = WaitingTimeAfterMeeting.GetInt(); - if (!SoulHunter_.IsModClient()) - { - SoulHunter_.Notify(string.Format(GetString("SoulHunterNotifyFreeze"), target.GetRealName(), waitingTime + 1)); - } + if (!SoulHunter_.IsModClient()) SoulHunter_.Notify(string.Format(GetString("SoulHunterNotifyFreeze"), target.GetRealName(), waitingTime + 1)); target.Notify(string.Format(GetString("SoulHunterTargetNotify"), SoulHunter_.GetRealName()), 300f); LastUpdate = now; @@ -192,10 +186,7 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl pc) { - if (!IsEnable || !GameStates.IsInTask || !SoulHunter_.IsAlive() || CurrentTarget.ID == byte.MaxValue) - { - return; - } + if (!IsEnable || !GameStates.IsInTask || !SoulHunter_.IsAlive() || CurrentTarget.ID == byte.MaxValue) return; if (!CurrentTarget.FROZEN && Math.Abs(Main.AllPlayerSpeed[SoulHunterId] - NormalSpeed) > 0.1f) { @@ -203,16 +194,10 @@ namespace EHR.Neutral SoulHunter_.MarkDirtySettings(); } - if (CurrentTarget.START_TIMESTAMP == 0) - { - return; - } + if (CurrentTarget.START_TIMESTAMP == 0) return; long now = TimeStamp; - if (LastUpdate >= now) - { - return; - } + if (LastUpdate >= now) return; LastUpdate = now; @@ -230,10 +215,7 @@ namespace EHR.Neutral Main.AllPlayerSpeed[SoulHunterId] = NormalSpeed; SoulHunter_.MarkDirtySettings(); - if (GetSoulForSuicide.GetBool()) - { - Souls++; - } + if (GetSoulForSuicide.GetBool()) Souls++; SoulHunter_.Notify(GetString("SoulHunterNotifySuccess")); Logger.Info("Target Died/Disconnected", "SoulHunter"); @@ -253,10 +235,7 @@ namespace EHR.Neutral CurrentTarget.START_TIMESTAMP = now; SendRPC(); } - else if (!SoulHunter_.IsModClient()) - { - SoulHunter_.Notify(string.Format(GetString("SoulHunterNotifyFreeze"), targetName, waitingTime - (now - CurrentTarget.START_TIMESTAMP) + 1)); - } + else if (!SoulHunter_.IsModClient()) SoulHunter_.Notify(string.Format(GetString("SoulHunterNotifyFreeze"), targetName, waitingTime - (now - CurrentTarget.START_TIMESTAMP) + 1)); } else { @@ -268,34 +247,22 @@ namespace EHR.Neutral target.Notify(GetString("SoulHunterTargetNotifySurvived")); SendRPC(); } - else if (!SoulHunter_.IsModClient()) - { - SoulHunter_.Notify(string.Format(GetString("SoulHunterNotify"), timeToKill - (now - CurrentTarget.START_TIMESTAMP) + 1, targetName)); - } + else if (!SoulHunter_.IsModClient()) SoulHunter_.Notify(string.Format(GetString("SoulHunterNotify"), timeToKill - (now - CurrentTarget.START_TIMESTAMP) + 1, targetName)); } } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (!hud || Main.PlayerStates[seer.PlayerId].Role is not SoulHunter { IsEnable: true } sh) - { - return string.Empty; - } + if (!hud || Main.PlayerStates[seer.PlayerId].Role is not SoulHunter { IsEnable: true } sh) return string.Empty; - if (!sh.IsTargetBlocked) - { - return string.Empty; - } + if (!sh.IsTargetBlocked) return string.Empty; return sh.CurrentTarget.FROZEN ? string.Format(GetString("SoulHunterNotifyFreeze"), GetPlayerById(sh.CurrentTarget.ID).GetRealName(), WaitingTimeAfterMeeting.GetInt() - (TimeStamp - sh.CurrentTarget.START_TIMESTAMP) + 1) : string.Format(GetString("SoulHunterNotify"), TimeToKillTarget.GetInt() - (TimeStamp - sh.CurrentTarget.START_TIMESTAMP) + 1, GetPlayerById(sh.CurrentTarget.ID).GetRealName()); } public override string GetProgressText(byte id, bool comms) { - if (Main.PlayerStates[id].Role is not SoulHunter { IsEnable: true } sh) - { - return string.Empty; - } + if (Main.PlayerStates[id].Role is not SoulHunter { IsEnable: true } sh) return string.Empty; int souldsNeeded = NumOfSoulsToWin.GetInt(); return $"<#777777>- <#{(sh.Souls >= souldsNeeded ? "00ff00" : "ffffff")}>{sh.Souls}/{souldsNeeded}"; diff --git a/Roles/Neutral/Spiritcaller.cs b/Roles/Neutral/Spiritcaller.cs index 990caac3c..bece78d45 100644 --- a/Roles/Neutral/Spiritcaller.cs +++ b/Roles/Neutral/Spiritcaller.cs @@ -30,28 +30,37 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupSingleRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Spiritcaller); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 60f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spiritcaller]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 11, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spiritcaller]); + ImpostorVision = new BooleanOptionItem(Id + 12, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spiritcaller]); + SpiritMax = new IntegerOptionItem(Id + 13, "SpiritcallerSpiritMax", new(1, 15, 1), 2, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spiritcaller]) .SetValueFormat(OptionFormat.Times); + SpiritAbilityCooldown = new FloatOptionItem(Id + 14, "SpiritcallerSpiritAbilityCooldown", new(5f, 90f, 1f), 30f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spiritcaller]) .SetValueFormat(OptionFormat.Seconds); + SpiritFreezeTime = new FloatOptionItem(Id + 15, "SpiritcallerFreezeTime", new(0f, 30f, 1f), 3f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spiritcaller]) .SetValueFormat(OptionFormat.Seconds); + SpiritProtectTime = new FloatOptionItem(Id + 16, "SpiritcallerProtectTime", new(0f, 30f, 1f), 5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spiritcaller]) .SetValueFormat(OptionFormat.Seconds); + SpiritCauseVision = new FloatOptionItem(Id + 17, "SpiritcallerCauseVision", new(0f, 5f, 0.05f), 0.4f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spiritcaller]) .SetValueFormat(OptionFormat.Multiplier); + SpiritCauseVisionTime = new FloatOptionItem(Id + 18, "SpiritcallerCauseVisionTime", new(0f, 45f, 1f), 10f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Spiritcaller]) .SetValueFormat(OptionFormat.Seconds); @@ -93,10 +102,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.GetAbilityUseLimit() < 1) - { - return true; - } + if (killer.GetAbilityUseLimit() < 1) return true; if (!target.GetCustomRole().IsAbleToBeSidekicked() && !target.GetCustomRole().IsImpostor()) { @@ -104,19 +110,23 @@ namespace EHR.Neutral target.RpcSetCustomRole(CustomRoles.EvilSpirit); - CustomRpcSender writer = CustomRpcSender.Create("SpiritCallerSendMessage"); + var writer = CustomRpcSender.Create("SpiritCallerSendMessage"); writer.StartMessage(target.GetClientId()); + writer.StartRpc(target.NetId, (byte)RpcCalls.SetName) .Write(target.Data.NetId) .Write(GetString("SpiritcallerNoticeTitle")) .EndRpc(); + writer.StartRpc(target.NetId, (byte)RpcCalls.SendChat) .Write(GetString("SpiritcallerNoticeMessage")) .EndRpc(); + writer.StartRpc(target.NetId, (byte)RpcCalls.SetName) .Write(target.Data.NetId) .Write(target.Data.PlayerName) .EndRpc(); + writer.EndMessage(); writer.SendMessage(); } @@ -126,17 +136,11 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask) - { - return; - } + if (!GameStates.IsInTask) return; if (pc.Is(CustomRoles.Spiritcaller)) { - if (ProtectTimeStamp < Utils.TimeStamp && ProtectTimeStamp != 0) - { - ProtectTimeStamp = 0; - } + if (ProtectTimeStamp < Utils.TimeStamp && ProtectTimeStamp != 0) ProtectTimeStamp = 0; } else if (PlayersHaunted.ContainsKey(pc.PlayerId) && PlayersHaunted[pc.PlayerId] < Utils.TimeStamp) { @@ -147,10 +151,7 @@ namespace EHR.Neutral public static void HauntPlayer(PlayerControl target) { - if (SpiritCauseVisionTime.GetFloat() > 0 || SpiritFreezeTime.GetFloat() > 0) - { - target.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Spiritcaller), GetString("HauntedByEvilSpirit"))); - } + if (SpiritCauseVisionTime.GetFloat() > 0 || SpiritFreezeTime.GetFloat() > 0) target.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Spiritcaller), GetString("HauntedByEvilSpirit"))); if (SpiritCauseVisionTime.GetFloat() > 0 && !PlayersHaunted.ContainsKey(target.PlayerId)) { @@ -164,6 +165,7 @@ namespace EHR.Neutral Main.AllPlayerSpeed[target.PlayerId] = Main.MinSpeed; ReportDeadBodyPatch.CanReport[target.PlayerId] = false; target.MarkDirtySettings(); + LateTask.New(() => { Main.AllPlayerSpeed[target.PlayerId] = Main.AllPlayerSpeed[target.PlayerId] - Main.MinSpeed + tmpSpeed; diff --git a/Roles/Neutral/Sprayer.cs b/Roles/Neutral/Sprayer.cs index d492581f9..275b0555d 100644 --- a/Roles/Neutral/Sprayer.cs +++ b/Roles/Neutral/Sprayer.cs @@ -34,28 +34,37 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Sprayer); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sprayer]) .SetValueFormat(OptionFormat.Seconds); + HasImpostorVision = new BooleanOptionItem(Id + 3, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sprayer]); + CanVent = new BooleanOptionItem(Id + 4, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sprayer]); + CD = new IntegerOptionItem(Id + 5, "AbilityCooldown", new(0, 90, 1), 15, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sprayer]) .SetValueFormat(OptionFormat.Seconds); + UseLimitOpt = new IntegerOptionItem(Id + 6, "AbilityUseLimit", new(1, 90, 1), 5, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sprayer]) .SetValueFormat(OptionFormat.Times); + LoweredVision = new FloatOptionItem(Id + 7, "FFA_LowerVision", new(0.05f, 1.5f, 0.05f), 0.25f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sprayer]) .SetValueFormat(OptionFormat.Multiplier); + LoweredSpeed = new FloatOptionItem(Id + 8, "FFA_DecreasedSpeed", new(0.05f, 3f, 0.05f), 0.8f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sprayer]) .SetValueFormat(OptionFormat.Multiplier); + EffectDuration = new IntegerOptionItem(Id + 10, "NegativeEffectDuration", new(1, 90, 1), 10, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sprayer]) .SetValueFormat(OptionFormat.Seconds); + MaxTrappedTimes = new IntegerOptionItem(Id + 9, "SprayerMaxTrappedTimes", new(1, 90, 1), 3, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sprayer]) .SetValueFormat(OptionFormat.Times); @@ -75,10 +84,7 @@ namespace EHR.Neutral SprayerId = playerId; playerId.SetAbilityUseLimit(UseLimitOpt.GetInt()); - foreach (PlayerControl pc in Main.AllAlivePlayerControls) - { - TrappedCount[pc.PlayerId] = 0; - } + foreach (PlayerControl pc in Main.AllAlivePlayerControls) TrappedCount[pc.PlayerId] = 0; } public override void SetKillCooldown(byte id) @@ -99,15 +105,9 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte id) { opt.SetVision(HasImpostorVision.GetBool()); - if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) - { - AURoleOptions.PhantomCooldown = CD.GetInt(); - } + if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) AURoleOptions.PhantomCooldown = CD.GetInt(); - if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = CD.GetInt(); - } + if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) AURoleOptions.ShapeshifterCooldown = CD.GetInt(); } public override bool OnSabotage(PlayerControl pc) @@ -129,10 +129,7 @@ namespace EHR.Neutral public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; PlaceTrap(); return false; @@ -140,42 +137,27 @@ namespace EHR.Neutral private void PlaceTrap() { - if (!IsEnable || SprayerId.GetAbilityUseLimit() <= 0 || SprayerPC.HasAbilityCD()) - { - return; - } + if (!IsEnable || SprayerId.GetAbilityUseLimit() <= 0 || SprayerPC.HasAbilityCD()) return; Vector2 pos = SprayerPC.Pos(); Traps[pos] = new(pos, [SprayerId]); SprayerPC.RpcRemoveAbilityUse(); - if (SprayerId.GetAbilityUseLimit() > 0) - { - SprayerPC.AddAbilityCD(CD.GetInt()); - } + if (SprayerId.GetAbilityUseLimit() > 0) SprayerPC.AddAbilityCD(CD.GetInt()); SprayerPC.Notify(GetString("SprayerNotify")); } public override void OnCheckPlayerPosition(PlayerControl pc) { - if (!IsEnable || !GameStates.IsInTask || Traps.Count == 0) - { - return; - } + if (!IsEnable || !GameStates.IsInTask || Traps.Count == 0) return; long now = TimeStamp; - if (pc.PlayerId == SprayerId) - { - return; - } + if (pc.PlayerId == SprayerId) return; LastUpdate.TryAdd(pc.PlayerId, now); - if (LastUpdate[pc.PlayerId] + 3 > now) - { - return; - } + if (LastUpdate[pc.PlayerId] + 3 > now) return; LastUpdate[pc.PlayerId] = now; @@ -188,6 +170,7 @@ namespace EHR.Neutral Main.AllPlayerSpeed[playerId] = LoweredSpeed.GetFloat(); LowerVisionList.Add(playerId); TrappedCount[playerId]++; + if (TrappedCount[playerId] > MaxTrappedTimes.GetInt()) { pc.Suicide(realKiller: SprayerPC); @@ -196,14 +179,12 @@ namespace EHR.Neutral else { pc.MarkDirtySettings(); + LateTask.New(() => { Main.AllPlayerSpeed[playerId] = tempSpeed; LowerVisionList.Remove(playerId); - if (GameStates.IsInTask) - { - pc.MarkDirtySettings(); - } + if (GameStates.IsInTask) pc.MarkDirtySettings(); }, EffectDuration.GetFloat(), "Sprayer Revert Effects"); } } @@ -218,10 +199,7 @@ namespace EHR.Neutral public override void AfterMeetingTasks() { - if (SprayerId.GetAbilityUseLimit() > 0) - { - SprayerPC.AddAbilityCD(Math.Max(15, CD.GetInt())); - } + if (SprayerId.GetAbilityUseLimit() > 0) SprayerPC.AddAbilityCD(Math.Max(15, CD.GetInt())); } } } \ No newline at end of file diff --git a/Roles/Neutral/Succubus.cs b/Roles/Neutral/Succubus.cs index 8868d5009..6d2440ba1 100644 --- a/Roles/Neutral/Succubus.cs +++ b/Roles/Neutral/Succubus.cs @@ -32,23 +32,31 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupSingleRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Succubus); + CharmCooldown = new FloatOptionItem(Id + 10, "SuccubusCharmCooldown", new(0f, 60f, 0.5f), 30f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Succubus]) .SetValueFormat(OptionFormat.Seconds); + CharmCooldownIncrese = new FloatOptionItem(Id + 11, "SuccubusCharmCooldownIncrese", new(0f, 180f, 0.5f), 10f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Succubus]) .SetValueFormat(OptionFormat.Seconds); + CharmMax = new IntegerOptionItem(Id + 12, "SuccubusCharmMax", new(1, 15, 1), 15, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Succubus]) .SetValueFormat(OptionFormat.Times); + KnowTargetRole = new BooleanOptionItem(Id + 13, "SuccubusKnowTargetRole", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Succubus]); + TargetKnowOtherTarget = new BooleanOptionItem(Id + 14, "SuccubusTargetKnowOtherTarget", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Succubus]); + CharmedCountMode = new StringOptionItem(Id + 15, "CharmedCountMode", CharmedCountModeStrings, 0, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Succubus]); + CanCharmNeutral = new BooleanOptionItem(Id + 16, "SuccubusCanCharmNeutral", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Succubus]); + CharmedDiesOnSuccubusDeath = new BooleanOptionItem(Id + 17, "CharmedDiesOnSuccubusDeath", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Succubus]); } @@ -86,10 +94,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.GetAbilityUseLimit() < 1) - { - return false; - } + if (killer.GetAbilityUseLimit() < 1) return false; if (CanBeCharmed(target)) { @@ -119,20 +124,11 @@ namespace EHR.Neutral public override bool KnowRole(PlayerControl player, PlayerControl target) { - if (base.KnowRole(player, target)) - { - return true; - } + if (base.KnowRole(player, target)) return true; - if (player.Is(CustomRoles.Charmed) && target.Is(CustomRoles.Succubus)) - { - return true; - } + if (player.Is(CustomRoles.Charmed) && target.Is(CustomRoles.Succubus)) return true; - if (KnowTargetRole.GetBool() && player.Is(CustomRoles.Succubus) && target.Is(CustomRoles.Charmed)) - { - return true; - } + if (KnowTargetRole.GetBool() && player.Is(CustomRoles.Succubus) && target.Is(CustomRoles.Charmed)) return true; return TargetKnowOtherTarget.GetBool() && player.Is(CustomRoles.Charmed) && target.Is(CustomRoles.Charmed); } @@ -145,20 +141,11 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl pc) { - if (!CharmedDiesOnSuccubusDeath.GetBool() || !GameStates.IsInTask || !IsEnable) - { - return; - } + if (!CharmedDiesOnSuccubusDeath.GetBool() || !GameStates.IsInTask || !IsEnable) return; - if (pc == null || pc.IsAlive()) - { - return; - } + if (pc == null || pc.IsAlive()) return; - foreach (PlayerControl charmed in Main.AllAlivePlayerControls.Where(x => x.Is(CustomRoles.Charmed))) - { - charmed.Suicide(realKiller: pc); - } + foreach (PlayerControl charmed in Main.AllAlivePlayerControls.Where(x => x.Is(CustomRoles.Charmed))) charmed.Suicide(realKiller: pc); } public override void SetButtonTexts(HudManager hud, byte id) diff --git a/Roles/Neutral/Sunnyboy.cs b/Roles/Neutral/Sunnyboy.cs index ae05d8285..710fa9fa0 100644 --- a/Roles/Neutral/Sunnyboy.cs +++ b/Roles/Neutral/Sunnyboy.cs @@ -7,9 +7,7 @@ namespace EHR.Neutral public static bool On; public override bool IsEnable => On; - public override void SetupCustomOption() - { - } + public override void SetupCustomOption() { } public override void Add(byte playerId) { diff --git a/Roles/Neutral/Tank.cs b/Roles/Neutral/Tank.cs index f844938d6..c3bec2fdd 100644 --- a/Roles/Neutral/Tank.cs +++ b/Roles/Neutral/Tank.cs @@ -32,10 +32,7 @@ namespace EHR.Neutral public override void Init() { On = false; - if (ShipStatus.Instance == null) - { - return; - } + if (ShipStatus.Instance == null) return; AllVents = ShipStatus.Instance.AllVents.Select(x => x.Id).ToHashSet(); } @@ -67,21 +64,15 @@ namespace EHR.Neutral public override string GetProgressText(byte playerId, bool comms) { - string progress = $"{Utils.ColorString(Utils.GetRoleColor(CustomRoles.Tank), $"{EnteredVents.Count}")}/{AllVents.Count}"; - if (IsWon) - { - progress = $"<#00ff00>{progress}"; - } + var progress = $"{Utils.ColorString(Utils.GetRoleColor(CustomRoles.Tank), $"{EnteredVents.Count}")}/{AllVents.Count}"; + if (IsWon) progress = $"<#00ff00>{progress}"; return base.GetProgressText(playerId, comms) + progress; } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId || seer.PlayerId != TankId || meeting || (seer.IsModClient() && !hud) || IsWon) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId || seer.PlayerId != TankId || meeting || (seer.IsModClient() && !hud) || IsWon) return string.Empty; string randomVentName = ShipStatus.Instance?.AllVents?.FirstOrDefault(x => x.Id == AllVents.Except(EnteredVents).FirstOrDefault())?.name ?? string.Empty; return randomVentName == string.Empty ? string.Empty : string.Format(Translator.GetString("Tank.Suffix"), randomVentName); diff --git a/Roles/Neutral/Technician.cs b/Roles/Neutral/Technician.cs index e86c0ea40..0792c9f26 100644 --- a/Roles/Neutral/Technician.cs +++ b/Roles/Neutral/Technician.cs @@ -32,11 +32,13 @@ namespace EHR.Neutral .AutoSetupOption(ref VentCooldown, 30f, new FloatValueRule(0f, 120f, 0.5f), OptionFormat.Seconds, overrideParent: CanVent) .AutoSetupOption(ref MaxInVentTime, 5f, new FloatValueRule(0f, 120f, 0.5f), OptionFormat.Seconds, overrideParent: CanVent); - int i = 0; + var i = 0; + foreach (SystemTypes system in new[] { SystemTypes.Electrical, SystemTypes.Comms, SystemTypes.LifeSupp, SystemTypes.Reactor }) { PointGains[system] = new IntegerOptionItem(646960 + i, $"Technician.PointGain.{system}", new(0, 10, 1), 1, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Technician]); + i++; } } @@ -94,6 +96,7 @@ namespace EHR.Neutral { SystemTypes actualSystemType = GetActualSystemType(systemType); TechnicianPC.RpcIncreaseAbilityUseLimitBy(PointGains[actualSystemType].GetInt()); + if (TechnicianPC.GetAbilityUseLimit() >= RequiredPoints.GetInt()) { if (WinsAlone.GetBool()) @@ -102,28 +105,17 @@ namespace EHR.Neutral CustomWinnerHolder.WinnerIds.Add(TechnicianPC.PlayerId); } else - { IsWon = true; - } } } public static void RepairSystem(byte playerId, SystemTypes systemType, byte amount) { - if (Main.PlayerStates[playerId].IsDead) - { - return; - } + if (Main.PlayerStates[playerId].IsDead) return; - if (Main.PlayerStates[playerId].Role is not Technician technician) - { - return; - } + if (Main.PlayerStates[playerId].Role is not Technician technician) return; - if (!GetsAnyPoint(systemType) || technician.IsWon || technician.Ignore) - { - return; - } + if (!GetsAnyPoint(systemType) || technician.IsWon || technician.Ignore) return; switch (systemType) { @@ -140,11 +132,8 @@ namespace EHR.Neutral } case SystemTypes.HeliSabotage: { - HeliSabotageSystem.Tags tags = (HeliSabotageSystem.Tags)(amount & HeliSabotageSystem.TagMask); - if (tags == HeliSabotageSystem.Tags.ActiveBit) - { - technician.FixedSabotage = false; - } + var tags = (HeliSabotageSystem.Tags)(amount & HeliSabotageSystem.TagMask); + if (tags == HeliSabotageSystem.Tags.ActiveBit) technician.FixedSabotage = false; if (!technician.FixedSabotage && tags == HeliSabotageSystem.Tags.FixBit) { @@ -171,11 +160,8 @@ namespace EHR.Neutral { if (Main.CurrentMap is MapNames.Mira or MapNames.Fungle) { - HqHudSystemType.Tags tags = (HqHudSystemType.Tags)(amount & HqHudSystemType.TagMask); - if (tags == HqHudSystemType.Tags.ActiveBit) - { - technician.FixedSabotage = false; - } + var tags = (HqHudSystemType.Tags)(amount & HqHudSystemType.TagMask); + if (tags == HqHudSystemType.Tags.ActiveBit) technician.FixedSabotage = false; if (!technician.FixedSabotage && tags == HqHudSystemType.Tags.FixBit) { @@ -186,10 +172,7 @@ namespace EHR.Neutral technician.IncreasePoints(systemType); } } - else if (amount == 0) - { - technician.IncreasePoints(systemType); - } + else if (amount == 0) technician.IncreasePoints(systemType); break; } @@ -198,20 +181,11 @@ namespace EHR.Neutral public static void SwitchSystemRepair(byte playerId, SwitchSystem switchSystem, byte amount) { - if (Main.PlayerStates[playerId].IsDead) - { - return; - } + if (Main.PlayerStates[playerId].IsDead) return; - if (!GetsAnyPoint(SystemTypes.Electrical) || Main.PlayerStates[playerId].Role is not Technician technician) - { - return; - } + if (!GetsAnyPoint(SystemTypes.Electrical) || Main.PlayerStates[playerId].Role is not Technician technician) return; - if (amount.HasBit(SwitchSystem.DamageSystem)) - { - return; - } + if (amount.HasBit(SwitchSystem.DamageSystem)) return; int fixbit = 1 << amount; switchSystem.ActualSwitches = (byte)(switchSystem.ExpectedSwitches ^ fixbit); @@ -221,7 +195,7 @@ namespace EHR.Neutral public override string GetProgressText(byte playerId, bool comms) { - int points = (int)Math.Round(playerId.GetAbilityUseLimit()); + var points = (int)Math.Round(playerId.GetAbilityUseLimit()); int needed = RequiredPoints.GetInt(); Color color = points >= needed ? Color.green : Color.white; return Utils.ColorString(color, $"{points}/{needed}"); diff --git a/Roles/Neutral/Terrorist.cs b/Roles/Neutral/Terrorist.cs index 4a8573227..8baf278d9 100644 --- a/Roles/Neutral/Terrorist.cs +++ b/Roles/Neutral/Terrorist.cs @@ -9,19 +9,18 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(11500, TabGroup.NeutralRoles, CustomRoles.Terrorist); + CanTerroristSuicideWin = new BooleanOptionItem(11510, "CanTerroristSuicideWin", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Terrorist]); + TerroristCanGuess = new BooleanOptionItem(11511, "CanGuess", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Terrorist]); + OverrideTasksData.Create(11512, TabGroup.NeutralRoles, CustomRoles.Terrorist); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/Neutral/Tiger.cs b/Roles/Neutral/Tiger.cs index fb07bf668..fd0b3cb39 100644 --- a/Roles/Neutral/Tiger.cs +++ b/Roles/Neutral/Tiger.cs @@ -26,18 +26,23 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Tiger); + Radius = new FloatOptionItem(Id + 2, "TigerRadius", new(0.5f, 10f, 0.5f), 3f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Tiger]) .SetValueFormat(OptionFormat.Multiplier); + EnrageCooldown = new FloatOptionItem(Id + 3, "EnrageCooldown", new(0f, 60f, 0.5f), 30f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Tiger]) .SetValueFormat(OptionFormat.Seconds); + EnrageDuration = new FloatOptionItem(Id + 4, "EnrageDuration", new(1f, 30f, 1f), 10f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Tiger]) .SetValueFormat(OptionFormat.Seconds); + KillCooldown = new FloatOptionItem(Id + 5, "KillCooldown", new(0f, 60f, 0.5f), 30f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Tiger]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 6, "CanVent", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Tiger]); } @@ -71,15 +76,9 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte playerId) { - if (Options.UsePhantomBasis.GetBool() && Options.UsePhantomBasisForNKs.GetBool()) - { - AURoleOptions.PhantomCooldown = EnrageCooldown.GetFloat() + EnrageDuration.GetFloat(); - } + if (Options.UsePhantomBasis.GetBool() && Options.UsePhantomBasisForNKs.GetBool()) AURoleOptions.PhantomCooldown = EnrageCooldown.GetFloat() + EnrageDuration.GetFloat(); - if (Options.UseUnshiftTrigger.GetBool() && Options.UseUnshiftTriggerForNKs.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = EnrageCooldown.GetFloat() + EnrageDuration.GetFloat(); - } + if (Options.UseUnshiftTrigger.GetBool() && Options.UseUnshiftTriggerForNKs.GetBool()) AURoleOptions.ShapeshifterCooldown = EnrageCooldown.GetFloat() + EnrageDuration.GetFloat(); } public override bool OnSabotage(PlayerControl pc) @@ -111,10 +110,7 @@ namespace EHR.Neutral public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !Options.UseUnshiftTrigger.GetBool()) return true; if (CooldownTimer <= 0f) { @@ -132,23 +128,14 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl pc) { - if (CooldownTimer > 0f) - { - CooldownTimer -= Time.fixedDeltaTime; - } + if (CooldownTimer > 0f) CooldownTimer -= Time.fixedDeltaTime; - if (float.IsNaN(EnrageTimer)) - { - return; - } + if (float.IsNaN(EnrageTimer)) return; EnrageTimer -= Time.fixedDeltaTime; Count++; - if (Count < 10) - { - return; - } + if (Count < 10) return; Count = 0; @@ -168,39 +155,21 @@ namespace EHR.Neutral public override void OnMurder(PlayerControl killer, PlayerControl target) { - if (float.IsNaN(EnrageTimer)) - { - return; - } + if (float.IsNaN(EnrageTimer)) return; PlayerControl victim = Main.AllAlivePlayerControls.Where(x => x.PlayerId != killer.PlayerId && x.PlayerId != target.PlayerId).MinBy(x => Vector2.Distance(killer.Pos(), x.Pos())); - if (victim == null || Vector2.Distance(killer.Pos(), victim.Pos()) > Radius.GetFloat()) - { - return; - } + if (victim == null || Vector2.Distance(killer.Pos(), victim.Pos()) > Radius.GetFloat()) return; - if (killer.RpcCheckAndMurder(victim, true)) - { - victim.Suicide(realKiller: killer); - } + if (killer.RpcCheckAndMurder(victim, true)) victim.Suicide(realKiller: killer); } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (seer.PlayerId != target.PlayerId) return string.Empty; - if (Main.PlayerStates[seer.PlayerId].Role is not Tiger { IsEnable: true } tg) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not Tiger { IsEnable: true } tg) return string.Empty; - if (float.IsNaN(tg.EnrageTimer)) - { - return string.Empty; - } + if (float.IsNaN(tg.EnrageTimer)) return string.Empty; return tg.EnrageTimer > 5 ? "\u25a9" : $"\u25a9 ({(int)(tg.EnrageTimer + 1)}s)"; } diff --git a/Roles/Neutral/Totocalcio.cs b/Roles/Neutral/Totocalcio.cs index 15aff189e..1d52bc850 100644 --- a/Roles/Neutral/Totocalcio.cs +++ b/Roles/Neutral/Totocalcio.cs @@ -29,20 +29,26 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Totocalcio); + MaxBetTimes = new IntegerOptionItem(Id + 10, "TotocalcioMaxBetTimes", new(1, 5, 1), 3, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Totocalcio]) .SetValueFormat(OptionFormat.Times); + BetCooldown = new FloatOptionItem(Id + 12, "TotocalcioBetCooldown", new(0f, 60f, 0.5f), 10f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Totocalcio]) .SetValueFormat(OptionFormat.Seconds); + BetCooldownIncrese = new FloatOptionItem(Id + 14, "TotocalcioBetCooldownIncrese", new(0f, 60f, 1f), 10f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Totocalcio]) .SetValueFormat(OptionFormat.Seconds); + MaxBetCooldown = new FloatOptionItem(Id + 16, "TotocalcioMaxBetCooldown", new(0f, 180f, 0.5f), 70f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Totocalcio]) .SetValueFormat(OptionFormat.Seconds); + KnowTargetRole = new BooleanOptionItem(Id + 18, "TotocalcioKnowTargetRole", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Totocalcio]); + BetTargetKnowTotocalcio = new BooleanOptionItem(Id + 20, "TotocalcioBetTargetKnowTotocalcio", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Totocalcio]); } @@ -63,10 +69,7 @@ namespace EHR.Neutral private void SendRPC(byte playerId) { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SyncTotocalcioTargetAndTimes, SendOption.Reliable); writer.Write(playerId); @@ -78,18 +81,12 @@ namespace EHR.Neutral public static void ReceiveRPC(MessageReader reader) { byte PlayerId = reader.ReadByte(); - if (Main.PlayerStates[PlayerId].Role is not Totocalcio tc) - { - return; - } + if (Main.PlayerStates[PlayerId].Role is not Totocalcio tc) return; int Times = reader.ReadInt32(); byte Target = reader.ReadByte(); tc.BetTimes = Times; - if (Target != byte.MaxValue) - { - tc.BetPlayer = Target; - } + if (Target != byte.MaxValue) tc.BetPlayer = Target; } public override bool CanUseKillButton(PlayerControl player) @@ -118,38 +115,24 @@ namespace EHR.Neutral public override bool KnowRole(PlayerControl player, PlayerControl target) { - if (base.KnowRole(player, target)) - { - return true; - } + if (base.KnowRole(player, target)) return true; - if (!KnowTargetRole.GetBool()) - { - return false; - } + if (!KnowTargetRole.GetBool()) return false; return player.Is(CustomRoles.Totocalcio) && BetPlayer == target.PlayerId; } public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer.PlayerId == target.PlayerId) - { - return true; - } + if (killer.PlayerId == target.PlayerId) return true; - if (BetPlayer == target.PlayerId) - { - return false; - } + if (BetPlayer == target.PlayerId) return false; - if (BetTimes < 1) - { - return false; - } + if (BetTimes < 1) return false; BetTimes--; PlayerControl betPlayer = Utils.GetPlayerById(BetPlayer); + if (betPlayer != null) { Utils.NotifyRoles(SpecifySeer: killer, SpecifyTarget: betPlayer, ForceLoop: true); @@ -164,10 +147,7 @@ namespace EHR.Neutral killer.RPCPlayCustomSound("Bet"); killer.Notify(GetString("TotocalcioBetPlayer")); - if (BetTargetKnowTotocalcio.GetBool()) - { - target.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Totocalcio), GetString("TotocalcioBetOnYou"))); - } + if (BetTargetKnowTotocalcio.GetBool()) target.Notify(Utils.ColorString(Utils.GetRoleColor(CustomRoles.Totocalcio), GetString("TotocalcioBetOnYou"))); Logger.Info($"Target selected:{killer.GetNameWithRole().RemoveHtmlTags()} => {target.GetNameWithRole().RemoveHtmlTags()}", "Totocalcio"); return false; @@ -177,24 +157,15 @@ namespace EHR.Neutral { if (!seer.Is(CustomRoles.Totocalcio)) { - if (!BetTargetKnowTotocalcio.GetBool()) - { - return string.Empty; - } + if (!BetTargetKnowTotocalcio.GetBool()) return string.Empty; - if (Main.PlayerStates[target.PlayerId].Role is not Totocalcio tc) - { - return string.Empty; - } + if (Main.PlayerStates[target.PlayerId].Role is not Totocalcio tc) return string.Empty; return seer.PlayerId == tc.BetPlayer ? Utils.ColorString(Utils.GetRoleColor(CustomRoles.Totocalcio), "♦") : string.Empty; } else { - if (Main.PlayerStates[seer.PlayerId].Role is not Totocalcio tc) - { - return string.Empty; - } + if (Main.PlayerStates[seer.PlayerId].Role is not Totocalcio tc) return string.Empty; return tc.BetPlayer == target.PlayerId ? Utils.ColorString(Utils.GetRoleColor(CustomRoles.Totocalcio), "♦") : string.Empty; } @@ -203,10 +174,7 @@ namespace EHR.Neutral public override string GetProgressText(byte playerId, bool comms) { PlayerControl player = Utils.GetPlayerById(playerId); - if (Main.PlayerStates[playerId].Role is not Totocalcio tc) - { - return string.Empty; - } + if (Main.PlayerStates[playerId].Role is not Totocalcio tc) return string.Empty; return player == null ? string.Empty : Utils.ColorString(tc.CanUseKillButton(player) ? Utils.GetRoleColor(CustomRoles.Totocalcio) : Color.gray, $"({tc.BetTimes})"); } diff --git a/Roles/Neutral/Traitor.cs b/Roles/Neutral/Traitor.cs index c2ce025b4..1abc7a808 100644 --- a/Roles/Neutral/Traitor.cs +++ b/Roles/Neutral/Traitor.cs @@ -18,13 +18,17 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Traitor); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Traitor]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 11, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Traitor]); + HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Traitor]); + CanSabotage = new BooleanOptionItem(Id + 15, "CanUseSabotage", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Traitor]); } diff --git a/Roles/Neutral/Tremor.cs b/Roles/Neutral/Tremor.cs index 62ea608b2..de226495b 100644 --- a/Roles/Neutral/Tremor.cs +++ b/Roles/Neutral/Tremor.cs @@ -31,19 +31,25 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Tremor); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Tremor]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 3, "CanVent", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Tremor]); + HasImpostorVision = new BooleanOptionItem(Id + 4, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Tremor]); + TimerStart = new IntegerOptionItem(Id + 5, "Tremor.TimerStart", new(0, 600, 5), 180, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Tremor]) .SetValueFormat(OptionFormat.Seconds); + TimerDecrease = new IntegerOptionItem(Id + 6, "Tremor.TimerDecrease", new(0, 180, 1), 15, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Tremor]) .SetValueFormat(OptionFormat.Seconds); + DoomTime = new IntegerOptionItem(Id + 7, "Tremor.DoomTime", new(0, 180, 1), 30, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Tremor]) .SetValueFormat(OptionFormat.Seconds); @@ -79,10 +85,7 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl pc) { - if (!GameStates.IsInTask || ExileController.Instance || !pc.IsAlive()) - { - return; - } + if (!GameStates.IsInTask || ExileController.Instance || !pc.IsAlive()) return; bool wasDoom = IsDoom; @@ -103,37 +106,26 @@ namespace EHR.Neutral { Count++; - if (Count % 3 == 0) - { - pc.RpcGuardAndKill(); - } + if (Count % 3 == 0) pc.RpcGuardAndKill(); - if (Count < 15) - { - return; - } + if (Count < 15) return; Count = 0; Vector2 pos = pc.Pos(); + Main.AllAlivePlayerControls .Where(x => x.PlayerId != pc.PlayerId && Vector2.Distance(pos, x.Pos()) <= 1.5f) .Do(pc.Kill); - if (LastUpdate == Utils.TimeStamp) - { - return; - } + if (LastUpdate == Utils.TimeStamp) return; LastUpdate = Utils.TimeStamp; DoomTimer--; Utils.SendRPC(CustomRPC.SyncRoleData, pc.PlayerId, DoomTimer); - if (DoomTimer <= 0) - { - pc.Suicide(); - } + if (DoomTimer <= 0) pc.Suicide(); } } @@ -146,29 +138,20 @@ namespace EHR.Neutral public void ReceiveRPC(MessageReader reader) { int value = reader.ReadPackedInt32(); + if (IsDoom) - { DoomTimer = value; - } else - { Timer = value; - } } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != TremorId || seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud) || meeting) - { - return string.Empty; - } + if (seer.PlayerId != TremorId || seer.PlayerId != target.PlayerId || (seer.IsModClient() && !hud) || meeting) return string.Empty; Color color = IsDoom ? Color.yellow : Color.cyan; string text = IsDoom ? DoomTimer.ToString() : Timer.ToString(); - if (hud) - { - text = $"{text}"; - } + if (hud) text = $"{text}"; return Utils.ColorString(color, text); } diff --git a/Roles/Neutral/Vengeance.cs b/Roles/Neutral/Vengeance.cs index f30894fcb..6d3c51973 100644 --- a/Roles/Neutral/Vengeance.cs +++ b/Roles/Neutral/Vengeance.cs @@ -26,10 +26,13 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Vengeance); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Vengeance]) .SetValueFormat(OptionFormat.Seconds); + RevengeTime = new IntegerOptionItem(Id + 11, "VengeanceRevengeTime", new(0, 30, 1), 15, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Vengeance]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 12, "CanVent", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Vengeance]); HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Vengeance]); } @@ -72,15 +75,9 @@ namespace EHR.Neutral public override bool OnCheckMurderAsTarget(PlayerControl killer, PlayerControl target) { - if (killer.PlayerId == target.PlayerId) - { - return true; - } + if (killer.PlayerId == target.PlayerId) return true; - if (IsRevenge) - { - return true; - } + if (IsRevenge) return true; LateTask.New(() => { target.TPToRandomVent(); }, 0.01f, log: false); @@ -97,10 +94,7 @@ namespace EHR.Neutral private void Countdown(int seconds, PlayerControl player) { - if (!player.IsAlive()) - { - return; - } + if (!player.IsAlive()) return; if (Success) { @@ -123,20 +117,11 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null) - { - return false; - } + if (killer == null) return false; - if (target == null) - { - return false; - } + if (target == null) return false; - if (!IsRevenge) - { - return true; - } + if (!IsRevenge) return true; if (target.PlayerId == Killer) { diff --git a/Roles/Neutral/Virus.cs b/Roles/Neutral/Virus.cs index 4805b5ef6..984162364 100644 --- a/Roles/Neutral/Virus.cs +++ b/Roles/Neutral/Virus.cs @@ -38,24 +38,33 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupSingleRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Virus); + KillCooldown = new FloatOptionItem(Id + 10, "VirusKillCooldown", new(0f, 60f, 0.5f), 30f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Virus]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 11, "VirusCanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Virus]); + ImpostorVision = new BooleanOptionItem(Id + 16, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Virus]); + InfectMax = new IntegerOptionItem(Id + 12, "VirusInfectMax", new(1, 15, 1), 2, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Virus]) .SetValueFormat(OptionFormat.Times); + KnowTargetRole = new BooleanOptionItem(Id + 13, "VirusKnowTargetRole", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Virus]); + TargetKnowOtherTarget = new BooleanOptionItem(Id + 14, "VirusTargetKnowOtherTarget", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Virus]); + KillInfectedPlayerAfterMeeting = new BooleanOptionItem(Id + 15, "VirusKillInfectedPlayerAfterMeeting", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Virus]); + ContagiousPlayersCanKillEachOther = new BooleanOptionItem(Id + 18, "ContagiousPlayersCanKillEachOther", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Virus]); + ContagiousCountMode = new StringOptionItem(Id + 17, "ContagiousCountMode", ContagiousCountModeStrings, 0, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Virus]); } @@ -94,20 +103,14 @@ namespace EHR.Neutral public override void OnMurder(PlayerControl killer, PlayerControl target) { - if (killer.GetAbilityUseLimit() < 1) - { - return; - } + if (killer.GetAbilityUseLimit() < 1) return; InfectedBodies.Add(target.PlayerId); } public static void OnKilledBodyReport(PlayerControl target) { - if (!CanBeInfected(target)) - { - return; - } + if (!CanBeInfected(target)) return; Utils.GetPlayerById(PlayerIdList[0]).RpcRemoveAbilityUse(); @@ -130,16 +133,10 @@ namespace EHR.Neutral { try { - if (!KillInfectedPlayerAfterMeeting.GetBool()) - { - return; - } + if (!KillInfectedPlayerAfterMeeting.GetBool()) return; PlayerControl virus = Main.AllAlivePlayerControls.FirstOrDefault(a => a.GetCustomRole() == CustomRoles.Virus); - if (virus == null || deathReason != PlayerState.DeathReason.Vote) - { - return; - } + if (virus == null || deathReason != PlayerState.DeathReason.Vote) return; if (exileIds.Contains(virus.PlayerId)) { @@ -147,14 +144,12 @@ namespace EHR.Neutral return; } - List infectedIdList = new List(); + var infectedIdList = new List(); + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { bool isInfected = InfectedPlayer.Contains(pc.PlayerId); - if (!isInfected) - { - continue; - } + if (!isInfected) continue; if (virus.IsAlive()) { @@ -165,9 +160,7 @@ namespace EHR.Neutral } } else - { Main.AfterMeetingDeathPlayers.Remove(pc.PlayerId); - } } CheckForEndVotingPatch.TryAddAfterMeetingDeathPlayers(PlayerState.DeathReason.Infected, [.. infectedIdList]); @@ -181,20 +174,11 @@ namespace EHR.Neutral public override bool KnowRole(PlayerControl player, PlayerControl target) { - if (base.KnowRole(player, target)) - { - return true; - } + if (base.KnowRole(player, target)) return true; - if (player.Is(CustomRoles.Contagious) && target.Is(CustomRoles.Virus)) - { - return true; - } + if (player.Is(CustomRoles.Contagious) && target.Is(CustomRoles.Virus)) return true; - if (KnowTargetRole.GetBool() && player.Is(CustomRoles.Virus) && target.Is(CustomRoles.Contagious)) - { - return true; - } + if (KnowTargetRole.GetBool() && player.Is(CustomRoles.Virus) && target.Is(CustomRoles.Contagious)) return true; return TargetKnowOtherTarget.GetBool() && player.Is(CustomRoles.Contagious) && target.Is(CustomRoles.Contagious); } diff --git a/Roles/Neutral/Vortex.cs b/Roles/Neutral/Vortex.cs index 4e1e0e50c..e5f78e935 100644 --- a/Roles/Neutral/Vortex.cs +++ b/Roles/Neutral/Vortex.cs @@ -17,13 +17,17 @@ namespace EHR.Neutral public override void SetupCustomOption() { Options.SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Vortex); + KillCooldown = new FloatOptionItem(Id + 2, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Vortex]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 3, "CanVent", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Vortex]); + HasImpostorVision = new BooleanOptionItem(Id + 4, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Vortex]); + IfTargetCannotBeTeleported = new StringOptionItem(Id + 5, "Vortex.IfTargetCannotBeTeleported", ["Vortex.NoTPMode.Block", "Vortex.NoTPMode.DoWithoutTP"], 0, TabGroup.NeutralRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Vortex]); } @@ -55,10 +59,7 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!killer.RpcCheckAndMurder(target, true)) - { - return false; - } + if (!killer.RpcCheckAndMurder(target, true)) return false; if (!target.TPToRandomVent()) { diff --git a/Roles/Neutral/Vulture.cs b/Roles/Neutral/Vulture.cs index 91153c725..c862ca2fc 100644 --- a/Roles/Neutral/Vulture.cs +++ b/Roles/Neutral/Vulture.cs @@ -43,21 +43,29 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Vulture); + ArrowsPointingToDeadBody = new BooleanOptionItem(Id + 10, "VultureArrowsPointingToDeadBody", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Vulture]); + NumberOfReportsToWin = new IntegerOptionItem(Id + 11, "VultureNumberOfReportsToWin", new(1, 10, 1), 4, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Vulture]); + CanVent = new BooleanOptionItem(Id + 12, "CanVent", true, TabGroup.NeutralRoles, true) .SetParent(CustomRoleSpawnChances[CustomRoles.Vulture]); + VultureReportCD = new FloatOptionItem(Id + 13, "VultureReportCooldown", new(0f, 180f, 2.5f), 15f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Vulture]) .SetValueFormat(OptionFormat.Seconds); + MaxEaten = new IntegerOptionItem(Id + 14, "VultureMaxEatenInOneRound", new(1, 10, 1), 2, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Vulture]); + HasImpVision = new BooleanOptionItem(Id + 15, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Vulture]); + ChangeRoleWhenCantWin = new BooleanOptionItem(Id + 16, "VultureChangeRoleWhenCantWin", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Vulture]); + ChangeRole = new StringOptionItem(Id + 17, "VultureChangeRole", ChangeRoles.Select(x => x.ToColoredString()).ToArray(), 0, TabGroup.NeutralRoles, noTranslation: true) .SetParent(CustomRoleSpawnChances[CustomRoles.Vulture]); } @@ -74,14 +82,13 @@ namespace EHR.Neutral BodyReportCount = 0; playerId.SetAbilityUseLimit(MaxEaten.GetInt()); LastReport = Utils.TimeStamp; + LateTask.New(() => { PlayerControl player = playerId.GetPlayer(); - if (player != null && player.Is(CustomRoles.Vulture) && GameStates.IsInTask) - { - player.Notify(GetString("VultureCooldownUp")); - } + if (player != null && player.Is(CustomRoles.Vulture) && GameStates.IsInTask) player.Notify(GetString("VultureCooldownUp")); }, VultureReportCD.GetFloat() + 8f, "Vulture CD"); + VultureId = playerId; } @@ -94,34 +101,28 @@ namespace EHR.Neutral public static void Clear() { - foreach (byte apc in PlayerIdList) - { - LocateArrow.RemoveAllTarget(apc); - } + foreach (byte apc in PlayerIdList) LocateArrow.RemoveAllTarget(apc); } public override void AfterMeetingTasks() { Clear(); + foreach (byte apc in PlayerIdList) { PlayerControl player = Utils.GetPlayerById(apc); - if (player == null) - { - continue; - } + if (player == null) continue; if (player.IsAlive()) { apc.SetAbilityUseLimit(MaxEaten.GetInt()); LastReport = Utils.TimeStamp; + LateTask.New(() => { - if (GameStates.IsInTask) - { - Utils.GetPlayerById(apc).Notify(GetString("VultureCooldownUp")); - } + if (GameStates.IsInTask) Utils.GetPlayerById(apc).Notify(GetString("VultureCooldownUp")); }, VultureReportCD.GetFloat(), "Vulture CD"); + Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); } } @@ -129,18 +130,12 @@ namespace EHR.Neutral public static void OnPlayerDead(PlayerControl target) { - if (!ArrowsPointingToDeadBody.GetBool() || target.Data.Disconnected) - { - return; - } + if (!ArrowsPointingToDeadBody.GetBool() || target.Data.Disconnected) return; foreach (byte pc in PlayerIdList) { PlayerControl player = Utils.GetPlayerById(pc); - if (player == null || !player.IsAlive()) - { - continue; - } + if (player == null || !player.IsAlive()) continue; LocateArrow.Add(pc, target.transform.position); Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); @@ -149,25 +144,16 @@ namespace EHR.Neutral public override bool CheckReportDeadBody(PlayerControl pc, NetworkedPlayerInfo target, PlayerControl killer) { - if (pc.GetAbilityUseLimit() <= 0) - { - return true; - } + if (pc.GetAbilityUseLimit() <= 0) return true; - if (Utils.TimeStamp - LastReport < VultureReportCD.GetFloat()) - { - return true; - } + if (Utils.TimeStamp - LastReport < VultureReportCD.GetFloat()) return true; BodyReportCount++; pc.RpcRemoveAbilityUse(); + if (target.Object != null) - { foreach (byte apc in PlayerIdList) - { LocateArrow.Remove(apc, target.Object.transform.position); - } - } pc.Notify(GetString("VultureBodyReported")); UnreportablePlayers.Remove(target.PlayerId); @@ -178,27 +164,19 @@ namespace EHR.Neutral public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId != VultureId) - { - return string.Empty; - } + if (seer.PlayerId != VultureId) return string.Empty; - if (target != null && seer.PlayerId != target.PlayerId) - { - return string.Empty; - } + if (target != null && seer.PlayerId != target.PlayerId) return string.Empty; return GameStates.IsMeeting ? string.Empty : Utils.ColorString(Color.white, LocateArrow.GetArrows(seer)); } public override void OnFixedUpdate(PlayerControl pc) { - if (!pc.IsAlive() || Main.HasJustStarted) - { - return; - } + if (!pc.IsAlive() || Main.HasJustStarted) return; byte playerId = pc.PlayerId; + if (BodyReportCount >= NumberOfReportsToWin.GetInt() && GameStates.IsInTask) { BodyReportCount = NumberOfReportsToWin.GetInt(); diff --git a/Roles/Neutral/WeaponMaster.cs b/Roles/Neutral/WeaponMaster.cs index aa0171f55..7b46e12cd 100644 --- a/Roles/Neutral/WeaponMaster.cs +++ b/Roles/Neutral/WeaponMaster.cs @@ -35,16 +35,21 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.WeaponMaster); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 22.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.WeaponMaster]) .SetValueFormat(OptionFormat.Seconds); + CanVent = new BooleanOptionItem(Id + 11, "CanVent", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.WeaponMaster]); + HasImpostorVision = new BooleanOptionItem(Id + 13, "ImpostorVision", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.WeaponMaster]); + Radius = new FloatOptionItem(Id + 12, "WMRadius", new(0f, 10f, 0.1f), 2f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.WeaponMaster]) .SetValueFormat(OptionFormat.Multiplier); + HighKCD = new FloatOptionItem(Id + 14, "GamblerHighKCD", new(0f, 180f, 2.5f), 35f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.WeaponMaster]) .SetValueFormat(OptionFormat.Seconds); @@ -69,10 +74,7 @@ namespace EHR.Neutral private void SendRPC() { - if (!Utils.DoRPC) - { - return; - } + if (!Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetWeaponMasterMode, SendOption.Reliable); writer.Write(WMId); @@ -84,10 +86,7 @@ namespace EHR.Neutral public static void ReceiveRPC(MessageReader reader) { byte id = reader.ReadByte(); - if (Main.PlayerStates[id].Role is not WeaponMaster { IsEnable: true } wm) - { - return; - } + if (Main.PlayerStates[id].Role is not WeaponMaster { IsEnable: true } wm) return; wm.Mode = reader.ReadByte(); wm.shieldUsed = reader.ReadBoolean(); @@ -112,15 +111,9 @@ namespace EHR.Neutral { opt.SetInt(Int32OptionNames.KillDistance, Mode == 2 ? 2 : 0); opt.SetVision(HasImpostorVision.GetBool()); - if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) - { - AURoleOptions.PhantomCooldown = 1f; - } + if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) AURoleOptions.PhantomCooldown = 1f; - if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = 1f; - } + if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) AURoleOptions.ShapeshifterCooldown = 1f; } public override bool CanUseKillButton(PlayerControl pc) @@ -147,10 +140,7 @@ namespace EHR.Neutral public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; SwitchMode(); return false; @@ -161,19 +151,12 @@ namespace EHR.Neutral byte id = PlayerIdList[0]; PlayerControl WM = Utils.GetPlayerById(id); - if (WM == null || !WM.IsAlive()) - { - return; - } + if (WM == null || !WM.IsAlive()) return; if (Mode == 3) - { Mode = 0; - } else - { Mode++; - } switch (Mode) { @@ -194,15 +177,9 @@ namespace EHR.Neutral public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (killer == null) - { - return false; - } + if (killer == null) return false; - if (target == null) - { - return false; - } + if (target == null) return false; switch (Mode) { @@ -213,19 +190,14 @@ namespace EHR.Neutral { foreach (PlayerControl player in Main.AllAlivePlayerControls) { - if (Pelican.IsEaten(player.PlayerId) || player == killer || player.Is(CustomRoles.Pestilence) || Veteran.VeteranInProtect.ContainsKey(target.PlayerId)) - { - continue; - } + if (Pelican.IsEaten(player.PlayerId) || player == killer || player.Is(CustomRoles.Pestilence) || Veteran.VeteranInProtect.ContainsKey(target.PlayerId)) continue; - if (Vector2.Distance(killer.transform.position, player.transform.position) <= Radius.GetFloat()) - { - player.Suicide(PlayerState.DeathReason.Kill, killer); - } + if (Vector2.Distance(killer.transform.position, player.transform.position) <= Radius.GetFloat()) player.Suicide(PlayerState.DeathReason.Kill, killer); } killer.SetKillCooldown(HighKCD.GetFloat()); }, 0.1f, "Weapon Master Axe Kill"); + return true; case 2: if (killer.RpcCheckAndMurder(target, true)) @@ -257,10 +229,7 @@ namespace EHR.Neutral public override void OnEnterVent(PlayerControl pc, Vent vent) { - if (Mode == 2) - { - pc?.MyPhysics?.RpcBootFromVent(vent.Id); - } + if (Mode == 2) pc?.MyPhysics?.RpcBootFromVent(vent.Id); } public override string GetProgressText(byte playerId, bool comms) diff --git a/Roles/Neutral/Werewolf.cs b/Roles/Neutral/Werewolf.cs index 8200c3451..73f7785d3 100644 --- a/Roles/Neutral/Werewolf.cs +++ b/Roles/Neutral/Werewolf.cs @@ -34,11 +34,15 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Werewolf); + KillCooldown = new FloatOptionItem(Id + 10, "KillCooldown", new(0f, 180f, 0.5f), 3f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Werewolf]) .SetValueFormat(OptionFormat.Seconds); + HasImpostorVision = new BooleanOptionItem(Id + 11, "ImpostorVision", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Werewolf]); + RampageCD = new FloatOptionItem(Id + 12, "WWRampageCD", new(0f, 180f, 0.5f), 35f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Werewolf]) .SetValueFormat(OptionFormat.Seconds); + RampageDur = new FloatOptionItem(Id + 13, "WWRampageDur", new(0f, 180f, 1f), 12f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Werewolf]) .SetValueFormat(OptionFormat.Seconds); } @@ -63,10 +67,7 @@ namespace EHR.Neutral LateTask.New(() => { - if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) - { - Utils.GetPlayerById(playerId).RpcResetAbilityCooldown(); - } + if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) Utils.GetPlayerById(playerId).RpcResetAbilityCooldown(); }, 9f, log: false); } @@ -88,15 +89,9 @@ namespace EHR.Neutral public override void ApplyGameOptions(IGameOptions opt, byte id) { opt.SetVision(HasImpostorVision.GetBool()); - if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) - { - AURoleOptions.PhantomCooldown = 1f; - } + if (UsePhantomBasis.GetBool() && UsePhantomBasisForNKs.GetBool()) AURoleOptions.PhantomCooldown = 1f; - if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) - { - AURoleOptions.ShapeshifterCooldown = RampageDur.GetFloat() + 0.5f; - } + if (UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool()) AURoleOptions.ShapeshifterCooldown = RampageDur.GetFloat() + 0.5f; AURoleOptions.EngineerCooldown = 0f; AURoleOptions.EngineerInVentMaxTime = 0f; @@ -104,10 +99,7 @@ namespace EHR.Neutral private void SendRPC() { - if (!IsEnable || !Utils.DoRPC) - { - return; - } + if (!IsEnable || !Utils.DoRPC) return; MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetWwTimer, SendOption.Reliable); writer.Write(WWId); @@ -131,10 +123,7 @@ namespace EHR.Neutral public override void OnFixedUpdate(PlayerControl player) { - if (!GameStates.IsInTask || !IsEnable || Main.HasJustStarted || player == null) - { - return; - } + if (!GameStates.IsInTask || !IsEnable || Main.HasJustStarted || player == null) return; long now = Utils.TimeStamp; @@ -143,10 +132,7 @@ namespace EHR.Neutral if (!player.IsModClient()) { long cooldown = lastTime + (long)RampageCD.GetFloat() - now; - if ((int)cooldown != CD) - { - player.Notify(string.Format(GetString("CDPT"), cooldown + 1), 1.1f, true); - } + if ((int)cooldown != CD) player.Notify(string.Format(GetString("CDPT"), cooldown + 1), 1.1f, true); CD = (int)cooldown; } @@ -155,10 +141,7 @@ namespace EHR.Neutral { lastTime = -10; bool unshift = UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool(); - if (!player.IsModClient()) - { - player.Notify(GetString(unshift ? "WWCanRampageUnshift" : "WWCanRampage")); - } + if (!player.IsModClient()) player.Notify(GetString(unshift ? "WWCanRampageUnshift" : "WWCanRampage")); player.RpcChangeRoleBasis(unshift ? CustomRoles.Werewolf : CustomRoles.EngineerEHR); SendRPC(); @@ -169,8 +152,9 @@ namespace EHR.Neutral if (LastFixedTime != now && RampageTime != -10) { LastFixedTime = now; - bool refresh = false; + var refresh = false; long remainTime = RampageTime + (long)RampageDur.GetFloat() - now; + switch (remainTime) { case < 0: @@ -186,19 +170,13 @@ namespace EHR.Neutral break; } - if (refresh) - { - SendRPC(); - } + if (refresh) SendRPC(); } } public override void OnEnterVent(PlayerControl pc, Vent vent) { - if (pc == null) - { - return; - } + if (pc == null) return; Rampage(pc); } @@ -216,10 +194,7 @@ namespace EHR.Neutral public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - if (!shapeshifting && !UseUnshiftTrigger.GetBool()) - { - return true; - } + if (!shapeshifting && !UseUnshiftTrigger.GetBool()) return true; Rampage(shapeshifter); return false; @@ -227,10 +202,7 @@ namespace EHR.Neutral private void Rampage(PlayerControl pc) { - if (!AmongUsClient.Instance.AmHost || IsRampaging) - { - return; - } + if (!AmongUsClient.Instance.AmHost || IsRampaging) return; LateTask.New(() => { @@ -246,12 +218,10 @@ namespace EHR.Neutral public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (!hud || seer == null || !GameStates.IsInTask || !PlayerControl.LocalPlayer.IsAlive() || Main.PlayerStates[seer.PlayerId].Role is not Werewolf { IsEnable: true } ww) - { - return string.Empty; - } + if (!hud || seer == null || !GameStates.IsInTask || !PlayerControl.LocalPlayer.IsAlive() || Main.PlayerStates[seer.PlayerId].Role is not Werewolf { IsEnable: true } ww) return string.Empty; + + var str = new StringBuilder(); - StringBuilder str = new StringBuilder(); if (ww.IsRampaging) { long remainTime = ww.RampageTime + (long)RampageDur.GetFloat() - Utils.TimeStamp; @@ -263,9 +233,7 @@ namespace EHR.Neutral str.Append(string.Format(GetString("WWCD"), cooldown + 1)); } else - { str.Append(GetString(UseUnshiftTrigger.GetBool() && UseUnshiftTriggerForNKs.GetBool() ? "WWCanRampageUnshift" : "WWCanRampage")); - } return str.ToString(); } diff --git a/Roles/Neutral/Workaholic.cs b/Roles/Neutral/Workaholic.cs index 4a422d1e5..0cfb3bba8 100644 --- a/Roles/Neutral/Workaholic.cs +++ b/Roles/Neutral/Workaholic.cs @@ -24,18 +24,25 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupRoleOptions(11700, TabGroup.NeutralRoles, CustomRoles.Workaholic); + WorkaholicCannotWinAtDeath = new BooleanOptionItem(11710, "WorkaholicCannotWinAtDeath", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Workaholic]); + WorkaholicVentCooldown = new FloatOptionItem(11711, "VentCooldown", new(0f, 180f, 0.5f), 30f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Workaholic]) .SetValueFormat(OptionFormat.Seconds); + WorkaholicVisibleToEveryone = new BooleanOptionItem(11712, "WorkaholicVisibleToEveryone", false, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Workaholic]); + WorkaholicGiveAdviceAlive = new BooleanOptionItem(11713, "WorkaholicGiveAdviceAlive", false, TabGroup.NeutralRoles) .SetParent(WorkaholicVisibleToEveryone); + OverrideTasksData.Create(11714, TabGroup.NeutralRoles, CustomRoles.Workaholic); + WorkaholicCanGuess = new BooleanOptionItem(11725, "CanGuess", true, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Workaholic]); + WorkaholicSpeed = new FloatOptionItem(11726, "WorkaholicSpeed", new(0.1f, 3f, 0.1f), 1.5f, TabGroup.NeutralRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Workaholic]) .SetValueFormat(OptionFormat.Multiplier); @@ -64,10 +71,7 @@ namespace EHR.Neutral { Logger.Info("Workaholic Tasks Finished", "Workaholic"); RPC.PlaySoundRPC(player.PlayerId, Sounds.KillSound); - foreach (PlayerControl pc in Main.AllAlivePlayerControls.Where(pc => pc.PlayerId != player.PlayerId).ToArray()) - { - pc.Suicide(pc.PlayerId == player.PlayerId ? PlayerState.DeathReason.Overtired : PlayerState.DeathReason.Ashamed, player); - } + foreach (PlayerControl pc in Main.AllAlivePlayerControls.Where(pc => pc.PlayerId != player.PlayerId).ToArray()) pc.Suicide(pc.PlayerId == player.PlayerId ? PlayerState.DeathReason.Overtired : PlayerState.DeathReason.Ashamed, player); CustomWinnerHolder.ResetAndSetWinner(CustomWinner.Workaholic); CustomWinnerHolder.WinnerIds.Add(player.PlayerId); diff --git a/Roles/Neutral/Wraith.cs b/Roles/Neutral/Wraith.cs index f4c7a88b2..43a6cf08b 100644 --- a/Roles/Neutral/Wraith.cs +++ b/Roles/Neutral/Wraith.cs @@ -15,19 +15,18 @@ namespace EHR.Neutral public override void SetupCustomOption() { SetupSingleRoleOptions(Id, TabGroup.NeutralRoles, CustomRoles.Wraith); + WraithCooldown = new FloatOptionItem(Id + 2, "WraithCooldown", new(0f, 60f, 0.5f), 20f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Wraith]) .SetValueFormat(OptionFormat.Seconds); + WraithDuration = new FloatOptionItem(Id + 3, "WraithDuration", new(0f, 30f, 0.5f), 10f, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Wraith]) .SetValueFormat(OptionFormat.Seconds); + WraithVentNormallyOnCooldown = new BooleanOptionItem(Id + 4, "WraithVentNormallyOnCooldown", true, TabGroup.NeutralRoles).SetParent(CustomRoleSpawnChances[CustomRoles.Wraith]); } - public override void Init() - { - } + public override void Init() { } - public override void Add(byte playerId) - { - } + public override void Add(byte playerId) { } } } \ No newline at end of file diff --git a/Roles/RoleBase.cs b/Roles/RoleBase.cs index 5d8a8289b..431b9e1c3 100644 --- a/Roles/RoleBase.cs +++ b/Roles/RoleBase.cs @@ -20,17 +20,11 @@ namespace EHR { string thisName = GetType().Name; string translatedName = Translator.GetString(thisName); - if (translatedName != string.Empty && !translatedName.StartsWith("*") && !translatedName.StartsWith("= 14) { x -= 13; TaskState ts = pc.GetTaskState(); + suffix = pc.GetCustomRoleTypes() switch { CustomRoleTypes.Impostor => $"Imp{x}", @@ -120,9 +97,7 @@ namespace EHR }; } else - { suffix = x.ToString(); - } pc.Notify(Translator.GetString($"NoPetActionMsg{suffix}")); } @@ -142,9 +117,7 @@ namespace EHR return target != null && killer != null; } - public virtual void OnMurder(PlayerControl killer, PlayerControl target) - { - } + public virtual void OnMurder(PlayerControl killer, PlayerControl target) { } public virtual bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { @@ -161,18 +134,14 @@ namespace EHR return false; } - public virtual void OnReportDeadBody() - { - } + public virtual void OnReportDeadBody() { } public virtual bool CheckReportDeadBody(PlayerControl reporter, NetworkedPlayerInfo target, PlayerControl killer) { return true; } - public virtual void AfterMeetingTasks() - { - } + public virtual void AfterMeetingTasks() { } public virtual string GetProgressText(byte playerId, bool comms) { @@ -182,9 +151,7 @@ namespace EHR return sb.ToString(); } - public virtual void SetButtonTexts(HudManager hud, byte id) - { - } + public virtual void SetButtonTexts(HudManager hud, byte id) { } public virtual string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { @@ -193,10 +160,7 @@ namespace EHR public virtual bool KnowRole(PlayerControl seer, PlayerControl target) { - if (Options.NeutralsKnowEachOther.GetBool() && seer.Is(Team.Neutral) && target.Is(Team.Neutral)) - { - return true; - } + if (Options.NeutralsKnowEachOther.GetBool() && seer.Is(Team.Neutral) && target.Is(Team.Neutral)) return true; CustomRoles seerRole = seer.GetCustomRole(); return seerRole.IsNK() && seerRole == target.GetCustomRole() && seer.GetTeam() == target.GetTeam(); @@ -205,20 +169,14 @@ namespace EHR // Option setup simplifier protected OptionSetupHandler StartSetup(int id) { - CustomRoles role = Enum.Parse(GetType().Name, true); - TabGroup tab = TabGroup.OtherRoles; + var role = Enum.Parse(GetType().Name, true); + var tab = TabGroup.OtherRoles; + if (role.IsImpostor()) - { tab = TabGroup.ImpostorRoles; - } else if (role.IsNeutral(true)) - { tab = TabGroup.NeutralRoles; - } - else if (role.IsCrewmate()) - { - tab = TabGroup.CrewmateRoles; - } + else if (role.IsCrewmate()) tab = TabGroup.CrewmateRoles; Options.SetupRoleOptions(id++, tab, role); return new(++id, tab, role); @@ -236,6 +194,7 @@ namespace EHR { bool generalOption = !Translator.GetString(fieldName).Contains("INVALID"); string name = overrideName == "" ? generalOption ? fieldName : $"{role}.{fieldName}" : overrideName; + field = (valueRule, defaultValue) switch { (null, bool bdv) => new BooleanOptionItem(++_id, name, bdv, tab), @@ -247,10 +206,7 @@ namespace EHR field.SetParent(overrideParent ?? Parent); - if (format != OptionFormat.None) - { - field?.SetValueFormat(format); - } + if (format != OptionFormat.None) field?.SetValueFormat(format); } catch (Exception e) { diff --git a/Roles/VanillaRole.cs b/Roles/VanillaRole.cs index 9ae2c3cb1..1d57a3328 100644 --- a/Roles/VanillaRole.cs +++ b/Roles/VanillaRole.cs @@ -6,9 +6,7 @@ public override bool IsEnable => On; - public override void SetupCustomOption() - { - } + public override void SetupCustomOption() { } public override void Init() { diff --git a/main.cs b/main.cs index a95c7d4d6..7c2bc1258 100644 --- a/main.cs +++ b/main.cs @@ -179,22 +179,17 @@ namespace EHR get { int count = PlayerControl.AllPlayerControls.Count; - PlayerControl[] result = new PlayerControl[count]; - int i = 0; + var result = new PlayerControl[count]; + var i = 0; + foreach (PlayerControl pc in PlayerControl.AllPlayerControls) { - if (pc == null || pc.PlayerId == 255) - { - continue; - } + if (pc == null || pc.PlayerId == 255) continue; result[i++] = pc; } - if (i == 0) - { - return []; - } + if (i == 0) return []; Array.Resize(ref result, i); return result; @@ -206,22 +201,17 @@ namespace EHR get { int count = PlayerControl.AllPlayerControls.Count; - PlayerControl[] result = new PlayerControl[count]; - int i = 0; + var result = new PlayerControl[count]; + var i = 0; + foreach (PlayerControl pc in PlayerControl.AllPlayerControls) { - if (pc == null || pc.PlayerId == 255 || !pc.IsAlive() || pc.Data.Disconnected || Pelican.IsEaten(pc.PlayerId)) - { - continue; - } + if (pc == null || pc.PlayerId == 255 || !pc.IsAlive() || pc.Data.Disconnected || Pelican.IsEaten(pc.PlayerId)) continue; result[i++] = pc; } - if (i == 0) - { - return []; - } + if (i == 0) return []; Array.Resize(ref result, i); return result; @@ -267,6 +257,7 @@ namespace EHR EHR.Logger.Disable("SwitchSystem"); EHR.Logger.Disable("ModNews"); EHR.Logger.Disable("CustomRpcSender"); + if (!DebugModeManager.AmDebugger) { EHR.Logger.Disable("2018k"); @@ -311,6 +302,7 @@ namespace EHR LastShapeshifterCooldown = Config.Bind("Other", "LastShapeshifterCooldown", (float)30); HasArgumentException = false; + try { RoleColors = new() @@ -675,6 +667,7 @@ namespace EHR { CustomRoles.Agent, "#ff8f8f" }, { CustomRoles.Taskinator, "#561dd1" } }; + Enum.GetValues().Where(x => x.GetCustomRoleTypes() == CustomRoleTypes.Impostor).Do(x => RoleColors.TryAdd(x, "#ff1919")); } catch (ArgumentException ex) @@ -713,13 +706,9 @@ namespace EHR Harmony.PatchAll(); if (!DebugModeManager.AmDebugger) - { ConsoleManager.DetachConsole(); - } else - { ConsoleManager.CreateConsole(); - } EHR.Logger.Msg("========= EHR loaded! =========", "Plugin Load"); } @@ -727,12 +716,14 @@ namespace EHR public static void LoadRoleClasses() { AllRoleClasses = []; + try { AllRoleClasses.AddRange(Assembly.GetAssembly(typeof(RoleBase))! .GetTypes() .Where(t => t.IsClass && !t.IsAbstract && t.IsSubclassOf(typeof(RoleBase))) .Select(t => (RoleBase)Activator.CreateInstance(t, null))); + AllRoleClasses.Sort(); } catch (Exception e) @@ -743,20 +734,14 @@ namespace EHR public void StartCoroutine(IEnumerator coroutine) { - if (coroutine == null) - { - return; - } + if (coroutine == null) return; coroutines.StartCoroutine(coroutine.WrapToIl2Cpp()); } public void StopCoroutine(IEnumerator coroutine) { - if (coroutine == null) - { - return; - } + if (coroutine == null) return; coroutines.StopCoroutine(coroutine.WrapToIl2Cpp()); } @@ -946,7 +931,5 @@ namespace EHR Random } - public class Coroutines : MonoBehaviour - { - } + public class Coroutines : MonoBehaviour { } } \ No newline at end of file