From c412d789c6a8b724528a9c79719dbd62dee012b9 Mon Sep 17 00:00:00 2001 From: Gurge44 Date: Sat, 5 Apr 2025 19:04:11 +0200 Subject: [PATCH] solution cleanup & sync room rush points --- .editorconfig | 235 +++++++++++++-- EHR.csproj | 2 +- EHR.sln.DotSettings | 61 ++-- GameMode/AllInOneGameMode.cs | 4 +- GameMode/CaptureTheFlag.cs | 43 ++- GameMode/CustomHnS.cs | 38 +-- GameMode/FreeForAll.cs | 6 +- GameMode/HotPotato.cs | 2 +- GameMode/KingOfTheZones.cs | 48 ++-- GameMode/MoveAndStop.cs | 15 +- GameMode/NaturalDisasters.cs | 28 +- GameMode/RoomRush.cs | 42 ++- GameMode/SoloPVP.cs | 8 +- GameMode/Speedrun.cs | 2 +- Main.cs | 4 +- Modules/Achievements.cs | 31 +- Modules/AddSteamID.cs | 5 +- Modules/AntiBlackout.cs | 32 +-- Modules/BanManager.cs | 12 +- Modules/Camouflague.cs | 7 +- Modules/ChatBubbleShower.cs | 13 +- Modules/ClientOptionItem.cs | 5 +- Modules/Cloud.cs | 5 +- Modules/CustomNetObject.cs | 2 +- Modules/CustomRoleSelector.cs | 73 +++-- Modules/CustomRolesHelper.cs | 9 +- Modules/CustomRpcSender.cs | 35 ++- Modules/CustomSounds.cs | 2 + Modules/CustomTeamManager.cs | 22 +- Modules/DebugModeManager.cs | 3 +- Modules/Debugger.cs | 15 +- Modules/DevManager.cs | 10 +- Modules/DisableDevice.cs | 6 +- Modules/EAC.cs | 14 +- Modules/ExtendedPlayerControl.cs | 271 ++++++++++-------- Modules/Extensions/CollectionExtensions.cs | 32 ++- Modules/Extensions/ObjectHelper.cs | 17 +- .../NormalGameOptionsSender.cs | 2 + .../PlayerGameOptionsSender.cs | 2 + Modules/GameState.cs | 4 +- Modules/GhostRolesManager.cs | 11 +- Modules/GuessManager.cs | 65 +++-- Modules/LateTask.cs | 8 +- Modules/LoadingScreen.cs | 2 +- Modules/LobbySharingAPI.cs | 27 +- Modules/MeetingTimeManager.cs | 3 +- Modules/NameColorManager.cs | 5 +- Modules/NameNotifyManager.cs | 2 +- Modules/OptionBackup/OptionBackupData.cs | 10 +- Modules/OptionHolder.cs | 28 +- Modules/OptionItem/OptionItem.cs | 18 +- Modules/OptionSaver.cs | 4 + Modules/OptionShower.cs | 2 +- Modules/PetsHelper.cs | 2 +- Modules/PrivateTagManager.cs | 11 +- Modules/Prompt.cs | 2 +- Modules/RPC.cs | 4 +- Modules/Random/MersenneTwister.cs | 40 +-- Modules/SpamManager.cs | 9 +- Modules/Statistics.cs | 19 +- Modules/TemplateManager.cs | 7 +- Modules/Translator.cs | 4 + Modules/Utils.cs | 65 ++--- Modules/Zoom.cs | 2 + Patches/AnnouncementPatch.cs | 2 + Patches/ChatCommandPatch.cs | 65 +++-- Patches/ChatControlPatch.cs | 19 +- Patches/CheckGameEndPatch.cs | 2 + Patches/ClientOptionsPatch.cs | 6 +- Patches/ClientPatch.cs | 31 +- Patches/ControlPatch.cs | 2 + Patches/CredentialsPatch.cs | 28 +- Patches/Crowded.cs | 103 ++++--- Patches/DleksPatch.cs | 5 +- Patches/EndGameManagerPatch.cs | 2 +- Patches/ExilePatch.cs | 10 +- Patches/FixNotAllServersShowingPatch.cs | 14 +- Patches/GameOptionsMenuPatch.cs | 22 +- Patches/GameStartManagerPatch.cs | 5 +- Patches/HudPatch.cs | 13 +- Patches/HudSpritePatch.cs | 2 +- Patches/IntroPatch.cs | 199 ++++++------- Patches/LobbyPatch.cs | 6 +- Patches/LogoAndStampPatch.cs | 112 ++++---- Patches/MainMenuManagerPatch.cs | 2 +- Patches/MapPickerMenuPatch.cs | 9 +- Patches/MeetingHudPatch.cs | 40 +-- Patches/OnGameStartedPatch.cs | 62 ++-- Patches/OutroPatch.cs | 12 +- Patches/PetActionsPatch.cs | 6 +- Patches/PhantomRolePatch.cs | 9 +- Patches/PlayerControlPatch.cs | 55 ++-- Patches/PlayerJoinAndLeftPatch.cs | 7 +- Patches/SabotageSystemPatch.cs | 6 +- Patches/ShipStatusPatch.cs | 30 +- Patches/TaskAssignPatch.cs | 3 +- Patches/TextBoxPatch.cs | 27 +- README.md | 7 +- Roles/AddOns/Common/Asthmatic.cs | 13 +- Roles/AddOns/GhostRoles/Bloodmoon.cs | 6 +- Roles/AddOns/Impostor/Circumvent.cs | 2 + Roles/AddOns/Impostor/Damocles.cs | 4 + Roles/AddOns/Impostor/Underdog.cs | 7 +- Roles/Coven/Banshee.cs | 8 +- Roles/Coven/Coven.cs | 9 +- Roles/Coven/CovenLeader.cs | 2 +- Roles/Coven/Dreamweaver.cs | 11 +- Roles/Coven/Illusionist.cs | 2 +- Roles/Coven/Poache.cs | 2 +- Roles/Coven/PotionMaster.cs | 11 +- Roles/Coven/SpellCaster.cs | 2 +- Roles/Coven/VoodooMaster.cs | 6 +- Roles/Crewmate/Alchemist.cs | 9 +- Roles/Crewmate/Ankylosaurus.cs | 6 +- Roles/Crewmate/Chef.cs | 6 +- Roles/Crewmate/CopyCat.cs | 2 +- Roles/Crewmate/CyberStar.cs | 4 +- Roles/Crewmate/Demolitionist.cs | 2 +- Roles/Crewmate/Deputy.cs | 4 +- Roles/Crewmate/Divinator.cs | 2 +- Roles/Crewmate/DonutDelivery.cs | 2 + Roles/Crewmate/Enigma.cs | 4 +- Roles/Crewmate/Inquirer.cs | 2 +- Roles/Crewmate/Judge.cs | 2 +- Roles/Crewmate/Lookout.cs | 2 + Roles/Crewmate/Lyncher.cs | 5 +- Roles/Crewmate/Mathematician.cs | 10 +- Roles/Crewmate/Medic.cs | 4 +- Roles/Crewmate/Merchant.cs | 4 +- Roles/Crewmate/Monarch.cs | 6 +- Roles/Crewmate/Negotiator.cs | 4 +- Roles/Crewmate/Oracle.cs | 2 +- Roles/Crewmate/Psychic.cs | 2 + Roles/Crewmate/Randomizer.cs | 2 + Roles/Crewmate/SabotageMaster.cs | 4 +- Roles/Crewmate/Sentinel.cs | 6 +- Roles/Crewmate/Sentry.cs | 9 +- Roles/Crewmate/Snitch.cs | 2 + Roles/Crewmate/Speedrunner.cs | 2 + Roles/Crewmate/Spiritualist.cs | 3 +- Roles/Crewmate/Telekinetic.cs | 2 +- Roles/Crewmate/TimeMaster.cs | 4 +- Roles/Crewmate/Wizard.cs | 10 +- Roles/Impostor/Abyssbringer.cs | 5 +- Roles/Impostor/AntiAdminer.cs | 6 +- Roles/Impostor/Assassin.cs | 2 +- Roles/Impostor/Assumer.cs | 2 + Roles/Impostor/Bard.cs | 10 +- Roles/Impostor/Blackmailer.cs | 5 +- Roles/Impostor/Bomber.cs | 2 +- Roles/Impostor/Cantankerous.cs | 2 + Roles/Impostor/Changeling.cs | 4 +- Roles/Impostor/Deathpact.cs | 2 + Roles/Impostor/Duellist.cs | 4 +- Roles/Impostor/Escapee.cs | 8 +- Roles/Impostor/Gangster.cs | 4 +- Roles/Impostor/Hitman.cs | 2 + Roles/Impostor/Hypocrite.cs | 8 +- Roles/Impostor/Kamikaze.cs | 2 +- Roles/Impostor/Mafioso.cs | 4 + Roles/Impostor/Mastermind.cs | 6 +- Roles/Impostor/Miner.cs | 4 +- Roles/Impostor/Occultist.cs | 12 +- Roles/Impostor/OverKiller.cs | 4 +- Roles/Impostor/Penguin.cs | 4 + Roles/Impostor/Sapper.cs | 2 +- Roles/Impostor/Silencer.cs | 4 +- Roles/Impostor/Sniper.cs | 2 + Roles/Impostor/Stasis.cs | 4 +- Roles/Impostor/Swooper.cs | 17 +- Roles/Impostor/Wasp.cs | 5 +- Roles/Impostor/Wiper.cs | 10 +- Roles/Impostor/Witch.cs | 4 + Roles/Impostor/YinYanger.cs | 4 +- Roles/Neutral/Amnesiac.cs | 4 +- Roles/Neutral/Amogus.cs | 2 +- Roles/Neutral/Arsonist.cs | 2 + Roles/Neutral/Auditor.cs | 10 +- Roles/Neutral/Bargainer.cs | 22 +- Roles/Neutral/Bubble.cs | 2 +- Roles/Neutral/Chemist.cs | 6 +- Roles/Neutral/Curser.cs | 7 +- Roles/Neutral/DarkHide.cs | 1 - Roles/Neutral/Doomsayer.cs | 5 +- Roles/Neutral/FFF.cs | 20 +- Roles/Neutral/Gaslighter.cs | 4 +- Roles/Neutral/HexMaster.cs | 4 +- Roles/Neutral/Jackal.cs | 2 +- Roles/Neutral/Jester.cs | 12 +- Roles/Neutral/Magistrate.cs | 4 +- Roles/Neutral/Mario.cs | 2 +- Roles/Neutral/Mycologist.cs | 2 + Roles/Neutral/Necromancer.cs | 6 +- Roles/Neutral/NoteKiller.cs | 18 +- Roles/Neutral/Pelican.cs | 4 +- Roles/Neutral/PlagueDoctor.cs | 2 + Roles/Neutral/QuizMaster.cs | 16 +- Roles/Neutral/Revolutionist.cs | 2 +- Roles/Neutral/Rogue.cs | 2 +- Roles/Neutral/Romantic.cs | 6 +- Roles/Neutral/RoomRusher.cs | 8 +- Roles/Neutral/Samurai.cs | 2 + Roles/Neutral/SchrodingersCat.cs | 4 +- Roles/Neutral/Seamstress.cs | 18 +- Roles/Neutral/Spirit.cs | 6 +- Roles/Neutral/Spiritcaller.cs | 3 +- Roles/Neutral/Starspawn.cs | 8 +- Roles/Neutral/Succubus.cs | 4 +- Roles/Neutral/Vengeance.cs | 2 +- Roles/Neutral/Weatherman.cs | 7 +- Roles/Neutral/Werewolf.cs | 4 +- Roles/Neutral/Wraith.cs | 7 +- Roles/RoleBase.cs | 2 +- 213 files changed, 1747 insertions(+), 1302 deletions(-) diff --git a/.editorconfig b/.editorconfig index ab1ba3a47..d4c127e61 100644 --- a/.editorconfig +++ b/.editorconfig @@ -7,17 +7,13 @@ dotnet_diagnostic.ca2211.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 +csharp_prefer_braces = when_multiline:none csharp_style_namespace_declarations = file_scoped:none csharp_style_prefer_method_group_conversion = true:silent csharp_style_prefer_top_level_statements = true:silent csharp_style_prefer_primary_constructors = true:suggestion -csharp_style_expression_bodied_methods = false:silent -csharp_style_expression_bodied_constructors = false:silent csharp_style_expression_bodied_operators = false:silent -csharp_style_expression_bodied_properties = true:silent csharp_style_expression_bodied_indexers = true:silent -csharp_style_expression_bodied_accessors = true:silent csharp_style_expression_bodied_lambdas = true:silent csharp_style_expression_bodied_local_functions = false:silent csharp_indent_labels = one_less_than_current @@ -60,10 +56,12 @@ resharper_align_multiline_binary_patterns = true resharper_align_multiline_calls_chain = false resharper_align_multiline_extends_list = true resharper_align_multiline_parameter = false +resharper_align_multiline_statement_conditions = false resharper_align_multiline_type_parameter_constraints = false resharper_align_multiline_type_parameter_list = false resharper_align_multiple_declaration = true resharper_align_tuple_components = true +resharper_blank_lines_before_block_statements = 1 resharper_braces_for_dowhile = required_for_multiline resharper_braces_for_fixed = required_for_multiline resharper_braces_for_for = required_for_multiline @@ -74,27 +72,219 @@ resharper_braces_for_using = required_for_multiline resharper_braces_for_while = required_for_multiline resharper_braces_redundant = true resharper_csharp_align_multiline_calls_chain = false +resharper_csharp_empty_block_style = together_same_line resharper_csharp_indent_statement_pars = outside_and_inside resharper_csharp_outdent_commas = true resharper_csharp_stick_comment = false -resharper_default_internal_modifier = implicit +resharper_csharp_wrap_lines = false resharper_default_private_modifier = explicit resharper_default_value_when_type_not_evident = default_expression +resharper_enforce_line_ending_style = true resharper_for_built_in_types = use_var_when_evident resharper_indent_braces_inside_statement_conditions = false resharper_indent_nested_foreach_stmt = true resharper_indent_nested_for_stmt = true resharper_indent_nested_while_stmt = true +resharper_indent_preprocessor_directives = normal resharper_indent_primary_constructor_decl_pars = inside +resharper_instance_members_qualify_declared_in = base_class resharper_local_function_body = expression_body resharper_object_creation_when_type_not_evident = explicitly_typed -resharper_parentheses_non_obvious_operations = none, shift, bitwise_and, bitwise_exclusive_or, bitwise_inclusive_or, bitwise, conditional_and, conditional_or, conditional +resharper_parentheses_non_obvious_operations = none, shift, bitwise_and, bitwise_exclusive_or, bitwise_inclusive_or, bitwise +resharper_place_simple_embedded_block_on_same_line = true +resharper_place_simple_embedded_statement_on_same_line = false +resharper_use_heuristics_for_body_style = false +resharper_use_indent_from_vs = false # Microsoft .NET properties +csharp_new_line_before_members_in_object_initializers = false +csharp_preferred_modifier_order = public, private, protected, internal, file, new, static, abstract, virtual, sealed, readonly, override, extern, unsafe, volatile, async, required:suggestion +dotnet_naming_rule.constants_rule.import_to_resharper = True +dotnet_naming_rule.constants_rule.resharper_description = Constant fields (not private) +dotnet_naming_rule.constants_rule.resharper_guid = 669e5282-fb4b-4e90-91e7-07d269d04b60 +dotnet_naming_rule.constants_rule.severity = suggestion +dotnet_naming_rule.constants_rule.style = upper_camel_case_style +dotnet_naming_rule.constants_rule.symbols = constants_symbols +dotnet_naming_rule.interface_should_be_begins_with_i_rule.import_to_resharper = True +dotnet_naming_rule.interface_should_be_begins_with_i_rule.resharper_description = interface_should_be_begins_with_i +dotnet_naming_rule.interface_should_be_begins_with_i_rule.resharper_guid = 60bf1ae3-25da-46bc-8281-c816299091c0 +dotnet_naming_rule.interface_should_be_begins_with_i_rule.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i_rule.style = i_upper_camel_case_style +dotnet_naming_rule.interface_should_be_begins_with_i_rule.symbols = interface_should_be_begins_with_i_symbols +dotnet_naming_rule.non_field_members_should_be_pascal_case_rule.import_to_resharper = True +dotnet_naming_rule.non_field_members_should_be_pascal_case_rule.resharper_description = non_field_members_should_be_pascal_case +dotnet_naming_rule.non_field_members_should_be_pascal_case_rule.resharper_guid = c4363532-209c-4073-90f0-b0d1296bc910 +dotnet_naming_rule.non_field_members_should_be_pascal_case_rule.severity = none +dotnet_naming_rule.non_field_members_should_be_pascal_case_rule.style = upper_camel_case_style +dotnet_naming_rule.non_field_members_should_be_pascal_case_rule.symbols = non_field_members_should_be_pascal_case_symbols +dotnet_naming_rule.parameters_rule.import_to_resharper = True +dotnet_naming_rule.parameters_rule.resharper_description = Parameters +dotnet_naming_rule.parameters_rule.resharper_guid = 8a85b61a-1024-4f87-b9ef-1fdae19930a1 +dotnet_naming_rule.parameters_rule.resharper_style = aaBb, __ + aaBb +dotnet_naming_rule.parameters_rule.severity = suggestion +dotnet_naming_rule.parameters_rule.style = lower_camel_case_style +dotnet_naming_rule.parameters_rule.symbols = parameters_symbols +dotnet_naming_rule.private_constants_rule.import_to_resharper = True +dotnet_naming_rule.private_constants_rule.resharper_description = Constant fields (private) +dotnet_naming_rule.private_constants_rule.resharper_guid = 236f7aa5-7b06-43ca-bf2a-9b31bfcff09a +dotnet_naming_rule.private_constants_rule.severity = suggestion +dotnet_naming_rule.private_constants_rule.style = upper_camel_case_style +dotnet_naming_rule.private_constants_rule.symbols = private_constants_symbols +dotnet_naming_rule.private_instance_fields_rule.import_to_resharper = True +dotnet_naming_rule.private_instance_fields_rule.resharper_description = Instance fields (private) +dotnet_naming_rule.private_instance_fields_rule.resharper_guid = 4a98fdf6-7d98-4f5a-afeb-ea44ad98c70c +dotnet_naming_rule.private_instance_fields_rule.severity = none +dotnet_naming_rule.private_instance_fields_rule.style = lower_camel_case_style_1 +dotnet_naming_rule.private_instance_fields_rule.symbols = private_instance_fields_symbols +dotnet_naming_rule.private_static_fields_rule.import_to_resharper = True +dotnet_naming_rule.private_static_fields_rule.resharper_description = Static fields (private) +dotnet_naming_rule.private_static_fields_rule.resharper_guid = f9fce829-e6f4-4cb2-80f1-5497c44f51df +dotnet_naming_rule.private_static_fields_rule.severity = suggestion +dotnet_naming_rule.private_static_fields_rule.style = upper_camel_case_style +dotnet_naming_rule.private_static_fields_rule.symbols = private_static_fields_symbols +dotnet_naming_rule.private_static_readonly_rule.import_to_resharper = True +dotnet_naming_rule.private_static_readonly_rule.resharper_description = Static readonly fields (private) +dotnet_naming_rule.private_static_readonly_rule.resharper_guid = 15b5b1f1-457c-4ca6-b278-5615aedc07d3 +dotnet_naming_rule.private_static_readonly_rule.severity = suggestion +dotnet_naming_rule.private_static_readonly_rule.style = upper_camel_case_style +dotnet_naming_rule.private_static_readonly_rule.symbols = private_static_readonly_symbols +dotnet_naming_rule.public_fields_rule.import_to_resharper = True +dotnet_naming_rule.public_fields_rule.resharper_description = Instance fields (not private) +dotnet_naming_rule.public_fields_rule.resharper_guid = 53eecf85-d821-40e8-ac97-fdb734542b84 +dotnet_naming_rule.public_fields_rule.severity = none +dotnet_naming_rule.public_fields_rule.style = upper_camel_case_style +dotnet_naming_rule.public_fields_rule.symbols = public_fields_symbols +dotnet_naming_rule.public_static_fields_rule.import_to_resharper = True +dotnet_naming_rule.public_static_fields_rule.resharper_description = Static fields (not private) +dotnet_naming_rule.public_static_fields_rule.resharper_guid = 70345118-4b40-4ece-937c-bbeb7a0b2e70 +dotnet_naming_rule.public_static_fields_rule.severity = suggestion +dotnet_naming_rule.public_static_fields_rule.style = upper_camel_case_style +dotnet_naming_rule.public_static_fields_rule.symbols = public_static_fields_symbols +dotnet_naming_rule.static_readonly_rule.import_to_resharper = True +dotnet_naming_rule.static_readonly_rule.resharper_description = Static readonly fields (not private) +dotnet_naming_rule.static_readonly_rule.resharper_guid = c873eafb-d57f-481d-8c93-77f6863c2f88 +dotnet_naming_rule.static_readonly_rule.severity = suggestion +dotnet_naming_rule.static_readonly_rule.style = upper_camel_case_style +dotnet_naming_rule.static_readonly_rule.symbols = static_readonly_symbols +dotnet_naming_rule.types_should_be_pascal_case_rule.import_to_resharper = True +dotnet_naming_rule.types_should_be_pascal_case_rule.resharper_description = types_should_be_pascal_case +dotnet_naming_rule.types_should_be_pascal_case_rule.resharper_guid = 749d8538-ec25-40b6-87c8-0ec37cfd4ba4 +dotnet_naming_rule.types_should_be_pascal_case_rule.severity = none +dotnet_naming_rule.types_should_be_pascal_case_rule.style = upper_camel_case_style +dotnet_naming_rule.types_should_be_pascal_case_rule.symbols = types_should_be_pascal_case_symbols +dotnet_naming_rule.unity_serialized_field_rule.import_to_resharper = True +dotnet_naming_rule.unity_serialized_field_rule.resharper_description = Unity serialized field +dotnet_naming_rule.unity_serialized_field_rule.resharper_guid = 5f0fdb63-c892-4d2c-9324-15c80b22a7ef +dotnet_naming_rule.unity_serialized_field_rule.severity = suggestion +dotnet_naming_rule.unity_serialized_field_rule.style = lower_camel_case_style +dotnet_naming_rule.unity_serialized_field_rule.symbols = unity_serialized_field_symbols +dotnet_naming_style.i_upper_camel_case_style.capitalization = pascal_case +dotnet_naming_style.i_upper_camel_case_style.required_prefix = I +dotnet_naming_style.lower_camel_case_style.capitalization = camel_case +dotnet_naming_style.lower_camel_case_style_1.capitalization = camel_case +dotnet_naming_style.lower_camel_case_style_1.required_prefix = _ +dotnet_naming_style.upper_camel_case_style.capitalization = pascal_case +dotnet_naming_symbols.constants_symbols.applicable_accessibilities = public, internal, protected, protected_internal, private_protected +dotnet_naming_symbols.constants_symbols.applicable_kinds = field +dotnet_naming_symbols.constants_symbols.required_modifiers = const +dotnet_naming_symbols.constants_symbols.resharper_applicable_kinds = constant_field +dotnet_naming_symbols.constants_symbols.resharper_required_modifiers = any +dotnet_naming_symbols.interface_should_be_begins_with_i_symbols.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface_should_be_begins_with_i_symbols.applicable_kinds = interface +dotnet_naming_symbols.interface_should_be_begins_with_i_symbols.resharper_applicable_kinds = interface +dotnet_naming_symbols.interface_should_be_begins_with_i_symbols.resharper_required_modifiers = any +dotnet_naming_symbols.non_field_members_should_be_pascal_case_symbols.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members_should_be_pascal_case_symbols.applicable_kinds = event, method, property +dotnet_naming_symbols.non_field_members_should_be_pascal_case_symbols.resharper_applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members_should_be_pascal_case_symbols.resharper_required_modifiers = any +dotnet_naming_symbols.parameters_symbols.applicable_accessibilities = * +dotnet_naming_symbols.parameters_symbols.applicable_kinds = parameter +dotnet_naming_symbols.parameters_symbols.resharper_applicable_kinds = parameter +dotnet_naming_symbols.parameters_symbols.resharper_required_modifiers = any +dotnet_naming_symbols.private_constants_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_constants_symbols.applicable_kinds = field +dotnet_naming_symbols.private_constants_symbols.required_modifiers = const +dotnet_naming_symbols.private_constants_symbols.resharper_applicable_kinds = constant_field +dotnet_naming_symbols.private_constants_symbols.resharper_required_modifiers = any +dotnet_naming_symbols.private_instance_fields_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_instance_fields_symbols.applicable_kinds = field +dotnet_naming_symbols.private_instance_fields_symbols.resharper_applicable_kinds = field, readonly_field +dotnet_naming_symbols.private_instance_fields_symbols.resharper_required_modifiers = instance +dotnet_naming_symbols.private_static_fields_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_static_fields_symbols.applicable_kinds = field +dotnet_naming_symbols.private_static_fields_symbols.required_modifiers = static +dotnet_naming_symbols.private_static_fields_symbols.resharper_applicable_kinds = field +dotnet_naming_symbols.private_static_fields_symbols.resharper_required_modifiers = static +dotnet_naming_symbols.private_static_readonly_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_static_readonly_symbols.applicable_kinds = field +dotnet_naming_symbols.private_static_readonly_symbols.required_modifiers = readonly, static +dotnet_naming_symbols.private_static_readonly_symbols.resharper_applicable_kinds = readonly_field +dotnet_naming_symbols.private_static_readonly_symbols.resharper_required_modifiers = static +dotnet_naming_symbols.public_fields_symbols.applicable_accessibilities = public, internal, protected, protected_internal, private_protected +dotnet_naming_symbols.public_fields_symbols.applicable_kinds = field +dotnet_naming_symbols.public_fields_symbols.resharper_applicable_kinds = field, readonly_field +dotnet_naming_symbols.public_fields_symbols.resharper_required_modifiers = instance +dotnet_naming_symbols.public_static_fields_symbols.applicable_accessibilities = public, internal, protected, protected_internal, private_protected +dotnet_naming_symbols.public_static_fields_symbols.applicable_kinds = field +dotnet_naming_symbols.public_static_fields_symbols.required_modifiers = static +dotnet_naming_symbols.public_static_fields_symbols.resharper_applicable_kinds = field +dotnet_naming_symbols.public_static_fields_symbols.resharper_required_modifiers = static +dotnet_naming_symbols.static_readonly_symbols.applicable_accessibilities = public, internal, protected, protected_internal, private_protected +dotnet_naming_symbols.static_readonly_symbols.applicable_kinds = field +dotnet_naming_symbols.static_readonly_symbols.required_modifiers = readonly, static +dotnet_naming_symbols.static_readonly_symbols.resharper_applicable_kinds = readonly_field +dotnet_naming_symbols.static_readonly_symbols.resharper_required_modifiers = static +dotnet_naming_symbols.types_should_be_pascal_case_symbols.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types_should_be_pascal_case_symbols.applicable_kinds = class, enum, interface, struct +dotnet_naming_symbols.types_should_be_pascal_case_symbols.resharper_applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types_should_be_pascal_case_symbols.resharper_required_modifiers = any +dotnet_naming_symbols.unity_serialized_field_symbols.applicable_accessibilities = * +dotnet_naming_symbols.unity_serialized_field_symbols.applicable_kinds = +dotnet_naming_symbols.unity_serialized_field_symbols.resharper_applicable_kinds = unity_serialised_field +dotnet_naming_symbols.unity_serialized_field_symbols.resharper_required_modifiers = instance +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:none +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:none +dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:none 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 + +# Standard properties +end_of_line = crlf + +# ReSharper inspection severities +resharper_arrange_accessor_owner_body_highlighting = none +resharper_arrange_object_creation_when_type_not_evident_highlighting = none +resharper_arrange_type_member_modifiers_highlighting = none +resharper_arrange_type_modifiers_highlighting = none +resharper_built_in_type_reference_style_for_member_access_highlighting = none +resharper_built_in_type_reference_style_highlighting = none +resharper_check_namespace_highlighting = none +resharper_convert_if_statement_to_switch_statement_highlighting = suggestion +resharper_duplicated_switch_section_bodies_highlighting = suggestion +resharper_empty_general_catch_clause_highlighting = none +resharper_extract_common_branching_code_highlighting = suggestion +resharper_foreach_can_be_converted_to_query_using_another_get_enumerator_highlighting = none +resharper_foreach_can_be_partly_converted_to_query_using_another_get_enumerator_highlighting = none +resharper_inconsistent_naming_highlighting = suggestion +resharper_invert_if_highlighting = none +resharper_loop_can_be_converted_to_query_highlighting = warning +resharper_mvc_action_not_resolved_highlighting = warning +resharper_mvc_area_not_resolved_highlighting = warning +resharper_mvc_controller_not_resolved_highlighting = warning +resharper_mvc_masterpage_not_resolved_highlighting = warning +resharper_mvc_partial_view_not_resolved_highlighting = warning +resharper_mvc_template_not_resolved_highlighting = warning +resharper_mvc_view_component_not_resolved_highlighting = warning +resharper_mvc_view_component_view_not_resolved_highlighting = warning +resharper_mvc_view_not_resolved_highlighting = warning +resharper_razor_assembly_not_resolved_highlighting = warning +resharper_switch_statement_handles_some_known_enum_values_with_default_highlighting = none +resharper_switch_statement_missing_some_enum_cases_no_default_highlighting = none +resharper_unity_performance_critical_code_invocation_highlighting = none +resharper_unity_performance_critical_code_null_comparison_highlighting = none +resharper_web_config_module_not_resolved_highlighting = warning +resharper_web_config_type_not_resolved_highlighting = warning +resharper_web_config_wrong_module_highlighting = warning [*.{cs,vb}] #### Naming styles #### @@ -117,31 +307,31 @@ dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case dotnet_naming_symbols.interface.applicable_kinds = interface dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interface.required_modifiers = +dotnet_naming_symbols.interface.required_modifiers = dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types.required_modifiers = +dotnet_naming_symbols.types.required_modifiers = dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.non_field_members.required_modifiers = +dotnet_naming_symbols.non_field_members.required_modifiers = # Naming styles dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = dotnet_naming_style.begins_with_i.capitalization = pascal_case -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = dotnet_naming_style.pascal_case.capitalization = pascal_case -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = dotnet_naming_style.pascal_case.capitalization = pascal_case dotnet_style_coalesce_expression = true:suggestion dotnet_style_null_propagation = true:suggestion @@ -177,3 +367,8 @@ dotnet_style_qualification_for_field = false:silent dotnet_style_qualification_for_property = false:silent dotnet_style_qualification_for_method = false:silent dotnet_style_qualification_for_event = false:silent + +[*.{appxmanifest,asax,ascx,aspx,axaml,blockshader,build,c,c++,c++m,cc,ccm,cginc,compute,cp,cpp,cppm,cs,cshtml,cu,cuh,cxx,cxxm,dtd,fs,fsi,fsscript,fsx,fx,fxh,h,h++,hh,hlsl,hlsli,hlslinc,hp,hpp,hxx,icc,inc,inl,ino,ipp,ixx,master,ml,mli,mpp,mq4,mq5,mqh,mxx,nuspec,paml,razor,resw,resx,shader,shaderFoundry,skin,tcc,tpp,urtshader,usf,ush,uxml,vb,xaml,xamlx,xoml,xsd}] +indent_style = space +indent_size = 4 +tab_width = 4 diff --git a/EHR.csproj b/EHR.csproj index 0a3ed1ca7..dd9011cdf 100644 --- a/EHR.csproj +++ b/EHR.csproj @@ -24,7 +24,7 @@ - + diff --git a/EHR.sln.DotSettings b/EHR.sln.DotSettings index cdbf9416d..13a2c5e6c 100644 --- a/EHR.sln.DotSettings +++ b/EHR.sln.DotSettings @@ -1,17 +1,25 @@ - + SOLUTION - SUGGESTION + SUGGESTION BaseClass False 0 - 1 + 1 0 - TOGETHER_SAME_LINE - False - True - NEVER + TOGETHER_SAME_LINE + False + True + NEVER AFK ATK AU @@ -58,19 +66,32 @@ TS UI VN - <Policy><Descriptor Staticness="Any" AccessRightKinds="Private, Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="non_field_members_should_be_pascal_case"><ElementKinds><Kind Name="PROPERTY" /><Kind Name="EVENT" /><Kind Name="METHOD" /></ElementKinds></Descriptor><Policy Inspect="False" Prefix="Get" Suffix="" Style="AaBb" /></Policy> - - True - <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Parameters"><ElementKinds><Kind Name="PARAMETER" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="aaBb"><ExtraRule Prefix="__" Suffix="" Style="aaBb" /></Policy></Policy> - True - True - True - True - False - constant("System.Exception") - -1 - -1 - try + <Policy><Descriptor Staticness="Any" AccessRightKinds="Private, Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="non_field_members_should_be_pascal_case"><ElementKinds><Kind Name="PROPERTY" /><Kind Name="EVENT" /><Kind Name="METHOD" /></ElementKinds></Descriptor><Policy Inspect="False" Prefix="Get" Suffix="" Style="AaBb" /></Policy> + + True + <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Parameters"><ElementKinds><Kind Name="PARAMETER" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="aaBb"><ExtraRule Prefix="__" Suffix="" Style="aaBb" /></Policy></Policy> + True + True + True + True + False + constant("System.Exception") + -1 + -1 + try { $SELECTION$ } diff --git a/GameMode/AllInOneGameMode.cs b/GameMode/AllInOneGameMode.cs index 2bcc1669d..403399f31 100644 --- a/GameMode/AllInOneGameMode.cs +++ b/GameMode/AllInOneGameMode.cs @@ -24,7 +24,7 @@ public static class AllInOneGameMode public static void SetupCustomOption() { var id = 69_218_001; - var color = ColorUtility.TryParseHtmlString("#f542ad", out Color c) ? c : Color.magenta; + Color color = ColorUtility.TryParseHtmlString("#f542ad", out Color c) ? c : Color.magenta; const CustomGameMode gameMode = CustomGameMode.AllInOne; foreach (CustomGameMode mode in Enum.GetValues()) @@ -105,7 +105,7 @@ public static class AllInOneGameMode { if (!AmongUsClient.Instance.AmHost || !GameStates.IsInTask || GameStates.IsEnded || Options.CurrentGameMode != CustomGameMode.AllInOne || Main.HasJustStarted || __instance.PlayerId >= 254 || __instance.Is(CustomRoles.Killer) || CustomGameMode.HideAndSeek.IsActiveOrIntegrated()) return; - var gameModes = Enum.GetValues().Where(x => x.IsActiveOrIntegrated()).Split(x => x is CustomGameMode.CaptureTheFlag or CustomGameMode.FFA or CustomGameMode.SoloKombat); + (List TrueList, List FalseList) gameModes = Enum.GetValues().Where(x => x.IsActiveOrIntegrated()).Split(x => x is CustomGameMode.CaptureTheFlag or CustomGameMode.FFA or CustomGameMode.SoloKombat); if (gameModes.TrueList.Count == 0 || gameModes.FalseList.Count == 0) return; bool doneWithTasks = Taskers.Contains(__instance.PlayerId) && __instance.GetTaskState().IsTaskFinished; diff --git a/GameMode/CaptureTheFlag.cs b/GameMode/CaptureTheFlag.cs index d82ee0ca9..e829ba736 100644 --- a/GameMode/CaptureTheFlag.cs +++ b/GameMode/CaptureTheFlag.cs @@ -158,7 +158,7 @@ public static class CaptureTheFlag .SetGameMode(CustomGameMode.CaptureTheFlag) .SetValueFormat(OptionFormat.Seconds) .SetColor(color); - + FlagPickupRange = new FloatOptionItem(id + 12, "CTF_FlagPickupRange", new(0.25f, 5f, 0.25f), 1.5f, TabGroup.GameSettings) .SetGameMode(CustomGameMode.CaptureTheFlag) .SetValueFormat(OptionFormat.Multiplier) @@ -167,7 +167,7 @@ public static class CaptureTheFlag public static bool KnowTargetRoleColor(PlayerControl target, ref string color) { - if (!ValidTag || !PlayerTeams.TryGetValue(target.PlayerId, out var team)) return false; + if (!ValidTag || !PlayerTeams.TryGetValue(target.PlayerId, out CTFTeam team)) return false; color = team switch { @@ -192,15 +192,15 @@ public static class CaptureTheFlag if (GameEndCriteria.GetValue() == 2) { - var timeLeft = TimeLimit.GetInt() - (Utils.TimeStamp - GameStartTS) + 1; + long timeLeft = TimeLimit.GetInt() - (Utils.TimeStamp - GameStartTS) + 1; - if (timeLeft >= 0) str += $"<#ffffff>{(timeLeft / 60):00}:{(timeLeft % 60):00}\n"; + if (timeLeft >= 0) str += $"<#ffffff>{timeLeft / 60:00}:{timeLeft % 60:00}\n"; else str += $"<#ffffff>{Translator.GetString("CTF_TimeIsUp")}\n"; } - if (TemporarilyOutPlayers.TryGetValue(seer.PlayerId, out var backTS)) + if (TemporarilyOutPlayers.TryGetValue(seer.PlayerId, out long backTS)) { - var timeLeft = backTS - Utils.TimeStamp; + long timeLeft = backTS - Utils.TimeStamp; str += $"{string.Format(Translator.GetString("CTF_BackIn"), timeLeft)}\n"; } @@ -253,7 +253,7 @@ public static class CaptureTheFlag } // If all players are on the same team, end the game - if (aapc.All(x => PlayerTeams.TryGetValue(x.PlayerId, out var team) && team == CTFTeam.Blue) || aapc.All(x => PlayerTeams.TryGetValue(x.PlayerId, out var team) && team == CTFTeam.Yellow)) + if (aapc.All(x => PlayerTeams.TryGetValue(x.PlayerId, out CTFTeam team) && team == CTFTeam.Blue) || aapc.All(x => PlayerTeams.TryGetValue(x.PlayerId, out CTFTeam team) && team == CTFTeam.Yellow)) { ResetSkins(); TeamData[PlayerTeams[aapc[0].PlayerId]].SetAsWinner(); @@ -263,10 +263,7 @@ public static class CaptureTheFlag return false; } - void ResetSkins() - { - DefaultOutfits.Select(x => (pc: x.Key.GetPlayer(), outfit: x.Value)).DoIf(x => x.pc != null && x.outfit != null, x => Utils.RpcChangeSkin(x.pc, x.outfit)); - } + void ResetSkins() => DefaultOutfits.Select(x => (pc: x.Key.GetPlayer(), outfit: x.Value)).DoIf(x => x.pc != null && x.outfit != null, x => Utils.RpcChangeSkin(x.pc, x.outfit)); } public static void OnGameStart() @@ -332,7 +329,7 @@ public static class CaptureTheFlag // Teleport players to their respective bases var sender = CustomRpcSender.Create("CTF - OnGameStart", SendOption.Reliable); var hasValue = false; - + foreach (PlayerControl pc in Main.AllAlivePlayerControls) { if (PlayerTeams.TryGetValue(pc.PlayerId, out CTFTeam team)) @@ -361,8 +358,8 @@ public static class CaptureTheFlag hasValue = false; } } - - sender.SendMessage(dispose: !hasValue); + + sender.SendMessage(!hasValue); ValidTag = true; GameStartTS = Utils.TimeStamp; @@ -376,7 +373,7 @@ public static class CaptureTheFlag foreach ((CTFTeam team, CTFTeamData data) in TeamData) { - var flagBase = team.GetFlagBase().Position; + Vector2 flagBase = team.GetFlagBase().Position; data.DropFlag(); data.Flag.TP(flagBase); data.Players.ToValidPlayers().Do(x => x.TP(flagBase)); @@ -385,7 +382,7 @@ public static class CaptureTheFlag public static void OnCheckMurder(PlayerControl killer, PlayerControl target) { - if (!ValidTag || TemporarilyOutPlayers.ContainsKey(killer.PlayerId) || !PlayerTeams.TryGetValue(target.PlayerId, out var targetTeam) || !PlayerTeams.TryGetValue(killer.PlayerId, out var killerTeam) || killerTeam == targetTeam || TeamData.Values.Any(x => x.FlagCarrier == killer.PlayerId)) return; + if (!ValidTag || TemporarilyOutPlayers.ContainsKey(killer.PlayerId) || !PlayerTeams.TryGetValue(target.PlayerId, out CTFTeam targetTeam) || !PlayerTeams.TryGetValue(killer.PlayerId, out CTFTeam killerTeam) || killerTeam == targetTeam || TeamData.Values.Any(x => x.FlagCarrier == killer.PlayerId)) return; new[] { killer, target }.Do(x => x.SetKillCooldown(TagCooldown.GetFloat())); @@ -417,7 +414,7 @@ public static class CaptureTheFlag break; } - if (PlayerData.TryGetValue(killer.PlayerId, out var data)) data.TagCount++; + if (PlayerData.TryGetValue(killer.PlayerId, out CTFPlayerData data)) data.TagCount++; Utils.NotifyRoles(SpecifySeer: killer, SpecifyTarget: killer); } @@ -512,7 +509,7 @@ public static class CaptureTheFlag } Flag.TP(flagCarrierPc.Pos()); - if (PlayerData.TryGetValue(FlagCarrier, out var data)) data.FlagTime += Time.fixedDeltaTime; + if (PlayerData.TryGetValue(FlagCarrier, out CTFPlayerData data)) data.FlagTime += Time.fixedDeltaTime; Utils.NotifyRoles(SpecifySeer: flagCarrierPc, SpecifyTarget: flagCarrierPc); CTFTeam enemy = team.GetOppositeTeam(); @@ -530,7 +527,7 @@ public static class CaptureTheFlag if (GameEndCriteria.GetValue() == 0 && RoundsPlayed >= RoundsToPlay.GetInt() && RoundsWon != enemyTeam.RoundsWon) { - var winner = TeamData.Values.MaxBy(x => x.RoundsWon); + CTFTeamData winner = TeamData.Values.MaxBy(x => x.RoundsWon); winner.SetAsWinner(); return; } @@ -615,13 +612,13 @@ public static class CaptureTheFlag if (GameEndCriteria.GetValue() == 2) { - var timeLeft = TimeLimit.GetInt() - (Utils.TimeStamp - GameStartTS) + 1; + long timeLeft = TimeLimit.GetInt() - (Utils.TimeStamp - GameStartTS) + 1; switch (timeLeft) { case <= 1 when TeamData[CTFTeam.Blue].RoundsWon != TeamData[CTFTeam.Yellow].RoundsWon: { - var winner = TeamData.Values.MaxBy(x => x.RoundsWon); + CTFTeamData winner = TeamData.Values.MaxBy(x => x.RoundsWon); winner.SetAsWinner(); return; } @@ -634,7 +631,7 @@ public static class CaptureTheFlag } } - if (!PlayerTeams.TryGetValue(__instance.PlayerId, out var team)) return; + if (!PlayerTeams.TryGetValue(__instance.PlayerId, out CTFTeam team)) return; bool blue = team == CTFTeam.Blue; int colorId = blue ? 1 : 5; @@ -644,7 +641,7 @@ public static class CaptureTheFlag Vector2 pos = __instance.Pos(); Vector2 blackRoomPS = Pelican.GetBlackRoomPS(); - if (TemporarilyOutPlayers.TryGetValue(__instance.PlayerId, out var endTS)) + if (TemporarilyOutPlayers.TryGetValue(__instance.PlayerId, out long endTS)) { if (Utils.TimeStamp >= endTS) { diff --git a/GameMode/CustomHnS.cs b/GameMode/CustomHnS.cs index 5297e255b..7f7da98ca 100644 --- a/GameMode/CustomHnS.cs +++ b/GameMode/CustomHnS.cs @@ -231,10 +231,9 @@ internal static class CustomHnS result[lp] = CustomRoles.GM; PlayerRoles[lp.PlayerId] = (new Hider(), CustomRoles.GM); } + foreach (byte spectator in ChatCommands.Spectators) - { PlayerRoles[spectator] = (new Hider(), CustomRoles.GM); - } LateTask.New(() => result.IntersectBy(Main.PlayerStates.Keys, x => x.Key.PlayerId).Do(x => x.Key.RpcSetCustomRole(x.Value)), 5f, log: false); @@ -332,17 +331,16 @@ internal static class CustomHnS : string.Empty; string GetColorFromDanger() // 0: Highest, 4: Lowest - { - return danger switch - { - 0 => "#ff1313", - 1 => "#ff6a00", - 2 => "#ffaa00", - 3 => "#ffea00", - 4 => "#ffff00", - _ => "#ffffff" - }; - } + => + danger switch + { + 0 => "#ff1313", + 1 => "#ff6a00", + 2 => "#ffaa00", + 3 => "#ffea00", + 4 => "#ffff00", + _ => "#ffffff" + }; } public static string GetRoleInfoText(PlayerControl seer) @@ -432,15 +430,9 @@ internal static class CustomHnS stateText = $"{name}{stateText}"; return stateText; - CustomRoles GetRole() - { - return state.Value.MainRole == CustomRoles.Agent ? CustomRoles.Hider : state.Value.MainRole; - } + CustomRoles GetRole() => state.Value.MainRole == CustomRoles.Agent ? CustomRoles.Hider : state.Value.MainRole; - string GetTaskCount() - { - return CustomRoles.Agent.IsEnable() || !ts.HasTasks ? string.Empty : $" ({ts.CompletedTasksCount}/{ts.AllTasksCount})"; - } + string GetTaskCount() => CustomRoles.Agent.IsEnable() || !ts.HasTasks ? string.Empty : $" ({ts.CompletedTasksCount}/{ts.AllTasksCount})"; } static string GetTaskText() @@ -472,7 +464,7 @@ internal static class CustomHnS if (killer == null || target == null || PlayerRoles[killer.PlayerId].Interface.Team != Team.Impostor || PlayerRoles[target.PlayerId].Interface.Team == Team.Impostor) return; killer.Kill(target); - + if (Main.GM.Value && AmongUsClient.Instance.AmHost) PlayerControl.LocalPlayer.KillFlash(); ChatCommands.Spectators.ToValidPlayers().Do(x => x.KillFlash()); @@ -517,4 +509,4 @@ internal static class CustomHnS if (DangerMeter.GetBool() || (TimeLeft + 1) % 60 == 0 || TimeLeft <= 60) Utils.NotifyRoles(); } } -} +} \ No newline at end of file diff --git a/GameMode/FreeForAll.cs b/GameMode/FreeForAll.cs index 42fcda04e..2cbdfb65b 100644 --- a/GameMode/FreeForAll.cs +++ b/GameMode/FreeForAll.cs @@ -157,8 +157,10 @@ internal static class FreeForAll List teamMembers = allPlayers.Select(x => x.PlayerId).Shuffle().Chunk(memberNum).ToList(); for (var i = 0; i < teamMembers.Count; i++) + { foreach (byte id in teamMembers[i]) PlayerTeams.Add(id, i); + } } } @@ -176,7 +178,7 @@ internal static class FreeForAll public static string GetHudText() { - return $"{(RoundTime / 60):00}:{(RoundTime % 60):00}"; + return $"{RoundTime / 60:00}:{RoundTime % 60:00}"; } public static void OnPlayerAttack(PlayerControl killer, PlayerControl target) @@ -484,4 +486,4 @@ internal static class FreeForAll } } } -} +} \ No newline at end of file diff --git a/GameMode/HotPotato.cs b/GameMode/HotPotato.cs index 8ad722d90..c0460898c 100644 --- a/GameMode/HotPotato.cs +++ b/GameMode/HotPotato.cs @@ -69,7 +69,7 @@ internal static class HotPotato public static string GetSuffixText(byte id) { - if (!Main.PlayerStates.TryGetValue(id, out var state) || state.IsDead) return string.Empty; + if (!Main.PlayerStates.TryGetValue(id, out PlayerState state) || state.IsDead) return string.Empty; return $"{(HotPotatoState.HolderID == id ? $"{Translator.GetString("HotPotato_HoldingNotify")}\n" : string.Empty)}{Translator.GetString("HotPotato_TimeLeftSuffix")}{HotPotatoState.TimeLeft}s"; } diff --git a/GameMode/KingOfTheZones.cs b/GameMode/KingOfTheZones.cs index aaaad5557..10f692103 100644 --- a/GameMode/KingOfTheZones.cs +++ b/GameMode/KingOfTheZones.cs @@ -97,7 +97,7 @@ public static class KingOfTheZones public static void SetupCustomOption() { var id = 69_219_001; - var color = ColorUtility.TryParseHtmlString("#ff0000", out Color c) ? c : Color.red; + Color color = ColorUtility.TryParseHtmlString("#ff0000", out Color c) ? c : Color.red; const CustomGameMode gameMode = CustomGameMode.KingOfTheZones; NumTeams = new IntegerOptionItem(id++, "KingOfTheZones.NumTeams", new(2, 7, 1), 2, TabGroup.GameSettings) @@ -182,7 +182,7 @@ public static class KingOfTheZones .SetColor(color); } - static Color GetColor(this KOTZTeam team) + private static Color GetColor(this KOTZTeam team) { return team switch { @@ -197,7 +197,7 @@ public static class KingOfTheZones }; } - static byte GetColorId(this KOTZTeam team) + private static byte GetColorId(this KOTZTeam team) { return team switch { @@ -274,12 +274,12 @@ public static class KingOfTheZones try { - var skin = new NetworkedPlayerInfo.PlayerOutfit().Set(name, team.GetColorId(), "", "", "", "", ""); + NetworkedPlayerInfo.PlayerOutfit skin = new NetworkedPlayerInfo.PlayerOutfit().Set(name, team.GetColorId(), "", "", "", "", ""); Utils.RpcChangeSkin(player, skin); } catch (Exception e) { Utils.ThrowException(e); } - var notify = Utils.ColorString(team.GetColor(), GetString($"KOTZ.Notify.AssignedToTeam.{team}")); + string notify = Utils.ColorString(team.GetColor(), GetString($"KOTZ.Notify.AssignedToTeam.{team}")); if (showTutorial) { @@ -306,8 +306,8 @@ public static class KingOfTheZones { int points = PointsToWin.GetInt(); int timeLimit = MaxGameLength.GetInt(); - string mins = $"{(timeLimit / 60):N0}"; - string secs = $"{(timeLimit % 60):N0}"; + var mins = $"{timeLimit / 60:N0}"; + var secs = $"{timeLimit % 60:N0}"; bool endByPoints = GameEndsByPoints.GetBool(); bool endByTime = GameEndsByTimeLimit.GetBool(); @@ -373,8 +373,8 @@ public static class KingOfTheZones } var sender = CustomRpcSender.Create("KOTZ.GameStart.RandomSpawns", SendOption.Reliable); - var spawnsConst = RandomSpawn.SpawnMap.GetSpawnMap().Positions.ExceptBy(Zones, x => x.Key).ToArray(); - var spawns = spawnsConst.ToList(); + KeyValuePair[] spawnsConst = RandomSpawn.SpawnMap.GetSpawnMap().Positions.ExceptBy(Zones, x => x.Key).ToArray(); + List> spawns = spawnsConst.ToList(); foreach (PlayerControl player in aapc) { @@ -382,7 +382,7 @@ public static class KingOfTheZones { sender.SetKillCooldown(player, TagCooldown.GetInt()); - var spawn = spawns.RandomElement(); + KeyValuePair spawn = spawns.RandomElement(); sender.TP(player, spawn.Value); spawns.RemoveAll(x => x.Key == spawn.Key); @@ -390,7 +390,7 @@ public static class KingOfTheZones } catch (Exception e) { Utils.ThrowException(e); } } - + sender.SendMessage(); TimeLeft = GameEndsByTimeLimit.GetBool() ? MaxGameLength.GetInt() : 0; @@ -403,7 +403,7 @@ public static class KingOfTheZones Main.AllPlayerSpeed.SetAllValues(Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod)); Utils.SyncAllSettings(); - yield return Utils.NotifyEveryoneAsync(speed: 1, noCache: false); + yield return Utils.NotifyEveryoneAsync(1, false); yield break; IEnumerator StartingCountdown() @@ -424,7 +424,7 @@ public static class KingOfTheZones { if (!GameGoing || !Main.IntroDestroyed) return false; - if (PlayerTeams.TryGetValue(pc.PlayerId, out var team)) + if (PlayerTeams.TryGetValue(pc.PlayerId, out KOTZTeam team)) { color = team switch { @@ -468,16 +468,16 @@ public static class KingOfTheZones long now = Utils.TimeStamp; bool justStarted = GameStartTS + 15 > now; - if (RespawnTimes.TryGetValue(seer.PlayerId, out var respawnTS)) + if (RespawnTimes.TryGetValue(seer.PlayerId, out long respawnTS)) sb.AppendLine(string.Format(GetString("KOTZ.Suffix.RespawnTime"), respawnTS - now)); - else if (SpawnProtectionTimes.TryGetValue(seer.PlayerId, out var protectionEndTS)) + else if (SpawnProtectionTimes.TryGetValue(seer.PlayerId, out long protectionEndTS)) sb.AppendLine(string.Format(GetString("KOTZ.Suffix.SpawnProtectionTime"), protectionEndTS - now)); - var room = seer.GetPlainShipRoom(); - var zone = room == null ? SystemTypes.Hallway : room.RoomId; + PlainShipRoom room = seer.GetPlainShipRoom(); + SystemTypes zone = room == null ? SystemTypes.Hallway : room.RoomId; if (justStarted) sb.Append(GetString(Zones.Count == 1 ? "KOTZ.SuffixHelp.Zones.Single" : "KOTZ.SuffixHelp.Zones.Plural")); - sb.AppendLine(string.Join(" | ", Zones.Select(x => Utils.ColorString(ZoneDomination[x].GetColor(), (zone == x ? "" : string.Empty) + GetString($"{x}") + (zone == x ? "" : string.Empty) + (ZoneMoveSchedules.TryGetValue(x, out var moveTS) ? $" {(ZoneDowntimeExpire.TryGetValue(x, out var downtimeEndTS) ? Utils.ColorString(Color.gray, $"{downtimeEndTS - now}") : $"<#ffff44>{moveTS - now}")}" : string.Empty))))); + sb.AppendLine(string.Join(" | ", Zones.Select(x => Utils.ColorString(ZoneDomination[x].GetColor(), (zone == x ? "" : string.Empty) + GetString($"{x}") + (zone == x ? "" : string.Empty) + (ZoneMoveSchedules.TryGetValue(x, out long moveTS) ? $" {(ZoneDowntimeExpire.TryGetValue(x, out long downtimeEndTS) ? Utils.ColorString(Color.gray, $"{downtimeEndTS - now}") : $"<#ffff44>{moveTS - now}")}" : string.Empty))))); if (justStarted) sb.Append(GetString("KOTZ.SuffixHelp.Points")); sb.AppendLine(string.Join(" | ", Points.IntersectBy(PlayerTeams.Values, x => x.Key).Select(x => Utils.ColorString(x.Key.GetColor(), $"{x.Value}")))); @@ -488,7 +488,7 @@ public static class KingOfTheZones if (tie && end) { - var tieTeams = string.Join(' ', Points.Where(x => x.Value == highestPoints).Select(x => Utils.ColorString(x.Key.GetColor(), "\u25a0"))); + string tieTeams = string.Join(' ', Points.Where(x => x.Value == highestPoints).Select(x => Utils.ColorString(x.Key.GetColor(), "\u25a0"))); sb.AppendLine($"{string.Format(GetString("KOTZ.Suffix.Tie"), tieTeams)}"); } else @@ -496,7 +496,7 @@ public static class KingOfTheZones if (GameEndsByTimeLimit.GetBool()) { if (justStarted) sb.Append(GetString("KOTZ.SuffixHelp.GameEndTimer")); - sb.AppendLine($"{(TimeLeft / 60):N0}:{(TimeLeft % 60):00}"); + sb.AppendLine($"{TimeLeft / 60:N0}:{TimeLeft % 60:00}"); } if (GameEndsByPoints.GetBool()) @@ -534,8 +534,8 @@ public static class KingOfTheZones return true; case 1: ResetSkins(); - var winner = PlayerTeams[aapc[0].PlayerId]; - var color = winner.GetColor(); + KOTZTeam winner = PlayerTeams[aapc[0].PlayerId]; + Color color = winner.GetColor(); CustomWinnerHolder.WinnerIds = PlayerTeams.Where(x => x.Value == winner).Select(x => x.Key).ToHashSet(); WinnerData = (color, Utils.ColorString(color, GetString($"KOTZ.EndScreen.Winner.{winner}"))); return true; @@ -546,7 +546,7 @@ public static class KingOfTheZones void ResetSkins() => DefaultOutfits.Select(x => (pc: x.Key.GetPlayer(), outfit: x.Value)).DoIf(x => x.pc != null && x.outfit != null, x => Utils.RpcChangeSkin(x.pc, x.outfit)); } - enum KOTZTeam + private enum KOTZTeam { None, Red, @@ -753,7 +753,7 @@ public static class KingOfTheZones if (tie) return; GameGoing = false; DefaultOutfits.Select(x => (pc: x.Key.GetPlayer(), outfit: x.Value)).DoIf(x => x.pc != null && x.outfit != null, x => Utils.RpcChangeSkin(x.pc, x.outfit)); - var winner = Points.GetKeyByValue(highestPoints); + KOTZTeam winner = Points.GetKeyByValue(highestPoints); CustomWinnerHolder.WinnerIds = PlayerTeams.Where(x => x.Value == winner).Select(x => x.Key).ToHashSet(); Color color = winner.GetColor(); WinnerData = (color, Utils.ColorString(color, GetString($"KOTZ.EndScreen.Winner.{winner}"))); diff --git a/GameMode/MoveAndStop.cs b/GameMode/MoveAndStop.cs index ac65cbd73..7ab8f985b 100644 --- a/GameMode/MoveAndStop.cs +++ b/GameMode/MoveAndStop.cs @@ -185,7 +185,7 @@ internal static class MoveAndStop private static int DefaultMinValue => 5; private static int DefaultMaxValue => 30; - public static string HUDText => $"{(RoundTime / 60):00}:{(RoundTime % 60):00}"; + public static string HUDText => $"{RoundTime / 60:00}:{RoundTime % 60:00}"; public static bool IsEventActive => Event.Duration + Event.StartTimeStamp > Utils.TimeStamp; private static int StartingGreenTime(PlayerControl pc) @@ -193,7 +193,7 @@ internal static class MoveAndStop if (Options.CurrentGameMode == CustomGameMode.AllInOne) return 60; bool tutorial = EnableTutorial.GetBool() && !HasPlayed.Contains(pc.FriendCode); - int time = 37; + var time = 37; if (tutorial) time += 10; if (Main.CurrentMap is MapNames.Airship or MapNames.Fungle) time += 5; if (Main.CurrentMap == MapNames.Airship) time += 7; @@ -390,7 +390,7 @@ internal static class MoveAndStop { if (!pc.IsAlive() || !AllPlayerTimers.TryGetValue(pc.PlayerId, out MoveAndStopPlayerData timers)) return string.Empty; - var text = IsEventActive ? $"{string.Format(GetString("MoveAndStop_EventActive"), GetString($"MoveAndStop_Event_{Event.Type}"), Event.Duration + Event.StartTimeStamp - Utils.TimeStamp)}\n" : "\n"; + string text = IsEventActive ? $"{string.Format(GetString("MoveAndStop_EventActive"), GetString($"MoveAndStop_Event_{Event.Type}"), Event.Duration + Event.StartTimeStamp - Utils.TimeStamp)}\n" : "\n"; text += IsEventActive && Event.Type == Events.FrozenTimers ? FixedUpdatePatch.LastSuffix[pc.PlayerId].Trim() : timers.ToString(); if (TimeSinceStart < 20 && EnableTutorial.GetBool() && !HasPlayed.Contains(pc.FriendCode) && Options.CurrentGameMode != CustomGameMode.AllInOne) @@ -399,7 +399,10 @@ internal static class MoveAndStop return text; } - public static int GetLivesRemaining(byte id) => AllPlayerTimers.TryGetValue(id, out MoveAndStopPlayerData data) ? data.Lives : 0; + public static int GetLivesRemaining(byte id) + { + return AllPlayerTimers.TryGetValue(id, out MoveAndStopPlayerData data) ? data.Lives : 0; + } [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.FixedUpdate))] private static class FixedUpdatePatch @@ -417,9 +420,9 @@ internal static class MoveAndStop PlayerControl pc = __instance; long now = Utils.TimeStamp; - if (TimeSinceStart > 35 && !IsEventActive && (now - Event.StartTimeStamp - Event.Duration) >= EventFrequency.GetInt()) + if (TimeSinceStart > 35 && !IsEventActive && now - Event.StartTimeStamp - Event.Duration >= EventFrequency.GetInt()) { - var pool = EventChances.SelectMany(x => Enumerable.Repeat(x.Key, x.Value.GetInt() / 5)).ToList(); + List pool = EventChances.SelectMany(x => Enumerable.Repeat(x.Key, x.Value.GetInt() / 5)).ToList(); if (Event.Duration == 0) pool.RemoveAll(x => x == Events.VentAccess); if (pool.Count > 0) diff --git a/GameMode/NaturalDisasters.cs b/GameMode/NaturalDisasters.cs index 751d298b9..798707065 100644 --- a/GameMode/NaturalDisasters.cs +++ b/GameMode/NaturalDisasters.cs @@ -42,8 +42,15 @@ public static class NaturalDisasters "ND_LimitReachedOptions.RemoveOldest" ]; - public static List GetActiveDisasters() => ActiveDisasters; - public static List GetAllDisasters() => AllDisasters; + public static List GetActiveDisasters() + { + return ActiveDisasters; + } + + public static List GetAllDisasters() + { + return AllDisasters; + } public static void SetupCustomOption() { @@ -299,7 +306,10 @@ public static class NaturalDisasters } } - public static void AddPreparingDisaster(Vector2 position, string disasterName, SystemTypes? room) => PreparingDisasters.Add(new(position, DisasterWarningTime.GetFloat(), Sprite(disasterName), disasterName, room)); + public static void AddPreparingDisaster(Vector2 position, string disasterName, SystemTypes? room) + { + PreparingDisasters.Add(new(position, DisasterWarningTime.GetFloat(), Sprite(disasterName), disasterName, room)); + } } public abstract class Disaster @@ -334,8 +344,10 @@ public static class NaturalDisasters 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); + } } } @@ -557,7 +569,7 @@ public static class NaturalDisasters case <= dragRange: Vector2 direction = (Position - pos).normalized; Vector2 newPosition = pos + (direction * 0.1f); - pc.TP(newPosition, noCheckState: true); + pc.TP(newPosition, true); continue; } } @@ -653,8 +665,10 @@ public static class NaturalDisasters else { foreach (PlayerControl pc in Main.AllAlivePlayerControls) + { if (Vector2.Distance(pc.Pos(), hit) <= Range / 2f) pc.Suicide(PlayerState.DeathReason.Lightning); + } } } } @@ -722,8 +736,10 @@ public static class NaturalDisasters if (base.RemoveIfExpired()) { foreach (PlayerControl pc in Main.AllAlivePlayerControls) + { if (AffectedPlayers.Remove(pc.PlayerId)) pc.MarkDirtySettings(); + } return true; } @@ -877,8 +893,10 @@ public static class NaturalDisasters // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < Sinkholes.Count; i++) + { if (Vector2.Distance(pos, Sinkholes[i].Position) <= Range) pc.Suicide(PlayerState.DeathReason.Sunken); + } } } @@ -906,8 +924,10 @@ public static class NaturalDisasters if (room == null) return; foreach (PlayerControl pc in Main.AllAlivePlayerControls) + { if (pc.GetPlainShipRoom() == room) pc.Suicide(PlayerState.DeathReason.Collapsed); + } CollapsedRooms.Add(room); Utils.NotifyRoles(); diff --git a/GameMode/RoomRush.cs b/GameMode/RoomRush.cs index 3b74c13ed..4d1e149a0 100644 --- a/GameMode/RoomRush.cs +++ b/GameMode/RoomRush.cs @@ -28,7 +28,6 @@ public static class RoomRush public static readonly HashSet HasPlayedFriendCodes = []; public static Dictionary VentLimit = []; - public static bool PointsSystem => WinByPointsInsteadOfDeaths.GetBool(); private static HashSet AllRooms = []; private static SystemTypes RoomGoal; @@ -132,6 +131,8 @@ public static class RoomRush } }; + public static bool PointsSystem => WinByPointsInsteadOfDeaths.GetBool(); + public static void SetupCustomOption() { var id = 69_217_001; @@ -243,7 +244,7 @@ public static class RoomRush if (showTutorial) { - int readingTime = 4; + var readingTime = 4; StringBuilder sb = new(Translator.GetString("RR_Tutorial_Basics")); sb.AppendLine(); @@ -372,7 +373,7 @@ public static class RoomRush bool involvesDecontamination = map switch { - MapNames.MiraHQ => (previous is SystemTypes.Laboratory or SystemTypes.Reactor) ^ (RoomGoal is SystemTypes.Laboratory or SystemTypes.Reactor), + MapNames.MiraHQ => previous is SystemTypes.Laboratory or SystemTypes.Reactor ^ RoomGoal is SystemTypes.Laboratory or SystemTypes.Reactor, MapNames.Polus => previous == SystemTypes.Specimens || RoomGoal == SystemTypes.Specimens, _ => false }; @@ -407,9 +408,26 @@ public static class RoomRush if (DisplayArrowToRoom.GetBool()) Main.AllPlayerControls.Do(x => LocateArrow.Add(x.PlayerId, goalPos)); Utils.NotifyRoles(); - + if (WinByPointsInsteadOfDeaths.GetBool()) + { Logger.Info($"Points: {string.Join(", ", Points.Select(x => $"{Main.AllPlayerNames[x.Key]}: {x.Value}"))}", "RoomRush"); + + if (Utils.DoRPC) + { + MessageWriter w = Utils.CreateRPC(CustomRPC.RoomRushDataSync); + w.WritePacked(3); + w.WritePacked(Points.Count); + + foreach ((byte key, int value) in Points) + { + w.Write(key); + w.WritePacked(value); + } + + Utils.EndRPC(w); + } + } } public static PlainShipRoom GetRoomClass(this SystemTypes systemTypes) @@ -434,7 +452,7 @@ public static class RoomRush color = done ? Color.white : Color.yellow; sb.Append(Utils.ColorString(color, TimeLeft.ToString()) + "\n"); - if (WinByPointsInsteadOfDeaths.GetBool() && Points.TryGetValue(seer.PlayerId, out var points)) + if (WinByPointsInsteadOfDeaths.GetBool() && Points.TryGetValue(seer.PlayerId, out int points)) { sb.Append(string.Format(Translator.GetString("RR_Points"), points, PointsToWin.GetInt())); @@ -465,11 +483,23 @@ public static class RoomRush case 1: int ventLimit = VentTimes.GetInt(); VentLimit = Main.AllPlayerControls.ToDictionary(x => x.PlayerId, _ => ventLimit); + if (WinByPointsInsteadOfDeaths.GetBool()) Points = Main.AllPlayerControls.ToDictionary(x => x.PlayerId, _ => 0); break; case 2: int limit = reader.ReadPackedInt32(); byte id = reader.ReadByte(); VentLimit[id] = limit; + break; + case 3: + int count = reader.ReadPackedInt32(); + + for (var i = 0; i < count; i++) + { + byte key = reader.ReadByte(); + int value = reader.ReadPackedInt32(); + Points[key] = value; + } + break; } } @@ -560,7 +590,7 @@ public static class RoomRush { if (playersOutsideRoom.Length == lateAapc.Length) { - var roomPos = Map.Positions.GetValueOrDefault(RoomGoal, RoomGoal.GetRoomClass().transform.position); + Vector2 roomPos = Map.Positions.GetValueOrDefault(RoomGoal, RoomGoal.GetRoomClass().transform.position); playersOutsideRoom.Do(x => x.TP(roomPos)); } else playersOutsideRoom.Do(x => x.TP(DonePlayers.RandomElement().GetPlayer())); diff --git a/GameMode/SoloPVP.cs b/GameMode/SoloPVP.cs index 0841cf3ba..93f0723a3 100644 --- a/GameMode/SoloPVP.cs +++ b/GameMode/SoloPVP.cs @@ -135,7 +135,7 @@ internal static class SoloPVP private static string GetStatsForVanilla(PlayerControl pc) { - string finalText = string.Empty; + var finalText = string.Empty; if (pc.IsHost()) return finalText; finalText += ""; @@ -153,7 +153,7 @@ internal static class SoloPVP if (rank != 1) { - var first = Main.PlayerStates.Keys.MinBy(GetRankFromScore); + byte first = Main.PlayerStates.Keys.MinBy(GetRankFromScore); finalText += $"\n1. {first.ColoredPlayerName()} - {string.Format(Translator.GetString("KillCount").TrimStart(' '), KBScore.GetValueOrDefault(first, 0))}"; } @@ -189,7 +189,7 @@ internal static class SoloPVP public static string GetHudText() { - return $"{(RoundTime / 60):00}:{(RoundTime % 60):00}"; + return $"{RoundTime / 60:00}:{RoundTime % 60:00}"; } public static void OnPlayerAttack(PlayerControl killer, PlayerControl target) @@ -356,7 +356,7 @@ internal static class SoloPVP if (BackCountdown[id] <= 0) OnPlayerBack(__instance); } - if (NameNotify.TryGetValue(id, out var nameNotify) && nameNotify.TimeStamp < now) + if (NameNotify.TryGetValue(id, out (string Text, long TimeStamp) nameNotify) && nameNotify.TimeStamp < now) NameNotify.Remove(id); Utils.NotifyRoles(SpecifySeer: __instance, SpecifyTarget: __instance); diff --git a/GameMode/Speedrun.cs b/GameMode/Speedrun.cs index 4782c2f89..b834af277 100644 --- a/GameMode/Speedrun.cs +++ b/GameMode/Speedrun.cs @@ -155,7 +155,7 @@ public static class Speedrun if (Main.GM.Value && AmongUsClient.Instance.AmHost) PlayerControl.LocalPlayer.KillFlash(); ChatCommands.Spectators.ToValidPlayers().Do(x => x.KillFlash()); } - + return allow; } diff --git a/Main.cs b/Main.cs index ed9cd2982..b3064934e 100644 --- a/Main.cs +++ b/Main.cs @@ -802,8 +802,8 @@ public class Main : BasePlugin public static IEnumerator GetRandomWord(Action onComplete) { - string api = "https://random-word.ryanrk.com/api/en/word/random"; - var request = UnityWebRequest.Get(api); + var api = "https://random-word.ryanrk.com/api/en/word/random"; + UnityWebRequest request = UnityWebRequest.Get(api); yield return request.SendWebRequest(); if (request.result != UnityWebRequest.Result.Success) diff --git a/Modules/Achievements.cs b/Modules/Achievements.cs index 8545d2890..3996a9c56 100644 --- a/Modules/Achievements.cs +++ b/Modules/Achievements.cs @@ -109,11 +109,11 @@ public static class Achievements ItsJustAPrankBro // As Bomber, Kill half the lobby in 1 bomb } - const string SaveFilePath = "./EHR_DATA/Achievements.json"; + private const string SaveFilePath = "./EHR_DATA/Achievements.json"; - const string ApiBaseUrl = "https://gurge44.pythonanywhere.com/achievements"; - const string ApiSaveEndpoint = $"{ApiBaseUrl}/save"; - const string ApiLoadEndpoint = $"{ApiBaseUrl}/load"; + private const string ApiBaseUrl = "https://gurge44.pythonanywhere.com/achievements"; + private const string ApiSaveEndpoint = $"{ApiBaseUrl}/save"; + private const string ApiLoadEndpoint = $"{ApiBaseUrl}/load"; public static readonly HashSet WaitingAchievements = []; public static HashSet CompletedAchievements = []; @@ -145,7 +145,7 @@ public static class Achievements IEnumerator CompleteAchievementAfterDelayAsync() { - float timer = 0f; + var timer = 0f; while (!GameStates.IsEnded && timer < delay) { @@ -171,8 +171,8 @@ public static class Achievements private static void ShowAchievementCompletion(Type type) { - var title = Translator.GetString("AchievementCompletedTitle"); - var description = Translator.GetString($"Achievement.{type}.Description"); + string title = Translator.GetString("AchievementCompletedTitle"); + string description = Translator.GetString($"Achievement.{type}.Description"); var message = $"{Translator.GetString($"Achievement.{type}")}\n{description}"; ChatBubbleShower.ShowChatBubbleInRound(message, title); @@ -180,7 +180,7 @@ public static class Achievements private static void SaveAllData() { - var json = JsonSerializer.Serialize(CompletedAchievements); + string json = JsonSerializer.Serialize(CompletedAchievements); File.WriteAllText(SaveFilePath, json); if (!Options.StoreCompletedAchievementsOnEHRDatabase.GetBool()) return; @@ -191,7 +191,7 @@ public static class Achievements { while (PlayerControl.LocalPlayer == null) yield return null; - var userId = PlayerControl.LocalPlayer.GetClient().GetHashedPuid(); + string userId = PlayerControl.LocalPlayer.GetClient().GetHashedPuid(); var data = new { @@ -199,7 +199,7 @@ public static class Achievements achievements = CompletedAchievements }; - var payload = JsonSerializer.Serialize(data); + string payload = JsonSerializer.Serialize(data); var request = new UnityWebRequest(ApiSaveEndpoint, UnityWebRequest.kHttpVerbPOST) { @@ -218,7 +218,7 @@ public static class Achievements { if (File.Exists(SaveFilePath)) { - var json = File.ReadAllText(SaveFilePath); + string json = File.ReadAllText(SaveFilePath); CompletedAchievements = JsonSerializer.Deserialize>(json); } else if (Options.StoreCompletedAchievementsOnEHRDatabase.GetBool()) @@ -230,16 +230,17 @@ public static class Achievements { while (PlayerControl.LocalPlayer == null) yield return null; - var userId = PlayerControl.LocalPlayer.GetClient().GetHashedPuid(); + string userId = PlayerControl.LocalPlayer.GetClient().GetHashedPuid(); var url = $"{ApiLoadEndpoint}?userId={userId}"; - var request = UnityWebRequest.Get(url); + UnityWebRequest request = UnityWebRequest.Get(url); yield return request.SendWebRequest(); - if (request.result != UnityWebRequest.Result.Success) { Logger.Error($"Error loading achievements: {request.error}", "Achievements.LoadAllData"); } + if (request.result != UnityWebRequest.Result.Success) + Logger.Error($"Error loading achievements: {request.error}", "Achievements.LoadAllData"); else { - var json = request.downloadHandler.text; + string json = request.downloadHandler.text; CompletedAchievements = JsonSerializer.Deserialize>(json); yield return File.WriteAllTextAsync(SaveFilePath, json); Logger.Info("Achievements loaded successfully.", "Achievements.LoadAllData"); diff --git a/Modules/AddSteamID.cs b/Modules/AddSteamID.cs index 35adf726d..525eb1ace 100644 --- a/Modules/AddSteamID.cs +++ b/Modules/AddSteamID.cs @@ -20,9 +20,6 @@ public static class AddSteamID ModUpdater.ShowPopup(GetString("AppIDAdded"), StringNames.Close, true); } } - catch (Exception e) - { - Utils.ThrowException(e); - } + catch (Exception e) { Utils.ThrowException(e); } } } \ No newline at end of file diff --git a/Modules/AntiBlackout.cs b/Modules/AntiBlackout.cs index 3366950f9..f4f49c9fa 100644 --- a/Modules/AntiBlackout.cs +++ b/Modules/AntiBlackout.cs @@ -84,15 +84,15 @@ public static class AntiBlackout var hasValue = false; var sender = CustomRpcSender.Create("AntiBlackout.RevivePlayersAndSetDummyImp", SendOption.Reliable); - foreach (var seer in Main.AllPlayerControls) + foreach (PlayerControl seer in Main.AllPlayerControls) { if (seer.IsModdedClient()) continue; - var seerIsAliveAndHasKillButton = seer.HasKillButton() && seer.IsAlive() && Options.CurrentGameMode == CustomGameMode.Standard; + bool seerIsAliveAndHasKillButton = seer.HasKillButton() && seer.IsAlive() && Options.CurrentGameMode == CustomGameMode.Standard; if (Options.CurrentGameMode is not (CustomGameMode.MoveAndStop or CustomGameMode.HotPotato or CustomGameMode.Speedrun or CustomGameMode.HideAndSeek or CustomGameMode.NaturalDisasters or CustomGameMode.RoomRush)) { - foreach (var target in Main.AllPlayerControls) + foreach (PlayerControl target in Main.AllPlayerControls) { if (seerIsAliveAndHasKillButton) { @@ -125,7 +125,7 @@ public static class AntiBlackout } } - sender.SendMessage(dispose: !hasValue); + sender.SendMessage(!hasValue); } public static void RestoreIsDead(bool doSend = true, [CallerMemberName] string callerMethodName = "") @@ -170,9 +170,9 @@ public static class AntiBlackout writer.StartMessage(5); writer.Write(AmongUsClient.Instance.GameId); - bool hasValue = false; + var hasValue = false; - foreach (var playerinfo in GameData.Instance.AllPlayers) + foreach (NetworkedPlayerInfo playerinfo in GameData.Instance.AllPlayers) { try { @@ -236,15 +236,15 @@ public static class AntiBlackout // skip host if (seerId == 0) continue; - var seer = seerId.GetPlayer(); - var target = targetId.GetPlayer(); + PlayerControl seer = seerId.GetPlayer(); + PlayerControl target = targetId.GetPlayer(); if (seer == null || target == null) continue; if (seer.IsModdedClient()) continue; - var isSelf = seerId == targetId; - var isDead = target.Data.IsDead; - var changedRoleType = roletype; + bool isSelf = seerId == targetId; + bool isDead = target.Data.IsDead; + RoleTypes changedRoleType = roletype; switch (isDead) { @@ -260,7 +260,7 @@ public static class AntiBlackout } case true: { - var seerIsKiller = seer.Is(Team.Impostor) || seer.HasDesyncRole(); + bool seerIsKiller = seer.Is(Team.Impostor) || seer.HasDesyncRole(); if (!seerIsKiller && target.Is(Team.Impostor)) changedRoleType = RoleTypes.ImpostorGhost; else changedRoleType = RoleTypes.CrewmateGhost; @@ -275,7 +275,7 @@ public static class AntiBlackout hasValue = true; } - foreach (var pc in selfExiled) + foreach (PlayerControl pc in selfExiled) { sender.AutoStartRpc(pc.NetId, (byte)RpcCalls.Exiled); sender.EndRpc(); @@ -301,7 +301,7 @@ public static class AntiBlackout PlayerControl[] apc = Main.AllPlayerControls; apc.DoIf(x => x.Is(CustomRoles.Killer), x => sender.RpcSetRole(x, RoleTypes.Impostor, x.OwnerId)); - foreach (var pc in apc) + foreach (PlayerControl pc in apc) { if (!pc.Is(CustomRoles.Killer)) { @@ -322,14 +322,14 @@ public static class AntiBlackout } } - sender.SendMessage(dispose: !hasValue); + sender.SendMessage(!hasValue); ResetAllCooldowns(); } private static void ResetAllCooldowns() { var sender = CustomRpcSender.Create("AntiBlackout.ResetAllCooldowns", SendOption.Reliable); - + foreach (PlayerControl seer in Main.AllPlayerControls) { try diff --git a/Modules/BanManager.cs b/Modules/BanManager.cs index 1e9e286c6..6c3a21bb7 100644 --- a/Modules/BanManager.cs +++ b/Modules/BanManager.cs @@ -64,10 +64,7 @@ public static class BanManager EACList.Add(line); } } - catch (Exception ex) - { - Logger.Exception(ex, "BanManager"); - } + catch (Exception ex) { Logger.Exception(ex, "BanManager"); } } private static string GetResourcesTxt(string path) @@ -227,16 +224,15 @@ public static class BanManager if (line == "") continue; if (!OnlyCheckPuid) + { if (line.Contains(code)) return true; + } if (line.Contains(hashedpuid)) return true; } } - catch (Exception ex) - { - Logger.Exception(ex, "CheckBanList"); - } + catch (Exception ex) { Logger.Exception(ex, "CheckBanList"); } return false; } diff --git a/Modules/Camouflague.cs b/Modules/Camouflague.cs index 70dbd4068..1867acd5b 100644 --- a/Modules/Camouflague.cs +++ b/Modules/Camouflague.cs @@ -77,7 +77,8 @@ public static class Camouflage public static void SetPetForOutfitIfNecessary(NetworkedPlayerInfo.PlayerOutfit outfit) { - if (Options.UsePets.GetBool()) { outfit.PetId = PetsHelper.GetPetId(); } + if (Options.UsePets.GetBool()) + outfit.PetId = PetsHelper.GetPetId(); } private static bool ShouldCamouflage(bool alreadyCamouflaged) @@ -128,7 +129,7 @@ public static class Camouflage private static IEnumerator UpdateCamouflageStatusAsync() { var sender = CustomRpcSender.Create("Camouflage.RpcSetSkin", SendOption.Reliable); - + foreach (PlayerControl pc in Main.AllPlayerControls) { if (pc.inVent || pc.walkingToVent || pc.onLadder || pc.inMovingPlat) @@ -143,7 +144,7 @@ public static class Camouflage } sender.SendMessage(); - yield return Utils.NotifyEveryoneAsync(speed: 5); + yield return Utils.NotifyEveryoneAsync(5); } public static void RpcSetSkin(PlayerControl target, bool forceRevert = false, bool revertToDefault = false, bool gameEnd = false, bool revive = false, bool notCommsOrCamo = false, CustomRpcSender sender = null) diff --git a/Modules/ChatBubbleShower.cs b/Modules/ChatBubbleShower.cs index 2c610357c..4ab9c8663 100644 --- a/Modules/ChatBubbleShower.cs +++ b/Modules/ChatBubbleShower.cs @@ -69,11 +69,11 @@ public static class ChatBubbleShower { const string color1 = "#00FFA5"; const string color2 = "#00A5FF"; - bool isColor1 = true; + var isColor1 = true; - for (int i = 0; i < 4; i++) + for (var i = 0; i < 4; i++) { - var color = isColor1 ? color1 : color2; + string color = isColor1 ? color1 : color2; isColor1 = !isColor1; var text = $"{title}\n{message}"; HudManagerPatch.AchievementUnlockedText = text; @@ -84,14 +84,11 @@ public static class ChatBubbleShower HudManagerPatch.AchievementUnlockedText = string.Empty; } } - catch (Exception e) - { - Utils.ThrowException(e); - } + catch (Exception e) { Utils.ThrowException(e); } } /// - /// Displays a chat bubble with a message and a title during the round for the local player. + /// Displays a chat bubble with a message and a title during the round for the local player. /// /// The message to display in the chat bubble. /// The title of the chat bubble. diff --git a/Modules/ClientOptionItem.cs b/Modules/ClientOptionItem.cs index 0cef8361d..4cd1b5838 100644 --- a/Modules/ClientOptionItem.cs +++ b/Modules/ClientOptionItem.cs @@ -100,10 +100,7 @@ public class ClientOptionItem UpdateToggle(); } - finally - { - NumOptions++; - } + finally { NumOptions++; } } public static ClientOptionItem Create( diff --git a/Modules/Cloud.cs b/Modules/Cloud.cs index 920f4fa5c..7e00be674 100644 --- a/Modules/Cloud.cs +++ b/Modules/Cloud.cs @@ -64,10 +64,7 @@ internal class Cloud //LOBBY_PORT = int.Parse(ar[1]); EAC_PORT = int.Parse(ar[2]); } - catch (Exception e) - { - Logger.Exception(e, "Cloud Init"); - } + catch (Exception e) { Logger.Exception(e, "Cloud Init"); } } private static string GetResourcesTxt(string path) diff --git a/Modules/CustomNetObject.cs b/Modules/CustomNetObject.cs index 8371c7d4c..19e4886b0 100644 --- a/Modules/CustomNetObject.cs +++ b/Modules/CustomNetObject.cs @@ -176,7 +176,7 @@ namespace EHR protected void CreateNetObject(string sprite, Vector2 position) { - if (GameStates.IsEnded || (GameStates.CurrentServerType == GameStates.ServerType.ModdedWithoutCNOSupport) || !AmongUsClient.Instance.AmHost) return; + if (GameStates.IsEnded || GameStates.CurrentServerType == GameStates.ServerType.ModdedWithoutCNOSupport || !AmongUsClient.Instance.AmHost) return; Logger.Info($" Create Custom Net Object {GetType().Name} (ID {MaxId + 1}) at {position}", "CNO.CreateNetObject"); playerControl = Object.Instantiate(AmongUsClient.Instance.PlayerPrefab, Vector2.zero, Quaternion.identity); playerControl.PlayerId = 254; diff --git a/Modules/CustomRoleSelector.cs b/Modules/CustomRoleSelector.cs index b452cf3cf..5aa66666e 100644 --- a/Modules/CustomRoleSelector.cs +++ b/Modules/CustomRoleSelector.cs @@ -41,7 +41,7 @@ internal static class CustomRoleSelector if (Options.CurrentGameMode != CustomGameMode.Standard) { - if (GameModeRoles.TryGetValue(Options.CurrentGameMode, out var role)) + if (GameModeRoles.TryGetValue(Options.CurrentGameMode, out CustomRoles role)) { AssignRoleToEveryone(role); return; @@ -51,9 +51,9 @@ internal static class CustomRoleSelector if (Options.CurrentGameMode == CustomGameMode.AllInOne) { - var prioritizedGameMode = AllInOneGameMode.GetPrioritizedGameModeForRoles(); + CustomGameMode prioritizedGameMode = AllInOneGameMode.GetPrioritizedGameModeForRoles(); - if (GameModeRoles.TryGetValue(prioritizedGameMode, out var allInOneRole)) + if (GameModeRoles.TryGetValue(prioritizedGameMode, out CustomRoles allInOneRole)) { AssignRoleToEveryone(allInOneRole); return; @@ -151,8 +151,8 @@ internal static class CustomRoleSelector else Roles[RoleAssignType.Crewmate].Add(new(CustomRoles.LovingCrewmate, 100, 2)); } - var covenLimits = Options.FactionMinMaxSettings[Team.Coven]; - var numCovens = rd.Next(covenLimits.MinSetting.GetInt(), covenLimits.MaxSetting.GetInt() + 1); + (OptionItem MinSetting, OptionItem MaxSetting) covenLimits = Options.FactionMinMaxSettings[Team.Coven]; + int numCovens = rd.Next(covenLimits.MinSetting.GetInt(), covenLimits.MaxSetting.GetInt() + 1); if (numCovens > 0 && !Main.SetRoles.ContainsValue(CustomRoles.CovenLeader) && !ChatCommands.DraftResult.ContainsValue(CustomRoles.CovenLeader)) { @@ -161,8 +161,8 @@ internal static class CustomRoleSelector readyRoleNum++; } - var neutralLimits = Options.FactionMinMaxSettings[Team.Neutral]; - var numNeutrals = rd.Next(neutralLimits.MinSetting.GetInt(), neutralLimits.MaxSetting.GetInt() + 1); + (OptionItem MinSetting, OptionItem MaxSetting) neutralLimits = Options.FactionMinMaxSettings[Team.Neutral]; + int numNeutrals = rd.Next(neutralLimits.MinSetting.GetInt(), neutralLimits.MaxSetting.GetInt() + 1); if (Roles[RoleAssignType.Impostor].Count == 0 && numNeutrals == 0 && !Main.SetRoles.Values.Any(x => x.IsImpostor() || x.IsNK())) { @@ -195,7 +195,7 @@ internal static class CustomRoleSelector try { - var impLimits = subCategoryLimits.Where(x => x.Key.GetTabFromOptionType() == TabGroup.ImpostorRoles).ToDictionary(x => x.Key, x => x.Value); + Dictionary impLimits = subCategoryLimits.Where(x => x.Key.GetTabFromOptionType() == TabGroup.ImpostorRoles).ToDictionary(x => x.Key, x => x.Value); if (impLimits.Count > 0 && impLimits.Sum(x => x.Value) < optImpNum) impLimits.Keys.Do(x => subCategoryLimits[x] = Options.RoleSubCategoryLimits[x][2].GetInt()); @@ -213,7 +213,7 @@ internal static class CustomRoleSelector Logger.Info($"Number of Non-Killing Neutral roles to select: {nnkLimit}", "NonKillingNeutralLimit"); Logger.Info($"Number of Madmate roles to select: {madmateNum}", "MadmateLimit"); - var allRoles = Roles.ToDictionary(x => x.Key, x => x.Value.ToList()); + Dictionary> allRoles = Roles.ToDictionary(x => x.Key, x => x.Value.ToList()); Roles.Keys.ToArray().Do(type => ApplySubCategoryLimits(type, subCategoryLimits)); @@ -225,21 +225,21 @@ internal static class CustomRoleSelector Logger.Info(string.Join(", ", Roles[RoleAssignType.Madmate].Select(x => x.Role.ToString())), "PreSelectedMadmateRoles"); Logger.Info(string.Join(", ", Roles[RoleAssignType.Coven].Select(x => x.Role.ToString())), "PreSelectedCovenRoles"); Logger.Msg("===================================================", "PreSelectedRoles"); - + try { - int attempts = 0; + var attempts = 0; List types = [RoleAssignType.NeutralKilling, RoleAssignType.NonKillingNeutral]; while (Roles[RoleAssignType.NeutralKilling].Count + Roles[RoleAssignType.NonKillingNeutral].Count > numNeutrals) { if (attempts++ > 100) break; - if (types.FindFirst(x => Roles[x].Count == 0, out var nullType)) types.Remove(nullType); + if (types.FindFirst(x => Roles[x].Count == 0, out RoleAssignType nullType)) types.Remove(nullType); if (types.Count == 0) break; RoleAssignType type = types.RandomElement(); - var toRemove = Roles[type].RandomElement(); + RoleAssignInfo toRemove = Roles[type].RandomElement(); Roles[type].Remove(toRemove); Logger.Info($"Removed {toRemove.Role} from {type}", "CustomRoleSelector"); @@ -340,13 +340,17 @@ internal static class CustomRoleSelector RoleAssignInfo item = Roles[RoleAssignType.Impostor][i]; if (item.SpawnChance == 100) + { for (var j = 0; j < item.MaxCount - item.AssignedCount; j++) AlwaysImpRoles.Add(item.Role); + } else { for (var j = 0; j < item.SpawnChance / 5; j++) + { for (var k = 0; k < item.MaxCount - item.AssignedCount; k++) ChanceImpRoles.Add(item.Role); + } } } @@ -392,8 +396,10 @@ internal static class CustomRoleSelector Imps = ImpRoleCounts; if (info.AssignedCount >= info.MaxCount) + { while (ChanceImpRoles.Contains(selected)) ChanceImpRoles.Remove(selected); + } if (readyRoleNum >= playerCount) goto EndOfAssign; if (readyImpNum >= optImpNum) break; @@ -413,13 +419,17 @@ internal static class CustomRoleSelector RoleAssignInfo item = Roles[RoleAssignType.NonKillingNeutral][i]; if (item.SpawnChance == 100) + { for (var j = 0; j < item.MaxCount - item.AssignedCount; j++) AlwaysNNKRoles.Add(item.Role); + } else { for (var j = 0; j < item.SpawnChance / 5; j++) + { for (var k = 0; k < item.MaxCount - item.AssignedCount; k++) ChanceNNKRoles.Add(item.Role); + } } } @@ -465,8 +475,10 @@ internal static class CustomRoleSelector NNKs = NNKRoleCounts; if (info.AssignedCount >= info.MaxCount) + { while (ChanceNNKRoles.Contains(selected)) ChanceNNKRoles.Remove(selected); + } if (readyRoleNum >= playerCount) goto EndOfAssign; if (readyNonNeutralKillingNum >= nnkNum) break; @@ -484,13 +496,17 @@ internal static class CustomRoleSelector RoleAssignInfo item = Roles[RoleAssignType.NeutralKilling][i]; if (item.SpawnChance == 100) + { for (var j = 0; j < item.MaxCount - item.AssignedCount; j++) AlwaysNKRoles.Add(item.Role); + } else { for (var j = 0; j < item.SpawnChance / 5; j++) + { for (var k = 0; k < item.MaxCount - item.AssignedCount; k++) ChanceNKRoles.Add(item.Role); + } } } @@ -536,8 +552,10 @@ internal static class CustomRoleSelector NKs = NKRoleCounts; if (info.AssignedCount >= info.MaxCount) + { while (ChanceNKRoles.Contains(selected)) ChanceNKRoles.Remove(selected); + } if (readyRoleNum >= playerCount) goto EndOfAssign; if (readyNeutralKillingNum >= nkNum) break; @@ -556,13 +574,17 @@ internal static class CustomRoleSelector RoleAssignInfo item = Roles[RoleAssignType.Madmate][i]; if (item.SpawnChance == 100) + { for (var j = 0; j < item.MaxCount - item.AssignedCount; j++) AlwaysMadmateRoles.Add(item.Role); + } else { for (var j = 0; j < item.SpawnChance / 5; j++) + { for (var k = 0; k < item.MaxCount - item.AssignedCount; k++) ChanceMadmateRoles.Add(item.Role); + } } } @@ -608,8 +630,10 @@ internal static class CustomRoleSelector Mads = MadRoleCounts; if (info.AssignedCount >= info.MaxCount) + { while (ChanceMadmateRoles.Contains(selected)) ChanceMadmateRoles.Remove(selected); + } if (readyRoleNum >= playerCount) goto EndOfAssign; if (readyMadmateNum >= madmateNum) break; @@ -627,13 +651,17 @@ internal static class CustomRoleSelector RoleAssignInfo item = Roles[RoleAssignType.Coven][i]; if (item.SpawnChance == 100) + { for (var j = 0; j < item.MaxCount - item.AssignedCount; j++) AlwaysCovenRoles.Add(item.Role); + } else { for (var j = 0; j < item.SpawnChance / 5; j++) + { for (var k = 0; k < item.MaxCount - item.AssignedCount; k++) ChanceCovenRoles.Add(item.Role); + } } } @@ -679,8 +707,10 @@ internal static class CustomRoleSelector Coven = CovenRoleCounts; if (info.AssignedCount >= info.MaxCount) + { while (ChanceCovenRoles.Contains(selected)) ChanceCovenRoles.Remove(selected); + } if (readyRoleNum >= playerCount) goto EndOfAssign; if (readyCovenNum >= numCovens) break; @@ -690,7 +720,7 @@ internal static class CustomRoleSelector // Crewmate Roles { - int attempts = 0; + var attempts = 0; Crew: @@ -704,13 +734,17 @@ internal static class CustomRoleSelector RoleAssignInfo item = Roles[RoleAssignType.Crewmate][i]; if (item.SpawnChance == 100) + { for (var j = 0; j < item.MaxCount - item.AssignedCount; j++) AlwaysCrewRoles.Add(item.Role); + } else { for (var j = 0; j < item.SpawnChance / 5; j++) + { for (var k = 0; k < item.MaxCount - item.AssignedCount; k++) ChanceCrewRoles.Add(item.Role); + } } } @@ -753,8 +787,10 @@ internal static class CustomRoleSelector Crews = CrewRoleCounts; if (info.AssignedCount >= info.MaxCount) + { while (ChanceCrewRoles.Contains(selected)) ChanceCrewRoles.Remove(selected); + } if (readyRoleNum >= playerCount) goto EndOfAssign; } @@ -788,7 +824,7 @@ internal static class CustomRoleSelector 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); - RoleResult.AddRange(AllPlayers.Zip(FinalRolesList.Shuffle()).ToDictionary(x => x.First.PlayerId, x => x.Second), overrideExistingKeys: false); + RoleResult.AddRange(AllPlayers.Zip(FinalRolesList.Shuffle()).ToDictionary(x => x.First.PlayerId, x => x.Second), false); Logger.Info(string.Join(", ", RoleResult.Values.Select(x => x.ToString())), "RoleResults"); if (RoleResult.Count < AllPlayers.Count) Logger.Error("Role assignment error: There are players who have not been assigned a role", "CustomRoleSelector"); @@ -809,10 +845,7 @@ internal static class CustomRoleSelector } } - RoleAssignInfo GetAssignInfo(CustomRoles role) - { - return Roles.Values.FirstOrDefault(x => x.Any(y => y.Role == role))?.FirstOrDefault(x => x.Role == role); - } + RoleAssignInfo GetAssignInfo(CustomRoles role) => Roles.Values.FirstOrDefault(x => x.Any(y => y.Role == role))?.FirstOrDefault(x => x.Role == role); void ApplySubCategoryLimits(RoleAssignType type, Dictionary dictionary) => Roles[type] = Roles[type] @@ -821,7 +854,7 @@ internal static class CustomRoleSelector .DistinctBy(x => x.Role) .Select(x => ( Info: x, - Limit: dictionary.TryGetValue(x.OptionType, out var limit) + Limit: dictionary.TryGetValue(x.OptionType, out int limit) ? (Exists: true, Value: limit) : (Exists: false, Value: 0))) .GroupBy(x => x.Info.OptionType) diff --git a/Modules/CustomRolesHelper.cs b/Modules/CustomRolesHelper.cs index 8a8f134be..f4f20c59f 100644 --- a/Modules/CustomRolesHelper.cs +++ b/Modules/CustomRolesHelper.cs @@ -45,9 +45,12 @@ internal static class CustomRolesHelper CustomRoles.Dasher ]; - public static bool IsExperimental(this CustomRoles role) => role is - CustomRoles.DoubleAgent or - CustomRoles.Weatherman; + public static bool IsExperimental(this CustomRoles role) + { + return role is + CustomRoles.DoubleAgent or + CustomRoles.Weatherman; + } public static bool IsForOtherGameMode(this CustomRoles role) { diff --git a/Modules/CustomRpcSender.cs b/Modules/CustomRpcSender.cs index ebc41f104..7d90a6238 100644 --- a/Modules/CustomRpcSender.cs +++ b/Modules/CustomRpcSender.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using AmongUs.GameOptions; @@ -113,7 +112,7 @@ public class CustomRpcSender else throw new InvalidOperationException(errorMsg); } - + Logger.Info($"\"{name}\" is finished (Length: {stream.Length})", "CustomRpcSender"); if (!dispose) @@ -343,12 +342,12 @@ public static class CustomRpcSenderExtensions .Write(true) .EndRpc(); } - + // From TOH: https://github.com/tukasa0001/TownOfHost public static void RpcSetName(this CustomRpcSender sender, PlayerControl player, string name, PlayerControl seer = null) { bool seerIsNull = seer == null; - var targetClientId = seerIsNull ? -1 : seer.GetClientId(); + int targetClientId = seerIsNull ? -1 : seer.GetClientId(); name = name.Replace("color=", string.Empty); @@ -388,10 +387,10 @@ public static class CustomRpcSenderExtensions sender.AutoStartRpc(physics.NetId, (byte)RpcCalls.ExitVent, clientId); sender.WritePacked(ventId); sender.EndRpc(); - + return true; } - + public static bool RpcGuardAndKill(this CustomRpcSender sender, PlayerControl killer, PlayerControl target = null, bool forObserver = false, bool fromSetKCD = false) { if (!AmongUsClient.Instance.AmHost) @@ -406,12 +405,12 @@ public static class CustomRpcSenderExtensions if (target == null) target = killer; - bool returnValue = false; + var returnValue = false; // Check Observer if (!forObserver && !MeetingStates.FirstMeeting) { - foreach (var x in Main.AllPlayerControls) + foreach (PlayerControl x in Main.AllPlayerControls) { if (x.Is(CustomRoles.Observer) && killer.PlayerId != x.PlayerId && sender.RpcGuardAndKill(x, target, true)) returnValue = true; @@ -428,15 +427,15 @@ public static class CustomRpcSenderExtensions sender.WriteNetObject(target); sender.Write((int)MurderResultFlags.FailedProtected); sender.EndRpc(); - + returnValue = true; } if (!fromSetKCD) killer.AddKillTimerToDict(true); - + return returnValue; } - + public static bool SetKillCooldown(this CustomRpcSender sender, PlayerControl player, float time = -1f, PlayerControl target = null, bool forceAnime = false) { if (player == null) return false; @@ -463,7 +462,7 @@ public static class CustomRpcSenderExtensions else Main.AllPlayerKillCooldown[player.PlayerId] *= 2; - bool returnValue = false; + var returnValue = false; if (player.Is(CustomRoles.Glitch) && Main.PlayerStates[player.PlayerId].Role is Glitch gc) { @@ -486,11 +485,11 @@ public static class CustomRpcSenderExtensions sender.AutoStartRpc(PlayerControl.LocalPlayer.NetId, (byte)CustomRPC.SetKillTimer, player.GetClientId()); sender.Write(time); sender.EndRpc(); - + returnValue = true; } - foreach (var x in Main.AllPlayerControls) + foreach (PlayerControl x in Main.AllPlayerControls) { if (x.Is(CustomRoles.Observer) && target.PlayerId != x.PlayerId && sender.RpcGuardAndKill(x, target, true, true)) returnValue = true; @@ -498,7 +497,7 @@ public static class CustomRpcSenderExtensions } if (player.GetCustomRole() is not CustomRoles.Inhibitor and not CustomRoles.Saboteur) player.ResetKillCooldown(); - + return returnValue; } @@ -529,7 +528,7 @@ public static class CustomRpcSenderExtensions sender.WriteNetObject(target); sender.Write(0); sender.EndRpc(); - + return true; } @@ -549,7 +548,7 @@ public static class CustomRpcSenderExtensions sender.EndRpc(); FixedUpdatePatch.LoversSuicide(player.PlayerId); } - + public static void Notify(this CustomRpcSender sender, PlayerControl pc, string text, float time = 6f, bool overrideAll = false, bool log = true, bool setName = true) { if (!AmongUsClient.Instance.AmHost || pc == null) return; @@ -601,7 +600,7 @@ public static class CustomRpcSenderExtensions } var newSid = (ushort)(nt.lastSequenceId + 8); - + sender.AutoStartRpc(nt.NetId, (byte)RpcCalls.SnapTo); sender.WriteVector2(location); sender.Write(newSid); diff --git a/Modules/CustomSounds.cs b/Modules/CustomSounds.cs index 8267ad963..481d51382 100644 --- a/Modules/CustomSounds.cs +++ b/Modules/CustomSounds.cs @@ -13,8 +13,10 @@ public static class CustomSoundsManager public static void RPCPlayCustomSound(this PlayerControl pc, string sound, bool force = false) { if (!force) + { if (!AmongUsClient.Instance.AmHost || !pc.IsModdedClient()) return; + } if (pc == null || PlayerControl.LocalPlayer.PlayerId == pc.PlayerId) { diff --git a/Modules/CustomTeamManager.cs b/Modules/CustomTeamManager.cs index 6eb77ef57..445b6dd59 100644 --- a/Modules/CustomTeamManager.cs +++ b/Modules/CustomTeamManager.cs @@ -46,9 +46,9 @@ internal static class CustomTeamManager var guessEachOther = new BooleanOptionItem(id++, "CTA.GuessEachOther", false, tab); var arrows = new BooleanOptionItem(id++, "CTA.Arrows", true, tab); var maxPlayers = new IntegerOptionItem(id++, "CTA.MaxPlayersAssignedToTeam", new(1, 15, 1), 15, tab); - + var teamPlayerCounts = new Dictionary(); - + foreach (Team teamType in Enum.GetValues()[1..]) { var min = new IntegerOptionItem(id++, "CTA.MinPlayers." + teamType, new(1, 15, 1), 1, tab); @@ -89,11 +89,11 @@ internal static class CustomTeamManager { foreach (byte id in players) { - if (Main.PlayerStates.TryGetValue(id, out var ps)) + if (Main.PlayerStates.TryGetValue(id, out PlayerState ps)) ps.countTypes = CountTypes.CustomTeam; } } - + if (!IsSettingEnabledForTeam(team, CTAOption.Arrows)) continue; foreach (byte player in players) @@ -105,15 +105,15 @@ internal static class CustomTeamManager } } } - + return; static HashSet TakeAsManyAsSet(IEnumerable playerIds, CustomTeam customTeam) { try { - var options = CustomTeamOptions.First(x => x.Team.Equals(customTeam)); - var grouped = playerIds.ToValidPlayers().GroupBy(x => x.GetTeam()).ToDictionary(x => x.Key, x => x.Shuffle()); + CustomTeamOptionGroup options = CustomTeamOptions.First(x => x.Team.Equals(customTeam)); + Dictionary> grouped = playerIds.ToValidPlayers().GroupBy(x => x.GetTeam()).ToDictionary(x => x.Key, x => x.Shuffle()); foreach ((Team team, List players) in grouped) { @@ -122,10 +122,10 @@ internal static class CustomTeamManager if (!options.TeamPlayerCounts.TryGetValue(team, out IntegerOptionItem[] counts) || counts.Length < 2) continue; - var num = IRandom.Instance.Next(counts[0].GetInt(), counts[1].GetInt() + 1); + int num = IRandom.Instance.Next(counts[0].GetInt(), counts[1].GetInt() + 1); if (players.Count <= num) continue; - var selected = players.Take(num).Shuffle(); + List selected = players.Take(num).Shuffle(); players.Clear(); players.AddRange(selected); } @@ -187,8 +187,10 @@ internal static class CustomTeamManager 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; } @@ -258,6 +260,7 @@ internal static class CustomTeamManager internal class CustomTeamOptionGroup { public readonly List AllOptions; + public CustomTeamOptionGroup(CustomTeam team, BooleanOptionItem enabled, BooleanOptionItem knowRoles, BooleanOptionItem winWithOriginalTeam, BooleanOptionItem killEachOther, BooleanOptionItem guessEachOther, BooleanOptionItem arrows, IntegerOptionItem maxPlayers, Dictionary teamPlayerCounts) { AllOptions = [enabled, knowRoles, winWithOriginalTeam, killEachOther, guessEachOther, arrows, maxPlayers]; @@ -267,6 +270,7 @@ internal static class CustomTeamManager MaxPlayers = maxPlayers; TeamPlayerCounts = teamPlayerCounts; } + public CustomTeam Team { get; } public BooleanOptionItem Enabled { get; } diff --git a/Modules/DebugModeManager.cs b/Modules/DebugModeManager.cs index c1df6ba19..605133a67 100644 --- a/Modules/DebugModeManager.cs +++ b/Modules/DebugModeManager.cs @@ -3,11 +3,10 @@ namespace EHR; public static class DebugModeManager { public static OptionItem EnableDebugMode; - public static bool AmDebugger { get; private set; } = + public static bool AmDebugger { get; private set; } #if DEBUG true; #else - false; #endif public static void Auth(HashAuth auth, string input) diff --git a/Modules/Debugger.cs b/Modules/Debugger.cs index c168b43c7..481082034 100644 --- a/Modules/Debugger.cs +++ b/Modules/Debugger.cs @@ -184,10 +184,7 @@ public class CustomLogger Main.Instance.StartCoroutine(InactivityCheck()); } - public static CustomLogger Instance - { - get { return PrivateInstance ??= new(); } - } + public static CustomLogger Instance => PrivateInstance ??= new(); public static void ClearLog(bool check = true) { @@ -206,11 +203,11 @@ public class CustomLogger if (message.Contains("")) message += ""; if (message.Contains("")) message += ""; - string logEntry = $""" -
- {message} -
- """; + var logEntry = $""" +
+ {message} +
+ """; File.AppendAllText(LOGFilePath, logEntry); diff --git a/Modules/DevManager.cs b/Modules/DevManager.cs index 281d30548..700f77548 100644 --- a/Modules/DevManager.cs +++ b/Modules/DevManager.cs @@ -70,8 +70,14 @@ public static class DevManager public bool up { get; set; } public string ip { get; set; } - public bool HasTag() => !string.IsNullOrEmpty(tag_name); + public bool HasTag() + { + return !string.IsNullOrEmpty(tag_name); + } - public string GetTag() => !HasTag() ? "" : $"{tag_name}\r\n"; + public string GetTag() + { + return !HasTag() ? "" : $"{tag_name}\r\n"; + } } } \ No newline at end of file diff --git a/Modules/DisableDevice.cs b/Modules/DisableDevice.cs index 118a5aab9..ee2144d97 100644 --- a/Modules/DisableDevice.cs +++ b/Modules/DisableDevice.cs @@ -130,14 +130,14 @@ internal static class DisableDevice if (Main.NormalOptions.MapId is 1 or 5) // Mira HQ or The Fungle sender.RpcDesyncRepairSystem(pc, SystemTypes.Comms, 17); - + hasValue = true; } } catch (Exception ex) { Logger.Exception(ex, "DisableDevice"); } } - - sender.SendMessage(dispose: !hasValue); + + sender.SendMessage(!hasValue); } } diff --git a/Modules/EAC.cs b/Modules/EAC.cs index b95dbffdd..328431097 100644 --- a/Modules/EAC.cs +++ b/Modules/EAC.cs @@ -72,7 +72,7 @@ internal static class EAC break; case RpcCalls.ReportDeadBody: - var targetId = sr.ReadByte(); + byte targetId = sr.ReadByte(); if (GameStates.IsMeeting && MeetingHud.Instance.state != MeetingHud.VoteStates.Animating && !pc.IsHost()) { @@ -117,7 +117,7 @@ internal static class EAC break; case RpcCalls.SendQuickChat: - QuickChatPhraseType quickChatPhraseType = (QuickChatPhraseType)sr.ReadByte(); + var quickChatPhraseType = (QuickChatPhraseType)sr.ReadByte(); switch (quickChatPhraseType) { @@ -456,15 +456,9 @@ internal static class EAC return false; - bool HasLadder(int ladderId) - { - return ShipStatus.Instance.Ladders.Any(l => l.Id == ladderId); - } + bool HasLadder(int ladderId) => ShipStatus.Instance.Ladders.Any(l => l.Id == ladderId); - bool HasVent(int ventId) - { - return ShipStatus.Instance.AllVents.Any(v => v.Id == ventId); - } + bool HasVent(int ventId) => ShipStatus.Instance.AllVents.Any(v => v.Id == ventId); } internal static void Report(PlayerControl pc, string reason) diff --git a/Modules/ExtendedPlayerControl.cs b/Modules/ExtendedPlayerControl.cs index 2ed01379c..da6235e00 100644 --- a/Modules/ExtendedPlayerControl.cs +++ b/Modules/ExtendedPlayerControl.cs @@ -104,13 +104,14 @@ internal static class ExtendedPlayerControl return vents; } -/* - public static void RpcSetVentInteraction(this PlayerControl player) - { - var ventilationSystem = ShipStatus.Instance.Systems[SystemTypes.Ventilation].CastFast(); - if (ventilationSystem != null) VentilationSystemDeterioratePatch.SerializeV2(ventilationSystem, player); - } -*/ + + /* + public static void RpcSetVentInteraction(this PlayerControl player) + { + var ventilationSystem = ShipStatus.Instance.Systems[SystemTypes.Ventilation].CastFast(); + if (ventilationSystem != null) VentilationSystemDeterioratePatch.SerializeV2(ventilationSystem, player); + } + */ // From: https://github.com/Rabek009/MoreGamemodes/blob/master/Modules/ExtendedPlayerControl.cs - coded by Rabek009 public static void SetChatVisible(this PlayerControl player, bool visible) { @@ -159,12 +160,13 @@ internal static class ExtendedPlayerControl AmongUsClient.Instance.SendOrDisconnect(writer); writer.Recycle(); } -/* - public static void RpcExile(this PlayerControl player) - { - RPC.ExileAsync(player); - } -*/ + + /* + public static void RpcExile(this PlayerControl player) + { + RPC.ExileAsync(player); + } + */ public static ClientData GetClient(this PlayerControl player) { try { return AmongUsClient.Instance.allClients.ToArray().FirstOrDefault(cd => cd.Character.PlayerId == player.PlayerId); } @@ -232,52 +234,52 @@ internal static class ExtendedPlayerControl return state.countTypes; } -/* - public static void RpcSetNameEx(this PlayerControl player, string name) - { - try + /* + public static void RpcSetNameEx(this PlayerControl player, string name) { - if (player == null) + try { - Logger.Warn("The player is null", "RpcSetNameEx"); - return; + if (player == null) + { + Logger.Warn("The player is null", "RpcSetNameEx"); + return; + } + + foreach (PlayerControl seer in Main.AllPlayerControls) + { + try { Main.LastNotifyNames[(player.PlayerId, seer.PlayerId)] = name; } + catch { } + } + + if (player.Data != null) Logger.Info($"Set: {player.Data.PlayerName} => {name} for Everyone", "RpcSetNameEx"); + + player.RpcSetName(name); } - - foreach (PlayerControl seer in Main.AllPlayerControls) - { - try { Main.LastNotifyNames[(player.PlayerId, seer.PlayerId)] = name; } - catch { } - } - - if (player.Data != null) Logger.Info($"Set: {player.Data.PlayerName} => {name} for Everyone", "RpcSetNameEx"); - - player.RpcSetName(name); + catch (Exception e) { ThrowException(e); } } - catch (Exception e) { ThrowException(e); } - } - public static void RpcSetNamePrivate(this PlayerControl player, string name, PlayerControl seer = null, bool force = false) - { - if (player == null || name == null || !AmongUsClient.Instance.AmHost) return; + 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 (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"); + 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; + int clientId = seer.GetClientId(); + if (clientId == -1) return; - MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(player.NetId, (byte)RpcCalls.SetName, SendOption.Reliable, clientId); - writer.Write(seer.Data.NetId); - writer.Write(name); - AmongUsClient.Instance.FinishRpcImmediately(writer); - } -*/ + MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(player.NetId, (byte)RpcCalls.SetName, SendOption.Reliable, clientId); + writer.Write(seer.Data.NetId); + writer.Write(name); + AmongUsClient.Instance.FinishRpcImmediately(writer); + } + */ // By TommyXL public static void RpcSetPetDesync(this PlayerControl player, string petId, PlayerControl seer) @@ -316,7 +318,7 @@ internal static class ExtendedPlayerControl { (byte, byte) key = (player.PlayerId, GetClientById(clientId).Character.PlayerId); - if (StartGameHostPatch.RpcSetRoleReplacer.RoleMap.TryGetValue(key, out var pair)) + if (StartGameHostPatch.RpcSetRoleReplacer.RoleMap.TryGetValue(key, out (RoleTypes RoleType, CustomRoles CustomRole) pair)) { pair.RoleType = role; StartGameHostPatch.RpcSetRoleReplacer.RoleMap[key] = pair; @@ -364,7 +366,7 @@ internal static class ExtendedPlayerControl sender.SyncGeneralOptions(player); sender.SendMessage(); - if (Options.AnonymousBodies.GetBool() && Main.AllPlayerNames.TryGetValue(player.PlayerId, out var name)) + if (Options.AnonymousBodies.GetBool() && Main.AllPlayerNames.TryGetValue(player.PlayerId, out string name)) RpcChangeSkin(player, new NetworkedPlayerInfo.PlayerOutfit().Set(name, 15, "", "", "", "", "")); Camouflage.RpcSetSkin(player); @@ -426,7 +428,7 @@ internal static class ExtendedPlayerControl CustomRoles newRoleVN = newCustomRole.GetVNRole(); RoleTypes newRoleDY = newCustomRole.GetDYRole(); - var writer = sender ?? CustomRpcSender.Create("RpcChangeRoleBasis", SendOption.Reliable); + CustomRpcSender writer = sender ?? CustomRpcSender.Create("RpcChangeRoleBasis", SendOption.Reliable); switch (oldRoleIsDesync, newRoleIsDesync) { @@ -549,7 +551,7 @@ internal static class ExtendedPlayerControl break; } } - + if (sender == null) writer.SendMessage(); if (loggerRoleMap) @@ -603,25 +605,25 @@ internal static class ExtendedPlayerControl } // 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; - - int clientId = seer.GetClientId(); - - if (AmongUsClient.Instance.ClientId == clientId) + /* + public static void RpcEnterVentDesync(this PlayerPhysics physics, int ventId, PlayerControl seer) { - physics.StopAllCoroutines(); - physics.StartCoroutine(physics.CoEnterVent(ventId)); - return; - } + if (physics == null) return; - MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(physics.NetId, (byte)RpcCalls.EnterVent, SendOption.Reliable, clientId); - writer.WritePacked(ventId); - AmongUsClient.Instance.FinishRpcImmediately(writer); - } -*/ + int clientId = seer.GetClientId(); + + if (AmongUsClient.Instance.ClientId == clientId) + { + physics.StopAllCoroutines(); + physics.StartCoroutine(physics.CoEnterVent(ventId)); + return; + } + + MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(physics.NetId, (byte)RpcCalls.EnterVent, SendOption.Reliable, clientId); + writer.WritePacked(ventId); + AmongUsClient.Instance.FinishRpcImmediately(writer); + } + */ public static void RpcExitVentDesync(this PlayerPhysics physics, int ventId, PlayerControl seer) { if (physics == null) return; @@ -639,24 +641,25 @@ internal static class ExtendedPlayerControl writer.WritePacked(ventId); AmongUsClient.Instance.FinishRpcImmediately(writer); } -/* - public static void RpcBootFromVentDesync(this PlayerPhysics physics, int ventId, PlayerControl seer) - { - if (physics == null) return; - int clientId = seer.GetClientId(); - - if (AmongUsClient.Instance.ClientId == clientId) + /* + public static void RpcBootFromVentDesync(this PlayerPhysics physics, int ventId, PlayerControl seer) { - physics.BootFromVent(ventId); - return; - } + if (physics == null) return; - MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(physics.NetId, (byte)RpcCalls.BootFromVent, SendOption.Reliable, clientId); - writer.WritePacked(ventId); - AmongUsClient.Instance.FinishRpcImmediately(writer); - } -*/ + int clientId = seer.GetClientId(); + + if (AmongUsClient.Instance.ClientId == clientId) + { + physics.BootFromVent(ventId); + return; + } + + MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(physics.NetId, (byte)RpcCalls.BootFromVent, SendOption.Reliable, clientId); + writer.WritePacked(ventId); + AmongUsClient.Instance.FinishRpcImmediately(writer); + } + */ public static void RpcCheckVanishDesync(this PlayerControl player, PlayerControl seer) { int clientId = seer.GetClientId(); @@ -671,21 +674,22 @@ internal static class ExtendedPlayerControl messageWriter.Write(0); // not used, lol AmongUsClient.Instance.FinishRpcImmediately(messageWriter); } -/* - public static void RpcStartVanishDesync(this PlayerControl player, PlayerControl seer) - { - int clientId = seer.GetClientId(); - if (AmongUsClient.Instance.ClientId == clientId) + /* + public static void RpcStartVanishDesync(this PlayerControl player, PlayerControl seer) { - player.SetRoleInvisibility(true, false, true); - return; - } + int clientId = seer.GetClientId(); - MessageWriter msg = AmongUsClient.Instance.StartRpcImmediately(player.NetId, (byte)RpcCalls.StartVanish, SendOption.None, clientId); - AmongUsClient.Instance.FinishRpcImmediately(msg); - } -*/ + if (AmongUsClient.Instance.ClientId == clientId) + { + player.SetRoleInvisibility(true, false, true); + return; + } + + MessageWriter msg = AmongUsClient.Instance.StartRpcImmediately(player.NetId, (byte)RpcCalls.StartVanish, SendOption.None, clientId); + AmongUsClient.Instance.FinishRpcImmediately(msg); + } + */ public static void RpcCheckAppearDesync(this PlayerControl player, bool shouldAnimate, PlayerControl seer) { int clientId = seer.GetClientId(); @@ -715,15 +719,16 @@ internal static class ExtendedPlayerControl messageWriter.Write(shouldAnimate); AmongUsClient.Instance.FinishRpcImmediately(messageWriter); } -/* - public static void RpcCheckAppear(this PlayerControl player, bool shouldAnimate) - { - player.CheckAppear(shouldAnimate); - MessageWriter messageWriter = AmongUsClient.Instance.StartRpcImmediately(player.NetId, (byte)RpcCalls.CheckAppear, SendOption.None); - messageWriter.Write(shouldAnimate); - AmongUsClient.Instance.FinishRpcImmediately(messageWriter); - } -*/ + + /* + public static void RpcCheckAppear(this PlayerControl player, bool shouldAnimate) + { + player.CheckAppear(shouldAnimate); + MessageWriter messageWriter = AmongUsClient.Instance.StartRpcImmediately(player.NetId, (byte)RpcCalls.CheckAppear, SendOption.None); + messageWriter.Write(shouldAnimate); + AmongUsClient.Instance.FinishRpcImmediately(messageWriter); + } + */ public static bool HasDesyncRole(this PlayerControl player) { return player.Is(CustomRoles.Bloodlust) || player.GetCustomRole().IsDesyncRole(); @@ -802,26 +807,26 @@ internal static class ExtendedPlayerControl if (!fromSetKCD) killer.AddKillTimerToDict(true); } - -/* - public static void RpcSpecificVanish(this PlayerControl player, PlayerControl seer) - { - if (!AmongUsClient.Instance.AmHost) return; - MessageWriter msg = AmongUsClient.Instance.StartRpcImmediately(player.NetId, (byte)RpcCalls.StartVanish, SendOption.None, seer.GetClientId()); - AmongUsClient.Instance.FinishRpcImmediately(msg); - } + /* + public static void RpcSpecificVanish(this PlayerControl player, PlayerControl seer) + { + if (!AmongUsClient.Instance.AmHost) return; - public static void RpcSpecificAppear(this PlayerControl player, PlayerControl seer, bool shouldAnimate) - { - if (!AmongUsClient.Instance.AmHost) return; + MessageWriter msg = AmongUsClient.Instance.StartRpcImmediately(player.NetId, (byte)RpcCalls.StartVanish, SendOption.None, seer.GetClientId()); + AmongUsClient.Instance.FinishRpcImmediately(msg); + } + + public static void RpcSpecificAppear(this PlayerControl player, PlayerControl seer, bool shouldAnimate) + { + if (!AmongUsClient.Instance.AmHost) return; + + MessageWriter msg = AmongUsClient.Instance.StartRpcImmediately(player.NetId, (byte)RpcCalls.StartAppear, SendOption.None, seer.GetClientId()); + msg.Write(shouldAnimate); + AmongUsClient.Instance.FinishRpcImmediately(msg); + } + */ - MessageWriter msg = AmongUsClient.Instance.StartRpcImmediately(player.NetId, (byte)RpcCalls.StartAppear, SendOption.None, seer.GetClientId()); - msg.Write(shouldAnimate); - AmongUsClient.Instance.FinishRpcImmediately(msg); - } -*/ - public static bool HasAbilityCD(this PlayerControl pc) { return Main.AbilityCD.ContainsKey(pc.PlayerId); @@ -1569,7 +1574,7 @@ internal static class ExtendedPlayerControl if (target.PlayerId == Godfather.GodfatherTarget) { - var realKiller = Main.PlayerStates.TryGetValue(target.PlayerId, out var state) ? state.RealKiller.ID.GetPlayer() ?? killer : killer; + PlayerControl realKiller = Main.PlayerStates.TryGetValue(target.PlayerId, out PlayerState state) ? state.RealKiller.ID.GetPlayer() ?? killer : killer; realKiller.RpcSetCustomRole(CustomRoles.Refugee); } @@ -1584,7 +1589,7 @@ internal static class ExtendedPlayerControl { Main.AllPlayerSpeed[target.PlayerId] = Main.MinSpeed; target.SyncSettings(); - var newSkin = new NetworkedPlayerInfo.PlayerOutfit().Set(GetString("Dead"), 15, "", "", "", "", ""); + NetworkedPlayerInfo.PlayerOutfit newSkin = new NetworkedPlayerInfo.PlayerOutfit().Set(GetString("Dead"), 15, "", "", "", "", ""); RpcChangeSkin(target, newSkin); LateTask.New(() => @@ -1672,10 +1677,20 @@ internal static class ExtendedPlayerControl } } - public static bool UsesPetInsteadOfKill(this PlayerControl pc) => pc != null && !pc.Is(CustomRoles.Bloodlust) && pc.GetCustomRole().UsesPetInsteadOfKill(); + public static bool UsesPetInsteadOfKill(this PlayerControl pc) + { + return pc != null && !pc.Is(CustomRoles.Bloodlust) && pc.GetCustomRole().UsesPetInsteadOfKill(); + } - public static bool IsLocalPlayer(this PlayerControl pc) => pc.PlayerId == PlayerControl.LocalPlayer.PlayerId; - public static bool IsLocalPlayer(this NetworkedPlayerInfo npi) => npi.PlayerId == PlayerControl.LocalPlayer.PlayerId; + public static bool IsLocalPlayer(this PlayerControl pc) + { + return pc.PlayerId == PlayerControl.LocalPlayer.PlayerId; + } + + public static bool IsLocalPlayer(this NetworkedPlayerInfo npi) + { + return npi.PlayerId == PlayerControl.LocalPlayer.PlayerId; + } public static bool IsModdedClient(this PlayerControl player) { @@ -1694,8 +1709,10 @@ internal static class ExtendedPlayerControl player.Data.Role.GetPlayersInAbilityRangeSorted(rangePlayersIL, ignoreColliders); foreach (PlayerControl pc in rangePlayersIL) + { if (predicate(pc)) rangePlayers.Add(pc); + } return rangePlayers; } diff --git a/Modules/Extensions/CollectionExtensions.cs b/Modules/Extensions/CollectionExtensions.cs index 83ddc0ee4..5b7949796 100644 --- a/Modules/Extensions/CollectionExtensions.cs +++ b/Modules/Extensions/CollectionExtensions.cs @@ -25,10 +25,12 @@ public static class CollectionExtensions public static TKey GetKeyByValue(this Dictionary dictionary, TValue value) { foreach (KeyValuePair pair in dictionary) + { if (pair.Value.Equals(value)) return pair.Key; + } - return default; + return default(TKey); } /// @@ -66,7 +68,7 @@ public static class CollectionExtensions /// public static T RandomElement(this IList collection) { - if (collection.Count == 0) return default; + if (collection.Count == 0) return default(T); return collection[IRandom.Instance.Next(collection.Count)]; } @@ -144,8 +146,10 @@ public static class CollectionExtensions } foreach (T element in collection) + { if (predicate(element)) action(element); + } return; } @@ -197,8 +201,10 @@ public static class CollectionExtensions 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; } @@ -241,7 +247,7 @@ public static class CollectionExtensions } } - element = default; + element = default(T); return false; } @@ -254,14 +260,21 @@ public static class CollectionExtensions } } - element = default; + element = default(T); return false; } + public static void NotifyPlayers(this IEnumerable players, string text, float time = 6f, bool overrideAll = false, bool log = true, bool setName = true) + { + var sender = CustomRpcSender.Create("NotifyPlayers", SendOption.Reliable); + players.Do(x => sender.Notify(x, text, time, overrideAll, log, setName)); + sender.SendMessage(); + } + #region ToValidPlayers /// - /// Converts a collection of player IDs to a collection of instances + /// Converts a collection of player IDs to a collection of instances /// /// /// @@ -271,7 +284,7 @@ public static class CollectionExtensions } /// - /// Converts a list of player IDs to a list of instances + /// Converts a list of player IDs to a list of instances /// /// /// @@ -450,13 +463,6 @@ public static class CollectionExtensions } #endregion - - public static void NotifyPlayers(this IEnumerable players, string text, float time = 6f, bool overrideAll = false, bool log = true, bool setName = true) - { - var sender = CustomRpcSender.Create("NotifyPlayers", SendOption.Reliable); - players.Do(x => sender.Notify(x, text, time, overrideAll, log, setName)); - sender.SendMessage(); - } } public static class Loop diff --git a/Modules/Extensions/ObjectHelper.cs b/Modules/Extensions/ObjectHelper.cs index 51accb3de..06e96e64d 100644 --- a/Modules/Extensions/ObjectHelper.cs +++ b/Modules/Extensions/ObjectHelper.cs @@ -1,5 +1,6 @@ using System; using System.Linq.Expressions; +using System.Reflection; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.InteropTypes; using UnityEngine; @@ -54,10 +55,10 @@ public static unsafe class FastDestroyableSingleton where T : MonoBehaviour static FastDestroyableSingleton() { FieldPtr = IL2CPP.GetIl2CppField(Il2CppClassPointerStore>.NativeClassPtr, nameof(DestroyableSingleton._instance)); - var constructor = typeof(T).GetConstructor([typeof(IntPtr)]); - var ptr = Expression.Parameter(typeof(IntPtr)); - var create = Expression.New(constructor!, ptr); - var lambda = Expression.Lambda>(create, ptr); + ConstructorInfo constructor = typeof(T).GetConstructor([typeof(IntPtr)]); + ParameterExpression ptr = Expression.Parameter(typeof(IntPtr)); + NewExpression create = Expression.New(constructor!, ptr); + Expression> lambda = Expression.Lambda>(create, ptr); CreateObject = lambda.Compile(); } @@ -92,10 +93,10 @@ public static class Il2CppCastHelper static CastHelper() { - var constructor = typeof(T).GetConstructor([typeof(IntPtr)]); - var ptr = Expression.Parameter(typeof(IntPtr)); - var create = Expression.New(constructor!, ptr); - var lambda = Expression.Lambda>(create, ptr); + ConstructorInfo constructor = typeof(T).GetConstructor([typeof(IntPtr)]); + ParameterExpression ptr = Expression.Parameter(typeof(IntPtr)); + NewExpression create = Expression.New(constructor!, ptr); + Expression> lambda = Expression.Lambda>(create, ptr); Cast = lambda.Compile(); } } diff --git a/Modules/GameOptionsSender/NormalGameOptionsSender.cs b/Modules/GameOptionsSender/NormalGameOptionsSender.cs index d482dcad9..5e1308a30 100644 --- a/Modules/GameOptionsSender/NormalGameOptionsSender.cs +++ b/Modules/GameOptionsSender/NormalGameOptionsSender.cs @@ -17,8 +17,10 @@ public sealed class NormalGameOptionsSender : GameOptionsSender 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)) _logicOptions = lo; + } } return _logicOptions is { IsDirty: true }; diff --git a/Modules/GameOptionsSender/PlayerGameOptionsSender.cs b/Modules/GameOptionsSender/PlayerGameOptionsSender.cs index 7150cd0b8..f804d97c7 100644 --- a/Modules/GameOptionsSender/PlayerGameOptionsSender.cs +++ b/Modules/GameOptionsSender/PlayerGameOptionsSender.cs @@ -100,8 +100,10 @@ public sealed class PlayerGameOptionsSender(PlayerControl player) : GameOptionsS if (GameManager.Instance?.LogicComponents != null) { foreach (GameLogicComponent com in GameManager.Instance.LogicComponents) + { if (com.TryCast(out LogicOptions lo)) lo.SetGameOptions(opt); + } } GameOptionsManager.Instance.CurrentGameOptions = opt; diff --git a/Modules/GameState.cs b/Modules/GameState.cs index bc31e845b..5b524ca61 100644 --- a/Modules/GameState.cs +++ b/Modules/GameState.cs @@ -107,7 +107,7 @@ public class PlayerState(byte playerId) try { Utils.RemovePlayerFromPreviousRoleData(Player); } catch (Exception e) { Utils.ThrowException(e); } - var previousHasTasks = Utils.HasTasks(Player.Data, false); + bool previousHasTasks = Utils.HasTasks(Player.Data, false); countTypes = role.GetCountTypes(); @@ -486,8 +486,10 @@ public class TaskState // 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; diff --git a/Modules/GhostRolesManager.cs b/Modules/GhostRolesManager.cs index aaa500d4b..0315cadfc 100644 --- a/Modules/GhostRolesManager.cs +++ b/Modules/GhostRolesManager.cs @@ -82,10 +82,7 @@ internal static class GhostRolesManager return (ApplyFormat(message), ApplyFormat(baseMessage)); - string ApplyFormat(string m) - { - return Utils.ColorString(Color.white, m.Replace(role.ToString(), role.ToColoredString())); - } + string ApplyFormat(string m) => Utils.ColorString(Color.white, m.Replace(role.ToString(), role.ToColoredString())); } } @@ -114,15 +111,13 @@ internal static class GhostRolesManager _ => suitableRole.IsGhostRole() && !AssignedGhostRoles.Any(x => x.Key == pc.PlayerId || x.Value.Role == suitableRole) }; - bool IsPartnerPickedRole() - { - return Main.PlayerStates[pc.PlayerId].Role switch + bool IsPartnerPickedRole() => + Main.PlayerStates[pc.PlayerId].Role switch { Romantic when Romantic.HasPickedPartner => true, Totocalcio tc when tc.BetPlayer != byte.MaxValue => true, _ => false }; - } } catch (Exception e) { diff --git a/Modules/GuessManager.cs b/Modules/GuessManager.cs index 42fe774b1..1e0423673 100644 --- a/Modules/GuessManager.cs +++ b/Modules/GuessManager.cs @@ -32,7 +32,10 @@ public static class GuessManager public static TextMeshPro textTemplate; - public static string GetFormatString() => Main.AllAlivePlayerControls.Aggregate(GetString("PlayerIdList"), (current, pc) => current + $"\n{pc.PlayerId.ToString()} → {pc.GetRealName()}"); + public static string GetFormatString() + { + return Main.AllAlivePlayerControls.Aggregate(GetString("PlayerIdList"), (current, pc) => current + $"\n{pc.PlayerId.ToString()} → {pc.GetRealName()}"); + } private static bool CheckCommand(ref string msg, string command, bool exact = true) { @@ -135,7 +138,7 @@ public static class GuessManager switch (pc.Is(CustomRoles.NecroGuesser)) { - case true when (target.IsAlive() || target.Is(CustomRoles.Gravestone) || ((Options.SeeEjectedRolesInMeeting.GetBool() || Options.CEMode.GetValue() == 2) && Main.PlayerStates[targetId].deathReason == PlayerState.DeathReason.Vote)): + case true when target.IsAlive() || target.Is(CustomRoles.Gravestone) || ((Options.SeeEjectedRolesInMeeting.GetBool() || Options.CEMode.GetValue() == 2) && Main.PlayerStates[targetId].deathReason == PlayerState.DeathReason.Vote): ShowMessage(target.IsAlive() ? "NecroGuesser.TargetAliveError" : "NecroGuesser.TargetRevealedError"); return true; case false when !target.IsAlive(): @@ -690,16 +693,16 @@ public static class GuessManager } } - static void GuesserSelectRole(CustomRoleTypes role, bool setPage = true) + private static void GuesserSelectRole(CustomRoleTypes role, bool setPage = true) { currentTeamType = role; if (setPage) Page = 1; - foreach (var RoleButton in RoleButtons) + foreach (KeyValuePair> RoleButton in RoleButtons) { - int index = 0; + var index = 0; - foreach (var RoleBtn in RoleButton.Value) + foreach (Transform RoleBtn in RoleButton.Value) { if (RoleBtn == null) continue; index++; @@ -710,7 +713,7 @@ public static class GuessManager continue; } - if ((Page * 40) < index) + if (Page * 40 < index) { RoleBtn.gameObject.SetActive(false); continue; @@ -720,16 +723,16 @@ public static class GuessManager } } - foreach (var RoleButton in RoleSelectButtons) + foreach (KeyValuePair RoleButton in RoleSelectButtons) { if (RoleButton.Value == null) continue; RoleButton.Value.color = new(0, 0, 0, RoleButton.Key == role ? 1 : 0.25f); } } - static void GuesserOnClick(byte playerId, MeetingHud __instance) + private static void GuesserOnClick(byte playerId, MeetingHud __instance) { - var pc = Utils.GetPlayerById(playerId); + PlayerControl pc = Utils.GetPlayerById(playerId); if (pc == null || !pc.IsAlive() || guesserUI != null || !GameStates.IsVoting) return; try @@ -745,9 +748,9 @@ public static class GuessManager guesserUI = container.gameObject; List i = [0, 0, 0, 0, 0]; - var buttonTemplate = __instance.playerStates[0].transform.FindChild("votePlayerBase"); - var maskTemplate = __instance.playerStates[0].transform.FindChild("MaskArea"); - var smallButtonTemplate = __instance.playerStates[0].Buttons.transform.Find("CancelButton"); + Transform buttonTemplate = __instance.playerStates[0].transform.FindChild("votePlayerBase"); + 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); @@ -775,9 +778,9 @@ public static class GuessManager List buttons = []; Transform selectedButton = null; - int tabCount = 0; + var tabCount = 0; - for (int index = 0; index < 5; index++) + for (var index = 0; index < 5; index++) { switch (PlayerControl.LocalPlayer.GetCustomRole(), index) { @@ -810,7 +813,7 @@ public static class GuessManager }; Logger.Info(Teamlabel.color.ToString(), ((CustomRoleTypes)index).ToString()); - Teamlabel.text = GetString("Type" + ((CustomRoleTypes)index)); + Teamlabel.text = GetString("Type" + (CustomRoleTypes)index); Teamlabel.alignment = TextAlignmentOptions.Center; Teamlabel.transform.localPosition = new Vector3(0, 0, Teamlabel.transform.localPosition.z); Teamlabel.transform.localScale *= 1.6f; @@ -819,14 +822,12 @@ public static class GuessManager if (PlayerControl.LocalPlayer.IsAlive()) CreateTeamButton(Teambutton, (CustomRoleTypes)index); continue; - static void CreateTeamButton(Transform teambutton, CustomRoleTypes type) - { + static void CreateTeamButton(Transform teambutton, CustomRoleTypes type) => teambutton.GetComponent().OnClick.AddListener((UnityAction)(() => { GuesserSelectRole(type); ReloadPage(); })); - } } static void ReloadPage() @@ -834,12 +835,13 @@ public static class GuessManager 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) + 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) { @@ -852,8 +854,8 @@ public static class GuessManager static void CreatePage(bool isNext, MeetingHud __instance, Transform container) { - var buttonTemplate = __instance.playerStates[0].transform.FindChild("votePlayerBase"); - var maskTemplate = __instance.playerStates[0].transform.FindChild("MaskArea"); + Transform buttonTemplate = __instance.playerStates[0].transform.FindChild("votePlayerBase"); + Transform maskTemplate = __instance.playerStates[0].transform.FindChild("MaskArea"); Transform PagebuttonParent = new GameObject().transform; PagebuttonParent.SetParent(container); Transform Pagebutton = Object.Instantiate(buttonTemplate, PagebuttonParent); @@ -870,7 +872,7 @@ public static class GuessManager Pagelabel.transform.localScale *= 1.6f; Pagelabel.autoSizeTextContainer = true; if (!isNext && Page <= 1) Pagebutton.GetComponent().color = new(1, 1, 1, 0.1f); - Pagebutton.GetComponent().OnClick.AddListener((Action)(ClickEvent)); + Pagebutton.GetComponent().OnClick.AddListener((Action)ClickEvent); PageButtons.Add(Pagebutton.GetComponent()); return; @@ -932,13 +934,14 @@ public static class GuessManager 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); int row = i[(int)role.GetCustomRoleTypes()] / 5; int col = i[(int)role.GetCustomRoleTypes()] % 5; - buttonParent.localPosition = new Vector3(-3.47f + 1.75f * col, 1.5f - 0.45f * row, -200f); + buttonParent.localPosition = new Vector3(-3.47f + (1.75f * col), 1.5f - (0.45f * row), -200f); buttonParent.localScale = new Vector3(0.55f, 0.55f, 1f); label.text = GetString(role.ToString()); label.color = Utils.GetRoleColor(role); @@ -950,6 +953,7 @@ public static class GuessManager button.GetComponent().OnClick.RemoveAllListeners(); if (PlayerControl.LocalPlayer.IsAlive()) + { button.GetComponent().OnClick.AddListener((Action)(() => { if (selectedButton != button) @@ -972,6 +976,7 @@ public static class GuessManager textTemplate.enabled = false; } })); + } i[(int)role.GetCustomRoleTypes()]++; } @@ -1057,14 +1062,14 @@ public static class GuessManager private static void InitializeGuesserPlayers() { - var players = Main.AllPlayerControls + Dictionary> players = Main.AllPlayerControls .GroupBy(x => x.GetTeam()) .ToDictionary(x => x.Key, x => x.Select(p => p.PlayerId).Shuffle()); foreach ((Team team, (OptionItem minSetting, OptionItem maxSetting)) in Options.NumGuessersOnEachTeam) { - if (!players.TryGetValue(team, out var teamPlayers)) continue; - var num = IRandom.Instance.Next(minSetting.GetInt(), maxSetting.GetInt() + 1); + if (!players.TryGetValue(team, out List teamPlayers)) continue; + int num = IRandom.Instance.Next(minSetting.GetInt(), maxSetting.GetInt() + 1); Guessers.UnionWith(teamPlayers.Take(num)); } } @@ -1079,4 +1084,4 @@ public static class GuessManager Object.Destroy(textTemplate.gameObject); } } -} +} \ No newline at end of file diff --git a/Modules/LateTask.cs b/Modules/LateTask.cs index 0efaaa288..c256e68f9 100644 --- a/Modules/LateTask.cs +++ b/Modules/LateTask.cs @@ -15,11 +15,11 @@ internal class LateTask private LateTask(Action action, float time, string name, bool log, string callerData) { - this.Action = action; + Action = action; Timer = time; - this.Name = name; - this.LOG = log; - this.CallerData = callerData; + Name = name; + LOG = log; + CallerData = callerData; Tasks.Add(this); if (log && name is not "" and not "No Name Task") Logger.Info("\"" + name + "\" is created", "LateTask"); } diff --git a/Modules/LoadingScreen.cs b/Modules/LoadingScreen.cs index a163ca422..97d1b291d 100644 --- a/Modules/LoadingScreen.cs +++ b/Modules/LoadingScreen.cs @@ -70,7 +70,7 @@ internal static class LoadingScreen PlayerAnimations anims = lp.MyPhysics.Animations; - bool visible = AmongUsClient.Instance.AmHost && AmongUsClient.Instance.IsGameStarted && !GameStates.IsCanMove && (!GameStates.IsInTask || ExileController.Instance) && !GameStates.IsMeeting && !HudManager.Instance.Chat.IsOpenOrOpening && !lp.inVent && !anims.IsPlayingAnyLadderAnimation() && !VentButtonDoClickPatch.Animating && !lp.onLadder || GameEndChecker.LoadingEndScreen; + bool visible = (AmongUsClient.Instance.AmHost && AmongUsClient.Instance.IsGameStarted && !GameStates.IsCanMove && (!GameStates.IsInTask || ExileController.Instance) && !GameStates.IsMeeting && !HudManager.Instance.Chat.IsOpenOrOpening && !lp.inVent && !anims.IsPlayingAnyLadderAnimation() && !VentButtonDoClickPatch.Animating && !lp.onLadder) || GameEndChecker.LoadingEndScreen; switch (visible) { diff --git a/Modules/LobbySharingAPI.cs b/Modules/LobbySharingAPI.cs index ed480fdf2..323daa80d 100644 --- a/Modules/LobbySharingAPI.cs +++ b/Modules/LobbySharingAPI.cs @@ -19,31 +19,31 @@ public static class LobbySharingAPI private static void NotifyLobbyCreated() { - var gameId = AmongUsClient.Instance.GameId; + int gameId = AmongUsClient.Instance.GameId; if (gameId == 32) return; - var roomCode = GameCode.IntToGameName(gameId); + string roomCode = GameCode.IntToGameName(gameId); if (roomCode == LastRoomCode || roomCode.IsNullOrWhiteSpace() || string.IsNullOrEmpty(roomCode)) return; LastRoomCode = roomCode; - var modLanguage = Options.ModLanguage.GetValue(); - var language = modLanguage == 0 ? Translator.GetUserTrueLang().ToString() : ((Options.ModLanguages)modLanguage).ToString(); + int modLanguage = Options.ModLanguage.GetValue(); + string language = modLanguage == 0 ? Translator.GetUserTrueLang().ToString() : ((Options.ModLanguages)modLanguage).ToString(); - var serverName = Utils.GetRegionName(); - var hostName = Main.AllPlayerNames[PlayerControl.LocalPlayer.PlayerId].RemoveHtmlTags(); + string serverName = Utils.GetRegionName(); + string hostName = Main.AllPlayerNames[PlayerControl.LocalPlayer.PlayerId].RemoveHtmlTags(); Main.Instance.StartCoroutine(SendLobbyCreatedRequest(roomCode, serverName, language, $"EHR v{Main.PluginDisplayVersion}", gameId, hostName)); } private static IEnumerator SendLobbyCreatedRequest(string roomCode, string serverName, string language, string version, int gameId, string hostName) { - var timeSinceLastRequest = Utils.TimeStamp - LastRequestTimeStamp; + long timeSinceLastRequest = Utils.TimeStamp - LastRequestTimeStamp; if (timeSinceLastRequest < BufferTime) yield return new WaitForSeconds(BufferTime); LastRequestTimeStamp = Utils.TimeStamp; var jsonData = $"{{\"roomCode\":\"{roomCode}\",\"serverName\":\"{serverName}\",\"language\":\"{language}\",\"version\":\"{version}\",\"gameId\":\"{gameId}\",\"hostName\":\"{hostName}\"}}"; byte[] jsonToSend = new UTF8Encoding().GetBytes(jsonData); - UnityWebRequest request = new UnityWebRequest("https://gurge44.pythonanywhere.com/lobby_created", "POST") + var request = new UnityWebRequest("https://gurge44.pythonanywhere.com/lobby_created", "POST") { uploadHandler = new UploadHandlerRaw(jsonToSend), downloadHandler = new DownloadHandlerBuffer() @@ -90,24 +90,21 @@ public static class LobbySharingAPI StartMessageEdit(); return; - void StartMessageEdit() - { - Main.Instance.StartCoroutine(SendLobbyStatusChangedRequest(LastRoomCode, status.ToString().Replace('_', ' '), PlayerControl.AllPlayerControls.Count)); - } + void StartMessageEdit() => Main.Instance.StartCoroutine(SendLobbyStatusChangedRequest(LastRoomCode, status.ToString().Replace('_', ' '), PlayerControl.AllPlayerControls.Count)); } private static IEnumerator SendLobbyStatusChangedRequest(string roomCode, string newStatus, int players) { if (string.IsNullOrEmpty(Token)) yield break; - var timeSinceLastRequest = Utils.TimeStamp - LastRequestTimeStamp; + long timeSinceLastRequest = Utils.TimeStamp - LastRequestTimeStamp; if (timeSinceLastRequest < BufferTime) yield return new WaitForSeconds(BufferTime); LastRequestTimeStamp = Utils.TimeStamp; var jsonData = $"{{\"roomCode\":\"{roomCode}\",\"token\":\"{Token}\",\"newStatus\":\"{newStatus}\",\"players\":\"{players}\"}}"; byte[] jsonToSend = new UTF8Encoding().GetBytes(jsonData); - UnityWebRequest request = new UnityWebRequest("https://gurge44.pythonanywhere.com/update_status", "POST") + var request = new UnityWebRequest("https://gurge44.pythonanywhere.com/update_status", "POST") { uploadHandler = new UploadHandlerRaw(jsonToSend), downloadHandler = new DownloadHandlerBuffer() @@ -139,7 +136,7 @@ public enum LobbyStatus } [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.ExitGame))] -static class ExitGamePatch +internal static class ExitGamePatch { public static void Prefix() { diff --git a/Modules/MeetingTimeManager.cs b/Modules/MeetingTimeManager.cs index e6b54c7ff..500447afa 100644 --- a/Modules/MeetingTimeManager.cs +++ b/Modules/MeetingTimeManager.cs @@ -58,7 +58,8 @@ public static class MeetingTimeManager BonusMeetingTime += TimeThief.TotalDecreasedMeetingTime(); } - if (Timelord.On) { BonusMeetingTime += -Timelord.GetTotalStolenTime(); } + if (Timelord.On) + BonusMeetingTime += -Timelord.GetTotalStolenTime(); if (TimeManager.PlayerIdList.Count > 0) { diff --git a/Modules/NameColorManager.cs b/Modules/NameColorManager.cs index c730c51e4..8a491bcc4 100644 --- a/Modules/NameColorManager.cs +++ b/Modules/NameColorManager.cs @@ -17,8 +17,10 @@ public static class NameColorManager 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 = ""; @@ -106,7 +108,8 @@ public static class NameColorManager 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) && seer.GetTeam() == ghostRole.Instance.Team) { color = ghostRole.Instance.Team.GetTextColor(); } + if (GhostRolesManager.AssignedGhostRoles.TryGetValue(target.PlayerId, out (CustomRoles Role, IGhostRole Instance) ghostRole) && seer.GetTeam() == ghostRole.Instance.Team) + color = ghostRole.Instance.Team.GetTextColor(); if (isMeeting && Haunter.AllHauntedPlayers.Contains(target.PlayerId)) color = Main.ImpostorColor; diff --git a/Modules/NameNotifyManager.cs b/Modules/NameNotifyManager.cs index c2eddf274..3135ba728 100644 --- a/Modules/NameNotifyManager.cs +++ b/Modules/NameNotifyManager.cs @@ -79,7 +79,7 @@ public static class NameNotifyManager writer.Write(overrideAll); AmongUsClient.Instance.FinishRpcImmediately(writer); } - + public static void SendRPC(CustomRpcSender sender, byte playerId, string text, long expireTS, bool overrideAll) { if (!AmongUsClient.Instance.AmHost) return; diff --git a/Modules/OptionBackup/OptionBackupData.cs b/Modules/OptionBackup/OptionBackupData.cs index 0cd513732..5ce8661a9 100644 --- a/Modules/OptionBackup/OptionBackupData.cs +++ b/Modules/OptionBackup/OptionBackupData.cs @@ -14,20 +14,28 @@ public class OptionBackupData 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 is not BoolOptionNames.GhostsDoTasks and not BoolOptionNames.Roles) 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)); @@ -76,6 +84,6 @@ public class OptionBackupData .OfType>() .FirstOrDefault(val => val.OptionName.Equals(name)); - return value == null ? default : value.Value; + return value == null ? default(TValue) : value.Value; } } \ No newline at end of file diff --git a/Modules/OptionHolder.cs b/Modules/OptionHolder.cs index 611bbfff9..c3b9b47be 100644 --- a/Modules/OptionHolder.cs +++ b/Modules/OptionHolder.cs @@ -830,7 +830,10 @@ public static class Options _ => CustomGameMode.Standard }; - public static bool IsActiveOrIntegrated(this CustomGameMode customGameMode) => CurrentGameMode == customGameMode || (CurrentGameMode == CustomGameMode.AllInOne && AllInOneGameMode.GameModeIntegrationSettings.TryGetValue(customGameMode, out var option) && option.GetBool()); + public static bool IsActiveOrIntegrated(this CustomGameMode customGameMode) + { + return CurrentGameMode == customGameMode || (CurrentGameMode == CustomGameMode.AllInOne && AllInOneGameMode.GameModeIntegrationSettings.TryGetValue(customGameMode, out OptionItem option) && option.GetBool()); + } [HarmonyPatch(typeof(TranslationController), nameof(TranslationController.Initialize))] [HarmonyPostfix] @@ -852,7 +855,7 @@ public static class Options GroupAddons(); Achievements.LoadAllData(); OptionShower.LastText = Translator.GetString("Loading"); - + if (AllCrewRolesHaveVanillaColor.GetBool()) { List toChange = Main.RoleColors.Keys.Where(x => x.IsCrewmate()).ToList(); @@ -1007,7 +1010,7 @@ public static class Options #region RoleListMaker - int id = 19820; + var id = 19820; foreach (Team team in new[] { Team.Impostor, Team.Neutral, Team.Coven }) { @@ -1027,12 +1030,12 @@ public static class Options _ => TabGroup.OtherRoles }; - var minSetting = new IntegerOptionItem(id++, $"FactionLimits.{team}.Min", new(0, 15, 1), defaultNum.Min, tab) + OptionItem minSetting = new IntegerOptionItem(id++, $"FactionLimits.{team}.Min", new(0, 15, 1), defaultNum.Min, tab) .SetGameMode(CustomGameMode.Standard) .SetHeader(true) .SetColor(team.GetColor()); - var maxSetting = new IntegerOptionItem(id++, $"FactionLimits.{team}.Max", new(0, 15, 1), defaultNum.Max, tab) + OptionItem maxSetting = new IntegerOptionItem(id++, $"FactionLimits.{team}.Max", new(0, 15, 1), defaultNum.Max, tab) .SetGameMode(CustomGameMode.Standard) .SetColor(team.GetColor()); @@ -1042,7 +1045,7 @@ public static class Options MinNNKs = new IntegerOptionItem(id++, "MinNNKs", new(0, 15, 1), 0, TabGroup.NeutralRoles) .SetGameMode(CustomGameMode.Standard) .SetHeader(true); - + MaxNNKs = new IntegerOptionItem(id++, "MaxNNKs", new(0, 15, 1), 2, TabGroup.NeutralRoles) .SetGameMode(CustomGameMode.Standard); @@ -1309,10 +1312,7 @@ public static class Options yield return null; } - void Log() - { - Logger.Info(" " + RoleLoadingText, MainLoadingText); - } + void Log() => Logger.Info(" " + RoleLoadingText, MainLoadingText); LoadingPercentage = 60; @@ -1446,7 +1446,7 @@ public static class Options .SetHeader(true); StoreCompletedAchievementsOnEHRDatabase = new BooleanOptionItem(19423, "StoreCompletedAchievementsOnEHRDatabase", true, TabGroup.SystemSettings); - + AllCrewRolesHaveVanillaColor = new BooleanOptionItem(19424, "AllCrewRolesHaveVanillaColor", false, TabGroup.SystemSettings) .SetHeader(true); @@ -2385,18 +2385,18 @@ public static class Options GuesserNumRestrictions = new BooleanOptionItem(19722, "GuesserNumRestrictions", false, TabGroup.TaskSettings) .SetParent(GuesserMode); - int goId = 19723; + var goId = 19723; NumGuessersOnEachTeam = Enum.GetValues()[1..].ToDictionary(x => x, x => { Color teamColor = x.GetColor(); - var min = new IntegerOptionItem(goId++, $"NumGuessersOn.{x}.Min", new(1, 15, 1), 15, TabGroup.TaskSettings) + OptionItem min = new IntegerOptionItem(goId++, $"NumGuessersOn.{x}.Min", new(1, 15, 1), 15, TabGroup.TaskSettings) .SetParent(GuesserNumRestrictions) .SetValueFormat(OptionFormat.Players) .SetColor(teamColor); - var max = new IntegerOptionItem(goId++, $"NumGuessersOn.{x}.Max", new(1, 15, 1), 15, TabGroup.TaskSettings) + OptionItem max = new IntegerOptionItem(goId++, $"NumGuessersOn.{x}.Max", new(1, 15, 1), 15, TabGroup.TaskSettings) .SetParent(GuesserNumRestrictions) .SetValueFormat(OptionFormat.Players) .SetColor(teamColor); diff --git a/Modules/OptionItem/OptionItem.cs b/Modules/OptionItem/OptionItem.cs index 960e16931..03b81e648 100644 --- a/Modules/OptionItem/OptionItem.cs +++ b/Modules/OptionItem/OptionItem.cs @@ -41,8 +41,10 @@ public abstract class OptionItem else if (IsSingleValue) SingleValue = DefaultValue; else + { for (var i = 0; i < NumPresets; i++) AllValues[i] = DefaultValue; + } if (FastOpts.TryAdd(id, this)) Options.Add(this); @@ -152,11 +154,13 @@ public abstract class OptionItem } /// - /// Register an event that will be called when the value of this option is updated. + /// Register an event that will be called when the value of this option is updated. /// - /// The event handler that has two arguments: - /// the first argument is the OptionItem instance that was updated, - /// the second one contains the old and the new value of the setting. + /// + /// The event handler that has two arguments: + /// the first argument is the OptionItem instance that was updated, + /// the second one contains the old and the new value of the setting. + /// /// public OptionItem RegisterUpdateValueEvent(EventHandler handler) { @@ -220,8 +224,8 @@ public abstract class OptionItem public bool IsCurrentlyHidden() { - var mode = EHR.Options.CurrentGameMode; - return CheckHidden() || (GameMode != CustomGameMode.All && GameMode != mode && !(mode == CustomGameMode.AllInOne && AllInOneGameMode.GameModeIntegrationSettings.TryGetValue(GameMode, out var option) && option.GetBool())); + CustomGameMode mode = EHR.Options.CurrentGameMode; + return CheckHidden() || (GameMode != CustomGameMode.All && GameMode != mode && !(mode == CustomGameMode.AllInOne && AllInOneGameMode.GameModeIntegrationSettings.TryGetValue(GameMode, out OptionItem option) && option.GetBool())); } private bool CheckHidden() @@ -279,8 +283,10 @@ public abstract class OptionItem if (values.Length == AllValues.Length) AllValues = values; else + { for (var i = 0; i < values.Length; i++) AllValues[i] = values[i]; + } } public static OptionItem operator ++(OptionItem item) diff --git a/Modules/OptionSaver.cs b/Modules/OptionSaver.cs index b5466d145..c1554c4f9 100644 --- a/Modules/OptionSaver.cs +++ b/Modules/OptionSaver.cs @@ -76,12 +76,16 @@ public static class OptionSaver 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() diff --git a/Modules/OptionShower.cs b/Modules/OptionShower.cs index 4a44e47e3..7f67dd5b0 100644 --- a/Modules/OptionShower.cs +++ b/Modules/OptionShower.cs @@ -78,7 +78,7 @@ public static class OptionShower Pages.Add(""); sb.Append($"{Utils.GetRoleName(CustomRoles.GM)}: {(Main.GM.Value ? GetString("RoleRate") : GetString("RoleOff"))}\n\n"); - int index = 0; + var index = 0; if (!CustomGameMode.HideAndSeek.IsActiveOrIntegrated()) { diff --git a/Modules/PetsHelper.cs b/Modules/PetsHelper.cs index 4e2ccb876..9b2cfd3aa 100644 --- a/Modules/PetsHelper.cs +++ b/Modules/PetsHelper.cs @@ -8,7 +8,7 @@ public static class PetsHelper { const string petId = ""; if (!GameStates.IsInGame || !Options.RemovePetsAtDeadPlayers.GetBool() || pc == null || !pc.Data.IsDead || pc.IsAlive() || pc.CurrentOutfit.PetId == petId) return; - + var sender = CustomRpcSender.Create("PetsHelper.RpcRemovePet", SendOption.Reliable); SetPet(pc, petId, sender); sender.SendMessage(); diff --git a/Modules/PrivateTagManager.cs b/Modules/PrivateTagManager.cs index 6a4492eca..00d762567 100644 --- a/Modules/PrivateTagManager.cs +++ b/Modules/PrivateTagManager.cs @@ -14,7 +14,7 @@ public static class PrivateTagManager Tags[friendcode] = tag; SaveTagsToFile(); } - + public static void DeleteTag(string friendcode) { Tags.Remove(friendcode); @@ -23,20 +23,17 @@ public static class PrivateTagManager private static void SaveTagsToFile() { - try - { - File.WriteAllText(TagFile, string.Join("\n", Tags.Select(x => $"{x.Key}={x.Value}"))); - } + try { File.WriteAllText(TagFile, string.Join("\n", Tags.Select(x => $"{x.Key}={x.Value}"))); } catch (Exception e) { Utils.ThrowException(e); } } - + public static void LoadTagsFromFile() { try { if (!File.Exists(TagFile)) return; - + Tags = File.ReadAllLines(TagFile) .Select(x => x.Split('=')) .ToDictionary(x => x[0], x => x[1]); diff --git a/Modules/Prompt.cs b/Modules/Prompt.cs index a293d06b3..aeef224b3 100644 --- a/Modules/Prompt.cs +++ b/Modules/Prompt.cs @@ -84,7 +84,7 @@ public static class Prompt } [HarmonyPatch(typeof(DialogueBox), nameof(DialogueBox.Hide))] - static class DialogueBoxHidePatch + private static class DialogueBoxHidePatch { public static void Prefix() { diff --git a/Modules/RPC.cs b/Modules/RPC.cs index 4899eaa1f..c4ffd1a36 100644 --- a/Modules/RPC.cs +++ b/Modules/RPC.cs @@ -505,7 +505,7 @@ internal static class RPCHandlerPatch byte sendTo = reader.ReadByte(); string title = reader.ReadString(); bool noSplit = reader.ReadBoolean(); - Utils.SendMessage(text, sendTo, title, noSplit: noSplit); + Utils.SendMessage(text, sendTo, title, noSplit); break; } case CustomRPC.NotificationPopper: @@ -1487,7 +1487,7 @@ internal static class StartRpcImmediatelyPatch } [HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.FinishRpcImmediately))] -static class FinishRpcImmediatelyPatch +internal static class FinishRpcImmediatelyPatch { public static bool Prefix(InnerNetClient __instance, [HarmonyArgument(0)] MessageWriter msg) { diff --git a/Modules/Random/MersenneTwister.cs b/Modules/Random/MersenneTwister.cs index d6bb96cc8..b8df2ecf8 100644 --- a/Modules/Random/MersenneTwister.cs +++ b/Modules/Random/MersenneTwister.cs @@ -34,24 +34,24 @@ public class MersenneTwister : IRandom /// 数値の上限を設定 /// これより下の値の一部は参考元のソースより拝借 /// - private const Int32 N = 624; + private const int N = 624; - private const Int32 M = 397; - private const UInt32 MatrixA = 0x9908b0df; - private const UInt32 UpperMask = 0x80000000; - private const UInt32 LowerMask = 0x7fffffff; - private const UInt32 TemperingMaskB = 0x9d2c5680; - private const UInt32 TemperingMaskC = 0xefc60000; - private readonly UInt32[] _mag01 = [0x0, MatrixA]; + private const int M = 397; + private const uint MatrixA = 0x9908b0df; + private const uint UpperMask = 0x80000000; + private const uint LowerMask = 0x7fffffff; + private const uint TemperingMaskB = 0x9d2c5680; + private const uint TemperingMaskC = 0xefc60000; + private readonly uint[] _mag01 = [0x0, MatrixA]; - private readonly UInt32[] _mt = new UInt32[N]; - private Int16 _mtItems; + private readonly uint[] _mt = new uint[N]; + private short _mtItems; - public MersenneTwister() : this((Int32)DateTime.UtcNow.Ticks) { } + public MersenneTwister() : this((int)DateTime.UtcNow.Ticks) { } - public MersenneTwister(Int32 seed) + public MersenneTwister(int seed) { - Init((UInt32)seed); + Init((uint)seed); } public int Next(int minValue, int maxValue) @@ -70,27 +70,27 @@ public class MersenneTwister : IRandom return Next(0, maxValue); } - private static UInt32 ShiftU(UInt32 y) + private static uint ShiftU(uint y) { return y >> 11; } - private static UInt32 ShiftS(UInt32 y) + private static uint ShiftS(uint y) { return y << 7; } - private static UInt32 ShiftT(UInt32 y) + private static uint ShiftT(uint y) { return y << 15; } - private static UInt32 ShiftL(UInt32 y) + private static uint ShiftL(uint y) { return y >> 18; } - private void Init(UInt32 seed) + private void Init(uint seed) { _mt[0] = seed & 0xffffffffU; @@ -103,12 +103,12 @@ public class MersenneTwister : IRandom public uint Next() { - UInt32 y; + uint y; /* _mag01[x] = x * MatrixA for x=0,1 */ if (_mtItems >= N) /* generate N words at one time */ { - Int16 kk = 0; + short kk = 0; for (; kk < N - M; ++kk) { diff --git a/Modules/SpamManager.cs b/Modules/SpamManager.cs index 7cd89aaa8..3fef0aee6 100644 --- a/Modules/SpamManager.cs +++ b/Modules/SpamManager.cs @@ -51,10 +51,7 @@ public static class SpamManager File.WriteAllText(BANEDWORDS_FILE_PATH, GetResourcesTxt($"EHR.Resources.Config.BanWords.{fileName}.txt")); } } - catch (Exception ex) - { - Logger.Exception(ex, "SpamManager"); - } + catch (Exception ex) { Logger.Exception(ex, "SpamManager"); } } } @@ -75,8 +72,10 @@ public static class SpamManager List sendList = []; while ((text = sr.ReadLine()) != null) + { if (text.Length > 1 && text != "") sendList.Add(text.Replace("\\n", "\n").ToLower()); + } return sendList; } @@ -137,8 +136,10 @@ public static class SpamManager 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()); diff --git a/Modules/Statistics.cs b/Modules/Statistics.cs index a158c30ff..5512e11b7 100644 --- a/Modules/Statistics.cs +++ b/Modules/Statistics.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using EHR.AddOns.Common; using EHR.Crewmate; @@ -18,9 +19,9 @@ public static class Statistics { if (CustomWinnerHolder.WinnerTeam is CustomWinner.None or CustomWinner.Draw or CustomWinner.Error || Main.AllPlayerControls.Length <= MinPlayers) return; - var lp = PlayerControl.LocalPlayer; - var role = lp.GetCustomRole(); - var addons = lp.GetCustomSubRoles(); + PlayerControl lp = PlayerControl.LocalPlayer; + CustomRoles role = lp.GetCustomRole(); + List addons = lp.GetCustomSubRoles(); try { @@ -101,7 +102,7 @@ public static class Statistics switch (CustomWinnerHolder.WinnerTeam) { - case CustomWinner.None when Main.PlayerStates.Values.FindFirst(x => x.SubRoles.Contains(CustomRoles.Avanger), out var state) && state.GetRealKiller().GetPlayer().Is(CustomRoles.OverKiller): + case CustomWinner.None when Main.PlayerStates.Values.FindFirst(x => x.SubRoles.Contains(CustomRoles.Avanger), out PlayerState state) && state.GetRealKiller().GetPlayer().Is(CustomRoles.OverKiller): Achievements.Type.FuriousAvenger.CompleteAfterGameEnd(); break; case CustomWinner.Crewmate when won && Main.AllPlayerControls.Count(x => x.IsImpostor() || x.IsNeutralKiller()) >= 2 && MeetingStates.MeetingNum < 3: @@ -139,7 +140,7 @@ public static class Statistics case CustomRoles.Bargainer when won && Bargainer.PurchasedItems.Count >= 3: Achievements.Type.P2W.CompleteAfterGameEnd(); break; - case CustomRoles.Lawyer when Lawyer.Target.TryGetValue(lp.PlayerId, out var ltg) && Main.PlayerStates.TryGetValue(ltg, out var ltgState) && ltgState.IsDead && ltgState.MainRole.IsCrewmate() && !ltgState.SubRoles.Contains(CustomRoles.Bloodlust) && won && CustomWinnerHolder.WinnerTeam == CustomWinner.Impostor: + case CustomRoles.Lawyer when Lawyer.Target.TryGetValue(lp.PlayerId, out byte ltg) && Main.PlayerStates.TryGetValue(ltg, out PlayerState ltgState) && ltgState.IsDead && ltgState.MainRole.IsCrewmate() && !ltgState.SubRoles.Contains(CustomRoles.Bloodlust) && won && CustomWinnerHolder.WinnerTeam == CustomWinner.Impostor: Achievements.Type.LiarLiar.CompleteAfterGameEnd(); break; } @@ -155,7 +156,7 @@ public static class Statistics if (gm == CustomGameMode.Standard) return; Main.NumWinsPerGM.TryAdd(gm, []); - Main.NumWinsPerGM[gm].AddRange(CustomWinnerHolder.WinnerIds.ToValidPlayers().ToDictionary(x => x.GetClient().GetHashedPuid(), _ => 0), overrideExistingKeys: false); + Main.NumWinsPerGM[gm].AddRange(CustomWinnerHolder.WinnerIds.ToValidPlayers().ToDictionary(x => x.GetClient().GetHashedPuid(), _ => 0), false); Main.NumWinsPerGM[gm].AdjustAllValues(x => ++x); void Reset() @@ -188,7 +189,7 @@ public static class Statistics if (amDictator) Achievements.Type.KimJongUnExperience.Complete(); - bool lpHasVS = states.FindFirst(x => x.VoterId == lp.PlayerId, out var lpVS); + bool lpHasVS = states.FindFirst(x => x.VoterId == lp.PlayerId, out MeetingHud.VoterState lpVS); bool exiled = exiledPlayer != null && exiledPlayer.Object != null; @@ -222,7 +223,7 @@ public static class Statistics { if (GameStates.IsEnded) return; - var aapc = Main.AllAlivePlayerControls; + PlayerControl[] aapc = Main.AllAlivePlayerControls; if (aapc.Length == 2 && lp.IsAlive() && aapc.All(x => x.IsNeutralKiller() || x.IsImpostor())) Achievements.Type.Duel.Complete(); @@ -272,7 +273,7 @@ public static class Statistics if ((targetState.MainRole == CustomRoles.Romantic && Romantic.PartnerId == killer.PlayerId) || (targetState.SubRoles.Contains(CustomRoles.Lovers) && killer.Is(CustomRoles.Lovers)) || - (targetState.MainRole == CustomRoles.Lawyer && Lawyer.Target.TryGetValue(target.PlayerId, out var ltg) && ltg == killer.PlayerId) || + (targetState.MainRole == CustomRoles.Lawyer && Lawyer.Target.TryGetValue(target.PlayerId, out byte ltg) && ltg == killer.PlayerId) || (targetState.Role is Totocalcio tc && tc.BetPlayer == killer.PlayerId)) Achievements.Type.WhatHaveIDone.CompleteAfterGameEnd(); diff --git a/Modules/TemplateManager.cs b/Modules/TemplateManager.cs index 2c2f3441f..eb9c40f4b 100644 --- a/Modules/TemplateManager.cs +++ b/Modules/TemplateManager.cs @@ -77,10 +77,7 @@ public static class TemplateManager File.WriteAllText(TemplateFilePath, GetResourcesTxt($"EHR.Resources.Config.template.{fileName}.txt")); } } - catch (Exception ex) - { - Logger.Exception(ex, "TemplateManager"); - } + catch (Exception ex) { Logger.Exception(ex, "TemplateManager"); } } else { @@ -126,8 +123,10 @@ public static class TemplateManager 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) diff --git a/Modules/Translator.cs b/Modules/Translator.cs index aba7ca195..1788b7171 100644 --- a/Modules/Translator.cs +++ b/Modules/Translator.cs @@ -135,8 +135,10 @@ public static class Translator string str = GetString(s, langId); if (replacementDic != null) + { foreach (KeyValuePair rd in replacementDic) str = str.Replace(rd.Key, rd.Value); + } return str; } @@ -225,8 +227,10 @@ public static class Translator 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); diff --git a/Modules/Utils.cs b/Modules/Utils.cs index cca99937a..1051ee6b6 100644 --- a/Modules/Utils.cs +++ b/Modules/Utils.cs @@ -157,7 +157,7 @@ public static class Utils } var newSid = (ushort)(nt.lastSequenceId + 8); - var sendOption = NumSnapToRPCsThisRound < 100 || GameStates.CurrentServerType != GameStates.ServerType.Vanilla || DateTime.UtcNow.Month < 4 ? SendOption.Reliable : SendOption.None; + SendOption sendOption = NumSnapToRPCsThisRound < 100 || GameStates.CurrentServerType != GameStates.ServerType.Vanilla || DateTime.UtcNow.Month < 4 ? SendOption.Reliable : SendOption.None; MessageWriter messageWriter = AmongUsClient.Instance.StartRpcImmediately(nt.NetId, (byte)RpcCalls.SnapTo, sendOption); NetHelpers.WriteVector2(location, messageWriter); messageWriter.Write(newSid); @@ -423,7 +423,7 @@ public static class Utils public static void RemovePlayerFromPreviousRoleData(PlayerControl target) { - if (!Main.PlayerStates.TryGetValue(target.PlayerId, out var state)) return; + if (!Main.PlayerStates.TryGetValue(target.PlayerId, out PlayerState state)) return; state.Role.Remove(target.PlayerId); } @@ -486,7 +486,7 @@ public static class Utils if (CustomGameMode.HideAndSeek.IsActiveOrIntegrated() && targetMainRole == CustomRoles.Agent && CustomHnS.PlayerRoles[seerId].Interface.Team != Team.Impostor) targetMainRole = CustomRoles.Hider; - if (!self && seerMainRole.IsImpostor() && targetMainRole == CustomRoles.DoubleAgent && DoubleAgent.ShownRoles.TryGetValue(targetId, out var shownRole)) + if (!self && seerMainRole.IsImpostor() && targetMainRole == CustomRoles.DoubleAgent && DoubleAgent.ShownRoles.TryGetValue(targetId, out CustomRoles shownRole)) targetMainRole = shownRole; var loversShowDifferentRole = false; @@ -1183,7 +1183,8 @@ public static class Utils void CheckAndAppendOptionString(OptionItem item) { - if (item.GetBool() && item.Parent == null && !item.IsCurrentlyHidden()) { sb.Append($"\n{item.GetName(true)}: {item.GetString()}"); } + if (item.GetBool() && item.Parent == null && !item.IsCurrentlyHidden()) + sb.Append($"\n{item.GetName(true)}: {item.GetString()}"); } } @@ -1521,15 +1522,15 @@ public static class Utils public static string GetWinCountsString() { - if (!Main.NumWinsPerGM.TryGetValue(Options.CurrentGameMode, out var dictionary) || dictionary.Count == 0) return string.Empty; + if (!Main.NumWinsPerGM.TryGetValue(Options.CurrentGameMode, out Dictionary dictionary) || dictionary.Count == 0) return string.Empty; StringBuilder sb = new(); sb.AppendLine($"<#ffffff>{GetString("WinsCountTitle")}:"); - bool any = false; + var any = false; foreach ((string hashedpuid, int wins) in dictionary) { - if (!Main.AllPlayerControls.FindFirst(x => x.GetClient().GetHashedPuid() == hashedpuid, out var player)) continue; + if (!Main.AllPlayerControls.FindFirst(x => x.GetClient().GetHashedPuid() == hashedpuid, out PlayerControl player)) continue; sb.AppendLine($"{player.PlayerId.ColoredPlayerName()}: {wins}"); any = true; } @@ -1635,9 +1636,8 @@ public static class Utils SendMessage(ChatCommands.AllCommands.Where(x => x.CanUseCommand(player, false) && !x.CommandForms.Contains("help")).Aggregate("", (s, c) => s + $"\n/{c.CommandForms.TakeWhile(f => f.All(char.IsAscii)).MinBy(f => f.Length)}{(c.Arguments.Length == 0 ? string.Empty : $" {c.Arguments.Split(' ').Select((x, i) => ID == 0 ? ColorString(GetColor(i), x) : x).Join(delimiter: " ")}")} \u2192 {c.Description}"), ID, GetString("CommandList")); return; - Color GetColor(int i) - { - return i switch + Color GetColor(int i) => + i switch { 0 => Palette.Orange, 1 => Color.magenta, @@ -1650,7 +1650,6 @@ public static class Utils _ => Color.white }; - } } public static void CheckTerroristWin(NetworkedPlayerInfo Terrorist) @@ -1729,7 +1728,7 @@ public static class Utils text = text.Replace("color=", string.Empty); title = title.Replace("color=", string.Empty); - var sender = Main.AllAlivePlayerControls.MinBy(x => x.PlayerId) ?? Main.AllPlayerControls.MinBy(x => x.PlayerId) ?? PlayerControl.LocalPlayer; + PlayerControl sender = Main.AllAlivePlayerControls.MinBy(x => x.PlayerId) ?? Main.AllPlayerControls.MinBy(x => x.PlayerId) ?? PlayerControl.LocalPlayer; if (sendTo != byte.MaxValue && receiver.IsLocalPlayer()) { @@ -1771,9 +1770,9 @@ public static class Utils } if (shortenedText.Length >= sizeLimit) - shortenedText.Chunk(sizeLimit).Do(x => SendMessage(new(x), sendTo, title, noSplit: true, writer: writer)); + shortenedText.Chunk(sizeLimit).Do(x => SendMessage(new(x), sendTo, title, true, writer)); else - SendMessage(shortenedText, sendTo, title, noSplit: true, writer: writer); + SendMessage(shortenedText, sendTo, title, true, writer); string sentText = shortenedText; shortenedText = line + "\n"; @@ -1785,7 +1784,7 @@ public static class Utils } } - if (shortenedText.Length > 0) SendMessage(shortenedText, sendTo, title, noSplit: true, writer: writer, final: true); + if (shortenedText.Length > 0) SendMessage(shortenedText, sendTo, title, true, writer, true); else if (writer != null && sendTo != byte.MaxValue && writer.CurrentState == CustomRpcSender.State.InRootMessage) { writer.StartRpc(sender.NetId, (byte)RpcCalls.SetName) @@ -1840,11 +1839,11 @@ public static class Utils { if (!AmongUsClient.Instance.AmHost || player == null) return; - var devUser = player.FriendCode.GetDevUser(); + DevManager.TagInfo devUser = player.FriendCode.GetDevUser(); bool mod = ChatCommands.IsPlayerModerator(player.FriendCode); bool vip = ChatCommands.IsPlayerVIP(player.FriendCode); bool hasTag = devUser.HasTag(); - bool hasPrivateTag = PrivateTagManager.Tags.TryGetValue(player.FriendCode, out var privateTag); + bool hasPrivateTag = PrivateTagManager.Tags.TryGetValue(player.FriendCode, out string privateTag); if (!player.AmOwner && !hasTag && !mod && !vip && !hasPrivateTag) return; @@ -1867,7 +1866,7 @@ public static class Utils if (GameStates.IsOnlineGame || GameStates.IsLocalGame) name = $"{GetString("HostText")}{GetString("Icon")}{name}"; - string modeText = $"{GetString($"Mode{Options.CurrentGameMode}")}"; + var modeText = $"{GetString($"Mode{Options.CurrentGameMode}")}"; name = Options.CurrentGameMode switch { @@ -1888,14 +1887,14 @@ public static class Utils if (hasTag || mod || vip || hasPrivateTag) { - var pTag = hasPrivateTag ? privateTag : string.Empty; + string pTag = hasPrivateTag ? privateTag : string.Empty; string tag = hasTag ? devUser.GetTag() : string.Empty; if (tag == "null") tag = string.Empty; bool host = player.IsHost(); - var separator = player.AmOwner || player.IsModdedClient() ? "\r\n" : " "; - var modTag = host ? string.Empty : $"{GetString("ModeratorTag")}{separator}"; - var vipTag = host ? string.Empty : $"{GetString("VIPTag")}{separator}"; + string separator = player.AmOwner || player.IsModdedClient() ? "\r\n" : " "; + string modTag = host ? string.Empty : $"{GetString("ModeratorTag")}{separator}"; + string vipTag = host ? string.Empty : $"{GetString("VIPTag")}{separator}"; name = $"{(hasTag ? tag.Replace("\r\n", separator) : string.Empty)}{(mod ? modTag : string.Empty)}{(vip ? vipTag : string.Empty)}{pTag}{name}"; } @@ -2045,7 +2044,7 @@ public static class Utils 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"); @@ -2346,7 +2345,7 @@ public static class Utils else if (Options.ChangeNameToRoleInfo.GetBool() && !seer.IsModdedClient() && Options.CurrentGameMode == CustomGameMode.Standard) { bool showLongInfo = LongRoleDescriptions.TryGetValue(seer.PlayerId, out (string Text, int Duration, bool Long) description) && GameStartTimeStamp + description.Duration > now; - string mHelp = (!showLongInfo || description.Long) ? "\n" + GetString("MyRoleCommandHelp") : string.Empty; + string mHelp = !showLongInfo || description.Long ? "\n" + GetString("MyRoleCommandHelp") : string.Empty; string color = seerTeam.GetTextColor(); string teamStr = seerTeam == Team.Impostor && seer.IsMadmate() ? "Madmate" : seerTeam.ToString(); string info = (showLongInfo ? description.Text : seer.GetRoleInfo()) + mHelp; @@ -2354,7 +2353,7 @@ public static class Utils } } - if (GameStartTimeStamp + 50 > TimeStamp && Main.HasPlayedGM.TryGetValue(Options.CurrentGameMode, out var playedFCs) && !playedFCs.Contains(seer.FriendCode)) + if (GameStartTimeStamp + 50 > TimeStamp && Main.HasPlayedGM.TryGetValue(Options.CurrentGameMode, out HashSet playedFCs) && !playedFCs.Contains(seer.FriendCode)) SelfSuffix.Append("\n\n" + GetString($"GameModeTutorial.{Options.CurrentGameMode}")); } @@ -2932,7 +2931,7 @@ public static class Utils if (Options.UsePets.GetBool()) { - pc.AddAbilityCD(includeDuration: false); + pc.AddAbilityCD(false); LateTask.New(() => { @@ -3117,9 +3116,9 @@ public static class Utils Logger.Exception(ex, "AfterPlayerDeathTasks"); } - if (Main.DiedThisRound.Contains(target.PlayerId) && IsRevivingRoleAlive() || Options.CurrentGameMode != CustomGameMode.Standard) return; + if ((Main.DiedThisRound.Contains(target.PlayerId) && IsRevivingRoleAlive()) || Options.CurrentGameMode != CustomGameMode.Standard) return; - var killer = target.GetRealKiller(); + PlayerControl killer = target.GetRealKiller(); if (killer != null) target.Notify($"<#ffffff>{string.Format(GetString("DeathCommand"), killer.PlayerId.ColoredPlayerName(), (killer.Is(CustomRoles.Bloodlust) ? $"{CustomRoles.Bloodlust.ToColoredString()} " : string.Empty) + killer.GetCustomRole().ToColoredString())}", 10f); } @@ -3353,7 +3352,7 @@ public static class Utils sb.Append(notify ? "<#777777>" : string.Empty); - var numberToUse = impShow ? impnum : nkShow ? neutralnum : covenNum; + int numberToUse = impShow ? impnum : nkShow ? neutralnum : covenNum; sb.Append(numberToUse == 1 ? GetString("RemainingText.Prefix.Single") : GetString("RemainingText.Prefix.Plural")); sb.Append(notify ? " " : "\n"); @@ -3453,12 +3452,12 @@ public static class Utils try { Texture2D texture = new(2, 2, TextureFormat.ARGB32, true); - Assembly assembly = Assembly.GetExecutingAssembly(); + var assembly = Assembly.GetExecutingAssembly(); Stream stream = assembly.GetManifestResourceStream(path); if (stream != null) { - var length = stream.Length; + long length = stream.Length; var byteTexture = new Il2CppStructArray(length); stream.Read(new Span(IntPtr.Add(byteTexture.Pointer, IntPtr.Size * 4).ToPointer(), (int)length)); texture.LoadImage(byteTexture, false); @@ -3557,7 +3556,7 @@ public static class Utils public static void EnterQuickSetupRoles(bool addons) { int all = Options.CustomRoleSpawnChances.Keys.Count(x => addons ? x.IsAdditionRole() : !x.IsAdditionRole()); - int count = 0; + var count = 0; foreach ((CustomRoles role, StringOptionItem option) in Options.CustomRoleSpawnChances) { @@ -3599,8 +3598,10 @@ public static class Utils 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 02858c253..40e09ab95 100644 --- a/Modules/Zoom.cs +++ b/Modules/Zoom.cs @@ -33,8 +33,10 @@ public static class Zoom case < 0: { if (GameStates.IsDead || GameStates.IsFreePlay || DebugModeManager.AmDebugger || GameStates.IsLobby) + { if (Camera.main.orthographicSize < 18.0f) SetZoomSize(true); + } break; } diff --git a/Patches/AnnouncementPatch.cs b/Patches/AnnouncementPatch.cs index 57c70f62a..acd06e3fb 100644 --- a/Patches/AnnouncementPatch.cs +++ b/Patches/AnnouncementPatch.cs @@ -106,8 +106,10 @@ public class ModNewsHistory 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)); }); diff --git a/Patches/ChatCommandPatch.cs b/Patches/ChatCommandPatch.cs index 904c8f981..c61e8f205 100644 --- a/Patches/ChatCommandPatch.cs +++ b/Patches/ChatCommandPatch.cs @@ -390,13 +390,13 @@ internal static class ChatCommands return; } - if (args.Length < 4 || !byte.TryParse(args[1], out var id)) return; + if (args.Length < 4 || !byte.TryParse(args[1], out byte id)) return; - var pc = id.GetPlayer(); + PlayerControl pc = id.GetPlayer(); if (pc == null) return; - var color = ColorUtility.TryParseHtmlString($"#{args[2].ToLower()}", out var c) ? c : Color.red; - var tag = Utils.ColorString(color, string.Join(' ', args[3..])); + Color color = ColorUtility.TryParseHtmlString($"#{args[2].ToLower()}", out Color c) ? c : Color.red; + string tag = Utils.ColorString(color, string.Join(' ', args[3..])); PrivateTagManager.AddTag(pc.FriendCode, tag); Utils.SendMessage("\n", player.PlayerId, string.Format(GetString("AddTagSuccess"), tag, id.ColoredPlayerName(), id)); @@ -410,9 +410,9 @@ internal static class ChatCommands return; } - if (args.Length < 2 || !byte.TryParse(args[1], out var id)) return; + if (args.Length < 2 || !byte.TryParse(args[1], out byte id)) return; - var pc = id.GetPlayer(); + PlayerControl pc = id.GetPlayer(); if (pc == null) return; PrivateTagManager.DeleteTag(pc.FriendCode); @@ -451,8 +451,8 @@ internal static class ChatCommands return; } - var info = string.Join("\n\n", Enum.GetValues()[1..].SkipLast(1) - .Select(x => (GameMode: x, Color: Main.RoleColors.GetValueOrDefault(CustomRoleSelector.GameModeRoles.TryGetValue(x, out var role) ? role : x == CustomGameMode.HideAndSeek ? CustomRoles.Hider : CustomRoles.Witness, "#000000"))) + string info = string.Join("\n\n", Enum.GetValues()[1..].SkipLast(1) + .Select(x => (GameMode: x, Color: Main.RoleColors.GetValueOrDefault(CustomRoleSelector.GameModeRoles.TryGetValue(x, out CustomRoles role) ? role : x == CustomGameMode.HideAndSeek ? CustomRoles.Hider : CustomRoles.Witness, "#000000"))) .Select(x => $"<{x.Color}>{GetString($"{x.GameMode}")}\n{GetString($"ModeDescribe.{x.GameMode}").Split("\n\n")[0]}")); Utils.SendMessage(info, player.PlayerId, GetString("GameModeListTitle")); @@ -468,7 +468,7 @@ internal static class ChatCommands return; } - var jailor = Main.PlayerStates[player.PlayerId].Role as Jailor ?? Main.PlayerStates.Select(x => x.Value.Role as Jailor).FirstOrDefault(x => x != null); + Jailor jailor = Main.PlayerStates[player.PlayerId].Role as Jailor ?? Main.PlayerStates.Select(x => x.Value.Role as Jailor).FirstOrDefault(x => x != null); if (jailor == null) return; bool amJailor = Jailor.PlayerIdList.Contains(player.PlayerId); @@ -495,7 +495,7 @@ internal static class ChatCommands StringBuilder sb = new(""); - var rot = Enum.GetValues() + Dictionary rot = Enum.GetValues() .Without(RoleOptionType.Coven_Miscellaneous) .GroupBy(x => x.ToString().Split('_')[0]) .ToDictionary(x => Enum.Parse(x.Key), x => x.ToArray()); @@ -509,7 +509,7 @@ internal static class ChatCommands int factionMin; int factionMax; - if (Options.FactionMinMaxSettings.TryGetValue(team, out var factionLimits)) + if (Options.FactionMinMaxSettings.TryGetValue(team, out (OptionItem MinSetting, OptionItem MaxSetting) factionLimits)) { factionMin = factionLimits.MinSetting.GetInt(); factionMax = factionLimits.MaxSetting.GetInt(); @@ -536,11 +536,11 @@ internal static class ChatCommands sb.Append("\n\n"); } - if (rot.TryGetValue(team, out var subCategories)) + if (rot.TryGetValue(team, out RoleOptionType[] subCategories)) { - foreach (var subCategory in subCategories) + foreach (RoleOptionType subCategory in subCategories) { - if (Options.RoleSubCategoryLimits.TryGetValue(subCategory, out var limits) && (team == Team.Neutral || limits[0].GetBool())) + if (Options.RoleSubCategoryLimits.TryGetValue(subCategory, out OptionItem[] limits) && (team == Team.Neutral || limits[0].GetBool())) { int min = limits[1].GetInt(); int max = limits[2].GetInt(); @@ -573,7 +573,7 @@ internal static class ChatCommands } } - Utils.SendMessage("\n", player.PlayerId, title: sb.ToString().Trim() + ""); + Utils.SendMessage("\n", player.PlayerId, sb.ToString().Trim() + ""); } private static void AnagramCommand(PlayerControl player, string text, string[] args) @@ -681,18 +681,18 @@ internal static class ChatCommands return; } - var guess = args[1].ToLower(); + string guess = args[1].ToLower(); guess = char.ToUpper(guess[0]) + guess[1..]; - var deadPlayer = NoteKiller.RealNames.GetKeyByValue(guess); + byte deadPlayer = NoteKiller.RealNames.GetKeyByValue(guess); - if (deadPlayer == 0 && (!NoteKiller.RealNames.TryGetValue(0, out var name) || name != guess)) + if (deadPlayer == 0 && (!NoteKiller.RealNames.TryGetValue(0, out string name) || name != guess)) { NoteKiller.CanGuess = false; Utils.SendMessage(GetString("DeathNoteCommand.WrongName"), player.PlayerId); return; } - var pc = deadPlayer.GetPlayer(); + PlayerControl pc = deadPlayer.GetPlayer(); if (pc == null || !pc.IsAlive()) { @@ -701,7 +701,7 @@ internal static class ChatCommands return; } - var state = Main.PlayerStates[pc.PlayerId]; + PlayerState state = Main.PlayerStates[pc.PlayerId]; state.deathReason = PlayerState.DeathReason.Kill; state.RealKiller.ID = player.PlayerId; state.SetDead(); @@ -729,8 +729,8 @@ internal static class ChatCommands Achievements.Type[] allAchievements = Enum.GetValues(); Achievements.Type[] union = Achievements.CompletedAchievements.Union(Achievements.WaitingAchievements).ToArray(); - string completedAchievements = $"{union.Join(ToAchievementString, "\n")}"; - string incompleteAchievements = $"{allAchievements.Except(union).Join(ToAchievementString, "\n")}"; + var completedAchievements = $"{union.Join(ToAchievementString, "\n")}"; + var incompleteAchievements = $"{allAchievements.Except(union).Join(ToAchievementString, "\n")}"; Utils.SendMessage(incompleteAchievements, player.PlayerId, GetString("IncompleteAchievementsTitle")); Utils.SendMessage(completedAchievements, player.PlayerId, GetString("CompletedAchievementsTitle") + $" <#00a5ff>(<#00ffa5>{union.Length}/{allAchievements.Length})"); @@ -841,7 +841,7 @@ internal static class ChatCommands IEnumerator RepeatedlySendMessage() { - for (int index = 0; index < 3; index++) + for (var index = 0; index < 3; index++) { foreach ((byte id, List roles) in DraftRoles) { @@ -1616,11 +1616,11 @@ internal static class ChatCommands if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) ChatManager.SendPreviousMessagesToAll(); - var tg = Utils.GetPlayerById(vl2.Target); - var msg = text[6..]; + PlayerControl tg = Utils.GetPlayerById(vl2.Target); + string msg = text[6..]; LateTask.New(() => tg?.RpcSendChat(msg), 0.2f, log: false); ChatManager.AddChatHistory(tg, msg); - + player.RpcRemoveAbilityUse(); } @@ -1721,8 +1721,8 @@ internal static class ChatCommands if (player.PlayerId != PlayerControl.LocalPlayer.PlayerId) ChatManager.SendPreviousMessagesToAll(); - var votedPlayer = voteId.GetPlayer(); - if (Main.PlayerStates.TryGetValue(player.PlayerId, out var state) && votedPlayer != null && state.Role.OnVote(player, votedPlayer)) return; + PlayerControl votedPlayer = voteId.GetPlayer(); + if (Main.PlayerStates.TryGetValue(player.PlayerId, out PlayerState state) && votedPlayer != null && state.Role.OnVote(player, votedPlayer)) return; if (!player.IsHost()) MeetingHud.Instance.CastVote(player.PlayerId, voteId); @@ -3167,7 +3167,7 @@ internal static class ChatUpdatePatch player.SetName(name); } - var writer = sender ?? CustomRpcSender.Create("MessagesToSend", SendOption.Reliable); + CustomRpcSender writer = sender ?? CustomRpcSender.Create("MessagesToSend", SendOption.Reliable); writer.StartMessage(clientId); writer.StartRpc(player.NetId, (byte)RpcCalls.SetName) @@ -3190,9 +3190,12 @@ internal static class ChatUpdatePatch } [HarmonyPatch(typeof(FreeChatInputField), nameof(FreeChatInputField.Awake))] -static class FreeChatFieldAwakePatch +internal static class FreeChatFieldAwakePatch { - public static void Postfix(FreeChatInputField __instance) => UpdateCharCountPatch.Postfix(__instance); + public static void Postfix(FreeChatInputField __instance) + { + UpdateCharCountPatch.Postfix(__instance); + } } [HarmonyPatch(typeof(FreeChatInputField), nameof(FreeChatInputField.UpdateCharCount))] diff --git a/Patches/ChatControlPatch.cs b/Patches/ChatControlPatch.cs index f793021f3..06172fdfc 100644 --- a/Patches/ChatControlPatch.cs +++ b/Patches/ChatControlPatch.cs @@ -6,6 +6,7 @@ using EHR.Coven; using EHR.Impostor; using EHR.Patches; using HarmonyLib; +using Hazel; using InnerNet; using UnityEngine; @@ -224,12 +225,12 @@ public static class ChatManager try { - var aapc = Main.AllAlivePlayerControls; + PlayerControl[] aapc = Main.AllAlivePlayerControls; if (aapc.Length == 0) return; - var filtered = ChatHistory.Where(a => Utils.GetPlayerById(Convert.ToByte(a.Split(':')[0].Trim())).IsAlive()).ToArray(); - var chat = FastDestroyableSingleton.Instance.Chat; - var writer = CustomRpcSender.Create("MessagesToSend", Hazel.SendOption.Reliable); + string[] filtered = ChatHistory.Where(a => Utils.GetPlayerById(Convert.ToByte(a.Split(':')[0].Trim())).IsAlive()).ToArray(); + ChatController chat = FastDestroyableSingleton.Instance.Chat; + var writer = CustomRpcSender.Create("MessagesToSend", SendOption.Reliable); for (int i = clear ? 0 : filtered.Length; i < 20; i++) { @@ -254,7 +255,7 @@ public static class ChatManager SendRPC(writer, senderPlayer, senderMessage); } } - + ChatUpdatePatch.SendLastMessages(writer); writer.SendMessage(); } @@ -274,23 +275,23 @@ public static class ChatManager public static void ClearChatForSpecificPlayer(PlayerControl target) { - var sender = Main.AllAlivePlayerControls.MinBy(x => x.PlayerId) ?? Main.AllPlayerControls.MinBy(x => x.PlayerId) ?? PlayerControl.LocalPlayer; + PlayerControl sender = Main.AllAlivePlayerControls.MinBy(x => x.PlayerId) ?? Main.AllPlayerControls.MinBy(x => x.PlayerId) ?? PlayerControl.LocalPlayer; if (sender == null) return; Logger.Info($"Desync Clear Chat for {target.GetNameWithRole()}", "ChatManager"); if (!target.IsLocalPlayer()) { - var clientId = target.GetClientId(); + int clientId = target.GetClientId(); if (clientId == -1) return; - var writer = CustomRpcSender.Create("MessagesToSend", Hazel.SendOption.Reliable); + var writer = CustomRpcSender.Create("MessagesToSend", SendOption.Reliable); Loop.Times(20, _ => SendRPC(writer, sender, Utils.EmptyMessage, clientId)); writer.SendMessage(); return; } - var chat = FastDestroyableSingleton.Instance.Chat; + ChatController chat = FastDestroyableSingleton.Instance.Chat; Loop.Times(20, _ => chat.AddChat(sender, Utils.EmptyMessage)); } } \ No newline at end of file diff --git a/Patches/CheckGameEndPatch.cs b/Patches/CheckGameEndPatch.cs index a562f580a..760b7cdde 100644 --- a/Patches/CheckGameEndPatch.cs +++ b/Patches/CheckGameEndPatch.cs @@ -304,8 +304,10 @@ internal static class GameEndChecker 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)); diff --git a/Patches/ClientOptionsPatch.cs b/Patches/ClientOptionsPatch.cs index 66935584c..79e3aac4b 100644 --- a/Patches/ClientOptionsPatch.cs +++ b/Patches/ClientOptionsPatch.cs @@ -60,7 +60,8 @@ public static class OptionsMenuBehaviourStartPatch } } - if (ShowFPS == null || ShowFPS.ToggleButton == null) { ShowFPS = ClientOptionItem.Create("ShowFPS", Main.ShowFps, __instance); } + if (ShowFPS == null || ShowFPS.ToggleButton == null) + ShowFPS = ClientOptionItem.Create("ShowFPS", Main.ShowFps, __instance); if (AutoStart == null || AutoStart.ToggleButton == null) { @@ -159,7 +160,8 @@ public static class OptionsMenuBehaviourStartPatch if (ShowPlayerInfoInLobby == null || ShowPlayerInfoInLobby.ToggleButton == null) ShowPlayerInfoInLobby = ClientOptionItem.Create("ShowPlayerInfoInLobby", Main.ShowPlayerInfoInLobby, __instance); - if (LobbyMusic == null || LobbyMusic.ToggleButton == null) { LobbyMusic = ClientOptionItem.Create("LobbyMusic", Main.LobbyMusic, __instance); } + if (LobbyMusic == null || LobbyMusic.ToggleButton == null) + LobbyMusic = ClientOptionItem.Create("LobbyMusic", Main.LobbyMusic, __instance); if (EnableCommandHelper == null || EnableCommandHelper.ToggleButton == null) EnableCommandHelper = ClientOptionItem.Create("EnableCommandHelper", Main.EnableCommandHelper, __instance); diff --git a/Patches/ClientPatch.cs b/Patches/ClientPatch.cs index cc9ca4d12..5802272f5 100644 --- a/Patches/ClientPatch.cs +++ b/Patches/ClientPatch.cs @@ -89,7 +89,7 @@ internal static class BanMenuSetVisiblePatch { if (!AmongUsClient.Instance.AmHost) return true; - show &= PlayerControl.LocalPlayer && (PlayerControl.LocalPlayer.Data != null); + show &= PlayerControl.LocalPlayer && PlayerControl.LocalPlayer.Data != null; __instance.BanButton.gameObject.SetActive(AmongUsClient.Instance.CanBan()); __instance.KickButton.gameObject.SetActive(AmongUsClient.Instance.CanKick()); __instance.MenuButton.gameObject.SetActive(show); @@ -154,7 +154,7 @@ public static class InnerNetClientPatch [HarmonyPrefix] public static bool SendInitialDataPrefix(InnerNetClient __instance, int clientId) { - if (!Constants.IsVersionModded() || (__instance.NetworkMode != NetworkModes.OnlineGame)) return true; + if (!Constants.IsVersionModded() || __instance.NetworkMode != NetworkModes.OnlineGame) return true; MessageWriter messageWriter = MessageWriter.Get(SendOption.Reliable); messageWriter.StartMessage(6); messageWriter.Write(__instance.GameId); @@ -180,7 +180,7 @@ public static class InnerNetClientPatch InnerNetObject innerNetObject = __instance.allObjects[i]; // False error - if (innerNetObject && ((innerNetObject.OwnerId != -4) || __instance.AmModdedHost) && hashSet.Add(innerNetObject.gameObject)) + if (innerNetObject && (innerNetObject.OwnerId != -4 || __instance.AmModdedHost) && hashSet.Add(innerNetObject.gameObject)) { var gameManager = innerNetObject as GameManager; @@ -203,7 +203,7 @@ public static class InnerNetClientPatch [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; __result = false; List obj = __instance.allObjects; @@ -213,7 +213,7 @@ public static class InnerNetClientPatch { InnerNetObject innerNetObject = __instance.allObjects[i]; // False error - if (innerNetObject && innerNetObject is not NetworkedPlayerInfo && innerNetObject.IsDirty && (innerNetObject.AmOwner || ((innerNetObject.OwnerId == -2) && __instance.AmHost))) + 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); @@ -259,7 +259,7 @@ public static class InnerNetClientPatch [HarmonyPostfix] public static void Spawn_Postfix(InnerNetClient __instance, InnerNetObject netObjParent, int ownerId = -2, SpawnFlags flags = SpawnFlags.None) { - if (!Constants.IsVersionModded() || (__instance.NetworkMode != NetworkModes.OnlineGame)) return; + if (!Constants.IsVersionModded() || __instance.NetworkMode != NetworkModes.OnlineGame) return; if (__instance.AmHost) { @@ -268,11 +268,11 @@ public static class InnerNetClientPatch case NetworkedPlayerInfo playerinfo: LateTask.New(() => { - if ((playerinfo != null) && AmongUsClient.Instance.AmConnected) + if (playerinfo != null && AmongUsClient.Instance.AmConnected) { ClientData client = AmongUsClient.Instance.GetClient(playerinfo.ClientId); - if ((client != null) && !client.IsDisconnected()) + if (client != null && !client.IsDisconnected()) { if (playerinfo.IsIncomplete) { @@ -288,13 +288,13 @@ public static class InnerNetClientPatch case PlayerControl player: LateTask.New(() => { - if ((player != null) && !player.notRealPlayer && !player.isDummy && AmongUsClient.Instance.AmConnected) + if (player != null && !player.notRealPlayer && !player.isDummy && AmongUsClient.Instance.AmConnected) { ClientData client = AmongUsClient.Instance.GetClient(player.OwnerId); - if ((client != null) && !client.IsDisconnected()) + if (client != null && !client.IsDisconnected()) { - if ((player.Data == null) || player.Data.IsIncomplete) + if (player.Data == null || player.Data.IsIncomplete) { Logger.Info($"Disconnecting Client [{client.Id}]{client.PlayerName} {client.FriendCode} for playercontrol timeout", "DelayedNetworkedData"); AmongUsClient.Instance.SendLateRejection(client.Id, DisconnectReasons.ClientTimeout); @@ -316,8 +316,8 @@ public static class InnerNetClientPatch [HarmonyPostfix] public static void FixedUpdatePostfix(InnerNetClient __instance) { - if (!Constants.IsVersionModded() || (__instance.NetworkMode != NetworkModes.OnlineGame)) return; - if (!__instance.AmHost || (__instance.Streams == null)) return; + if (!Constants.IsVersionModded() || __instance.NetworkMode != NetworkModes.OnlineGame) return; + if (!__instance.AmHost || __instance.Streams == null) return; if (Timer == 0) { @@ -374,6 +374,7 @@ internal static class DirtyAllDataPatch internal static class NetworkedPlayerInfoSerializePatch { public static int IgnorePatchTimes; + public static bool Prefix(NetworkedPlayerInfo __instance, MessageWriter writer, bool initialState, ref bool __result) { if (IgnorePatchTimes > 0) @@ -396,7 +397,7 @@ internal static class NetworkedPlayerInfoSerializePatch NetworkedPlayerInfo.PlayerOutfit playerOutfit = new(); Main.AllClientRealNames.TryGetValue(__instance.ClientId, out string name); - if ((CheckForEndVotingPatch.TempExiledPlayer != null) && (CheckForEndVotingPatch.TempExiledPlayer.ClientId == __instance.ClientId)) + if (CheckForEndVotingPatch.TempExiledPlayer != null && CheckForEndVotingPatch.TempExiledPlayer.ClientId == __instance.ClientId) name = CheckForEndVotingPatch.EjectionText; playerOutfit.Set(name ?? " ", oldOutfit.ColorId, oldOutfit.HatId, oldOutfit.SkinId, oldOutfit.VisorId, oldOutfit.PetId, oldOutfit.NamePlateId); @@ -460,7 +461,7 @@ internal static class AuthTimeoutPatch public static void EnableUdpMatchmakingPrefix(AmongUsClient._CoJoinOnlinePublicGame_d__1 __instance) { // Skip to state 1, which just calls CoJoinOnlineGameDirect - if ((__instance.__1__state == 0) && !ServerManager.Instance.IsHttp) + if (__instance.__1__state == 0 && !ServerManager.Instance.IsHttp) { __instance.__1__state = 1; diff --git a/Patches/ControlPatch.cs b/Patches/ControlPatch.cs index 0ff23de0d..2b4c54a09 100644 --- a/Patches/ControlPatch.cs +++ b/Patches/ControlPatch.cs @@ -27,8 +27,10 @@ internal static class ControllerManagerUpdatePatch if (Input.GetKeyDown(KeyCode.Tab)) OptionShower.Next(); 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(); diff --git a/Patches/CredentialsPatch.cs b/Patches/CredentialsPatch.cs index 07caa87ba..24284ca50 100644 --- a/Patches/CredentialsPatch.cs +++ b/Patches/CredentialsPatch.cs @@ -17,7 +17,7 @@ internal static class PingTrackerUpdatePatch public static PingTracker Instance; private static readonly StringBuilder Sb = new(); private static long LastUpdate; - private static List LastFPS = []; + private static readonly List LastFPS = []; private static int Delay => GameStates.IsInTask ? 8 : 1; private static void Postfix(PingTracker __instance) @@ -58,7 +58,7 @@ internal static class PingTrackerUpdatePatch if (Main.ShowFps.Value) { - var fps = LastFPS.Average(); + float fps = LastFPS.Average(); Color fpscolor = fps switch { @@ -68,7 +68,7 @@ internal static class PingTrackerUpdatePatch }; AppendSeparator(); - Sb.Append($"{Utils.ColorString(fpscolor, Utils.ColorString(Color.cyan, GetString("FPSGame")) + ((int)fps))}"); + Sb.Append($"{Utils.ColorString(fpscolor, Utils.ColorString(Color.cyan, GetString("FPSGame")) + (int)fps)}"); } if (GameStates.InGame) Sb.Append("\r\n."); @@ -109,11 +109,11 @@ public static class UpdateFriendCodeUIPatch public static void Prefix() { - string credentialsText = $"Gurge44 \u00a9 2025"; + var credentialsText = $"Gurge44 \u00a9 2025"; credentialsText += "\t\t\t"; credentialsText += $"{Main.ModName} - {Main.PluginVersion}"; - var friendCode = GameObject.Find("FriendCode"); + GameObject friendCode = GameObject.Find("FriendCode"); if (friendCode != null && VersionShower == null) { @@ -127,7 +127,7 @@ public static class UpdateFriendCodeUIPatch tmp.SetText(credentialsText); } - var newRequest = GameObject.Find("NewRequest"); + GameObject newRequest = GameObject.Find("NewRequest"); if (newRequest != null) { @@ -135,7 +135,7 @@ public static class UpdateFriendCodeUIPatch newRequest.transform.localScale = new(0.8f, 1f, 1f); } - var friendsButton = GameObject.Find("FriendsButton"); + GameObject friendsButton = GameObject.Find("FriendsButton"); if (friendsButton != null) { @@ -146,18 +146,19 @@ public static class UpdateFriendCodeUIPatch } [HarmonyPatch(typeof(FriendsListUI), nameof(FriendsListUI.Open))] -static class FriendsListUIOpenPatch +internal static class FriendsListUIOpenPatch { public static bool Prefix(FriendsListUI __instance) { try { - if (__instance.gameObject.activeSelf || __instance.currentSceneName == "") { __instance.Close(); } + if (__instance.gameObject.activeSelf || __instance.currentSceneName == "") + __instance.Close(); else { FriendsListBar[] componentsInChildren = __instance.GetComponentsInChildren(true); - for (int index = 0; index < componentsInChildren.Length; ++index) + for (var index = 0; index < componentsInChildren.Length; ++index) { if (componentsInChildren[index] != null) Object.Destroy(componentsInChildren[index].gameObject); @@ -167,7 +168,7 @@ static class FriendsListUIOpenPatch __instance.currentSceneName = activeScene.name; __instance.UpdateFriendCodeUI(); - if (DestroyableSingleton.InstanceExists && FastDestroyableSingleton.Instance != null && FastDestroyableSingleton.Instance.Chat != null && FastDestroyableSingleton.Instance.Chat.IsOpenOrOpening || ShipStatus.Instance != null) + if ((DestroyableSingleton.InstanceExists && FastDestroyableSingleton.Instance != null && FastDestroyableSingleton.Instance.Chat != null && FastDestroyableSingleton.Instance.Chat.IsOpenOrOpening) || ShipStatus.Instance != null) return false; __instance.friendBars = new(); @@ -349,10 +350,7 @@ internal static class TitleLogoPatch return; - static void ResetParent(GameObject obj) - { - obj.transform.SetParent(LeftPanel.transform.parent); - } + static void ResetParent(GameObject obj) => obj.transform.SetParent(LeftPanel.transform.parent); void FormatButtonColor(PassiveButton button, Color inActiveColor, Color activeColor, Color inActiveTextColor, Color activeTextColor) { diff --git a/Patches/Crowded.cs b/Patches/Crowded.cs index d1028319f..8a81e15fb 100644 --- a/Patches/Crowded.cs +++ b/Patches/Crowded.cs @@ -31,7 +31,8 @@ internal static class Crowded { if (GameOptionsManager.Instance.GameHostOptions != null) { - if (GameOptionsManager.Instance.GameHostOptions.MaxPlayers > 15) { GameOptionsManager.Instance.GameHostOptions.SetInt(Int32OptionNames.MaxPlayers, 15); } + if (GameOptionsManager.Instance.GameHostOptions.MaxPlayers > 15) + GameOptionsManager.Instance.GameHostOptions.SetInt(Int32OptionNames.MaxPlayers, 15); } } } @@ -54,7 +55,7 @@ internal static class Crowded { var playerButton = __instance.MaxPlayerButtons[i]; var tmp = playerButton.GetComponentInChildren(); - var newValue = Mathf.Max(byte.Parse(tmp.text) - 10, byte.Parse(playerButton.name) - 2); + int newValue = Mathf.Max(byte.Parse(tmp.text) - 10, byte.Parse(playerButton.name) - 2); tmp.text = newValue.ToString(); } @@ -62,7 +63,7 @@ internal static class Crowded })); Object.Destroy(firstButtonRenderer); - var lastButtonRenderer = __instance.MaxPlayerButtons[^1]; + Il2CppSystem.Object lastButtonRenderer = __instance.MaxPlayerButtons[^1]; lastButtonRenderer.GetComponentInChildren().text = "+"; // False error lastButtonRenderer.enabled = false; // False error var lastButtonButton = lastButtonRenderer.GetComponent(); // False error @@ -75,7 +76,7 @@ internal static class Crowded var playerButton = __instance.MaxPlayerButtons[i]; var tmp = playerButton.GetComponentInChildren(); - var newValue = Mathf.Min(byte.Parse(tmp.text) + 10, + int newValue = Mathf.Min(byte.Parse(tmp.text) + 10, MaxPlayers - 14 + byte.Parse(playerButton.name)); tmp.text = newValue.ToString(); @@ -94,34 +95,35 @@ internal static class Crowded playerButton.OnClick.AddListener((Action)(() => { - var maxPlayers = byte.Parse(text.text); - var maxImp = Mathf.Min(__instance.GetTargetOptions().NumImpostors, maxPlayers / 2); + byte maxPlayers = byte.Parse(text.text); + int maxImp = Mathf.Min(__instance.GetTargetOptions().NumImpostors, maxPlayers / 2); __instance.GetTargetOptions().SetInt(Int32OptionNames.NumImpostors, maxImp); __instance.ImpostorButtons[1].TextMesh.text = maxImp.ToString(); __instance.SetMaxPlayersButtons(maxPlayers); })); } - foreach (var button in __instance.MaxPlayerButtons) { button.enabled = button.GetComponentInChildren().text == __instance.GetTargetOptions().MaxPlayers.ToString(); } + foreach (SpriteRenderer button in __instance.MaxPlayerButtons) + button.enabled = button.GetComponentInChildren().text == __instance.GetTargetOptions().MaxPlayers.ToString(); } { - var secondButton = __instance.ImpostorButtons[1]; + ImpostorsOptionButton secondButton = __instance.ImpostorButtons[1]; secondButton.SpriteRenderer.enabled = false; Object.Destroy(secondButton.transform.FindChild("ConsoleHighlight").gameObject); Object.Destroy(secondButton.PassiveButton); Object.Destroy(secondButton.BoxCollider); - var secondButtonText = secondButton.TextMesh; + TextMeshPro secondButtonText = secondButton.TextMesh; secondButtonText.text = __instance.GetTargetOptions().NumImpostors.ToString(); - var firstButton = __instance.ImpostorButtons[0]; + ImpostorsOptionButton firstButton = __instance.ImpostorButtons[0]; firstButton.SpriteRenderer.enabled = false; firstButton.TextMesh.text = "-"; - var firstPassiveButton = firstButton.PassiveButton; + PassiveButton firstPassiveButton = firstButton.PassiveButton; firstPassiveButton.OnClick.RemoveAllListeners(); firstPassiveButton.OnClick.AddListener((Action)(() => { - var newVal = Mathf.Clamp( + int newVal = Mathf.Clamp( byte.Parse(secondButtonText.text) - 1, 1, __instance.GetTargetOptions().MaxPlayers / 2 @@ -131,15 +133,15 @@ internal static class Crowded secondButtonText.text = newVal.ToString(); })); - var thirdButton = __instance.ImpostorButtons[2]; + ImpostorsOptionButton thirdButton = __instance.ImpostorButtons[2]; thirdButton.SpriteRenderer.enabled = false; thirdButton.TextMesh.text = "+"; - var thirdPassiveButton = thirdButton.PassiveButton; + PassiveButton thirdPassiveButton = thirdButton.PassiveButton; thirdPassiveButton.OnClick.RemoveAllListeners(); thirdPassiveButton.OnClick.AddListener((Action)(() => { - var newVal = Mathf.Clamp( + int newVal = Mathf.Clamp( byte.Parse(secondButtonText.text) + 1, 1, __instance.GetTargetOptions().MaxPlayers / 2 @@ -173,7 +175,7 @@ internal static class Crowded var playerButton = Instance.MaxPlayerButtons[i]; var tmp = playerButton.GetComponentInChildren(); - var newValue = Mathf.Min(byte.Parse(tmp.text) + 10, + int newValue = Mathf.Min(byte.Parse(tmp.text) + 10, MaxPlayers - 14 + byte.Parse(playerButton.name)); tmp.text = newValue.ToString(); @@ -193,14 +195,13 @@ internal static class Crowded { if (__instance.mode != SettingsMode.Host) return true; - if (__instance.CrewArea) { __instance.CrewArea.SetCrewSize(opts.MaxPlayers, opts.NumImpostors); } + if (__instance.CrewArea) + __instance.CrewArea.SetCrewSize(opts.MaxPlayers, opts.NumImpostors); var selectedAsString = opts.MaxPlayers.ToString(); for (var i = 1; i < __instance.MaxPlayerButtons.Count - 1; i++) - { __instance.MaxPlayerButtons[i].enabled = __instance.MaxPlayerButtons[i].GetComponentInChildren().text == selectedAsString; // False errors - } return false; } @@ -237,7 +238,8 @@ internal static class Crowded [SuppressMessage("ReSharper", "UnusedMember.Global")] public static bool Prefix(CreateOptionsPicker __instance, int maxPlayers) { - if (DestroyableSingleton.InstanceExists || __instance.mode != SettingsMode.Host) { return true; } + if (DestroyableSingleton.InstanceExists || __instance.mode != SettingsMode.Host) + return true; IGameOptions targetOptions = __instance.GetTargetOptions(); targetOptions.SetInt(Int32OptionNames.MaxPlayers, maxPlayers); @@ -390,7 +392,11 @@ public class AbstractPagingBehaviour(IntPtr ptr) : MonoBehaviour(ptr) } protected virtual int MaxPageIndex => throw new("MaxPageIndex must be overridden"); - public virtual void Start() => OnPageChanged(); + + public virtual void Start() + { + OnPageChanged(); + } public virtual void Update() { @@ -402,15 +408,18 @@ public class AbstractPagingBehaviour(IntPtr ptr) : MonoBehaviour(ptr) Cycle(true); } - public virtual void OnPageChanged() => throw new("OnPageChanged must be overridden"); + public virtual void OnPageChanged() + { + throw new("OnPageChanged must be overridden"); + } /// - /// Loops around if you go over the limits.
- /// Attempting to go up a page while on the first page will take you to the last page and vice versa. + /// Loops around if you go over the limits.
+ /// Attempting to go up a page while on the first page will take you to the last page and vice versa. ///
public virtual void Cycle(bool increment) { - var change = increment ? 1 : -1; + int change = increment ? 1 : -1; PageIndex = Mathf.Clamp(PageIndex + change, 0, MaxPageIndex); } } @@ -421,7 +430,11 @@ public class MeetingHudPagingBehaviour(IntPtr ptr) : AbstractPagingBehaviour(ptr [HideFromIl2Cpp] private IEnumerable Targets => meetingHud.playerStates.OrderBy(p => p.AmDead); protected override int MaxPageIndex => (Targets.Count() - 1) / MaxPerPage; - public override void Start() => OnPageChanged(); + + public override void Start() + { + OnPageChanged(); + } public override void Update() { @@ -435,15 +448,15 @@ public class MeetingHudPagingBehaviour(IntPtr ptr) : AbstractPagingBehaviour(ptr { var i = 0; - foreach (var button in Targets) + foreach (PlayerVoteArea button in Targets) { if (i >= PageIndex * MaxPerPage && i < (PageIndex + 1) * MaxPerPage) { button.gameObject.SetActive(true); - var relativeIndex = i % MaxPerPage; - var row = relativeIndex / 3; - var col = relativeIndex % 3; - var buttonTransform = button.transform; + int relativeIndex = i % MaxPerPage; + int row = relativeIndex / 3; + int col = relativeIndex % 3; + Transform buttonTransform = button.transform; buttonTransform.localPosition = meetingHud.VoteOrigin + new Vector3( @@ -483,20 +496,20 @@ public class ShapeShifterPagingBehaviour(IntPtr ptr) : AbstractPagingBehaviour(p PageText.text = $"({PageIndex + 1}/{MaxPageIndex + 1})"; var i = 0; - foreach (var panel in Targets) + foreach (ShapeshifterPanel panel in Targets) { if (i >= PageIndex * MaxPerPage && i < (PageIndex + 1) * MaxPerPage) { panel.gameObject.SetActive(true); - var relativeIndex = i % MaxPerPage; - var row = relativeIndex / 3; - var col = relativeIndex % 3; - var buttonTransform = panel.transform; + int relativeIndex = i % MaxPerPage; + int row = relativeIndex / 3; + int col = relativeIndex % 3; + Transform buttonTransform = panel.transform; buttonTransform.localPosition = new( - shapeshifterMinigame.XStart + shapeshifterMinigame.XOffset * col, - shapeshifterMinigame.YStart + shapeshifterMinigame.YOffset * row, + shapeshifterMinigame.XStart + (shapeshifterMinigame.XOffset * col), + shapeshifterMinigame.YStart + (shapeshifterMinigame.YOffset * row), buttonTransform.localPosition.z ); } @@ -534,20 +547,20 @@ public class VitalsPagingBehaviour(IntPtr ptr) : AbstractPagingBehaviour(ptr) PageText.text = $"({PageIndex + 1}/{MaxPageIndex + 1})"; var i = 0; - foreach (var panel in Targets) + foreach (VitalsPanel panel in Targets) { if (i >= PageIndex * MaxPerPage && i < (PageIndex + 1) * MaxPerPage) { panel.gameObject.SetActive(true); - var relativeIndex = i % MaxPerPage; - var row = relativeIndex / 3; - var col = relativeIndex % 3; - var panelTransform = panel.transform; + int relativeIndex = i % MaxPerPage; + int row = relativeIndex / 3; + int col = relativeIndex % 3; + Transform panelTransform = panel.transform; panelTransform.localPosition = new( - vitalsMinigame.XStart + vitalsMinigame.XOffset * col, - vitalsMinigame.YStart + vitalsMinigame.YOffset * row, + vitalsMinigame.XStart + (vitalsMinigame.XOffset * col), + vitalsMinigame.YStart + (vitalsMinigame.YOffset * row), panelTransform.localPosition.z ); } diff --git a/Patches/DleksPatch.cs b/Patches/DleksPatch.cs index 4ee845b5a..fdc9ec745 100644 --- a/Patches/DleksPatch.cs +++ b/Patches/DleksPatch.cs @@ -33,10 +33,7 @@ internal static class AllMapIconsPatch dleksIcon.NameImage = Utils.LoadSprite("EHR.Resources.Images.DleksBanner-Wordart.png", 100f); __instance.AllMapIcons.Add(dleksIcon); } - catch (Exception e) - { - Utils.ThrowException(e); - } + catch (Exception e) { Utils.ThrowException(e); } } } diff --git a/Patches/EndGameManagerPatch.cs b/Patches/EndGameManagerPatch.cs index 70fa75f92..d74576220 100644 --- a/Patches/EndGameManagerPatch.cs +++ b/Patches/EndGameManagerPatch.cs @@ -67,7 +67,7 @@ public static class EndGameManagerPatch } [HarmonyPatch(typeof(EndGameNavigation), nameof(EndGameNavigation.NextGame))] -static class EndGameNavigationNextGamePatch +internal static class EndGameNavigationNextGamePatch { public static void Postfix() { diff --git a/Patches/ExilePatch.cs b/Patches/ExilePatch.cs index 5b022a51f..c75f128e4 100644 --- a/Patches/ExilePatch.cs +++ b/Patches/ExilePatch.cs @@ -100,7 +100,7 @@ internal static class ExileControllerWrapUpPatch if (Options.RandomSpawn.GetBool() && Main.CurrentMap != MapNames.Airship) { - RandomSpawn.SpawnMap map = RandomSpawn.SpawnMap.GetSpawnMap(); + var map = RandomSpawn.SpawnMap.GetSpawnMap(); Main.AllAlivePlayerControls.Do(map.RandomTeleport); } @@ -108,12 +108,12 @@ internal static class ExileControllerWrapUpPatch Utils.CountAlivePlayers(true); if (exiled == null) return; - var id = exiled.PlayerId; + byte id = exiled.PlayerId; LateTask.New(() => { PlayerControl player = id.GetPlayer(); - if (player != null) Utils.AfterPlayerDeathTasks(player, onMeeting: true); + if (player != null) Utils.AfterPlayerDeathTasks(player, true); }, 2.5f, "AfterPlayerDeathTasks For Exiled Player"); } @@ -139,7 +139,7 @@ internal static class ExileControllerWrapUpPatch var sender = CustomRpcSender.Create("ExileControllerWrapUpPatch.WrapUpFinalizer", SendOption.Reliable); Main.AfterMeetingDeathPlayers.Do(x => sender.RpcExileV2(x.Key.GetPlayer())); - sender.SendMessage(dispose: Main.AfterMeetingDeathPlayers.Count == 0); + sender.SendMessage(Main.AfterMeetingDeathPlayers.Count == 0); Main.AfterMeetingDeathPlayers.Do(x => { @@ -156,7 +156,7 @@ internal static class ExileControllerWrapUpPatch Utils.AfterMeetingTasks(); Utils.SyncAllSettings(); Utils.CheckAndSetVentInteractions(); - Main.Instance.StartCoroutine(Utils.NotifyEveryoneAsync(speed: 5)); + Main.Instance.StartCoroutine(Utils.NotifyEveryoneAsync(5)); } }, 2f, "AntiBlackout Reset & AfterMeetingTasks"); } diff --git a/Patches/FixNotAllServersShowingPatch.cs b/Patches/FixNotAllServersShowingPatch.cs index 7652d21d7..c7b379ed8 100644 --- a/Patches/FixNotAllServersShowingPatch.cs +++ b/Patches/FixNotAllServersShowingPatch.cs @@ -14,10 +14,10 @@ public static class FixNotAllServersShowingPatch public static bool Prefix(ServerDropdown __instance) { if (SceneManager.GetActiveScene().name == "FindAGame") return true; - var bg = __instance.background; + SpriteRenderer bg = __instance.background; bg.size = new Vector2(4, 1); - var sm = FastDestroyableSingleton.Instance; - var tc = FastDestroyableSingleton.Instance; + ServerManager sm = FastDestroyableSingleton.Instance; + TranslationController tc = FastDestroyableSingleton.Instance; int totalCols = Mathf.Max(1, Mathf.CeilToInt(sm.AvailableRegions.Length / (float)5)); int rowLimit = Mathf.Min(sm.AvailableRegions.Length, 5); @@ -25,7 +25,7 @@ public static class FixNotAllServersShowingPatch { IRegionInfo ri = sm.AvailableRegions[index]; var b = __instance.ButtonPool.Get(); - b.transform.localPosition = new Vector3(((index / 5) - (totalCols - 1) / 2f) * 3.15f, __instance.y_posButton - 0.5f * (index % 5), -1f); + b.transform.localPosition = new Vector3(((index / 5) - ((totalCols - 1) / 2f)) * 3.15f, __instance.y_posButton - (0.5f * (index % 5)), -1f); b.Text.text = tc.GetStringWithDefault(ri.TranslateName, ri.Name, new Il2CppReferenceArray(0)); b.Text.ForceMeshUpdate(); b.Button.OnClick.RemoveAllListeners(); @@ -33,9 +33,9 @@ public static class FixNotAllServersShowingPatch __instance.controllerSelectable.Add(b.Button); } - float h = 1.2f + 0.5f * (rowLimit - 1); - float w = (totalCols > 1) ? (3.15f * (totalCols - 1) + bg.size.x) : bg.size.x; - bg.transform.localPosition = new Vector3(0f, __instance.initialYPos - (h - 1.2f) / 2f, 0f); + float h = 1.2f + (0.5f * (rowLimit - 1)); + float w = totalCols > 1 ? (3.15f * (totalCols - 1)) + bg.size.x : bg.size.x; + bg.transform.localPosition = new Vector3(0f, __instance.initialYPos - ((h - 1.2f) / 2f), 0f); bg.size = new Vector2(w, h); return false; } diff --git a/Patches/GameOptionsMenuPatch.cs b/Patches/GameOptionsMenuPatch.cs index 1e9c0557e..c114b08b4 100644 --- a/Patches/GameOptionsMenuPatch.cs +++ b/Patches/GameOptionsMenuPatch.cs @@ -413,15 +413,17 @@ public static class GameOptionsMenuPatch { UIReloadTS = Utils.TimeStamp; - var tab = ModGameOptionsMenu.TabIndex; + int tab = ModGameOptionsMenu.TabIndex; if (GameSettingMenu.Instance == null) return; GameSettingMenu.Instance.Close(); OptionsConsole optionsConsole = null; - foreach (var console in Object.FindObjectsOfType()) + + foreach (OptionsConsole console in Object.FindObjectsOfType()) { if (console.HostOnly) optionsConsole = console; } + if (optionsConsole == null) return; if (Camera.main != null) @@ -430,7 +432,8 @@ public static class GameOptionsMenuPatch gameObject.transform.localPosition = optionsConsole.CustomPosition; } - LateTask.New(() => { + LateTask.New(() => + { if (GameSettingMenu.Instance == null) return; GameSettingMenu.Instance.ChangeTab(tab, false); }, 0.01f); @@ -756,10 +759,7 @@ public static class StringOptionPatch return $" {string.Join('/', teams.Select(GetColoredShortTeamName))}"; - string GetColoredShortTeamName(Team t) - { - return Utils.ColorString(t.GetColor(), Translator.GetString($"ShortTeamName.{t}").ToUpper()); - } + string GetColoredShortTeamName(Team t) => Utils.ColorString(t.GetColor(), Translator.GetString($"ShortTeamName.{t}").ToUpper()); } [HarmonyPatch(nameof(StringOption.UpdateValue))] @@ -956,8 +956,10 @@ public class GameSettingMenuPatch } foreach (TabGroup tab in tabGroups) + { if (ModSettingsButtons.TryGetValue(tab, out PassiveButton button)) __instance.ControllerSelectable.Add(button); + } HiddenBySearch.Do(x => x.SetHidden(false)); HiddenBySearch.Clear(); @@ -1209,12 +1211,16 @@ public class GameSettingMenuPatch TabGroup[] tabGroups = Enum.GetValues(); foreach (TabGroup tab in tabGroups) + { if (ModSettingsTabs.TryGetValue(tab, out settingsTab) && settingsTab != null) settingsTab.gameObject.SetActive(false); + } foreach (TabGroup tab in tabGroups) + { if (ModSettingsButtons.TryGetValue(tab, out button) && button != null) button.SelectButton(false); + } } if (tabNum < 3) return true; @@ -1343,4 +1349,4 @@ public class RpcSyncSettingsPatch { OptionItem.SyncAllOptions(); } -} +} \ No newline at end of file diff --git a/Patches/GameStartManagerPatch.cs b/Patches/GameStartManagerPatch.cs index 69c40c197..1e6c89689 100644 --- a/Patches/GameStartManagerPatch.cs +++ b/Patches/GameStartManagerPatch.cs @@ -307,7 +307,7 @@ public static class GameStartManagerPatch var canStartGame = true; var mismatchedClientName = string.Empty; - string warningMessage = ""; + var warningMessage = ""; if (AmongUsClient.Instance.AmHost) { @@ -347,7 +347,8 @@ public static class GameStartManagerPatch } } - if (warningMessage == "") { warningText.gameObject.SetActive(false); } + if (warningMessage == "") + warningText.gameObject.SetActive(false); else { warningText.text = warningMessage; diff --git a/Patches/HudPatch.cs b/Patches/HudPatch.cs index 8b61d6af9..4527c3bc9 100644 --- a/Patches/HudPatch.cs +++ b/Patches/HudPatch.cs @@ -26,7 +26,10 @@ internal static class HudManagerPatch public static string AchievementUnlockedText = string.Empty; - public static void ClearLowerInfoText() => LowerInfoText.text = string.Empty; + public static void ClearLowerInfoText() + { + LowerInfoText.text = string.Empty; + } public static bool Prefix(HudManager __instance) { @@ -50,12 +53,16 @@ internal static class HudManagerPatch 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; @@ -223,7 +230,7 @@ internal static class HudManagerPatch case CustomRoles.CTFPlayer: __instance.AbilityButton?.OverrideText(GetString("CTF_ButtonText")); break; - case CustomRoles.RRPlayer when __instance.AbilityButton != null && RoomRush.VentLimit.TryGetValue(PlayerControl.LocalPlayer.PlayerId, out var ventLimit): + case CustomRoles.RRPlayer when __instance.AbilityButton != null && RoomRush.VentLimit.TryGetValue(PlayerControl.LocalPlayer.PlayerId, out int ventLimit): __instance.AbilityButton.SetUsesRemaining(ventLimit); break; } @@ -840,7 +847,7 @@ internal static class DialogueBoxShowPatch public static bool Prefix(DialogueBox __instance, [HarmonyArgument(0)] string dialogue) { __instance.target.text = dialogue; - + if (Minigame.Instance) Minigame.Instance.Close(); if (Minigame.Instance) Minigame.Instance.Close(); diff --git a/Patches/HudSpritePatch.cs b/Patches/HudSpritePatch.cs index 14eda9ca2..4987f4a15 100644 --- a/Patches/HudSpritePatch.cs +++ b/Patches/HudSpritePatch.cs @@ -515,4 +515,4 @@ public static class HudSpritePatch } } } -} +} \ No newline at end of file diff --git a/Patches/IntroPatch.cs b/Patches/IntroPatch.cs index c2baedda3..0a198f611 100644 --- a/Patches/IntroPatch.cs +++ b/Patches/IntroPatch.cs @@ -144,7 +144,7 @@ internal static class SetUpRoleTextPatch 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")); } @@ -219,7 +219,7 @@ internal static class SetUpRoleTextPatch sb.Append("------------Modded Settings------------\n"); string disabledRoleStr = GetString("Rate0"); - int i = 0; + var i = 0; foreach (OptionItem o in OptionItem.AllOptions) { @@ -306,7 +306,7 @@ internal static class BeginCrewmatePatch } } - if ((role == CustomRoles.LovingCrewmate) || PlayerControl.LocalPlayer.Is(CustomRoles.Lovers)) + if (role == CustomRoles.LovingCrewmate || PlayerControl.LocalPlayer.Is(CustomRoles.Lovers)) { teamToDisplay = new(); teamToDisplay.Add(PlayerControl.LocalPlayer); @@ -336,7 +336,7 @@ internal static class BeginCrewmatePatch foreach (PlayerControl pc in Main.AllPlayerControls) { - if (FreeForAll.PlayerTeams.TryGetValue(pc.PlayerId, out int team) && (team == ffaTeam)) + if (FreeForAll.PlayerTeams.TryGetValue(pc.PlayerId, out int team) && team == ffaTeam) teamToDisplay.Add(pc); } } @@ -358,91 +358,94 @@ internal static class BeginCrewmatePatch __instance.ImpostorText.gameObject.SetActive(true); __instance.ImpostorText.text = GetString("SubText.Bloodlust"); } - else switch (role) + else { - case CustomRoles.LovingCrewmate or CustomRoles.LovingImpostor: + switch (role) { - __instance.TeamTitle.color = __instance.BackgroundBar.material.color = Utils.GetRoleColor(role); - PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(role.GetRoleTypes()); - byte otherLoverId = Main.LoversPlayers.First(x => x.PlayerId != PlayerControl.LocalPlayer.PlayerId).PlayerId; - __instance.ImpostorText.gameObject.SetActive(true); - __instance.ImpostorText.text = string.Format(GetString($"SubText.{role}"), otherLoverId.ColoredPlayerName()); - break; - } - case CustomRoles.DoubleAgent: - { - __instance.TeamTitle.text = GetString("TeamImpostor"); - __instance.TeamTitle.color = __instance.BackgroundBar.material.color = new Color32(140, 255, 255, byte.MaxValue); - PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(RoleTypes.Shapeshifter); - __instance.ImpostorText.gameObject.SetActive(true); - __instance.ImpostorText.text = GetString("SubText.Crewmate"); - break; - } - default: - { - switch (role.GetCustomRoleTypes()) + case CustomRoles.LovingCrewmate or CustomRoles.LovingImpostor: { - case CustomRoleTypes.Impostor: - { - __instance.TeamTitle.text = GetString("TeamImpostor"); - __instance.TeamTitle.color = __instance.BackgroundBar.material.color = new Color32(255, 25, 25, byte.MaxValue); - PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(RoleTypes.Impostor); - __instance.ImpostorText.gameObject.SetActive(true); - __instance.ImpostorText.text = GetString("SubText.Impostor"); - break; - } - case CustomRoleTypes.Crewmate: - { - __instance.TeamTitle.text = GetString("TeamCrewmate"); - __instance.TeamTitle.color = __instance.BackgroundBar.material.color = new Color32(140, 255, 255, byte.MaxValue); - PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(RoleTypes.Crewmate); - __instance.ImpostorText.gameObject.SetActive(true); - __instance.ImpostorText.text = GetString("SubText.Crewmate"); - break; - } - case CustomRoleTypes.Neutral: - { - if (Options.UniqueNeutralRevealScreen.GetBool()) - { - __instance.TeamTitle.text = GetString($"{role}"); - __instance.TeamTitle.color = __instance.BackgroundBar.material.color = Utils.GetRoleColor(role); - PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(RoleTypes.Shapeshifter); - __instance.ImpostorText.gameObject.SetActive(true); - __instance.ImpostorText.text = GetString($"{role}Info"); - } - else - { - __instance.TeamTitle.text = GetString("TeamNeutral"); - __instance.TeamTitle.color = __instance.BackgroundBar.material.color = new Color32(255, 171, 27, byte.MaxValue); - PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(RoleTypes.Shapeshifter); - __instance.ImpostorText.gameObject.SetActive(true); - __instance.ImpostorText.text = GetString("SubText.Neutral"); - } - - break; - } - - case CustomRoleTypes.Coven: - { - __instance.TeamTitle.text = GetString("TeamCoven"); - __instance.TeamTitle.color = __instance.BackgroundBar.material.color = Team.Coven.GetColor(); - PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(RoleTypes.Phantom); - __instance.ImpostorText.gameObject.SetActive(true); - __instance.ImpostorText.text = GetString("SubText.Coven"); - break; - } - } - - if ((Main.LoversPlayers.Count == 2) && Main.LoversPlayers.Exists(x => x.IsLocalPlayer())) - { - __instance.TeamTitle.color = __instance.BackgroundBar.material.color = Utils.GetRoleColor(CustomRoles.Lovers); + __instance.TeamTitle.color = __instance.BackgroundBar.material.color = Utils.GetRoleColor(role); + PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(role.GetRoleTypes()); byte otherLoverId = Main.LoversPlayers.First(x => x.PlayerId != PlayerControl.LocalPlayer.PlayerId).PlayerId; __instance.ImpostorText.gameObject.SetActive(true); - __instance.ImpostorText.DestroyTranslator(); - __instance.ImpostorText.text = string.Format(GetString("SubText.LovingCrewmate"), otherLoverId.ColoredPlayerName()); + __instance.ImpostorText.text = string.Format(GetString($"SubText.{role}"), otherLoverId.ColoredPlayerName()); + break; } + case CustomRoles.DoubleAgent: + { + __instance.TeamTitle.text = GetString("TeamImpostor"); + __instance.TeamTitle.color = __instance.BackgroundBar.material.color = new Color32(140, 255, 255, byte.MaxValue); + PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(RoleTypes.Shapeshifter); + __instance.ImpostorText.gameObject.SetActive(true); + __instance.ImpostorText.text = GetString("SubText.Crewmate"); + break; + } + default: + { + switch (role.GetCustomRoleTypes()) + { + case CustomRoleTypes.Impostor: + { + __instance.TeamTitle.text = GetString("TeamImpostor"); + __instance.TeamTitle.color = __instance.BackgroundBar.material.color = new Color32(255, 25, 25, byte.MaxValue); + PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(RoleTypes.Impostor); + __instance.ImpostorText.gameObject.SetActive(true); + __instance.ImpostorText.text = GetString("SubText.Impostor"); + break; + } + case CustomRoleTypes.Crewmate: + { + __instance.TeamTitle.text = GetString("TeamCrewmate"); + __instance.TeamTitle.color = __instance.BackgroundBar.material.color = new Color32(140, 255, 255, byte.MaxValue); + PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(RoleTypes.Crewmate); + __instance.ImpostorText.gameObject.SetActive(true); + __instance.ImpostorText.text = GetString("SubText.Crewmate"); + break; + } + case CustomRoleTypes.Neutral: + { + if (Options.UniqueNeutralRevealScreen.GetBool()) + { + __instance.TeamTitle.text = GetString($"{role}"); + __instance.TeamTitle.color = __instance.BackgroundBar.material.color = Utils.GetRoleColor(role); + PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(RoleTypes.Shapeshifter); + __instance.ImpostorText.gameObject.SetActive(true); + __instance.ImpostorText.text = GetString($"{role}Info"); + } + else + { + __instance.TeamTitle.text = GetString("TeamNeutral"); + __instance.TeamTitle.color = __instance.BackgroundBar.material.color = new Color32(255, 171, 27, byte.MaxValue); + PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(RoleTypes.Shapeshifter); + __instance.ImpostorText.gameObject.SetActive(true); + __instance.ImpostorText.text = GetString("SubText.Neutral"); + } - break; + break; + } + + case CustomRoleTypes.Coven: + { + __instance.TeamTitle.text = GetString("TeamCoven"); + __instance.TeamTitle.color = __instance.BackgroundBar.material.color = Team.Coven.GetColor(); + PlayerControl.LocalPlayer.Data.Role.IntroSound = GetIntroSound(RoleTypes.Phantom); + __instance.ImpostorText.gameObject.SetActive(true); + __instance.ImpostorText.text = GetString("SubText.Coven"); + break; + } + } + + if (Main.LoversPlayers.Count == 2 && Main.LoversPlayers.Exists(x => x.IsLocalPlayer())) + { + __instance.TeamTitle.color = __instance.BackgroundBar.material.color = Utils.GetRoleColor(CustomRoles.Lovers); + byte otherLoverId = Main.LoversPlayers.First(x => x.PlayerId != PlayerControl.LocalPlayer.PlayerId).PlayerId; + __instance.ImpostorText.gameObject.SetActive(true); + __instance.ImpostorText.DestroyTranslator(); + __instance.ImpostorText.text = string.Format(GetString("SubText.LovingCrewmate"), otherLoverId.ColoredPlayerName()); + } + + break; + } } } @@ -611,7 +614,7 @@ internal static class BeginCrewmatePatch { 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; @@ -863,7 +866,7 @@ internal static class IntroCutsceneDestroyPatch if (pc.GetCustomRole().UsesPetInsteadOfKill()) pc.AddAbilityCD(10); else - pc.AddAbilityCD(includeDuration: false); + pc.AddAbilityCD(false); } if (CustomGameMode.Standard.IsActiveOrIntegrated()) @@ -875,8 +878,8 @@ internal static class IntroCutsceneDestroyPatch LateTask.New(() => { var sender = CustomRpcSender.Create("Intro - FixKillCooldown", SendOption.Reliable); - var hasValue = aapc.Aggregate(false, (current, pc) => current || sender.SetKillCooldown(pc, kcd - 2)); - sender.SendMessage(dispose: !hasValue); + bool hasValue = aapc.Aggregate(false, (current, pc) => current || sender.SetKillCooldown(pc, kcd - 2)); + sender.SendMessage(!hasValue); }, 2f, "FixKillCooldownTask"); } else if (Options.FixFirstKillCooldown.GetBool()) @@ -887,7 +890,7 @@ internal static class IntroCutsceneDestroyPatch var hasValue = false; aapc.Do(x => x.ResetKillCooldown(false)); aapc.Where(x => Main.AllPlayerKillCooldown[x.PlayerId] - 2f > 0f).Do(pc => hasValue |= sender.SetKillCooldown(pc, Main.AllPlayerKillCooldown[pc.PlayerId] - 2f)); - sender.SendMessage(dispose: !hasValue); + sender.SendMessage(!hasValue); }, 2f, "FixKillCooldownTask"); } else Utils.SyncAllSettings(); @@ -919,6 +922,7 @@ internal static class IntroCutsceneDestroyPatch LateTask.New(() => { var sender = CustomRpcSender.Create("Pet Assign On Game Start", SendOption.Reliable); + foreach (PlayerControl pc in aapc) { if (pc.Is(CustomRoles.GM)) continue; @@ -927,6 +931,7 @@ internal static class IntroCutsceneDestroyPatch PetsHelper.SetPet(pc, petId, sender); Logger.Info($"{pc.GetNameWithRole()} => {GetString(petId)} Pet", "PetAssign"); } + sender.SendMessage(); AntiBlackout.SendGameData(); @@ -937,7 +942,7 @@ internal static class IntroCutsceneDestroyPatch var sender = CustomRpcSender.Create("Shapeshift After Pet Assign On Game Start", SendOption.Reliable); sender.Notify(lp, GetString("GLHF"), 2f); - bool hasValue = true; + var hasValue = true; foreach (PlayerControl pc in aapc) { @@ -947,12 +952,12 @@ internal static class IntroCutsceneDestroyPatch { if (AmongUsClient.Instance.AmClient) pc.Shapeshift(pc, false); - + sender.AutoStartRpc(pc.NetId, 46); sender.WriteNetObject(pc); sender.Write(false); sender.EndRpc(); - + sender.Notify(pc, GetString("GLHF"), 2f); hasValue = true; @@ -966,8 +971,8 @@ internal static class IntroCutsceneDestroyPatch hasValue = false; } } - - sender.SendMessage(dispose: !hasValue); + + sender.SendMessage(!hasValue); }, 0.4f, "Show Pet For Everyone"); LateTask.New(() => Main.ProcessShapeshifts = true, 1f, "Enable SS Processing"); @@ -982,7 +987,7 @@ internal static class IntroCutsceneDestroyPatch try { - var spectators = ChatCommands.Spectators.ToList().ToValidPlayers(); + System.Collections.Generic.List spectators = ChatCommands.Spectators.ToList().ToValidPlayers(); if (Main.GM.Value) spectators.Add(PlayerControl.LocalPlayer); if (CustomGameMode.FFA.IsActiveOrIntegrated() && FreeForAll.FFAChatDuringGame.GetBool()) @@ -993,8 +998,8 @@ internal static class IntroCutsceneDestroyPatch { var sender = CustomRpcSender.Create("Set Spectators Dead", SendOption.Reliable); spectators.ForEach(sender.RpcExileV2); - sender.SendMessage(dispose: spectators.Count == 0); - spectators.ForEach(x => + sender.SendMessage(spectators.Count == 0); + spectators.ForEach(x => { Main.PlayerStates[x.PlayerId].SetDead(); Utils.AfterPlayerDeathTasks(x); @@ -1005,7 +1010,7 @@ internal static class IntroCutsceneDestroyPatch if (Options.RandomSpawn.GetBool() && Main.CurrentMap != MapNames.Airship && AmongUsClient.Instance.AmHost && !CustomGameMode.CaptureTheFlag.IsActiveOrIntegrated() && !CustomGameMode.KingOfTheZones.IsActiveOrIntegrated()) { - RandomSpawn.SpawnMap map = RandomSpawn.SpawnMap.GetSpawnMap(); + var map = RandomSpawn.SpawnMap.GetSpawnMap(); aapc.Do(map.RandomTeleport); } @@ -1034,7 +1039,7 @@ internal static class IntroCutsceneDestroyPatch if (CustomGameMode.KingOfTheZones.IsActiveOrIntegrated()) Main.Instance.StartCoroutine(KingOfTheZones.GameStart()); - + if (CustomGameMode.HotPotato.IsActiveOrIntegrated()) HotPotato.OnGameStart(); diff --git a/Patches/LobbyPatch.cs b/Patches/LobbyPatch.cs index 731a6a389..b2d3553a4 100644 --- a/Patches/LobbyPatch.cs +++ b/Patches/LobbyPatch.cs @@ -46,8 +46,8 @@ public static class HostInfoPanelSetUpPatch { if (HostText == null) HostText = __instance.content.transform.FindChild("Name").GetComponent(); - var name = AmongUsClient.Instance.GetHost().PlayerName; - var split = name.Split('\n'); + string name = AmongUsClient.Instance.GetHost().PlayerName; + string[] split = name.Split('\n'); name = Options.GetSuffixMode() == SuffixModes.None ? split[^1] : split[^2]; if (name == string.Empty) return; @@ -73,7 +73,7 @@ public static class LobbyPatch // https://github.com/SuperNewRoles/SuperNewRoles/blob/master/SuperNewRoles/Patches/LobbyBehaviourPatch.cs [HarmonyPatch(typeof(LobbyBehaviour), nameof(LobbyBehaviour.Update))] -static class LobbyBehaviourUpdatePatch +internal static class LobbyBehaviourUpdatePatch { public static void Postfix(LobbyBehaviour __instance) { diff --git a/Patches/LogoAndStampPatch.cs b/Patches/LogoAndStampPatch.cs index 94393c522..556e1a95b 100644 --- a/Patches/LogoAndStampPatch.cs +++ b/Patches/LogoAndStampPatch.cs @@ -77,71 +77,71 @@ public static class CredentialsPatch SponsersData += $"\n\n({GetString("OnlyShowPart")})"; } -/* - static void ViewBoosterPatch(MainMenuManager __instance) - { - var template = __instance.transform.FindChild("StatsPopup"); - var obj = Object.Instantiate(template, template.transform.parent).gameObject; - Object.Destroy(obj.GetComponent()); + /* + static void ViewBoosterPatch(MainMenuManager __instance) + { + var template = __instance.transform.FindChild("StatsPopup"); + var obj = Object.Instantiate(template, template.transform.parent).gameObject; + Object.Destroy(obj.GetComponent()); - var devtitletext = obj.transform.FindChild("StatNumsText_TMP"); - devtitletext.GetComponent().text = GetString("Developer"); - devtitletext.GetComponent().alignment = TextAlignmentOptions.Center; - devtitletext.localPosition = new(-2.4f, 1.65f, -2f); - devtitletext.localScale = new(0.8f, 0.8f, 0.8f); + var devtitletext = obj.transform.FindChild("StatNumsText_TMP"); + devtitletext.GetComponent().text = GetString("Developer"); + devtitletext.GetComponent().alignment = TextAlignmentOptions.Center; + devtitletext.localPosition = new(-2.4f, 1.65f, -2f); + devtitletext.localScale = new(0.8f, 0.8f, 0.8f); - var devtext = obj.transform.FindChild("StatsText_TMP"); - devtext.GetComponent().text = DevsData; - devtext.GetComponent().alignment = TextAlignmentOptions.Capline; - devtext.localPosition = new(-2.4f, 1.27f, -2f); - devtext.localScale = new(0.5f, 0.5f, 1f); + var devtext = obj.transform.FindChild("StatsText_TMP"); + devtext.GetComponent().text = DevsData; + devtext.GetComponent().alignment = TextAlignmentOptions.Capline; + devtext.localPosition = new(-2.4f, 1.27f, -2f); + devtext.localScale = new(0.5f, 0.5f, 1f); - var transtitletext = Object.Instantiate(devtitletext, obj.transform); - transtitletext.GetComponent().text = GetString("Translator"); - transtitletext.GetComponent().alignment = TextAlignmentOptions.Center; - transtitletext.localPosition = new(0f, 1.65f, -2f); - transtitletext.localScale = new(0.8f, 0.8f, 1f); + var transtitletext = Object.Instantiate(devtitletext, obj.transform); + transtitletext.GetComponent().text = GetString("Translator"); + transtitletext.GetComponent().alignment = TextAlignmentOptions.Center; + transtitletext.localPosition = new(0f, 1.65f, -2f); + transtitletext.localScale = new(0.8f, 0.8f, 1f); - var transtext = Object.Instantiate(devtext, obj.transform); - transtext.GetComponent().text = TransData; - transtext.GetComponent().alignment = TextAlignmentOptions.Capline; - transtext.localPosition = new(0f, 1.27f, -2f); - transtext.localScale = new(0.5f, 0.5f, 1f); + var transtext = Object.Instantiate(devtext, obj.transform); + transtext.GetComponent().text = TransData; + transtext.GetComponent().alignment = TextAlignmentOptions.Capline; + transtext.localPosition = new(0f, 1.27f, -2f); + transtext.localScale = new(0.5f, 0.5f, 1f); - var boostertitletext = Object.Instantiate(devtitletext, obj.transform); - boostertitletext.GetComponent().text = GetString("Booster"); - boostertitletext.GetComponent().alignment = TextAlignmentOptions.Center; - boostertitletext.localPosition = new(-2.4f, -1f, -2f); - boostertitletext.localScale = new(0.8f, 0.8f, 1f); + var boostertitletext = Object.Instantiate(devtitletext, obj.transform); + boostertitletext.GetComponent().text = GetString("Booster"); + boostertitletext.GetComponent().alignment = TextAlignmentOptions.Center; + boostertitletext.localPosition = new(-2.4f, -1f, -2f); + boostertitletext.localScale = new(0.8f, 0.8f, 1f); - var boostertext = Object.Instantiate(devtext, obj.transform); - boostertext.GetComponent().text = BoosterData; - boostertext.GetComponent().alignment = TextAlignmentOptions.Capline; - boostertext.localPosition = new(-2.4f, -1.38f, -2f); - boostertext.localScale = new(0.5f, 0.5f, 1f); + var boostertext = Object.Instantiate(devtext, obj.transform); + boostertext.GetComponent().text = BoosterData; + boostertext.GetComponent().alignment = TextAlignmentOptions.Capline; + boostertext.localPosition = new(-2.4f, -1.38f, -2f); + boostertext.localScale = new(0.5f, 0.5f, 1f); - var sponsortitletext = Object.Instantiate(devtitletext, obj.transform); - sponsortitletext.GetComponent().text = GetString("Sponsor"); - sponsortitletext.GetComponent().alignment = TextAlignmentOptions.Center; - sponsortitletext.localPosition = new(2.4f, 1.65f, -2f); - sponsortitletext.localScale = new(0.8f, 0.8f, 1f); + var sponsortitletext = Object.Instantiate(devtitletext, obj.transform); + sponsortitletext.GetComponent().text = GetString("Sponsor"); + sponsortitletext.GetComponent().alignment = TextAlignmentOptions.Center; + sponsortitletext.localPosition = new(2.4f, 1.65f, -2f); + sponsortitletext.localScale = new(0.8f, 0.8f, 1f); - var sponsortext = Object.Instantiate(devtext, obj.transform); - sponsortext.GetComponent().text = SponsersData; - sponsortext.GetComponent().alignment = TextAlignmentOptions.Capline; - sponsortext.localPosition = new(2.4f, 1.27f, -2f); - sponsortext.localScale = new(0.5f, 0.5f, 1f); + var sponsortext = Object.Instantiate(devtext, obj.transform); + sponsortext.GetComponent().text = SponsersData; + sponsortext.GetComponent().alignment = TextAlignmentOptions.Capline; + sponsortext.localPosition = new(2.4f, 1.27f, -2f); + sponsortext.localScale = new(0.5f, 0.5f, 1f); - var textobj = obj.transform.FindChild("Title_TMP"); - Object.Destroy(textobj.GetComponent()); - textobj.GetComponent().text = GetString("DevAndSpnTitle"); - textobj.GetComponent().alignment = TextAlignmentOptions.Center; - textobj.localScale = new(1.2f, 1.2f, 1f); - textobj.localPosition = new(0f, 2.2f, -2f); - obj.transform.FindChild("Background").localScale = new(1.5f, 1f, 1f); - obj.transform.FindChild("CloseButton").localPosition = new(-3.75f, 2.65f, 0); - } -*/ + var textobj = obj.transform.FindChild("Title_TMP"); + Object.Destroy(textobj.GetComponent()); + textobj.GetComponent().text = GetString("DevAndSpnTitle"); + textobj.GetComponent().alignment = TextAlignmentOptions.Center; + textobj.localScale = new(1.2f, 1.2f, 1f); + textobj.localPosition = new(0f, 2.2f, -2f); + obj.transform.FindChild("Background").localScale = new(1.5f, 1f, 1f); + obj.transform.FindChild("CloseButton").localPosition = new(-3.75f, 2.65f, 0); + } + */ public static void Postfix(MainMenuManager __instance) { diff --git a/Patches/MainMenuManagerPatch.cs b/Patches/MainMenuManagerPatch.cs index 614cc8bfb..5b2232a53 100644 --- a/Patches/MainMenuManagerPatch.cs +++ b/Patches/MainMenuManagerPatch.cs @@ -97,7 +97,7 @@ public static class MainMenuManagerPatch 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; } diff --git a/Patches/MapPickerMenuPatch.cs b/Patches/MapPickerMenuPatch.cs index 31f8c265e..68a2c608c 100644 --- a/Patches/MapPickerMenuPatch.cs +++ b/Patches/MapPickerMenuPatch.cs @@ -20,7 +20,7 @@ internal static class CreateOptionsPickerPatch public static void Postfix_Initialize(CreateGameMapPicker __instance) { if (SceneManager.GetActiveScene().name == "FindAGame") return; - + const int dleksPos = 3; MapSelectButton[] AllMapButton = __instance.transform.GetComponentsInChildren(); @@ -32,11 +32,13 @@ internal static class CreateOptionsPickerPatch dlekS_ehT.transform.SetSiblingIndex(dleksPos + 2); var dlekS_ehT_MapButton = dlekS_ehT.GetComponent(); DleksButton = dlekS_ehT_MapButton; - foreach (var icon in dlekS_ehT_MapButton.MapIcon) + + foreach (SpriteRenderer icon in dlekS_ehT_MapButton.MapIcon) { if (icon == null || icon.transform == null) continue; icon.flipX = true; } + dlekS_ehT_MapButton.Button.OnClick.RemoveAllListeners(); dlekS_ehT_MapButton.Button.OnClick.AddListener((Action)(() => @@ -92,6 +94,7 @@ internal static class CreateOptionsPickerPatch __instance.SelectMap(0); SetDleks = false; } + return false; } @@ -176,4 +179,4 @@ internal static class CreateOptionsPickerPatch transform2.position = position2; } } -} +} \ No newline at end of file diff --git a/Patches/MeetingHudPatch.cs b/Patches/MeetingHudPatch.cs index 92dc0df80..7eb0e7b16 100644 --- a/Patches/MeetingHudPatch.cs +++ b/Patches/MeetingHudPatch.cs @@ -218,14 +218,12 @@ internal static class CheckForEndVotingPatch continue; - void AddVote() - { + void AddVote() => statesList.Add(new() { VoterId = ps.TargetPlayerId, VotedForId = ps.VotedFor }); - } } if ((Blackmailer.On || NiceSwapper.On) && !RunRoleCode) @@ -276,7 +274,7 @@ internal static class CheckForEndVotingPatch if (tie) { var target = byte.MaxValue; - var playerNum = Main.AllPlayerControls.Length; + int playerNum = Main.AllPlayerControls.Length; foreach (KeyValuePair data in VotingData.Where(x => x.Key < playerNum && x.Value == max)) { @@ -441,8 +439,8 @@ internal static class CheckForEndVotingPatch name += Utils.ColorString(team.RoleRevealScreenBackgroundColor == "*" || !ColorUtility.TryParseHtmlString(team.RoleRevealScreenBackgroundColor, out Color color) ? Color.yellow : color, team.RoleRevealScreenTitle == "*" ? team.TeamName : team.RoleRevealScreenTitle); else { - var color = player.GetTeam().GetColor(); - var str = GetString($"Team{player.GetTeam()}"); + Color color = player.GetTeam().GetColor(); + string str = GetString($"Team{player.GetTeam()}"); name += Utils.ColorString(color, str); } @@ -515,7 +513,7 @@ internal static class CheckForEndVotingPatch { foreach ((byte id, Vector2 pos) in Lazy.BeforeMeetingPositions) { - var pc = id.GetPlayer(); + PlayerControl pc = id.GetPlayer(); if (pc == null || !pc.IsAlive()) continue; pc.TP(pos); @@ -615,8 +613,10 @@ internal static class ExtendedMeetingHud VoteNum = 0; if (CheckForEndVotingPatch.CheckRole(ps.TargetPlayerId, CustomRoles.Brakar)) + { if (!Main.BrakarVoteFor.Contains(target.PlayerId)) Main.BrakarVoteFor.Add(target.PlayerId); + } Collector.CollectorVotes(target, ps); } @@ -783,8 +783,10 @@ internal static class MeetingHudStartPatch MimicMsg = GetString("MimicDeadMsg") + "\n" + MimicMsg; foreach (PlayerControl ipc in Main.AllPlayerControls) + { if (ipc.GetCustomRole().IsImpostorTeam()) 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"); @@ -799,10 +801,7 @@ internal static class MeetingHudStartPatch Enigma.MsgToSend.Clear(); return; - void AddMsg(string text, byte sendTo = 255, string title = "") - { - msgToSend.Add((text, sendTo, title)); - } + void AddMsg(string text, byte sendTo = 255, string title = "") => msgToSend.Add((text, sendTo, title)); } public static void Prefix( /*MeetingHud __instance*/) @@ -1063,7 +1062,7 @@ internal static class MeetingHudStartPatch if (Magistrate.CallCourtNextMeeting) { - var name = target.Is(CustomRoles.Magistrate) ? GetString("Magistrate.CourtName") : GetString("Magistrate.JuryName"); + string name = target.Is(CustomRoles.Magistrate) ? GetString("Magistrate.CourtName") : GetString("Magistrate.JuryName"); pva.NameText.text = name; } } @@ -1294,7 +1293,7 @@ internal static class MeetingHudCmdCastVotePatch // All below are from: https://github.com/EnhancedNetwork/TownofHost-Enhanced (with some modifications) [HarmonyPatch(typeof(MeetingHud), nameof(MeetingHud.RpcClose))] -static class MeetingHudRpcClosePatch +internal static class MeetingHudRpcClosePatch { public static bool Prefix(MeetingHud __instance) { @@ -1302,17 +1301,18 @@ static class MeetingHudRpcClosePatch if (Options.CurrentGameMode == CustomGameMode.Standard) { - if (AmongUsClient.Instance.AmClient) { __instance.Close(); } + if (AmongUsClient.Instance.AmClient) + __instance.Close(); - var writer = MessageWriter.Get(SendOption.Reliable); + MessageWriter writer = MessageWriter.Get(SendOption.Reliable); writer.StartMessage(5); writer.Write(AmongUsClient.Instance.GameId); if (CheckForEndVotingPatch.TempExiledPlayer != null) { - var info = CheckForEndVotingPatch.TempExiledPlayer; - var player = info.Object; + NetworkedPlayerInfo info = CheckForEndVotingPatch.TempExiledPlayer; + PlayerControl player = info.Object; if (player != null) { @@ -1343,7 +1343,7 @@ static class MeetingHudRpcClosePatch } [HarmonyPatch(typeof(MeetingHud), nameof(MeetingHud.HandleRpc))] -static class MeetingHudHandleRpcPatch +internal static class MeetingHudHandleRpcPatch { public static bool Prefix(MeetingHud __instance, [HarmonyArgument(0)] byte callId, [HarmonyArgument(1)] MessageReader reader) { @@ -1362,7 +1362,7 @@ static class MeetingHudHandleRpcPatch { try { - var temp = reader.ReadString(); + string temp = reader.ReadString(); if (temp.Contains(" (p.Data.DefaultOutfit.ColorId < 0) || (Palette.PlayerColors.Length <= p.Data.DefaultOutfit.ColorId)).Select(p => $"{p.name}").ToArray(); + 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) { @@ -320,7 +320,7 @@ internal static class ChangeRoleSettings 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.AllPlayerSpeed[pc.PlayerId] = Main.RealOptionsData.GetFloat(FloatOptionNames.PlayerSpeedMod); @@ -542,10 +542,10 @@ internal static class StartGameHostPatch var num = 10; var totalSeconds = (float)(DateTime.Now - start).TotalSeconds; - if ((GameOptionsManager.Instance.CurrentGameOptions.MapId == 5) || (GameOptionsManager.Instance.CurrentGameOptions.MapId == 4)) + if (GameOptionsManager.Instance.CurrentGameOptions.MapId == 5 || GameOptionsManager.Instance.CurrentGameOptions.MapId == 4) num = 15; - int clientsReady = 0; + var clientsReady = 0; int allClientsCount = AUClient.allClients.Count; lock (AUClient.allClients) @@ -554,7 +554,7 @@ internal static class StartGameHostPatch { ClientData allClient = AUClient.allClients[index]; // False error - if ((allClient.Id != AUClient.ClientId) && !allClient.IsReady) + if (allClient.Id != AUClient.ClientId && !allClient.IsReady) { if (totalSeconds < (double)num) flag = false; @@ -632,11 +632,11 @@ internal static class StartGameHostPatch if (CustomGameMode.Standard.IsActiveOrIntegrated()) { - bool bloodlustSpawn = (random.Next(100) < (Options.CustomAdtRoleSpawnRate.TryGetValue(CustomRoles.Bloodlust, out IntegerOptionItem option0) ? option0.GetFloat() : 0)) && CustomRoles.Bloodlust.IsEnable() && Options.RoleSubCategoryLimits[RoleOptionType.Neutral_Killing][2].GetInt() > 0; - bool physicistSpawn = (random.Next(100) < (Options.CustomAdtRoleSpawnRate.TryGetValue(CustomRoles.Physicist, out IntegerOptionItem option1) ? option1.GetFloat() : 0)) && CustomRoles.Physicist.IsEnable(); - bool nimbleSpawn = (random.Next(100) < (Options.CustomAdtRoleSpawnRate.TryGetValue(CustomRoles.Nimble, out IntegerOptionItem option2) ? option2.GetFloat() : 0)) && CustomRoles.Nimble.IsEnable(); - bool finderSpawn = (random.Next(100) < (Options.CustomAdtRoleSpawnRate.TryGetValue(CustomRoles.Finder, out IntegerOptionItem option3) ? option3.GetFloat() : 0)) && CustomRoles.Finder.IsEnable(); - bool noisySpawn = (random.Next(100) < (Options.CustomAdtRoleSpawnRate.TryGetValue(CustomRoles.Noisy, out IntegerOptionItem option4) ? option4.GetFloat() : 0)) && CustomRoles.Noisy.IsEnable(); + bool bloodlustSpawn = random.Next(100) < (Options.CustomAdtRoleSpawnRate.TryGetValue(CustomRoles.Bloodlust, out IntegerOptionItem option0) ? option0.GetFloat() : 0) && CustomRoles.Bloodlust.IsEnable() && Options.RoleSubCategoryLimits[RoleOptionType.Neutral_Killing][2].GetInt() > 0; + bool physicistSpawn = random.Next(100) < (Options.CustomAdtRoleSpawnRate.TryGetValue(CustomRoles.Physicist, out IntegerOptionItem option1) ? option1.GetFloat() : 0) && CustomRoles.Physicist.IsEnable(); + bool nimbleSpawn = random.Next(100) < (Options.CustomAdtRoleSpawnRate.TryGetValue(CustomRoles.Nimble, out IntegerOptionItem option2) ? option2.GetFloat() : 0) && CustomRoles.Nimble.IsEnable(); + bool finderSpawn = random.Next(100) < (Options.CustomAdtRoleSpawnRate.TryGetValue(CustomRoles.Finder, out IntegerOptionItem option3) ? option3.GetFloat() : 0) && CustomRoles.Finder.IsEnable(); + bool noisySpawn = random.Next(100) < (Options.CustomAdtRoleSpawnRate.TryGetValue(CustomRoles.Noisy, out IntegerOptionItem option4) ? option4.GetFloat() : 0) && CustomRoles.Noisy.IsEnable(); if (Options.EveryoneCanVent.GetBool()) { @@ -657,11 +657,11 @@ internal static class StartGameHostPatch KeyValuePair kp = RoleResult.FirstOrDefault(x => x.Key == player.PlayerId); - bool bloodlustBanned = hasBanned && banned.Any(x => (x.Key == kp.Value) && x.Value.Contains(CustomRoles.Bloodlust)); - bool nimbleBanned = hasBanned && banned.Any(x => (x.Key == kp.Value) && x.Value.Contains(CustomRoles.Nimble)); - bool physicistBanned = hasBanned && banned.Any(x => (x.Key == kp.Value) && x.Value.Contains(CustomRoles.Physicist)); - bool finderBanned = hasBanned && banned.Any(x => (x.Key == kp.Value) && x.Value.Contains(CustomRoles.Finder)); - bool noisyBanned = hasBanned && banned.Any(x => (x.Key == kp.Value) && x.Value.Contains(CustomRoles.Noisy)); + bool bloodlustBanned = hasBanned && banned.Any(x => x.Key == kp.Value && x.Value.Contains(CustomRoles.Bloodlust)); + bool nimbleBanned = hasBanned && banned.Any(x => x.Key == kp.Value && x.Value.Contains(CustomRoles.Nimble)); + bool physicistBanned = hasBanned && banned.Any(x => x.Key == kp.Value && x.Value.Contains(CustomRoles.Physicist)); + bool finderBanned = hasBanned && banned.Any(x => x.Key == kp.Value && x.Value.Contains(CustomRoles.Finder)); + bool noisyBanned = hasBanned && banned.Any(x => x.Key == kp.Value && x.Value.Contains(CustomRoles.Noisy)); if (kp.Value.IsCrewmate()) { @@ -699,7 +699,7 @@ internal static class StartGameHostPatch 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(); + 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) { @@ -713,7 +713,7 @@ internal static class StartGameHostPatch { 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; } @@ -725,7 +725,7 @@ internal static class StartGameHostPatch { foreach ((CustomRoles otherAddon, (bool otherSpawnFlag, _)) in roleSpawnMapping) { - if ((otherAddon != addon) && otherSpawnFlag && BasisChangingAddons.TryGetValue(otherAddon, out List otherList)) + if (otherAddon != addon && otherSpawnFlag && BasisChangingAddons.TryGetValue(otherAddon, out List otherList)) roleList.ExceptWith(otherList); } @@ -810,14 +810,14 @@ internal static class StartGameHostPatch 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 (!overrideLovers && CustomRoles.Lovers.IsEnable() && ((CustomRoles.FFF.IsEnable() ? -1 : IRandom.Instance.Next(1, 100)) <= Lovers.LoverSpawnChances.GetInt())) AssignLoversRolesFromList(); + if (!overrideLovers && CustomRoles.Lovers.IsEnable() && (CustomRoles.FFF.IsEnable() ? -1 : IRandom.Instance.Next(1, 100)) <= Lovers.LoverSpawnChances.GetInt()) AssignLoversRolesFromList(); // Add-on assignment PlayerControl[] aapc = Main.AllAlivePlayerControls.Shuffle(); @@ -831,7 +831,7 @@ internal static class StartGameHostPatch .Where(x => x.IsEnable() && aapc.Any(p => CustomRolesHelper.CheckAddonConflict(x, p))) .SelectMany(x => Enumerable.Repeat(x, Math.Clamp(x.GetCount(), 0, aapc.Length))) .Where(x => IRandom.Instance.Next(1, 100) <= (Options.CustomAdtRoleSpawnRate.TryGetValue(x, out IntegerOptionItem sc) ? sc.GetFloat() : 0)) - .OrderBy(x => Options.CustomAdtRoleSpawnRate.TryGetValue(x, out IntegerOptionItem sc) && (sc.GetInt() == 100) ? IRandom.Instance.Next(100) : IRandom.Instance.Next(100, 1000)) + .OrderBy(x => Options.CustomAdtRoleSpawnRate.TryGetValue(x, out IntegerOptionItem sc) && sc.GetInt() == 100 ? IRandom.Instance.Next(100) : IRandom.Instance.Next(100, 1000)) .Select(x => { PlayerControl suitablePlayer = aapc @@ -853,7 +853,7 @@ internal static class StartGameHostPatch 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.MainRole == CustomRoles.Traitor) && Traitor.CanGetImpostorOnlyAddons.GetBool())) + if (!state.MainRole.IsImpostor() && !(state.MainRole == CustomRoles.Traitor && Traitor.CanGetImpostorOnlyAddons.GetBool())) state.SubRoles.RemoveAll(x => x.IsImpOnlyAddon()); } @@ -1002,7 +1002,7 @@ internal static class StartGameHostPatch 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"); } @@ -1042,7 +1042,7 @@ internal static class StartGameHostPatch hasValue |= sender.RpcResetAbilityCooldown(pc); } - sender.SendMessage(dispose: !hasValue); + sender.SendMessage(!hasValue); } private static bool IsBasisChangingPlayer(byte id, CustomRoles role) @@ -1112,7 +1112,7 @@ internal static class StartGameHostPatch { try { - if ((seer.PlayerId == target.PlayerId) || target.IsLocalPlayer()) continue; + if (seer.PlayerId == target.PlayerId || target.IsLocalPlayer()) continue; if (rolesMap.TryGetValue((seer.PlayerId, target.PlayerId), out (RoleTypes, CustomRoles) roleMap)) { @@ -1174,7 +1174,7 @@ internal static class StartGameHostPatch stream.StartMessage(5); stream.Write(AmongUsClient.Instance.GameId); - bool hasValue = false; + var hasValue = false; foreach (NetworkedPlayerInfo playerInfo in GameData.Instance.AllPlayers) { @@ -1251,7 +1251,7 @@ internal static class StartGameHostPatch return; } - 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.Curser) && !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(); + 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.Curser) && !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); @@ -1357,7 +1357,7 @@ internal static class StartGameHostPatch try { PlayerControl player = Utils.GetPlayerById(playerId); - if ((player == null) || role.IsDesyncRole()) continue; + if (player == null || role.IsDesyncRole()) continue; if (CustomGameMode.Speedrun.IsActiveOrIntegrated() && Speedrun.CanKill.Contains(playerId)) continue; @@ -1447,10 +1447,10 @@ internal static class StartGameHostPatch { try { - 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; int targetClientId = target.GetClientId(); if (targetClientId == -1) continue; @@ -1493,7 +1493,7 @@ internal static class StartGameHostPatch LoadingBarManager loadingBarManager = FastDestroyableSingleton.Instance; float step = (75f - 65f) / Senders.Count; - int index = 0; + var index = 0; foreach (CustomRpcSender sender in Senders.Values) { diff --git a/Patches/OutroPatch.cs b/Patches/OutroPatch.cs index 8aeddb153..0f441372c 100644 --- a/Patches/OutroPatch.cs +++ b/Patches/OutroPatch.cs @@ -128,7 +128,7 @@ internal static class EndGamePatch Main.AllPlayerControls.Do(x => KingOfTheZones.PlayedFCs.Add(x.FriendCode)); break; default: - if (Main.HasPlayedGM.TryGetValue(Options.CurrentGameMode, out var playedFCs)) + if (Main.HasPlayedGM.TryGetValue(Options.CurrentGameMode, out HashSet playedFCs)) playedFCs.UnionWith(Main.AllPlayerControls.Select(x => x.FriendCode)); break; @@ -162,8 +162,10 @@ internal static class SetEverythingUpPatch Il2CppArrayBase pbs = __instance?.transform.GetComponentsInChildren(); if (pbs != null) + { foreach (PoolablePlayer pb in pbs) pb.ToggleName(false); + } List list = EndGameResult.CachedWinners.ToArray().ToList(); @@ -522,7 +524,7 @@ internal static class SetEverythingUpPatch if (Options.CurrentGameMode != CustomGameMode.Standard) { - var winCounts = Utils.GetWinCountsString(); + string winCounts = Utils.GetWinCountsString(); if (winCounts != string.Empty) { @@ -543,7 +545,7 @@ internal static class SetEverythingUpPatch RoleSummaryRectTransform.anchoredPosition = new(Pos.x + 3.5f, Pos.y - 0.7f); RoleSummary.text = sb.ToString(); - var showInitially = Main.ShowResult; + bool showInitially = Main.ShowResult; ResultsToggleButton = new SimpleButton( __instance.transform, @@ -553,7 +555,7 @@ internal static class SetEverythingUpPatch new(0, 255, 255, 255), () => { - var setToActive = !RoleSummary.gameObject.activeSelf; + bool setToActive = !RoleSummary.gameObject.activeSelf; RoleSummary.gameObject.SetActive(setToActive); Main.ShowResult = setToActive; ResultsToggleButton.Label.text = GetString(setToActive ? "HideResults" : "ShowResults"); @@ -561,7 +563,7 @@ internal static class SetEverythingUpPatch GetString(showInitially ? "HideResults" : "ShowResults")) { Scale = new(1.5f, 0.5f), - FontSize = 2f, + FontSize = 2f }; return; diff --git a/Patches/PetActionsPatch.cs b/Patches/PetActionsPatch.cs index 5d9c56138..98ce06633 100644 --- a/Patches/PetActionsPatch.cs +++ b/Patches/PetActionsPatch.cs @@ -156,7 +156,7 @@ internal static class ExternalRpcPetPatch if (target.Is(CustomRoles.Spy) && !Spy.OnKillAttempt(pc, target)) goto Skip; if (!Starspawn.CheckInteraction(pc, target)) goto Skip; - + Seamstress.OnAnyoneCheckMurder(pc, target); if (Main.PlayerStates[pc.PlayerId].Role.OnCheckMurder(pc, target)) @@ -184,7 +184,7 @@ internal static class ExternalRpcPetPatch PlayerControl tempTarget = target; target = Main.AllAlivePlayerControls.Where(x => x.PlayerId != target.PlayerId && x.PlayerId != pc.PlayerId).MinBy(x => Vector2.Distance(x.Pos(), target.Pos())); Logger.Info($"Target was {tempTarget.GetNameWithRole()}, new target is {target.GetNameWithRole()}", "Detour"); - + if (tempTarget.IsLocalPlayer()) { Detour.TotalRedirections++; @@ -192,7 +192,7 @@ internal static class ExternalRpcPetPatch } } - if (target != null && Spirit.TryGetSwapTarget(target, out var newTarget)) + if (target != null && Spirit.TryGetSwapTarget(target, out PlayerControl newTarget)) { Logger.Info($"Target was {target.GetNameWithRole()}, new target is {newTarget.GetNameWithRole()}", "Spirit"); target = newTarget; diff --git a/Patches/PhantomRolePatch.cs b/Patches/PhantomRolePatch.cs index 48fe669af..029b3dd67 100644 --- a/Patches/PhantomRolePatch.cs +++ b/Patches/PhantomRolePatch.cs @@ -70,14 +70,14 @@ public static class PhantomRolePatch return false; } - CustomRpcSender sender = CustomRpcSender.Create($"Cancel vanish for {phantom.GetRealName()}"); + var sender = CustomRpcSender.Create($"Cancel vanish for {phantom.GetRealName()}"); sender.StartMessage(phantom.GetClientId()); sender.StartRpc(phantom.NetId, (byte)RpcCalls.SetRole) .Write((ushort)RoleTypes.Phantom) .Write(true) .EndRpc(); - + sender.StartRpc(phantom.NetId, (byte)RpcCalls.ProtectPlayer) .WriteNetObject(phantom) .Write(0) @@ -245,10 +245,7 @@ public static class PhantomRoleUseAbilityPatch if (__instance.Player.AmOwner && !__instance.Player.Data.IsDead && __instance.Player.moveable && !Minigame.Instance && !__instance.IsCoolingDown && !__instance.fading) { - bool RoleEffectAnimation(RoleEffectAnimation x) - { - return x.effectType == global::RoleEffectAnimation.EffectType.Vanish_Charge; - } + bool RoleEffectAnimation(RoleEffectAnimation x) => x.effectType == global::RoleEffectAnimation.EffectType.Vanish_Charge; if (!__instance.Player.currentRoleAnimations.Find((Func)RoleEffectAnimation) && !__instance.Player.walkingToVent && !__instance.Player.inMovingPlat) { diff --git a/Patches/PlayerControlPatch.cs b/Patches/PlayerControlPatch.cs index 8d3ae142a..86e021f26 100644 --- a/Patches/PlayerControlPatch.cs +++ b/Patches/PlayerControlPatch.cs @@ -162,7 +162,7 @@ internal static class CheckMurderPatch } } - if (Spirit.TryGetSwapTarget(target, out var newTarget)) + if (Spirit.TryGetSwapTarget(target, out PlayerControl newTarget)) { Logger.Info($"Target was {target.GetNameWithRole()}, new target is {newTarget.GetNameWithRole()}", "Spirit"); target = newTarget; @@ -204,12 +204,16 @@ internal static class CheckMurderPatch 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(false); @@ -308,10 +312,7 @@ internal static class CheckMurderPatch return false; } - bool CheckMurder() - { - return Main.PlayerStates[killer.PlayerId].Role.OnCheckMurder(killer, target) || target.Is(CustomRoles.Fragile); - } + bool CheckMurder() => Main.PlayerStates[killer.PlayerId].Role.OnCheckMurder(killer, target) || target.Is(CustomRoles.Fragile); } if (!killer.RpcCheckAndMurder(target, true)) return false; @@ -602,9 +603,9 @@ internal static class MurderPlayerPatch { if (GameStates.IsLobby || AntiBlackout.SkipTasks) return false; - var protectedByClient = resultFlags.HasFlag(MurderResultFlags.DecisionByHost) && target.IsProtected(); - var protectedByHost = resultFlags.HasFlag(MurderResultFlags.FailedProtected); - var failed = resultFlags.HasFlag(MurderResultFlags.FailedError); + bool protectedByClient = resultFlags.HasFlag(MurderResultFlags.DecisionByHost) && target.IsProtected(); + bool protectedByHost = resultFlags.HasFlag(MurderResultFlags.FailedProtected); + bool failed = resultFlags.HasFlag(MurderResultFlags.FailedError); __state = !protectedByClient && !protectedByHost && !failed; Logger.Info($"{__instance.GetNameWithRole().RemoveHtmlTags()} => {target.GetNameWithRole().RemoveHtmlTags()} - {nameof(protectedByClient)}: {protectedByClient}, {nameof(protectedByHost)}: {protectedByHost}, {nameof(failed)}: {failed}", "MurderPlayer"); @@ -745,7 +746,7 @@ internal static class MurderPlayerPatch __instance.MarkDirtySettings(); target.MarkDirtySettings(); - Main.Instance.StartCoroutine(NotifyEveryoneAsync(speed: 4, noCache: false)); + Main.Instance.StartCoroutine(NotifyEveryoneAsync(4, false)); Statistics.OnMurder(killer, target); } @@ -844,7 +845,7 @@ internal static class ShapeshiftPatch // 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(() => Main.Instance.StartCoroutine(NotifyEveryoneAsync(speed: 3)), 1.2f, "ShapeShiftNotify"); + LateTask.New(() => Main.Instance.StartCoroutine(NotifyEveryoneAsync(3)), 1.2f, "ShapeShiftNotify"); if (!(shapeshifting && doSSwithoutAnim) && !isSSneeded && !Swapster.FirstSwapTarget.ContainsKey(shapeshifter.PlayerId)) LateTask.New(shapeshifter.RpcResetAbilityCooldown, 0.01f, log: false); @@ -989,8 +990,8 @@ internal static class ReportDeadBodyPatch } - if ((!Occultist.OnAnyoneReportDeadBody(target)) || - (!Altruist.OnAnyoneCheckReportDeadBody(__instance, target))) + if (!Occultist.OnAnyoneReportDeadBody(target) || + !Altruist.OnAnyoneCheckReportDeadBody(__instance, target)) { Notify("PlayerWasRevived"); return false; @@ -1071,19 +1072,19 @@ internal static class ReportDeadBodyPatch { PlayerControl receiver = id.GetPlayer(); if (receiver == null) continue; - + PlayerControl killer = receiver.GetRealKiller(); if (killer == null) continue; SendMessage("\n", receiver.PlayerId, string.Format(GetString("DeathCommand"), killer.PlayerId.ColoredPlayerName(), (killer.Is(CustomRoles.Bloodlust) ? $"{CustomRoles.Bloodlust.ToColoredString()} " : string.Empty) + killer.GetCustomRole().ToColoredString())); } } - + Main.DiedThisRound = []; Main.AllAlivePlayerControls.DoIf(x => x.Is(CustomRoles.Lazy), x => Lazy.BeforeMeetingPositions[x.PlayerId] = x.Pos()); - if (Lovers.PrivateChat.GetBool()) ChatManager.SendPreviousMessagesToAll(clear: true); + if (Lovers.PrivateChat.GetBool()) ChatManager.SendPreviousMessagesToAll(true); if (target == null) { @@ -1173,8 +1174,10 @@ internal static class ReportDeadBodyPatch Vulture.Clear(); foreach (PlayerState state in Main.PlayerStates.Values) + { if (state.Role.IsEnable) state.Role.OnReportDeadBody(); + } Main.AbilityCD.Clear(); SendRPC(CustomRPC.SyncAbilityCD, 2); @@ -1201,7 +1204,7 @@ internal static class ReportDeadBodyPatch MeetingTimeManager.OnReportDeadBody(); NameNotifyManager.Reset(); - NotifyRoles(ForMeeting: true, ForceLoop: true, CamouflageIsForMeeting: true, GuesserIsForMeeting: true); + NotifyRoles(true, ForceLoop: true, CamouflageIsForMeeting: true, GuesserIsForMeeting: true); Main.ProcessShapeshifts = false; @@ -1217,7 +1220,7 @@ internal static class ReportDeadBodyPatch if (Magistrate.CallCourtNextMeeting) { - var name = pc.GetRealName(); + string name = pc.GetRealName(); RpcChangeSkin(pc, new NetworkedPlayerInfo.PlayerOutfit().Set(name, 15, "", "", "", "", "")); } } @@ -1420,8 +1423,10 @@ internal static class FixedUpdatePatch 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.IsModdedClient() && player.Is(CustomRoles.Haste)) player.ForceKillTimerContinue = true; @@ -1434,7 +1439,7 @@ internal static class FixedUpdatePatch player.RpcSetCustomRole(CustomRoles.Pestilence); player.Notify(GetString("PlagueBearerToPestilence")); player.RpcGuardAndKill(player); - + if (!PlagueBearer.PestilenceList.Contains(playerId)) PlagueBearer.PestilenceList.Add(playerId); @@ -1503,7 +1508,7 @@ internal static class FixedUpdatePatch // Ability Use Gain every 5 seconds - if (inTask && alive && Main.PlayerStates.TryGetValue(playerId, out PlayerState state) && state.TaskState.RemainingTasksCount <= 0 && (!LastAddAbilityTime.TryGetValue(playerId, out var ts) || ts + 5 < now)) + if (inTask && alive && Main.PlayerStates.TryGetValue(playerId, out PlayerState state) && state.TaskState.RemainingTasksCount <= 0 && (!LastAddAbilityTime.TryGetValue(playerId, out long ts) || ts + 5 < now)) { LastAddAbilityTime[playerId] = now; @@ -1519,8 +1524,10 @@ internal static class FixedUpdatePatch 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); @@ -1800,7 +1807,7 @@ internal static class FixedUpdatePatch break; } - if (self && GameStartTimeStamp + 50 > TimeStamp && Main.HasPlayedGM.TryGetValue(Options.CurrentGameMode, out var playedFCs) && !playedFCs.Contains(seer.FriendCode)) + if (self && GameStartTimeStamp + 50 > TimeStamp && Main.HasPlayedGM.TryGetValue(Options.CurrentGameMode, out HashSet playedFCs) && !playedFCs.Contains(seer.FriendCode)) Suffix.Append("\n\n" + GetString($"GameModeTutorial.{Options.CurrentGameMode}")); if (MeetingStates.FirstMeeting && Main.ShieldPlayer == target.FriendCode && !string.IsNullOrEmpty(target.FriendCode) && !self && Options.CurrentGameMode is CustomGameMode.Standard or CustomGameMode.SoloKombat or CustomGameMode.FFA) @@ -2099,8 +2106,10 @@ internal static class CoEnterVentPatch }, 1f, "VentguardBlockedVentBootFromVent"); if (Ventguard.VentguardNotifyOnBlockedVentUse.GetBool()) + { foreach (PlayerControl ventguard in Main.AllAlivePlayerControls.Where(x => x.Is(CustomRoles.Ventguard)).ToArray()) ventguard.Notify(GetString("VentguardNotify")); + } return true; } @@ -2176,7 +2185,7 @@ internal static class PlayerControlCompleteTaskPatch var task = __instance.myTasks[(Index)Convert.ToInt32(idx)] as PlayerTask; Benefactor.OnTaskComplete(__instance, task); } - catch (System.Exception e) { ThrowException(e); } + catch (Exception e) { ThrowException(e); } } } @@ -2283,11 +2292,13 @@ internal static class PlayerControlSetRolePatch else { var sender = CustomRpcSender.Create("Set Desync Ghost Role", SendOption.Reliable); + foreach ((PlayerControl seer, RoleTypes role) in ghostRoles) { Logger.Info($"Desync {targetName} => {role} for {seer.GetNameWithRole().RemoveHtmlTags()}", "PlayerControl.RpcSetRole"); sender.RpcSetRole(__instance, role, seer.GetClientId()); } + sender.SendMessage(); return false; @@ -2379,7 +2390,7 @@ internal static class ShouldProcessRpcPatch } [HarmonyPatch(typeof(PlayerPhysics), nameof(PlayerPhysics.RpcBootFromVent))] -static class BootFromVentPatch +internal static class BootFromVentPatch { public static bool Prefix(PlayerPhysics __instance) { diff --git a/Patches/PlayerJoinAndLeftPatch.cs b/Patches/PlayerJoinAndLeftPatch.cs index fe6a64e01..1eaf6d0e5 100644 --- a/Patches/PlayerJoinAndLeftPatch.cs +++ b/Patches/PlayerJoinAndLeftPatch.cs @@ -90,7 +90,8 @@ internal static class OnGameJoinedPatch else Logger.Info($"Not sending lobby status to the server because the server type is {GameStates.CurrentServerType} (IsOnlineGame: {GameStates.IsOnlineGame})", "OnGameJoinedPatch"); }, 5f, "NotifyLobbyCreated"); } - else { LateTask.New(() => Main.Instance.StartCoroutine(OptionShower.GetText()), 10f, "OptionShower.GetText on client"); } + else + LateTask.New(() => Main.Instance.StartCoroutine(OptionShower.GetText()), 10f, "OptionShower.GetText on client"); } } @@ -114,8 +115,10 @@ internal static class OnPlayerJoinedPatch public static bool IsDisconnected(this ClientData client) { foreach (ClientData clientData in AmongUsClient.Instance.allClients) + { if (clientData.Id == client.Id) return false; + } return true; } @@ -503,7 +506,7 @@ internal static class SetColorPatch { if (__instance != null && !Main.PlayerColors.ContainsKey(__instance.PlayerId)) { - var client = __instance.GetClient(); + ClientData client = __instance.GetClient(); if (client != null) { diff --git a/Patches/SabotageSystemPatch.cs b/Patches/SabotageSystemPatch.cs index 6e54c08a0..1d6580fce 100644 --- a/Patches/SabotageSystemPatch.cs +++ b/Patches/SabotageSystemPatch.cs @@ -177,13 +177,15 @@ public static class MushroomMixupSabotageSystemPatch var sender = CustomRpcSender.Create("MushroomMixupSabotageSystemPatch.Postfix", SendOption.Reliable); Main.AllAlivePlayerControls.DoIf(x => x.GetRoleTypes() != RoleTypes.Engineer, x => sender.RpcResetAbilityCooldown(x)); sender.SendMessage(); - + Main.AllAlivePlayerControls.Do(x => x.CheckAndSetUnshiftState()); }, 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); + } } } } @@ -253,8 +255,10 @@ public static class ElectricTaskInitializePatch if (GameStates.IsInTask) { foreach (PlayerControl pc in Main.AllAlivePlayerControls) + { if (pc.GetCustomRole().NeedUpdateOnLights() || pc.Is(CustomRoles.Torch) || pc.Is(CustomRoles.Sleep) || Beacon.IsAffectedPlayer(pc.PlayerId)) Utils.NotifyRoles(SpecifyTarget: pc, ForceLoop: true); + } } Logger.Info("Lights sabotage called", "ElectricTask"); diff --git a/Patches/ShipStatusPatch.cs b/Patches/ShipStatusPatch.cs index d8e89199b..d5879f79b 100644 --- a/Patches/ShipStatusPatch.cs +++ b/Patches/ShipStatusPatch.cs @@ -22,7 +22,7 @@ internal static class ShipFixedUpdatePatch { if (!AmongUsClient.Instance.AmHost) return; - if (Main.IsFixedCooldown && (Main.RefixCooldownDelay >= 0)) + if (Main.IsFixedCooldown && Main.RefixCooldownDelay >= 0) Main.RefixCooldownDelay -= Time.fixedDeltaTime; else if (!float.IsNaN(Main.RefixCooldownDelay)) { @@ -78,12 +78,12 @@ internal static class RepairSystemPatch [HarmonyArgument(2)] byte amount) { Logger.Msg($"SystemType: {systemType}, PlayerName: {player.GetNameWithRole().RemoveHtmlTags()}, amount: {amount}", "RepairSystem"); - if (RepairSender.Enabled && (AmongUsClient.Instance.NetworkMode != NetworkModes.OnlineGame)) + 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 ((!CustomGameMode.Standard.IsActiveOrIntegrated() || Options.DisableSabotage.GetBool()) && (systemType == SystemTypes.Sabotage)) return false; + if ((!CustomGameMode.Standard.IsActiveOrIntegrated() || Options.DisableSabotage.GetBool()) && systemType == SystemTypes.Sabotage) return false; if (player.Is(CustomRoles.Fool) && systemType is SystemTypes.Comms or SystemTypes.Electrical) return false; switch (player.GetCustomRole()) @@ -104,7 +104,7 @@ internal static class RepairSystemPatch switch (systemType) { - case SystemTypes.Doors when player.Is(CustomRoles.Unlucky) && player.IsAlive() && (IRandom.Instance.Next(0, 100) < Options.UnluckySabotageSuicideChance.GetInt()): + case SystemTypes.Doors when player.Is(CustomRoles.Unlucky) && player.IsAlive() && IRandom.Instance.Next(0, 100) < Options.UnluckySabotageSuicideChance.GetInt(): { player.Suicide(); return false; @@ -113,9 +113,9 @@ internal static class RepairSystemPatch { if (Main.NormalOptions.MapId == 4) { - 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.DisableAirshipCargoLightsPanel.GetBool() && (Vector2.Distance(player.transform.position, new(30.56f, 2.12f)) <= 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.DisableAirshipCargoLightsPanel.GetBool() && Vector2.Distance(player.transform.position, new(30.56f, 2.12f)) <= 2f) return false; } var switchSystem = ShipStatus.Instance?.Systems?[SystemTypes.Electrical]?.CastFast(); @@ -314,7 +314,7 @@ internal static class CheckTaskCompletionPatch { public static bool Prefix(ref bool __result) { - if (Options.DisableTaskWin.GetBool() || Options.NoGameEnd.GetBool() || (TaskState.InitialTotalTasks == 0) || (Options.DisableTaskWinIfAllCrewsAreDead.GetBool() && !Main.AllAlivePlayerControls.Any(x => x.Is(CustomRoleTypes.Crewmate))) || (Options.DisableTaskWinIfAllCrewsAreConverted.GetBool() && Main.AllAlivePlayerControls.Where(x => x.Is(Team.Crewmate) && x.GetRoleTypes() is RoleTypes.Crewmate or RoleTypes.Engineer or RoleTypes.Scientist or RoleTypes.CrewmateGhost or RoleTypes.GuardianAngel).All(x => x.IsConverted())) || !CustomGameMode.Standard.IsActiveOrIntegrated()) + if (Options.DisableTaskWin.GetBool() || Options.NoGameEnd.GetBool() || TaskState.InitialTotalTasks == 0 || (Options.DisableTaskWinIfAllCrewsAreDead.GetBool() && !Main.AllAlivePlayerControls.Any(x => x.Is(CustomRoleTypes.Crewmate))) || (Options.DisableTaskWinIfAllCrewsAreConverted.GetBool() && Main.AllAlivePlayerControls.Where(x => x.Is(Team.Crewmate) && x.GetRoleTypes() is RoleTypes.Crewmate or RoleTypes.Engineer or RoleTypes.Scientist or RoleTypes.CrewmateGhost or RoleTypes.GuardianAngel).All(x => x.IsConverted())) || !CustomGameMode.Standard.IsActiveOrIntegrated()) { __result = false; return false; @@ -329,7 +329,7 @@ public static class HauntMenuMinigameSetFilterTextPatch { public static bool Prefix(HauntMenuMinigame __instance) { - if ((__instance.HauntTarget != null) && Options.GhostCanSeeOtherRoles.GetBool() && (!Main.DiedThisRound.Contains(PlayerControl.LocalPlayer.PlayerId) || !Utils.IsRevivingRoleAlive())) + if (__instance.HauntTarget != null && Options.GhostCanSeeOtherRoles.GetBool() && (!Main.DiedThisRound.Contains(PlayerControl.LocalPlayer.PlayerId) || !Utils.IsRevivingRoleAlive())) { byte id = __instance.HauntTarget.PlayerId; __instance.FilterText.text = Utils.GetDisplayRoleName(id) + Utils.GetProgressText(id); @@ -457,7 +457,7 @@ internal static class ShipStatusSerializePatch { if (!AmongUsClient.Instance.AmHost) return; if (initialState) return; - + var cancel = false; foreach (PlayerControl pc in PlayerControl.AllPlayerControls) @@ -468,7 +468,7 @@ internal static class ShipStatusSerializePatch var hudOverrideSystem = __instance.Systems[SystemTypes.Comms].TryCast(); - if ((Options.CurrentGameMode == CustomGameMode.Standard) && hudOverrideSystem is { IsDirty: true }) + if (Options.CurrentGameMode == CustomGameMode.Standard && hudOverrideSystem is { IsDirty: true }) { SerializeHudOverrideSystemV2(hudOverrideSystem); hudOverrideSystem.IsDirty = false; @@ -476,7 +476,7 @@ internal static class ShipStatusSerializePatch var hqHudSystem = __instance.Systems[SystemTypes.Comms].TryCast(); - if ((Options.CurrentGameMode == CustomGameMode.Standard) && hqHudSystem is { IsDirty: true }) + if (Options.CurrentGameMode == CustomGameMode.Standard && hqHudSystem is { IsDirty: true }) { SerializeHqHudSystemV2(hqHudSystem); hqHudSystem.IsDirty = false; @@ -553,7 +553,7 @@ internal static class VentilationSystemDeterioratePatch foreach (NetworkedPlayerInfo playerInfo in GameData.Instance.AllPlayers) { - if ((playerInfo != null) && !playerInfo.Disconnected) + if (playerInfo != null && !playerInfo.Disconnected) AllPlayers.Add(playerInfo); } @@ -620,7 +620,7 @@ internal static class VentilationSystemDeterioratePatch foreach (PlayerControl pc in PlayerControl.AllPlayerControls) { if (pc.AmOwner) continue; - if ((player != null) && (pc != player)) continue; + if (player != null && pc != player) continue; if (BlockVentInteraction(pc)) { @@ -635,7 +635,7 @@ internal static class VentilationSystemDeterioratePatch foreach (NetworkedPlayerInfo playerInfo in GameData.Instance.AllPlayers) { - if ((playerInfo != null) && !playerInfo.Disconnected) + if (playerInfo != null && !playerInfo.Disconnected) AllPlayers.Add(playerInfo); } diff --git a/Patches/TaskAssignPatch.cs b/Patches/TaskAssignPatch.cs index 292b85955..e22e49f6c 100644 --- a/Patches/TaskAssignPatch.cs +++ b/Patches/TaskAssignPatch.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using AmongUs.GameOptions; @@ -106,8 +105,10 @@ internal static class AddTasksFromListPatch List disabledTasks = []; foreach (NormalPlayerTask task in unusedTasks) + { if ((DisableTasksSettings.TryGetValue(task.TaskType, out OptionItem setting) && setting.GetBool()) || IsTaskAlwaysDisabled(task.TaskType)) disabledTasks.Add(task); + } foreach (NormalPlayerTask task in disabledTasks) { diff --git a/Patches/TextBoxPatch.cs b/Patches/TextBoxPatch.cs index 6daa08265..cd41d9b44 100644 --- a/Patches/TextBoxPatch.cs +++ b/Patches/TextBoxPatch.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using HarmonyLib; using TMPro; @@ -7,7 +8,7 @@ using UnityEngine; namespace EHR.Patches; [HarmonyPatch(typeof(TextBoxTMP), nameof(TextBoxTMP.IsCharAllowed))] -static class TextBoxTMPIsCharAllowed +internal static class TextBoxTMPIsCharAllowed { public static bool Prefix(TextBoxTMP __instance, [HarmonyArgument(0)] char i, ref bool __result) { @@ -151,7 +152,7 @@ internal static class TextBoxTMPSetTextPatch string text = "/" + (exactMatch ? inputForm : command.CommandForms.Where(x => x.All(char.IsAscii) && x.StartsWith(inputForm)).MaxBy(x => x.Length)); var info = $"{command.Description}"; - string additionalInfo = string.Empty; + var additionalInfo = string.Empty; if (exactMatch && command.Arguments.Length > 0) { @@ -190,16 +191,15 @@ internal static class TextBoxTMPSetTextPatch if (additionalInfo.Length == 0 && argName.Replace('[', '{').Replace(']', '}') is "{id}" or "{id1}" or "{id2}") { - var allIds = Main.AllPlayerControls.ToDictionary(x => x.PlayerId.ColoredPlayerName(), x => x.PlayerId); + Dictionary allIds = Main.AllPlayerControls.ToDictionary(x => x.PlayerId.ColoredPlayerName(), x => x.PlayerId); additionalInfo = $"{Translator.GetString("PlayerIdList").TrimEnd(' ')}\n{string.Join('\n', allIds.Select(x => $"{x.Key} \uffeb {x.Value}"))}"; OptionShower.CurrentPage = 0; } continue; - bool IsInvalidArg() - { - return arg != argName && argName switch + bool IsInvalidArg() => + arg != argName && argName switch { "{id}" or "{id1}" or "{id2}" => !byte.TryParse(arg, out byte id) || Main.AllPlayerControls.All(x => x.PlayerId != id), "{number}" or "{level}" or "{duration}" or "{number1}" or "{number2}" => !int.TryParse(arg, out int num) || num < 0, @@ -211,11 +211,9 @@ internal static class TextBoxTMPSetTextPatch "{color}" => arg.Length != 6 || !arg.All(x => char.IsDigit(x) || x is >= 'a' and <= 'f') || !ColorUtility.TryParseHtmlString($"#{arg}", out _), _ => false }; - } - bool IsValidArg() - { - return argName switch + bool IsValidArg() => + argName switch { "{id}" or "{id1}" or "{id2}" => byte.TryParse(arg, out byte id) && Main.AllPlayerControls.Any(x => x.PlayerId == id), "{team}" => arg is "crew" or "imp", @@ -225,20 +223,17 @@ internal static class TextBoxTMPSetTextPatch "{color}" => arg.Length == 6 && arg.All(x => char.IsDigit(x) || x is >= 'a' and <= 'f') && ColorUtility.TryParseHtmlString($"#{arg}", out _), _ => false }; - } - string GetExtraArgInfo() - { - return !IsValidArg() + string GetExtraArgInfo() => + !IsValidArg() ? string.Empty : argName switch { "{id}" or "{id1}" or "{id2}" => $" ({byte.Parse(arg).ColoredPlayerName()})", "{role}" or "{addon}" when ChatCommands.GetRoleByName(arg, out CustomRoles role) => $" ({role.ToColoredString()})", - "{color}" when ColorUtility.TryParseHtmlString($"#{arg}", out var color) => $" ({Utils.ColorString(color, "COLOR")})", + "{color}" when ColorUtility.TryParseHtmlString($"#{arg}", out Color color) => $" ({Utils.ColorString(color, "COLOR")})", _ => string.Empty }; - } } } diff --git a/README.md b/README.md index f1530b149..6b6aefbe4 100644 --- a/README.md +++ b/README.md @@ -470,6 +470,7 @@ for your Among Us mod. We are committed to ensuring that your data privacy and s ------------------------------------------------------------------------------------------------------------ #### 2. **Information Collected** + When using this integration, we collect the following non-personal information: - **Lobby Code:** A six-letter code that uniquely identifies a game lobby. @@ -490,6 +491,7 @@ Furthermore, the following information is collected to enhance the user experien ------------------------------------------------------------------------------------------------------------ #### 3. **How Information is Used** + The collected information is used solely for the following purposes: - To notify players about available lobbies via the designated Discord server. @@ -530,11 +532,14 @@ When disabled, no lobby information will be collected or transmitted. ------------------------------------------------------------------------------------------------------------ #### 7. **Changes to this Privacy Policy** -We may update this Privacy Policy from time to time. Any changes will be communicated through an update in the mod or via the official EHR Discord channel. + +We may update this Privacy Policy from time to time. Any changes will be communicated through an update in the mod or +via the official EHR Discord channel. ------------------------------------------------------------------------------------------------------------ #### 8. **Contact Us** + If you have any questions about this Privacy Policy or how your data is handled, please contact us at: **[The EHR Discord Server](https://discord.gg/m3ayxfumC8)** diff --git a/Roles/AddOns/Common/Asthmatic.cs b/Roles/AddOns/Common/Asthmatic.cs index 27c01a25d..334de3b1b 100644 --- a/Roles/AddOns/Common/Asthmatic.cs +++ b/Roles/AddOns/Common/Asthmatic.cs @@ -39,8 +39,15 @@ internal class Asthmatic : IAddon .SetValueFormat(OptionFormat.Seconds); } - private static int RandomRedTime(char _) => IRandom.Instance.Next(MinRedTime, MaxRedTime); - private static int RandomGreenTime(char _) => IRandom.Instance.Next(MinGreenTime, MaxGreenTime); + private static int RandomRedTime(char _) + { + return IRandom.Instance.Next(MinRedTime, MaxRedTime); + } + + private static int RandomGreenTime(char _) + { + return IRandom.Instance.Next(MinGreenTime, MaxGreenTime); + } public static void Init() { @@ -62,8 +69,10 @@ internal class Asthmatic : IAddon 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, RandomRedTime, RandomGreenTime); + } }, 8f, "Add Asthmatic Timers"); } diff --git a/Roles/AddOns/GhostRoles/Bloodmoon.cs b/Roles/AddOns/GhostRoles/Bloodmoon.cs index cf7ca946a..c7b751a71 100644 --- a/Roles/AddOns/GhostRoles/Bloodmoon.cs +++ b/Roles/AddOns/GhostRoles/Bloodmoon.cs @@ -97,13 +97,11 @@ internal class Bloodmoon : IGhostRole (string TextColor, string TimeColor) colors = GetColors(); return string.Format(Translator.GetString("Bloodmoon.Suffix"), timeLeft, colors.TextColor, colors.TimeColor); - (string TextColor, string TimeColor) GetColors() - { - return timeLeft switch + (string TextColor, string TimeColor) GetColors() => + timeLeft switch { > 5 => ("#ffff00", "#ffa500"), _ => ("#ff0000", "#ffff00") }; - } } } \ No newline at end of file diff --git a/Roles/AddOns/Impostor/Circumvent.cs b/Roles/AddOns/Impostor/Circumvent.cs index 69a08206f..047942759 100644 --- a/Roles/AddOns/Impostor/Circumvent.cs +++ b/Roles/AddOns/Impostor/Circumvent.cs @@ -42,8 +42,10 @@ internal class Circumvent : IAddon LateTask.New(() => { foreach (KeyValuePair state in Main.PlayerStates) + { if (state.Value.SubRoles.Contains(CustomRoles.Circumvent)) Limits[state.Key] = Limit.GetInt(); + } }, 3f, "Add Circumvents"); } diff --git a/Roles/AddOns/Impostor/Damocles.cs b/Roles/AddOns/Impostor/Damocles.cs index 0de7a3350..00a693d4b 100644 --- a/Roles/AddOns/Impostor/Damocles.cs +++ b/Roles/AddOns/Impostor/Damocles.cs @@ -99,8 +99,10 @@ public class Damocles : IAddon writer.Write(pev.Count); if (pev.Count > 0) + { foreach (int vent in pev.ToArray()) writer.Write(vent); + } AmongUsClient.Instance.FinishRpcImmediately(writer); } @@ -113,8 +115,10 @@ public class Damocles : IAddon int elements = reader.ReadInt32(); if (elements > 0) + { for (var i = 0; i < elements; i++) PreviouslyEnteredVents[playerId].Add(reader.ReadInt32()); + } } public static void OnMurder(byte id) diff --git a/Roles/AddOns/Impostor/Underdog.cs b/Roles/AddOns/Impostor/Underdog.cs index 921c85248..eafe3ca42 100644 --- a/Roles/AddOns/Impostor/Underdog.cs +++ b/Roles/AddOns/Impostor/Underdog.cs @@ -2,11 +2,10 @@ public class Underdog : IAddon { - public AddonTypes Type => AddonTypes.ImpOnly; - public static OptionItem UnderdogMaximumPlayersNeededToKill; public static OptionItem UnderdogKillCooldownWithMorePlayersAlive; public static OptionItem UnderdogKillCooldownWithLessPlayersAlive; + public AddonTypes Type => AddonTypes.ImpOnly; public void SetupCustomOption() { @@ -15,11 +14,11 @@ public class Underdog : IAddon UnderdogMaximumPlayersNeededToKill = new IntegerOptionItem(651090, "UnderdogMaximumPlayersNeededToKill", new(1, 15, 1), 8, TabGroup.Addons) .SetValueFormat(OptionFormat.Players) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Underdog]); - + UnderdogKillCooldownWithMorePlayersAlive = new IntegerOptionItem(651091, "UnderdogKillCooldownWithMorePlayersAlive", new(0, 90, 1), 30, TabGroup.Addons) .SetValueFormat(OptionFormat.Seconds) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Underdog]); - + UnderdogKillCooldownWithLessPlayersAlive = new IntegerOptionItem(651092, "HitmanLowKCD", new(0, 90, 1), 15, TabGroup.Addons) .SetValueFormat(OptionFormat.Seconds) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Underdog]); diff --git a/Roles/Coven/Banshee.cs b/Roles/Coven/Banshee.cs index 61c379414..9d6990449 100644 --- a/Roles/Coven/Banshee.cs +++ b/Roles/Coven/Banshee.cs @@ -59,8 +59,8 @@ public class Banshee : Coven public override bool OnVanish(PlayerControl pc) { - var radius = Radius.GetFloat(); - var pos = pc.Pos(); + float radius = Radius.GetFloat(); + Vector2 pos = pc.Pos(); IEnumerable nearbyPlayers = Utils.GetPlayersInRadius(radius, pos).Without(pc); if (!HasNecronomicon) ScreechedPlayers = nearbyPlayers.Select(x => x.PlayerId).ToHashSet(); @@ -70,7 +70,7 @@ public class Banshee : Coven { if (Utils.DoRPC) { - var w = Utils.CreateRPC(CustomRPC.SyncRoleData); + MessageWriter w = Utils.CreateRPC(CustomRPC.SyncRoleData); w.Write(BansheeId); w.WritePacked(1); w.WritePacked(ScreechedPlayers.Count); @@ -113,7 +113,7 @@ public class Banshee : Coven public static void OnReceiveChat() { - var screechedPlayers = Instances.SelectMany(x => x.ScreechedPlayers).ToValidPlayers().ToHashSet(); + HashSet screechedPlayers = Instances.SelectMany(x => x.ScreechedPlayers).ToValidPlayers().ToHashSet(); if (screechedPlayers.Count == 0) return; LateTask.New(() => screechedPlayers.Do(ChatManager.ClearChatForSpecificPlayer), Utils.CalculatePingDelay()); diff --git a/Roles/Coven/Coven.cs b/Roles/Coven/Coven.cs index f00e925f0..9de842ce1 100644 --- a/Roles/Coven/Coven.cs +++ b/Roles/Coven/Coven.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System.Collections.Generic; +using System.Linq; using HarmonyLib; namespace EHR.Coven; @@ -20,10 +21,10 @@ public abstract class Coven : RoleBase private static void GiveNecronomicon() { - var psDict = Main.PlayerStates.Where(x => x.Value.Role is Coven { HasNecronomicon: false } coven && coven.NecronomiconReceivePriority != NecronomiconReceivePriorities.Never).ToDictionary(x => x.Key, x => x.Value); + Dictionary psDict = Main.PlayerStates.Where(x => x.Value.Role is Coven { HasNecronomicon: false } coven && coven.NecronomiconReceivePriority != NecronomiconReceivePriorities.Never).ToDictionary(x => x.Key, x => x.Value); if (psDict.Count == 0) return; - var receiver = psDict.Shuffle().OrderBy(x => ((Coven)x.Value.Role).NecronomiconReceivePriority).ThenByDescending(x => !x.Value.IsDead).First(); + KeyValuePair receiver = psDict.Shuffle().OrderBy(x => ((Coven)x.Value.Role).NecronomiconReceivePriority).ThenByDescending(x => !x.Value.IsDead).First(); var covenRole = (Coven)receiver.Value.Role; covenRole.HasNecronomicon = true; @@ -31,7 +32,7 @@ public abstract class Coven : RoleBase LateTask.New(() => { - var holders = Main.PlayerStates.Where(s => s.Value.Role is Coven { HasNecronomicon: true }).Select(s => s.Key.ColoredPlayerName()).ToArray(); + string[] holders = Main.PlayerStates.Where(s => s.Value.Role is Coven { HasNecronomicon: true }).Select(s => s.Key.ColoredPlayerName()).ToArray(); Main.AllPlayerControls.Where(x => x.Is(Team.Coven)).Select(x => x.PlayerId).Without(receiver.Key).Do(x => Utils.SendMessage("\n", x, string.Format(Translator.GetString("PlayerReceivedTheNecronomicon"), receiver.Key.ColoredPlayerName(), Main.CovenColor, holders.Length, string.Join(", ", holders)))); Utils.SendMessage("\n", receiver.Key, string.Format(Translator.GetString("YouReceivedTheNecronomicon"), Main.CovenColor)); }, 12f, log: false); diff --git a/Roles/Coven/CovenLeader.cs b/Roles/Coven/CovenLeader.cs index 083f8faed..6ac5c7696 100644 --- a/Roles/Coven/CovenLeader.cs +++ b/Roles/Coven/CovenLeader.cs @@ -42,7 +42,7 @@ public class CovenLeader : Coven public override void SetKillCooldown(byte id) { - var kcd = Options.CovenLeaderKillCooldown.GetFloat(); + float kcd = Options.CovenLeaderKillCooldown.GetFloat(); Main.AllPlayerKillCooldown[id] = HasNecronomicon ? kcd / 2f : kcd; } diff --git a/Roles/Coven/Dreamweaver.cs b/Roles/Coven/Dreamweaver.cs index ecff98d9e..95b0fb21d 100644 --- a/Roles/Coven/Dreamweaver.cs +++ b/Roles/Coven/Dreamweaver.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using EHR.Modules; using Hazel; @@ -80,14 +81,14 @@ public class Dreamweaver : Coven { if (lowLoad || GameStates.IsMeeting || ExileController.Instance || !Main.IntroDestroyed || !pc.IsAlive() || !pc.Is(CustomRoles.Insane) || Main.KillTimers[pc.PlayerId] > 0f) return; - var pos = pc.Pos(); - var nearbyPlayers = Utils.GetPlayersInRadius(1.5f, pos).Without(pc).ToArray(); + Vector2 pos = pc.Pos(); + PlayerControl[] nearbyPlayers = Utils.GetPlayersInRadius(1.5f, pos).Without(pc).ToArray(); if (nearbyPlayers.Length == 0) return; - var nearestPlayer = nearbyPlayers.MinBy(x => Vector2.Distance(x.Pos(), pos)); + PlayerControl nearestPlayer = nearbyPlayers.MinBy(x => Vector2.Distance(x.Pos(), pos)); RoleBase roleBase = Main.PlayerStates[pc.PlayerId].Role; - var type = roleBase.GetType(); + Type type = roleBase.GetType(); if (type.GetMethod("OnCheckMurder")?.DeclaringType == type) { diff --git a/Roles/Coven/Illusionist.cs b/Roles/Coven/Illusionist.cs index 3b57efa43..f5accbc76 100644 --- a/Roles/Coven/Illusionist.cs +++ b/Roles/Coven/Illusionist.cs @@ -79,7 +79,7 @@ public class Illusionist : Coven public override bool OnShapeshift(PlayerControl shapeshifter, PlayerControl target, bool shapeshifting) { - var sampledPlayer = SampledPlayerId.GetPlayer(); + PlayerControl sampledPlayer = SampledPlayerId.GetPlayer(); if (sampledPlayer == null) return false; bool shouldAnimate = ShapeshiftAnimation.GetBool(); diff --git a/Roles/Coven/Poache.cs b/Roles/Coven/Poache.cs index 03d5b3d89..9e93ed2d4 100644 --- a/Roles/Coven/Poache.cs +++ b/Roles/Coven/Poache.cs @@ -69,7 +69,7 @@ public class Poache : Coven public override void OnGlobalFixedUpdate(PlayerControl pc, bool lowLoad) { - if (lowLoad || GameStates.IsMeeting || ExileController.Instance || !Main.IntroDestroyed || !pc.IsAlive() || !KillDelays.FindFirst(x => x.ID == pc.PlayerId, out var killData) || Utils.TimeStamp < killData.KillTimeStamp) return; + if (lowLoad || GameStates.IsMeeting || ExileController.Instance || !Main.IntroDestroyed || !pc.IsAlive() || !KillDelays.FindFirst(x => x.ID == pc.PlayerId, out (byte ID, long KillTimeStamp) killData) || Utils.TimeStamp < killData.KillTimeStamp) return; pc.Suicide(realKiller: PoacheId.GetPlayer()); KillDelays.Remove(killData); diff --git a/Roles/Coven/PotionMaster.cs b/Roles/Coven/PotionMaster.cs index 5d08297ea..d184e4ebc 100644 --- a/Roles/Coven/PotionMaster.cs +++ b/Roles/Coven/PotionMaster.cs @@ -106,7 +106,7 @@ public class PotionMaster : Coven toRemove.ForEach(x => { ShieldedPlayers.Remove(x); - var player = x.GetPlayer(); + PlayerControl player = x.GetPlayer(); Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: player); Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); Utils.SendRPC(CustomRPC.SyncRoleData, PotionMasterId, 2, x); @@ -114,7 +114,7 @@ public class PotionMaster : Coven foreach (byte shieldedId in ShieldedPlayers.Keys) { - var player = shieldedId.GetPlayer(); + PlayerControl player = shieldedId.GetPlayer(); Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: player); Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); } @@ -126,7 +126,10 @@ public class PotionMaster : Coven return seer.Is(Team.Coven) && RevealedPlayers.Contains(target.PlayerId); } - public static bool OnAnyoneCheckMurder(PlayerControl target) => !Instances.Any(x => x.ShieldedPlayers.ContainsKey(target.PlayerId)); + public static bool OnAnyoneCheckMurder(PlayerControl target) + { + return !Instances.Any(x => x.ShieldedPlayers.ContainsKey(target.PlayerId)); + } public void ReceiveRPC(MessageReader reader) { @@ -145,7 +148,7 @@ public class PotionMaster : Coven { if (seer.PlayerId == target.PlayerId && seer.IsModdedClient() && !hud) return string.Empty; if (seer.PlayerId != target.PlayerId && seer.PlayerId != PotionMasterId) return string.Empty; - if (!ShieldedPlayers.TryGetValue(target.PlayerId, out var shieldExpireTS)) return string.Empty; + if (!ShieldedPlayers.TryGetValue(target.PlayerId, out long shieldExpireTS)) return string.Empty; return string.Format(Translator.GetString("PotionMaster.Suffix"), shieldExpireTS - Utils.TimeStamp, Main.CovenColor); } diff --git a/Roles/Coven/SpellCaster.cs b/Roles/Coven/SpellCaster.cs index 9789e067e..c15980d59 100644 --- a/Roles/Coven/SpellCaster.cs +++ b/Roles/Coven/SpellCaster.cs @@ -116,7 +116,7 @@ public class SpellCaster : Coven LateTask.New(() => { - var spellCasterStr = CustomRoles.SpellCaster.ToColoredString(); + string spellCasterStr = CustomRoles.SpellCaster.ToColoredString(); Utils.SendMessage(string.Format(Translator.GetString("SpellCaster.WinConditionMet"), spellCasterStr), byte.MaxValue, diff --git a/Roles/Coven/VoodooMaster.cs b/Roles/Coven/VoodooMaster.cs index 074de6edc..bfd9ec99f 100644 --- a/Roles/Coven/VoodooMaster.cs +++ b/Roles/Coven/VoodooMaster.cs @@ -1,4 +1,6 @@ -namespace EHR.Coven; +using System; + +namespace EHR.Coven; public class VoodooMaster : Coven { @@ -53,7 +55,7 @@ public class VoodooMaster : Coven if (killer.GetAbilityUseLimit() > 0) { RoleBase roleBase = Main.PlayerStates[target.PlayerId].Role; - var type = roleBase.GetType(); + Type type = roleBase.GetType(); if (type.GetMethod("OnCheckMurder")?.DeclaringType == type) roleBase.OnCheckMurder(target, target); else if (type.GetMethod("OnPet")?.DeclaringType == type) roleBase.OnPet(target); diff --git a/Roles/Crewmate/Alchemist.cs b/Roles/Crewmate/Alchemist.cs index 30293a707..15d27bfc2 100644 --- a/Roles/Crewmate/Alchemist.cs +++ b/Roles/Crewmate/Alchemist.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Linq; using AmongUs.GameOptions; -using AsmResolver.PE.DotNet.Metadata.Tables; using EHR.Modules; using EHR.Neutral; using Hazel; @@ -303,10 +302,10 @@ public class Alchemist : RoleBase { case < 0: var sender = CustomRpcSender.Create("RpcExitVentDesync", SendOption.Reliable); - var ventId = ventedId == -10 ? Main.LastEnteredVent[player.PlayerId].Id : ventedId; - var hasValue = Main.AllPlayerControls.Where(pc => player.PlayerId != pc.PlayerId).Aggregate(false, (current, pc) => current || sender.RpcExitVentDesync(player.MyPhysics, ventId, pc)); - sender.SendMessage(dispose: !hasValue); - + int ventId = ventedId == -10 ? Main.LastEnteredVent[player.PlayerId].Id : ventedId; + bool hasValue = Main.AllPlayerControls.Where(pc => player.PlayerId != pc.PlayerId).Aggregate(false, (current, pc) => current || sender.RpcExitVentDesync(player.MyPhysics, ventId, pc)); + sender.SendMessage(!hasValue); + player.Notify(GetString("SwooperInvisStateOut")); SendRPC(); refresh = true; diff --git a/Roles/Crewmate/Ankylosaurus.cs b/Roles/Crewmate/Ankylosaurus.cs index be98a8116..e9adc41c7 100644 --- a/Roles/Crewmate/Ankylosaurus.cs +++ b/Roles/Crewmate/Ankylosaurus.cs @@ -8,14 +8,14 @@ public class Ankylosaurus : RoleBase { public static bool On; - public override bool IsEnable => On; - private static OptionItem Speed; private static OptionItem Vision; private static OptionItem Lives; private int LivesLeft; + public override bool IsEnable => On; + public override void SetupCustomOption() { StartSetup(647100) @@ -39,7 +39,7 @@ public class Ankylosaurus : RoleBase { Main.AllPlayerSpeed[playerId] = Speed.GetFloat(); - var vision = Vision.GetFloat(); + float vision = Vision.GetFloat(); opt.SetFloat(FloatOptionNames.CrewLightMod, vision); opt.SetFloat(FloatOptionNames.ImpostorLightMod, vision); } diff --git a/Roles/Crewmate/Chef.cs b/Roles/Crewmate/Chef.cs index 5c32b1950..dafc4abd5 100644 --- a/Roles/Crewmate/Chef.cs +++ b/Roles/Crewmate/Chef.cs @@ -253,16 +253,14 @@ public class Chef : RoleBase return string.Empty; - string GetEventString(PlayerEvent e) - { - return e switch + string GetEventString(PlayerEvent e) => + e switch { IncreasedSpeedEvent => Translator.GetString("ChefBoost.Speed"), IncreasedVisionEvent => Translator.GetString("ChefBoost.Vision"), ShieldEvent => Translator.GetString("ChefBoost.Shield"), _ => string.Empty }; - } } private abstract class PlayerEvent diff --git a/Roles/Crewmate/CopyCat.cs b/Roles/Crewmate/CopyCat.cs index ea4b2c0e8..e22e3da19 100644 --- a/Roles/Crewmate/CopyCat.cs +++ b/Roles/Crewmate/CopyCat.cs @@ -138,7 +138,7 @@ public class CopyCat : RoleBase sender.SetKillCooldown(pc); sender.Notify(pc, string.Format(GetString("CopyCatRoleChange"), Utils.GetRoleName(role))); sender.SendMessage(); - + pc.SyncSettings(); return false; } diff --git a/Roles/Crewmate/CyberStar.cs b/Roles/Crewmate/CyberStar.cs index 1ac20d661..1ac1f03f4 100644 --- a/Roles/Crewmate/CyberStar.cs +++ b/Roles/Crewmate/CyberStar.cs @@ -15,7 +15,7 @@ internal class CyberStar : RoleBase NeutralKnowCyberStarDead = new BooleanOptionItem(5304, "NeutralKnowCyberStarDead", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.CyberStar]); - + CovenKnowCyberStarDead = new BooleanOptionItem(5305, "CovenKnowCyberStarDead", false, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.CyberStar]); } @@ -23,4 +23,4 @@ internal class CyberStar : RoleBase public override void Init() { } public override void Add(byte playerId) { } -} +} \ No newline at end of file diff --git a/Roles/Crewmate/Demolitionist.cs b/Roles/Crewmate/Demolitionist.cs index a7f4f45e5..ab8ebab18 100644 --- a/Roles/Crewmate/Demolitionist.cs +++ b/Roles/Crewmate/Demolitionist.cs @@ -26,7 +26,7 @@ internal class Demolitionist : RoleBase public static void OnDeath(PlayerControl killer, PlayerControl target) { - var warningMark = Utils.ColorString(Color.yellow, "\u26a0"); + string warningMark = Utils.ColorString(Color.yellow, "\u26a0"); killer.Notify($"{warningMark} {Utils.ColorString(Utils.GetRoleColor(CustomRoles.Demolitionist), Translator.GetString("OnDemolitionistDead"))} {warningMark}"); killer.KillFlash(); diff --git a/Roles/Crewmate/Deputy.cs b/Roles/Crewmate/Deputy.cs index 1dc0d9b17..65a8b34d4 100644 --- a/Roles/Crewmate/Deputy.cs +++ b/Roles/Crewmate/Deputy.cs @@ -91,10 +91,10 @@ public class Deputy : RoleBase var sender = CustomRpcSender.Create("Deputy.OnCheckMurder", SendOption.Reliable); sender.SetKillCooldown(target, DeputyHandcuffCDForTarget.GetFloat()); sender.Notify(target, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Deputy), GetString("HandcuffedByDeputy"))); - + if (target.IsModdedClient()) sender.RpcResetAbilityCooldown(target); else sender.RpcGuardAndKill(target, target); - + sender.SendMessage(); } }, DeputyHandcuffDelay.GetInt(), "DeputyHandcuffDelay"); diff --git a/Roles/Crewmate/Divinator.cs b/Roles/Crewmate/Divinator.cs index f35f366e3..5b399e9d9 100644 --- a/Roles/Crewmate/Divinator.cs +++ b/Roles/Crewmate/Divinator.cs @@ -52,7 +52,7 @@ public class Divinator : RoleBase AbilityChargesWhenFinishedTasks = new FloatOptionItem(Id + 16, "AbilityChargesWhenFinishedTasks", new(0f, 5f, 0.05f), 0.2f, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Divinator]) .SetValueFormat(OptionFormat.Times); - + NumRolesListedForEachPlayer = new IntegerOptionItem(Id + 17, "NumRolesListedForEachPlayer", new(1, 10, 1), 5, TabGroup.CrewmateRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Divinator]); diff --git a/Roles/Crewmate/DonutDelivery.cs b/Roles/Crewmate/DonutDelivery.cs index fbe611da3..35ba830b8 100644 --- a/Roles/Crewmate/DonutDelivery.cs +++ b/Roles/Crewmate/DonutDelivery.cs @@ -144,8 +144,10 @@ public class DonutDelivery : RoleBase 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/Enigma.cs b/Roles/Crewmate/Enigma.cs index 184d7c918..8f1430eb6 100644 --- a/Roles/Crewmate/Enigma.cs +++ b/Roles/Crewmate/Enigma.cs @@ -414,8 +414,8 @@ public class Enigma : RoleBase public override string GetMessage(PlayerControl killer, bool showStageClue) { CustomRoles role = killer.GetCustomRole(); - - string str = "EnigmaClueRole3"; + + var str = "EnigmaClueRole3"; if (role.IsImpostor()) str = "EnigmaClueRole1"; if (role.IsNeutral()) str = "EnigmaClueRole2"; if (role.IsCoven()) str = "EnigmaClueRole4"; diff --git a/Roles/Crewmate/Inquirer.cs b/Roles/Crewmate/Inquirer.cs index b989b0732..c260c8f2c 100644 --- a/Roles/Crewmate/Inquirer.cs +++ b/Roles/Crewmate/Inquirer.cs @@ -36,4 +36,4 @@ public class Inquirer : RoleBase { playerId.SetAbilityUseLimit(AbilityUseLimit.GetInt()); } -} +} \ No newline at end of file diff --git a/Roles/Crewmate/Judge.cs b/Roles/Crewmate/Judge.cs index bd79f22cb..bd8610efe 100644 --- a/Roles/Crewmate/Judge.cs +++ b/Roles/Crewmate/Judge.cs @@ -350,4 +350,4 @@ public class Judge : RoleBase CreateJudgeButton(__instance); } } -} +} \ No newline at end of file diff --git a/Roles/Crewmate/Lookout.cs b/Roles/Crewmate/Lookout.cs index 0af0c7a14..ecb5ba6e8 100644 --- a/Roles/Crewmate/Lookout.cs +++ b/Roles/Crewmate/Lookout.cs @@ -28,8 +28,10 @@ internal class Lookout : RoleBase var sb = new StringBuilder(); for (var i = 0; i < aapc.Length; i++) + { if (i % 3 == 0) sb.AppendLine(); + } for (var i = 0; i < aapc.Length; i++) { diff --git a/Roles/Crewmate/Lyncher.cs b/Roles/Crewmate/Lyncher.cs index f79567996..d11a921f7 100644 --- a/Roles/Crewmate/Lyncher.cs +++ b/Roles/Crewmate/Lyncher.cs @@ -72,10 +72,7 @@ public class Lyncher : RoleBase return; - void Action() - { - KnownCharacters = AllRoleNames.ToDictionary(x => x.Key, _ => new List()); - } + void Action() => KnownCharacters = AllRoleNames.ToDictionary(x => x.Key, _ => new List()); } public override void Remove(byte playerId) diff --git a/Roles/Crewmate/Mathematician.cs b/Roles/Crewmate/Mathematician.cs index 974b1d420..0b295a62d 100644 --- a/Roles/Crewmate/Mathematician.cs +++ b/Roles/Crewmate/Mathematician.cs @@ -42,10 +42,7 @@ internal class Mathematician : RoleBase ChatManager.SendPreviousMessagesToAll(); LateTask.New(() => Utils.SendMessage(question, title: Translator.GetString("Mathematician")), 0.2f, log: false); } - catch (Exception e) - { - Utils.ThrowException(e); - } + catch (Exception e) { Utils.ThrowException(e); } } public static void Reply(PlayerControl pc, string answerStr) @@ -65,10 +62,7 @@ internal class Mathematician : RoleBase Achievements.Type.TheBestInSchool.Complete(); } } - catch (Exception e) - { - Utils.ThrowException(e); - } + catch (Exception e) { Utils.ThrowException(e); } } public override void OnReportDeadBody() diff --git a/Roles/Crewmate/Medic.cs b/Roles/Crewmate/Medic.cs index 9aae89d85..41477bbeb 100644 --- a/Roles/Crewmate/Medic.cs +++ b/Roles/Crewmate/Medic.cs @@ -239,7 +239,7 @@ public class Medic : RoleBase Utils.NotifyRoles(SpecifySeer: killer, SpecifyTarget: target); } } - + sender.SendMessage(); if (killer.IsLocalPlayer()) @@ -260,8 +260,10 @@ public class Medic : RoleBase if (notify) { foreach (byte id in PlayerIdList) + { foreach (byte id2 in ProtectList) Utils.NotifyRoles(SpecifySeer: Utils.GetPlayerById(id), SpecifyTarget: Utils.GetPlayerById(id2)); + } } } diff --git a/Roles/Crewmate/Merchant.cs b/Roles/Crewmate/Merchant.cs index 96fcbad68..d55e9a84b 100644 --- a/Roles/Crewmate/Merchant.cs +++ b/Roles/Crewmate/Merchant.cs @@ -121,8 +121,8 @@ internal class Merchant : RoleBase && (Cleanser.CleansedCanGetAddon.GetBool() || (!Cleanser.CleansedCanGetAddon.GetBool() && !x.Is(CustomRoles.Cleansed))) && ((OptionCanTargetCrew.GetBool() && x.IsCrewmate()) || (OptionCanTargetImpostor.GetBool() && x.GetCustomRole().IsImpostor()) || - (OptionCanTargetNeutral.GetBool() && (x.GetCustomRole().IsNeutral() || x.IsNeutralKiller()) || - (OptionCanTargetCoven.GetBool() && x.Is(Team.Coven)))) + (OptionCanTargetNeutral.GetBool() && (x.GetCustomRole().IsNeutral() || x.IsNeutralKiller())) || + (OptionCanTargetCoven.GetBool() && x.Is(Team.Coven))) ).ToList(); if (availableTargets.Count <= 0) return; diff --git a/Roles/Crewmate/Monarch.cs b/Roles/Crewmate/Monarch.cs index f97eccabf..68d6cfd4c 100644 --- a/Roles/Crewmate/Monarch.cs +++ b/Roles/Crewmate/Monarch.cs @@ -76,7 +76,7 @@ public class Monarch : RoleBase { killer.RpcRemoveAbilityUse(); target.RpcSetCustomRole(CustomRoles.Knighted); - + var sender = CustomRpcSender.Create("Monarch.OnCheckMurder", SendOption.Reliable); sender.Notify(killer, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Monarch), GetString("MonarchKnightedPlayer")), setName: false); @@ -87,9 +87,9 @@ public class Monarch : RoleBase sender.RpcGuardAndKill(target, killer); sender.RpcGuardAndKill(target, target); - + sender.SendMessage(); - + Utils.NotifyRoles(SpecifySeer: killer, SpecifyTarget: target); Utils.NotifyRoles(SpecifySeer: target, SpecifyTarget: killer); diff --git a/Roles/Crewmate/Negotiator.cs b/Roles/Crewmate/Negotiator.cs index c4ad48783..6a97bd146 100644 --- a/Roles/Crewmate/Negotiator.cs +++ b/Roles/Crewmate/Negotiator.cs @@ -50,7 +50,7 @@ public class Negotiator : RoleBase Instances.Add(this); NegotiatorId = playerId; TargetId = byte.MaxValue; - Penalty = default; + Penalty = default(NegotiationType); PermanentPenalties = []; playerId.SetAbilityUseLimit(AbilityUseLimit.GetInt()); } @@ -102,7 +102,7 @@ public class Negotiator : RoleBase 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(CustomRoles)) target.RpcSetCustomRole(addon); break; case NegotiationType.LowVision: diff --git a/Roles/Crewmate/Oracle.cs b/Roles/Crewmate/Oracle.cs index b97066e83..d9e766d69 100644 --- a/Roles/Crewmate/Oracle.cs +++ b/Roles/Crewmate/Oracle.cs @@ -85,7 +85,7 @@ public class Oracle : RoleBase return false; } - var team = target.GetTeam(); + Team team = target.GetTeam(); if (IRandom.Instance.Next(100) < FailChance.GetInt()) team = Enum.GetValues().Without(team).RandomElement(); diff --git a/Roles/Crewmate/Psychic.cs b/Roles/Crewmate/Psychic.cs index b5d84f061..502d8e1b1 100644 --- a/Roles/Crewmate/Psychic.cs +++ b/Roles/Crewmate/Psychic.cs @@ -122,8 +122,10 @@ public class Psychic : RoleBase 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); diff --git a/Roles/Crewmate/Randomizer.cs b/Roles/Crewmate/Randomizer.cs index 86189b511..a72133501 100644 --- a/Roles/Crewmate/Randomizer.cs +++ b/Roles/Crewmate/Randomizer.cs @@ -224,8 +224,10 @@ internal static class EffectExtenstions 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); diff --git a/Roles/Crewmate/SabotageMaster.cs b/Roles/Crewmate/SabotageMaster.cs index a06220927..8645855f8 100644 --- a/Roles/Crewmate/SabotageMaster.cs +++ b/Roles/Crewmate/SabotageMaster.cs @@ -122,7 +122,7 @@ public class SabotageMaster : RoleBase public override void OnPet(PlayerControl pc) { SystemTypes[] systemTypes = [SystemTypes.Electrical, SystemTypes.Reactor, SystemTypes.Laboratory, SystemTypes.LifeSupp, SystemTypes.HeliSabotage, SystemTypes.Comms]; - if (!CanFixSabotageFromAnywhereWithPet.GetBool() || !systemTypes.FindFirst(Utils.IsActive, out var activeSystem) || PetLimit-- < 1) return; + if (!CanFixSabotageFromAnywhereWithPet.GetBool() || !systemTypes.FindFirst(Utils.IsActive, out SystemTypes activeSystem) || PetLimit-- < 1) return; switch (activeSystem) { @@ -288,8 +288,10 @@ public class SabotageMaster : RoleBase SystemTypes room = openedDoor.Room; foreach (OpenableDoor door in shipStatus.AllDoors) + { if (door.Id != openedDoorId && door.Room == room) door.SetDoorway(true); + } } break; diff --git a/Roles/Crewmate/Sentinel.cs b/Roles/Crewmate/Sentinel.cs index 75b269b14..8921979ba 100644 --- a/Roles/Crewmate/Sentinel.cs +++ b/Roles/Crewmate/Sentinel.cs @@ -9,8 +9,8 @@ namespace EHR.Crewmate; public class PatrollingState(byte sentinelId, int patrolDuration, float patrolRadius, PlayerControl sentinel = null, bool isPatrolling = false, Vector2? startingPosition = null, long patrolStartTimeStamp = 0) { + private readonly Dictionary LastPostitionCheck = []; private List LastNearbyKillers = []; - private Dictionary LastPostitionCheck = []; private long LastUpdate; public byte SentinelId => sentinelId; @@ -75,7 +75,7 @@ public class PatrollingState(byte sentinelId, int patrolDuration, float patrolRa long timeLeft = PatrolDuration - (TimeStamp - PatrolStartTimeStamp); if (wasInRange && !nowInRange) pc.Notify(GetString("KillerEscapedFromSentinel")); - if (nowInRange && timeLeft >= 0) pc.Notify(string.Format(GetString("KillerNotifyPatrol"), timeLeft), 3f, overrideAll: true); + if (nowInRange && timeLeft >= 0) pc.Notify(string.Format(GetString("KillerNotifyPatrol"), timeLeft), 3f, true); LastNearbyKillers = killers.Select(x => x.PlayerId).ToList(); } @@ -207,8 +207,10 @@ internal class Sentinel : RoleBase 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 3d3d56eda..820ddff42 100644 --- a/Roles/Crewmate/Sentry.cs +++ b/Roles/Crewmate/Sentry.cs @@ -160,13 +160,10 @@ internal class Sentry : RoleBase if (players.Length == 0) players = noDataString; if (bodies.Length == 0) bodies = noDataString; - pc.Notify(string.Format(Translator.GetString("Sentry.Notify.Info"), roomName, players, bodies), ShowInfoDuration.GetInt(), overrideAll: fromDevice); + pc.Notify(string.Format(Translator.GetString("Sentry.Notify.Info"), roomName, players, bodies), ShowInfoDuration.GetInt(), fromDevice); return; - static string GetColoredNames(IEnumerable ids) - { - return ids.Where(x => Utils.GetPlayerById(x) != null).Select(x => Utils.ColorString(Main.PlayerColors[x], Utils.GetPlayerById(x).GetRealName())).Join(); - } + static string GetColoredNames(IEnumerable ids) => ids.Where(x => Utils.GetPlayerById(x) != null).Select(x => Utils.ColorString(Main.PlayerColors[x], Utils.GetPlayerById(x).GetRealName())).Join(); } private bool IsInMonitoredRoom(PlayerControl pc) @@ -194,8 +191,10 @@ internal class Sentry : RoleBase 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) diff --git a/Roles/Crewmate/Snitch.cs b/Roles/Crewmate/Snitch.cs index 33779f88a..5bdd86407 100644 --- a/Roles/Crewmate/Snitch.cs +++ b/Roles/Crewmate/Snitch.cs @@ -131,8 +131,10 @@ public class Snitch : RoleBase TargetArrow.Add(snitchId, targetId); if (TargetList.Add(targetId)) + { if (CanGetColoredArrow) TargetColorlist.Add(targetId, target.GetRoleColor()); + } Utils.NotifyRoles(SpecifySeer: snitch, SpecifyTarget: target); } diff --git a/Roles/Crewmate/Speedrunner.cs b/Roles/Crewmate/Speedrunner.cs index ea3dc15c7..477abac66 100644 --- a/Roles/Crewmate/Speedrunner.cs +++ b/Roles/Crewmate/Speedrunner.cs @@ -72,8 +72,10 @@ internal class Speedrunner : RoleBase LateTask.New(() => { foreach (PlayerControl pc in Main.AllAlivePlayerControls) + { if (!pc.Is(Team.Crewmate)) Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); + } }, 0.1f, log: false); } } diff --git a/Roles/Crewmate/Spiritualist.cs b/Roles/Crewmate/Spiritualist.cs index 369b2b3f4..ace4f3f01 100644 --- a/Roles/Crewmate/Spiritualist.cs +++ b/Roles/Crewmate/Spiritualist.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Linq; +using Hazel; using static EHR.Options; using static EHR.Translator; @@ -99,7 +100,7 @@ internal class Spiritualist : RoleBase TargetArrow.Add(spiritualist, target.PlayerId); - var writer = CustomRpcSender.Create("SpiritualistSendMessage", Hazel.SendOption.Reliable); + var writer = CustomRpcSender.Create("SpiritualistSendMessage", SendOption.Reliable); writer.StartMessage(target.GetClientId()); writer.StartRpc(target.NetId, (byte)RpcCalls.SetName) diff --git a/Roles/Crewmate/Telekinetic.cs b/Roles/Crewmate/Telekinetic.cs index 82a433b23..fdb6b6ccc 100644 --- a/Roles/Crewmate/Telekinetic.cs +++ b/Roles/Crewmate/Telekinetic.cs @@ -57,7 +57,7 @@ public class Telekinetic : RoleBase { On = true; TelekineticPC = Utils.GetPlayerById(playerId); - CurrentMode = default; + CurrentMode = default(Mode); Timer = 40; } diff --git a/Roles/Crewmate/TimeMaster.cs b/Roles/Crewmate/TimeMaster.cs index 359b21f4e..d29578bba 100644 --- a/Roles/Crewmate/TimeMaster.cs +++ b/Roles/Crewmate/TimeMaster.cs @@ -122,7 +122,7 @@ internal class TimeMaster : RoleBase foreach ((byte playerId, Vector2 pos) in track) { - var player = playerId.GetPlayer(); + PlayerControl player = playerId.GetPlayer(); if (player == null || !player.IsAlive()) continue; player.TP(pos); @@ -133,7 +133,7 @@ internal class TimeMaster : RoleBase foreach (DeadBody deadBody in Object.FindObjectsOfType()) { - if (!Main.PlayerStates.TryGetValue(deadBody.ParentId, out var ps)) continue; + if (!Main.PlayerStates.TryGetValue(deadBody.ParentId, out PlayerState ps)) continue; if (ps.RealKiller.TimeStamp.AddSeconds(length) >= DateTime.Now) { diff --git a/Roles/Crewmate/Wizard.cs b/Roles/Crewmate/Wizard.cs index 34ac5ed81..fa01102da 100644 --- a/Roles/Crewmate/Wizard.cs +++ b/Roles/Crewmate/Wizard.cs @@ -111,7 +111,7 @@ public class Wizard : RoleBase }; PlayerBuffs = []; - SelectedBuff = default; + SelectedBuff = default(Buff); TaskMode = false; Count = 0; playerId.SetAbilityUseLimit(AbilityUseLimit.GetInt()); @@ -178,7 +178,7 @@ public class Wizard : RoleBase public override void OnPet(PlayerControl pc) { if (SelectedBuff == Buff.KCD) - SelectedBuff = default; + SelectedBuff = default(Buff); else SelectedBuff++; @@ -285,16 +285,14 @@ public class Wizard : RoleBase return string.Format(Translator.GetString("Wizard.SelectedBuff"), SelectedBuff, BuffValues[SelectedBuff], GetBuffFormat(SelectedBuff)); - string GetBuffFormat(Buff buff) - { - return buff switch + string GetBuffFormat(Buff buff) => + buff switch { Buff.Speed => "x", Buff.Vision => "x", Buff.KCD => "s", _ => throw new ArgumentOutOfRangeException(nameof(buff), buff, "Invalid buff") }; - } } private enum Buff diff --git a/Roles/Impostor/Abyssbringer.cs b/Roles/Impostor/Abyssbringer.cs index 25df04910..2a835554a 100644 --- a/Roles/Impostor/Abyssbringer.cs +++ b/Roles/Impostor/Abyssbringer.cs @@ -191,10 +191,7 @@ public class Abyssbringer : RoleBase Notify(); } - void Notify() - { - Utils.NotifyRoles(SpecifySeer: abyssbringer, SpecifyTarget: abyssbringer); - } + void Notify() => Utils.NotifyRoles(SpecifySeer: abyssbringer, SpecifyTarget: abyssbringer); } } diff --git a/Roles/Impostor/AntiAdminer.cs b/Roles/Impostor/AntiAdminer.cs index 99350982d..f9c36e6ce 100644 --- a/Roles/Impostor/AntiAdminer.cs +++ b/Roles/Impostor/AntiAdminer.cs @@ -148,7 +148,7 @@ internal class AntiAdminer : RoleBase Count = notify || ExtraAbilityStartTimeStamp > 0 ? 1 : 5; - var oldPlayersNearDevices = PlayersNearDevices.ToDictionary(x => x.Key, x => x.Value); + Dictionary> oldPlayersNearDevices = PlayersNearDevices.ToDictionary(x => x.Key, x => x.Value); PlayersNearDevices = []; bool Admin = false, Camera = false, DoorLog = false, Vital = false; float usableDistance = DisableDevice.UsableDistance; @@ -285,7 +285,7 @@ internal class AntiAdminer : RoleBase IsCameraWatch = Camera; } - if (IsMonitor) notify |= oldPlayersNearDevices.Count != PlayersNearDevices.Count || oldPlayersNearDevices.Any(x => !PlayersNearDevices.TryGetValue(x.Key, out var c) || !x.Value.SetEquals(c)); + if (IsMonitor) notify |= oldPlayersNearDevices.Count != PlayersNearDevices.Count || oldPlayersNearDevices.Any(x => !PlayersNearDevices.TryGetValue(x.Key, out HashSet c) || !x.Value.SetEquals(c)); if (notify || change) Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); @@ -295,7 +295,7 @@ internal class AntiAdminer : RoleBase { if (Main.PlayerStates[id].MainRole is CustomRoles.Monitor or CustomRoles.AntiAdminer) return; - if (!PlayersNearDevices.TryGetValue(id, out var devices)) + if (!PlayersNearDevices.TryGetValue(id, out HashSet devices)) PlayersNearDevices[id] = [device]; else devices.Add(device); } diff --git a/Roles/Impostor/Assassin.cs b/Roles/Impostor/Assassin.cs index 8d4724555..d331368d9 100644 --- a/Roles/Impostor/Assassin.cs +++ b/Roles/Impostor/Assassin.cs @@ -113,7 +113,7 @@ internal class Assassin : RoleBase public override bool CanUseKillButton(PlayerControl pc) { if (pc == null || !pc.IsAlive()) return false; - return CanKillAfterAssassinate || (!pc.IsShifted() && ((pc.Data.Role as PhantomRole) is null or { IsInvisible: false })); + return CanKillAfterAssassinate || (!pc.IsShifted() && (pc.Data.Role as PhantomRole) is null or { IsInvisible: false }); } public override bool OnCheckMurder(PlayerControl killer, PlayerControl target) diff --git a/Roles/Impostor/Assumer.cs b/Roles/Impostor/Assumer.cs index c058c9a07..51c459649 100644 --- a/Roles/Impostor/Assumer.cs +++ b/Roles/Impostor/Assumer.cs @@ -72,8 +72,10 @@ public class Assumer : RoleBase 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); + } } instance.Assumption = (byte.MaxValue, 0); diff --git a/Roles/Impostor/Bard.cs b/Roles/Impostor/Bard.cs index 2bdb520b4..7cb2a3a94 100644 --- a/Roles/Impostor/Bard.cs +++ b/Roles/Impostor/Bard.cs @@ -23,14 +23,8 @@ public class Bard : RoleBase { BardCreations++; - try - { - name = ModUpdater.Get("https://v1.hitokoto.cn/?encode=text"); - } - catch - { - name = Translator.GetString("ByBardGetFailed"); - } + try { name = ModUpdater.Get("https://v1.hitokoto.cn/?encode=text"); } + catch { name = Translator.GetString("ByBardGetFailed"); } name += "\n\t\t——" + Translator.GetString("ByBard"); } diff --git a/Roles/Impostor/Blackmailer.cs b/Roles/Impostor/Blackmailer.cs index bb2568748..a0a434351 100644 --- a/Roles/Impostor/Blackmailer.cs +++ b/Roles/Impostor/Blackmailer.cs @@ -100,10 +100,7 @@ internal class Blackmailer : RoleBase x.VotedFor = bmVotedFor; }); } - finally - { - CheckForEndVotingPatch.RunRoleCode = true; - } + finally { CheckForEndVotingPatch.RunRoleCode = true; } } public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) diff --git a/Roles/Impostor/Bomber.cs b/Roles/Impostor/Bomber.cs index 2a84d4577..3f8be85c3 100644 --- a/Roles/Impostor/Bomber.cs +++ b/Roles/Impostor/Bomber.cs @@ -143,7 +143,7 @@ internal class Bomber : RoleBase float radius = IsNuker ? NukeRadius.GetFloat() : BomberRadius.GetFloat(); - int murderCount = 0; + var murderCount = 0; foreach (PlayerControl tg in Main.AllPlayerControls) { diff --git a/Roles/Impostor/Cantankerous.cs b/Roles/Impostor/Cantankerous.cs index 8e229e404..15fee1926 100644 --- a/Roles/Impostor/Cantankerous.cs +++ b/Roles/Impostor/Cantankerous.cs @@ -62,8 +62,10 @@ public class Cantankerous : RoleBase 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) diff --git a/Roles/Impostor/Changeling.cs b/Roles/Impostor/Changeling.cs index 7ff373e85..136429909 100644 --- a/Roles/Impostor/Changeling.cs +++ b/Roles/Impostor/Changeling.cs @@ -18,7 +18,7 @@ internal class Changeling : RoleBase private static readonly string[] AvailableRolesMode = [ "CL.All", // 0 - "CL.Enabled", // 1 + "CL.Enabled" // 1 ]; private static List Roles = []; @@ -123,4 +123,4 @@ internal class Changeling : RoleBase { return seer.PlayerId != target.PlayerId || ChangelingId != seer.PlayerId ? string.Empty : string.Format(Translator.GetString("ChangelingCurrentRole"), CurrentRole.ToColoredString()); } -} +} \ No newline at end of file diff --git a/Roles/Impostor/Deathpact.cs b/Roles/Impostor/Deathpact.cs index 3935dd0cc..baa78a07a 100644 --- a/Roles/Impostor/Deathpact.cs +++ b/Roles/Impostor/Deathpact.cs @@ -229,8 +229,10 @@ public class Deathpact : RoleBase var 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; } diff --git a/Roles/Impostor/Duellist.cs b/Roles/Impostor/Duellist.cs index a62da5e9c..b0f64989e 100644 --- a/Roles/Impostor/Duellist.cs +++ b/Roles/Impostor/Duellist.cs @@ -61,9 +61,9 @@ public class Duellist : RoleBase { if (Main.KillTimers[duellist.PlayerId] < 1f) duellist.SetKillCooldown(1f); // Give the other player a chance to kill - if (DuelPair.TryGetValue(duellist.PlayerId, out var previousTargetId)) + if (DuelPair.TryGetValue(duellist.PlayerId, out byte previousTargetId)) { - var previousTarget = GetPlayerById(previousTargetId); + PlayerControl previousTarget = GetPlayerById(previousTargetId); if (previousTarget != null) previousTarget.TPToRandomVent(); } diff --git a/Roles/Impostor/Escapee.cs b/Roles/Impostor/Escapee.cs index e1152eaa7..a2188174e 100644 --- a/Roles/Impostor/Escapee.cs +++ b/Roles/Impostor/Escapee.cs @@ -6,12 +6,12 @@ namespace EHR.Impostor; internal class Escapee : RoleBase { public static bool On; - public override bool IsEnable => On; - + public static OptionItem EscapeeSSCD; public static OptionItem CanVent; - + public Vector2? EscapeeLocation; + public override bool IsEnable => On; public override void SetupCustomOption() { @@ -20,7 +20,7 @@ internal class Escapee : RoleBase EscapeeSSCD = new FloatOptionItem(3611, "ShapeshiftCooldown", new(1f, 180f, 1f), 5f, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Escapee]) .SetValueFormat(OptionFormat.Seconds); - + CanVent = new BooleanOptionItem(3612, "CanVent", false, TabGroup.ImpostorRoles) .SetParent(Options.CustomRoleSpawnChances[CustomRoles.Escapee]); } diff --git a/Roles/Impostor/Gangster.cs b/Roles/Impostor/Gangster.cs index 506ce329d..f90cc322a 100644 --- a/Roles/Impostor/Gangster.cs +++ b/Roles/Impostor/Gangster.cs @@ -94,9 +94,9 @@ public class Gangster : RoleBase sender.SetKillCooldown(killer); sender.RpcGuardAndKill(target, killer); sender.RpcGuardAndKill(target, target); - + sender.SendMessage(); - + Utils.NotifyRoles(SpecifySeer: killer, SpecifyTarget: target); Utils.NotifyRoles(SpecifySeer: target, SpecifyTarget: killer); diff --git a/Roles/Impostor/Hitman.cs b/Roles/Impostor/Hitman.cs index 6945f7c0e..a352a1af7 100644 --- a/Roles/Impostor/Hitman.cs +++ b/Roles/Impostor/Hitman.cs @@ -99,8 +99,10 @@ public class Hitman : RoleBase 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() diff --git a/Roles/Impostor/Hypocrite.cs b/Roles/Impostor/Hypocrite.cs index 198bc2761..120d3be5e 100644 --- a/Roles/Impostor/Hypocrite.cs +++ b/Roles/Impostor/Hypocrite.cs @@ -11,10 +11,10 @@ public class Hypocrite : RoleBase private static OptionItem NonImpGetsNotifyWhenLowTasks; private static OptionItem NotifyAtXTasksLeft; - public override bool IsEnable => On; - private PlayerControl HypocritePC; + public override bool IsEnable => On; + public override void SetupCustomOption() { StartSetup(645200) @@ -49,12 +49,14 @@ public class Hypocrite : RoleBase else if (NonImpGetsNotifyWhenLowTasks.GetBool() && completedTaskCount + 1 >= totalTaskCount - NotifyAtXTasksLeft.GetInt()) { Logger.Info($"Hypocrite ({pc.GetNameWithRole()}) has {NotifyAtXTasksLeft.GetInt()} tasks left", "Hypocrite"); - + LateTask.New(() => { foreach (PlayerControl player in Main.AllAlivePlayerControls) + { if (!player.Is(Team.Impostor)) Utils.NotifyRoles(SpecifySeer: player, SpecifyTarget: player); + } }, 0.1f, log: false); } } diff --git a/Roles/Impostor/Kamikaze.cs b/Roles/Impostor/Kamikaze.cs index 0116f6adc..1b5a6576f 100644 --- a/Roles/Impostor/Kamikaze.cs +++ b/Roles/Impostor/Kamikaze.cs @@ -103,7 +103,7 @@ internal class Kamikaze : RoleBase else { victim.SetRealKiller(kamikazePc); - var state = Main.PlayerStates[victim.PlayerId]; + PlayerState state = Main.PlayerStates[victim.PlayerId]; state.IsDead = true; state.deathReason = PlayerState.DeathReason.Kamikazed; Medic.IsDead(victim); diff --git a/Roles/Impostor/Mafioso.cs b/Roles/Impostor/Mafioso.cs index d59e353b2..5c4e06017 100644 --- a/Roles/Impostor/Mafioso.cs +++ b/Roles/Impostor/Mafioso.cs @@ -126,8 +126,10 @@ public class Mafioso : RoleBase writer.Write(PreviouslyUsedVents.Count); if (PreviouslyUsedVents.Count > 0) + { foreach (int vent in PreviouslyUsedVents.ToArray()) writer.Write(vent); + } AmongUsClient.Instance.FinishRpcImmediately(writer); } @@ -140,8 +142,10 @@ public class Mafioso : RoleBase int elements = reader.ReadInt32(); if (elements > 0) + { for (var i = 0; i < elements; i++) PreviouslyUsedVents.Add(reader.ReadInt32()); + } } private void SendRPCSyncPistolCD() diff --git a/Roles/Impostor/Mastermind.cs b/Roles/Impostor/Mastermind.cs index 9098a01b9..d6246497c 100644 --- a/Roles/Impostor/Mastermind.cs +++ b/Roles/Impostor/Mastermind.cs @@ -184,17 +184,17 @@ public class Mastermind : RoleBase } var sender = CustomRpcSender.Create("Mastermind.ForceKillForManipulatedPlayer", SendOption.Reliable); - + const MurderResultFlags resultFlags = (MurderResultFlags)(8 | 1); if (AmongUsClient.Instance.AmClient) killer.MurderPlayer(target, resultFlags); sender.AutoStartRpc(killer.NetId, 12); sender.WriteNetObject(target); sender.Write((int)resultFlags); sender.EndRpc(); - + sender.Notify(killer, GetString("MastermindTargetSurvived")); killer.RpcChangeRoleBasis(killer.GetCustomRole(), sender: sender); - + sender.SendMessage(); LateTask.New(() => diff --git a/Roles/Impostor/Miner.cs b/Roles/Impostor/Miner.cs index c41f832cf..1e36ff8d3 100644 --- a/Roles/Impostor/Miner.cs +++ b/Roles/Impostor/Miner.cs @@ -5,9 +5,9 @@ namespace EHR.Impostor; internal class Miner : RoleBase { public static bool On; - public override bool IsEnable => On; - + public static OptionItem MinerSSCD; + public override bool IsEnable => On; public override void SetupCustomOption() { diff --git a/Roles/Impostor/Occultist.cs b/Roles/Impostor/Occultist.cs index fa0654206..52a38d06e 100644 --- a/Roles/Impostor/Occultist.cs +++ b/Roles/Impostor/Occultist.cs @@ -60,7 +60,7 @@ public class Occultist : RoleBase playerId.SetAbilityUseLimit(AbilityUseLimit.GetInt()); } - void SwitchAction() + private void SwitchAction() { InRevivingMode = Main.AllAlivePlayerControls.Length >= 4 && !InRevivingMode; Utils.SendRPC(CustomRPC.SyncRoleData, OccultistPC.PlayerId, 1, InRevivingMode); @@ -131,10 +131,10 @@ public class Occultist : RoleBase if (now - data.StartTimeStamp >= ReviveTime.GetInt()) { - var player = id.GetPlayer(); + PlayerControl player = id.GetPlayer(); if (player == null) continue; - switch (player.GetCustomSubRoles().FindFirst(x => x.IsConverted(), out var convertedAddon)) + switch (player.GetCustomSubRoles().FindFirst(x => x.IsConverted(), out CustomRoles convertedAddon)) { case false when !player.Is(Team.Impostor): player.RpcSetCustomRole(RevivedPlayers.GetValue() == 0 ? CustomRoles.Refugee : CustomRoles.Madmate); @@ -165,12 +165,12 @@ public class Occultist : RoleBase public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { if (seer.PlayerId != OccultistPC.PlayerId || seer.PlayerId != target.PlayerId || meeting || (seer.IsModdedClient() && !hud)) return string.Empty; - var str = string.Format(Translator.GetString("OccultistSuffix"), Translator.GetString(InRevivingMode ? "OccultistMode.Revive" : "OccultistMode.Report"), Translator.GetString($"OccultistActionSwitchMode.{ActionSwitchMode}")); + string str = string.Format(Translator.GetString("OccultistSuffix"), Translator.GetString(InRevivingMode ? "OccultistMode.Revive" : "OccultistMode.Report"), Translator.GetString($"OccultistActionSwitchMode.{ActionSwitchMode}")); if (Main.AllAlivePlayerControls.Length < 4) str = str.Split('(')[0].TrimEnd(' '); return str; } - enum ActionSwitchModes + private enum ActionSwitchModes { Vent, Pet, @@ -178,7 +178,7 @@ public class Occultist : RoleBase Vanish } - class ReviveData(long startTimeStamp, Vector2 position, bool done) + private class ReviveData(long startTimeStamp, Vector2 position, bool done) { public long StartTimeStamp { get; } = startTimeStamp; public Vector2 Position { get; } = position; diff --git a/Roles/Impostor/OverKiller.cs b/Roles/Impostor/OverKiller.cs index a8a02e860..d134c51f0 100644 --- a/Roles/Impostor/OverKiller.cs +++ b/Roles/Impostor/OverKiller.cs @@ -1,7 +1,5 @@ using System.Collections; using System.Collections.Generic; -using Hazel; -using InnerNet; namespace EHR.Impostor; @@ -76,7 +74,7 @@ internal class OverKiller : RoleBase IEnumerator SpawnFakeDeadBodies() { var sender = CustomRpcSender.Create("Butcher kill"); - + for (var i = 0; i < 26; i++) { Vector2 location = new(ops.x + ((float)(rd.Next(0, 201) - 100) / 100), ops.y + ((float)(rd.Next(0, 201) - 100) / 100)); diff --git a/Roles/Impostor/Penguin.cs b/Roles/Impostor/Penguin.cs index f2e9692c6..4281eee43 100644 --- a/Roles/Impostor/Penguin.cs +++ b/Roles/Impostor/Penguin.cs @@ -43,8 +43,10 @@ public class Penguin : RoleBase 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; } @@ -298,8 +300,10 @@ public class Penguin : RoleBase public static void OnSpawnAirship() { foreach (KeyValuePair state in Main.PlayerStates) + { if (state.Value.Role is Penguin { IsEnable: true } pg) pg.RestartAbduct(); + } } private void RestartAbduct() diff --git a/Roles/Impostor/Sapper.cs b/Roles/Impostor/Sapper.cs index 9b704db80..15aeae165 100644 --- a/Roles/Impostor/Sapper.cs +++ b/Roles/Impostor/Sapper.cs @@ -37,7 +37,7 @@ public class Sapper : RoleBase Radius = new FloatOptionItem(Id + 13, "SapperRadius", new(0f, 10f, 0.25f), 3f, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sapper]) .SetValueFormat(OptionFormat.Multiplier); - + CanSabotage = new BooleanOptionItem(Id + 14, "CanSabotage", false, TabGroup.ImpostorRoles) .SetParent(CustomRoleSpawnChances[CustomRoles.Sapper]); } diff --git a/Roles/Impostor/Silencer.cs b/Roles/Impostor/Silencer.cs index 6988f5c6c..c54c4a761 100644 --- a/Roles/Impostor/Silencer.cs +++ b/Roles/Impostor/Silencer.cs @@ -76,7 +76,7 @@ public class Silencer : RoleBase LocalPlayerTotalSilences++; if (LocalPlayerTotalSilences >= 5) Achievements.Type.Censorship.Complete(); - if (target.Is(CustomRoles.Snitch) && Snitch.IsExposed.TryGetValue(target.PlayerId, out var exposed) && exposed) + if (target.Is(CustomRoles.Snitch) && Snitch.IsExposed.TryGetValue(target.PlayerId, out bool exposed) && exposed) Achievements.Type.YouWontTellAnyone.Complete(); } }); @@ -93,7 +93,7 @@ public class Silencer : RoleBase LocalPlayerTotalSilences++; if (LocalPlayerTotalSilences >= 5) Achievements.Type.Censorship.Complete(); - if (target.Is(CustomRoles.Snitch) && Snitch.IsExposed.TryGetValue(target.PlayerId, out var exposed) && exposed) + if (target.Is(CustomRoles.Snitch) && Snitch.IsExposed.TryGetValue(target.PlayerId, out bool exposed) && exposed) Achievements.Type.YouWontTellAnyone.Complete(); } } diff --git a/Roles/Impostor/Sniper.cs b/Roles/Impostor/Sniper.cs index b50ead554..7a1daf1d5 100644 --- a/Roles/Impostor/Sniper.cs +++ b/Roles/Impostor/Sniper.cs @@ -356,8 +356,10 @@ public class Sniper : RoleBase 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 { diff --git a/Roles/Impostor/Stasis.cs b/Roles/Impostor/Stasis.cs index fd202f99b..84adce01e 100644 --- a/Roles/Impostor/Stasis.cs +++ b/Roles/Impostor/Stasis.cs @@ -117,9 +117,9 @@ public class Stasis : RoleBase IEnumerator Countdown() { - var imps = AffectsOtherImpostors.GetBool() ? [pc] : Main.AllAlivePlayerControls.Where(x => x.Is(Team.Impostor)).ToArray(); + PlayerControl[] imps = AffectsOtherImpostors.GetBool() ? [pc] : Main.AllAlivePlayerControls.Where(x => x.Is(Team.Impostor)).ToArray(); - for (int i = 0; i < time; i++) + for (var i = 0; i < time; i++) { // ReSharper disable once AccessToModifiedClosure imps.NotifyPlayers($"<#00ffa5>{Translator.GetString("Stasis.TimeFrozenNotify")} <#888888>- {time - i}", overrideAll: true); diff --git a/Roles/Impostor/Swooper.cs b/Roles/Impostor/Swooper.cs index b6cf31ac2..a712cae07 100644 --- a/Roles/Impostor/Swooper.cs +++ b/Roles/Impostor/Swooper.cs @@ -120,7 +120,8 @@ public class Swooper : RoleBase { try { - if (UsedRole == CustomRoles.Chameleon) { AURoleOptions.EngineerCooldown = Cooldown + 1f; } + if (UsedRole == CustomRoles.Chameleon) + AURoleOptions.EngineerCooldown = Cooldown + 1f; } catch (Exception e) { Utils.ThrowException(e); } } @@ -169,7 +170,7 @@ public class Swooper : RoleBase if (!player.IsModdedClient() && UsedRole != CustomRoles.Chameleon) { long cooldown = lastTime + (long)Cooldown - now; - if ((int)cooldown != CD) player.Notify(string.Format(GetString("CDPT"), cooldown + 1), 3f, overrideAll: true); + if ((int)cooldown != CD) player.Notify(string.Format(GetString("CDPT"), cooldown + 1), 3f, true); CD = (int)cooldown; } @@ -194,12 +195,12 @@ public class Swooper : RoleBase { case < 0: lastTime = now; - + var sender = CustomRpcSender.Create("RpcExitVentDesync", SendOption.Reliable); - var ventId = ventedId == -10 ? Main.LastEnteredVent[player.PlayerId].Id : ventedId; - var hasValue = Main.AllPlayerControls.Where(pc => player.PlayerId != pc.PlayerId).Aggregate(false, (current, pc) => current || sender.RpcExitVentDesync(player.MyPhysics, ventId, pc)); - sender.SendMessage(dispose: !hasValue); - + int ventId = ventedId == -10 ? Main.LastEnteredVent[player.PlayerId].Id : ventedId; + bool hasValue = Main.AllPlayerControls.Where(pc => player.PlayerId != pc.PlayerId).Aggregate(false, (current, pc) => current || sender.RpcExitVentDesync(player.MyPhysics, ventId, pc)); + sender.SendMessage(!hasValue); + player.Notify(GetString("SwooperInvisStateOut")); InvisTime = -10; SendRPC(); @@ -283,7 +284,7 @@ public class Swooper : RoleBase if (Medic.ProtectList.Contains(target.PlayerId)) return false; if (target.Is(CustomRoles.Bait)) return true; if (!IsInvis) return true; - if (!killer.RpcCheckAndMurder(target, check: true)) return false; + if (!killer.RpcCheckAndMurder(target, true)) return false; target.Suicide(PlayerState.DeathReason.Swooped, killer); killer.SetKillCooldown(); diff --git a/Roles/Impostor/Wasp.cs b/Roles/Impostor/Wasp.cs index 795aeba83..3aca4f3af 100644 --- a/Roles/Impostor/Wasp.cs +++ b/Roles/Impostor/Wasp.cs @@ -216,7 +216,10 @@ public class Wasp : RoleBase return Instances.Any(x => x.MeetingKills.Contains(target)) ? Utils.ColorString(Palette.ImpostorRed, "\u25c0") : string.Empty; } - HashSet GetStungPlayers(byte[] exileIds) => WaspPC == null || !WaspPC.IsAlive() || Main.AfterMeetingDeathPlayers.ContainsKey(WaspPC.PlayerId) || exileIds.Any(x => x == WaspPC.PlayerId) ? [] : MeetingKills; + private HashSet GetStungPlayers(byte[] exileIds) + { + return WaspPC == null || !WaspPC.IsAlive() || Main.AfterMeetingDeathPlayers.ContainsKey(WaspPC.PlayerId) || exileIds.Any(x => x == WaspPC.PlayerId) ? [] : MeetingKills; + } public void ReceiveRPC(MessageReader reader) { diff --git a/Roles/Impostor/Wiper.cs b/Roles/Impostor/Wiper.cs index a46f20f0c..609d95eee 100644 --- a/Roles/Impostor/Wiper.cs +++ b/Roles/Impostor/Wiper.cs @@ -71,17 +71,17 @@ public class Wiper : RoleBase WipeOutEveryoneInRoom(pc); return false; } - - bool IsInvalidRoom(PlainShipRoom room) + + private bool IsInvalidRoom(PlainShipRoom room) { return room == null || room.RoomId is SystemTypes.Outside or SystemTypes.Hallway or SystemTypes.Ventilation || room.RoomId.ToString().Contains("Decontamination"); } - void WipeOutEveryoneInRoom(PlayerControl pc) + private void WipeOutEveryoneInRoom(PlayerControl pc) { if (new[] { SystemTypes.Electrical, SystemTypes.Reactor, SystemTypes.Laboratory, SystemTypes.LifeSupp, SystemTypes.Comms, SystemTypes.HeliSabotage, SystemTypes.MushroomMixupSabotage }.Any(Utils.IsActive)) return; - var room = pc.GetPlainShipRoom(); + PlainShipRoom room = pc.GetPlainShipRoom(); if (IsInvalidRoom(room)) return; Main.AllAlivePlayerControls.Without(pc).DoIf(x => x.GetPlainShipRoom() == room, x => x.Suicide(PlayerState.DeathReason.WipedOut, pc)); @@ -91,7 +91,7 @@ public class Wiper : RoleBase { if (!GameStates.IsInTask || ExileController.Instance || !Main.IntroDestroyed) return; - var room = pc.GetPlainShipRoom(); + PlainShipRoom room = pc.GetPlainShipRoom(); if (room != LastRoom) { diff --git a/Roles/Impostor/Witch.cs b/Roles/Impostor/Witch.cs index e79bd7f2e..74a6e5824 100644 --- a/Roles/Impostor/Witch.cs +++ b/Roles/Impostor/Witch.cs @@ -230,8 +230,10 @@ public class Witch : RoleBase 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; } @@ -268,8 +270,10 @@ public class Witch : RoleBase 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 4f97fee1d..748050195 100644 --- a/Roles/Impostor/YinYanger.cs +++ b/Roles/Impostor/YinYanger.cs @@ -140,12 +140,12 @@ public class YinYanger : RoleBase public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.IsModdedClient() && !hud || meeting) return string.Empty; + if ((seer.IsModdedClient() && !hud) || meeting) return string.Empty; if (Main.PlayerStates[seer.PlayerId].Role is YinYanger { IsEnable: true } yy) { if (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)"; - else if (yy.YinYangedPlayers.Contains(target.PlayerId)) return "\u262f"; + if (yy.YinYangedPlayers.Contains(target.PlayerId)) return "\u262f"; } return string.Empty; diff --git a/Roles/Neutral/Amnesiac.cs b/Roles/Neutral/Amnesiac.cs index 6f0399633..a21f07855 100644 --- a/Roles/Neutral/Amnesiac.cs +++ b/Roles/Neutral/Amnesiac.cs @@ -189,7 +189,7 @@ public class Amnesiac : RoleBase amneNotifyString = Utils.ColorString(Utils.GetRoleColor(CustomRoles.Amnesiac), GetString($"Remembered{RememberedRole}")); break; case Team.Coven: - RememberedRole = targetRole == CustomRoles.CovenLeader ? Enum.GetValues().FindFirst(x => x.IsCoven() && !x.RoleExist(true), out var unusedCovenRole) ? unusedCovenRole : null : targetRole; + RememberedRole = targetRole == CustomRoles.CovenLeader ? Enum.GetValues().FindFirst(x => x.IsCoven() && !x.RoleExist(true), out CustomRoles unusedCovenRole) ? unusedCovenRole : null : targetRole; if (RememberedRole.HasValue) amneNotifyString = Utils.ColorString(Utils.GetRoleColor(CustomRoles.Amnesiac), GetString("RememberedCoven")); break; } @@ -218,7 +218,7 @@ public class Amnesiac : RoleBase sender.RpcGuardAndKill(target, amnesiac); sender.RpcGuardAndKill(target, target); - + sender.SendMessage(); if (role.IsRecruitingRole()) amnesiac.SetAbilityUseLimit(0); diff --git a/Roles/Neutral/Amogus.cs b/Roles/Neutral/Amogus.cs index d3fa24330..8c6291d21 100644 --- a/Roles/Neutral/Amogus.cs +++ b/Roles/Neutral/Amogus.cs @@ -216,7 +216,7 @@ public class Amogus : RoleBase return $"{base.GetProgressText(playerId, comms)} {string.Format(Translator.GetString("ExtraVotesPT"), ExtraVotes)}"; } - enum Levels + private enum Levels { Amogus, Sugoma, diff --git a/Roles/Neutral/Arsonist.cs b/Roles/Neutral/Arsonist.cs index ead6969a5..485a4508b 100644 --- a/Roles/Neutral/Arsonist.cs +++ b/Roles/Neutral/Arsonist.cs @@ -112,8 +112,10 @@ internal class Arsonist : RoleBase 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(); diff --git a/Roles/Neutral/Auditor.cs b/Roles/Neutral/Auditor.cs index 103b35bb5..602002b0d 100644 --- a/Roles/Neutral/Auditor.cs +++ b/Roles/Neutral/Auditor.cs @@ -70,7 +70,7 @@ public class Auditor : RoleBase if (!Instances.Any(x => x.LoweredVisionPlayers.ContainsKey(id))) return; opt.SetVision(false); - var vision = LoweredVision.GetFloat(); + float vision = LoweredVision.GetFloat(); opt.SetFloat(FloatOptionNames.CrewLightMod, vision); opt.SetFloat(FloatOptionNames.ImpostorLightMod, vision); } @@ -93,7 +93,7 @@ public class Auditor : RoleBase } case Modes.Smokebombing: { - var containsKey = LoweredVisionPlayers.ContainsKey(target.PlayerId); + bool containsKey = LoweredVisionPlayers.ContainsKey(target.PlayerId); LoweredVisionPlayers[target.PlayerId] = Utils.TimeStamp + LoweredVisionDuration.GetInt(); if (!containsKey) target.MarkDirtySettings(); killer.SetKillCooldown(SmokebombCooldown.GetFloat()); @@ -138,7 +138,7 @@ public class Auditor : RoleBase return false; } - void SwitchMode(PlayerControl pc) + private void SwitchMode(PlayerControl pc) { Mode = Mode == Modes.Auditing ? Modes.Smokebombing : Modes.Auditing; Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: pc); @@ -188,7 +188,7 @@ public class Auditor : RoleBase return string.Format(Translator.GetString($"Auditor.Suffix.{Mode}"), Translator.GetString($"OccultistActionSwitchMode.{AbilityTrigger}")); } - enum AbilityTriggers + private enum AbilityTriggers { Vent, Pet, @@ -196,7 +196,7 @@ public class Auditor : RoleBase Vanish } - enum Modes + private enum Modes { Auditing, Smokebombing diff --git a/Roles/Neutral/Bargainer.cs b/Roles/Neutral/Bargainer.cs index 56ea8e3a9..9a6b9f709 100644 --- a/Roles/Neutral/Bargainer.cs +++ b/Roles/Neutral/Bargainer.cs @@ -116,9 +116,8 @@ internal class Bargainer : RoleBase MoneySettings[action] = (boolOpt, intOpt); continue; - int GetDefaultValue() - { - return action switch + int GetDefaultValue() => + action switch { MoneyGainingAction.Kill => 30, MoneyGainingAction.Sabotage => 10, @@ -126,7 +125,6 @@ internal class Bargainer : RoleBase _ => 0 }; - } } foreach (Item item in Enum.GetValues()) @@ -144,9 +142,8 @@ internal class Bargainer : RoleBase ItemSettings[item] = (boolOpt, intOpt); continue; - int GetDefaultValue() - { - return item switch + int GetDefaultValue() => + item switch { Item.EnergyDrink => 40, Item.LensOfTruth => 60, @@ -154,7 +151,6 @@ internal class Bargainer : RoleBase _ => 0 }; - } void SetupExtraSettings() { @@ -196,14 +192,18 @@ internal class Bargainer : RoleBase 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; } @@ -364,9 +364,8 @@ internal class Bargainer : RoleBase break; - static (int Duration, byte Target) GetData(Item item) - { - return item switch + static (int Duration, byte Target) GetData(Item item) => + item switch { Item.EnergyDrink => (int.MaxValue, byte.MaxValue), Item.LensOfTruth => (AlignmentVisibleValue, Main.AllAlivePlayerControls.RandomElement().PlayerId), @@ -374,7 +373,6 @@ internal class Bargainer : RoleBase _ => (0, byte.MaxValue) }; - } } case false when InShop: { diff --git a/Roles/Neutral/Bubble.cs b/Roles/Neutral/Bubble.cs index e57b4a0db..54263f9f9 100644 --- a/Roles/Neutral/Bubble.cs +++ b/Roles/Neutral/Bubble.cs @@ -137,7 +137,7 @@ internal class Bubble : RoleBase IEnumerable players = GetPlayersInRadius(ExplosionRadius.GetFloat(), encasedPc.Pos()); - int numDied = 0; + var numDied = 0; foreach (PlayerControl pc in players) { diff --git a/Roles/Neutral/Chemist.cs b/Roles/Neutral/Chemist.cs index cc8b1a0fa..1d116f3e8 100644 --- a/Roles/Neutral/Chemist.cs +++ b/Roles/Neutral/Chemist.cs @@ -165,9 +165,8 @@ internal class Chemist : RoleBase return; - static int GetDefaultValue(Item item) - { - return item switch + static int GetDefaultValue(Item item) => + item switch { Item.Explosive => 1, Item.Grenade => 1, @@ -175,7 +174,6 @@ internal class Chemist : RoleBase Item.MethylamineGas => 100, _ => 0 }; - } } public override void Init() diff --git a/Roles/Neutral/Curser.cs b/Roles/Neutral/Curser.cs index 4d8176154..36dfc1c1f 100644 --- a/Roles/Neutral/Curser.cs +++ b/Roles/Neutral/Curser.cs @@ -91,7 +91,7 @@ public class Curser : RoleBase target.RpcRemoveAbilityUse(); break; case 1: - var addons = Options.GroupedAddons[AddonTypes.Harmful].Where(x => !target.Is(x) && !x.IsNotAssignableMidGame() && CustomRolesHelper.CheckAddonConflict(x, target)); + IEnumerable addons = Options.GroupedAddons[AddonTypes.Harmful].Where(x => !target.Is(x) && !x.IsNotAssignableMidGame() && CustomRolesHelper.CheckAddonConflict(x, target)); target.RpcSetCustomRole(addons.RandomElement()); break; case 2: @@ -123,14 +123,15 @@ public class Curser : RoleBase opt.SetFloat(FloatOptionNames.ImpostorLightMod, vision); } - if (instance.LowerSpeedPlayers.Contains(playerId)) { Main.AllPlayerSpeed[playerId] = LowerSpeed.GetFloat(); } + if (instance.LowerSpeedPlayers.Contains(playerId)) + Main.AllPlayerSpeed[playerId] = LowerSpeed.GetFloat(); } } public void OnDeath() { LowerVisionPlayers.UnionWith(LowerSpeedPlayers); - var players = LowerVisionPlayers.ToValidPlayers().ToArray(); + PlayerControl[] players = LowerVisionPlayers.ToValidPlayers().ToArray(); LowerVisionPlayers.Clear(); LowerSpeedPlayers.Clear(); players.Do(x => x.MarkDirtySettings()); diff --git a/Roles/Neutral/DarkHide.cs b/Roles/Neutral/DarkHide.cs index 22eeebb9e..06d0cb25a 100644 --- a/Roles/Neutral/DarkHide.cs +++ b/Roles/Neutral/DarkHide.cs @@ -2,7 +2,6 @@ using AmongUs.GameOptions; using EHR.Modules; using Hazel; -using InnerNet; namespace EHR.Neutral; diff --git a/Roles/Neutral/Doomsayer.cs b/Roles/Neutral/Doomsayer.cs index b8e96dcef..bd7552ef3 100644 --- a/Roles/Neutral/Doomsayer.cs +++ b/Roles/Neutral/Doomsayer.cs @@ -104,7 +104,10 @@ public class Doomsayer : RoleBase PlayerIdList.Remove(playerId); } - public override void ApplyGameOptions(IGameOptions opt, byte id) => opt.SetVision(ImpostorVision.GetBool()); + public override void ApplyGameOptions(IGameOptions opt, byte id) + { + opt.SetVision(ImpostorVision.GetBool()); + } public static void SendRPC(PlayerControl player) { diff --git a/Roles/Neutral/FFF.cs b/Roles/Neutral/FFF.cs index 398342bd0..09ffdfe03 100644 --- a/Roles/Neutral/FFF.cs +++ b/Roles/Neutral/FFF.cs @@ -100,16 +100,16 @@ public class FFF : RoleBase } if ( - ((target.Is(CustomRoles.Madmate) || target.Is(CustomRoles.Gangster)) && CanKillMadmate.GetBool()) - || ((target.Is(CustomRoles.Charmed) || target.Is(CustomRoles.Succubus)) && CanKillCharmed.GetBool()) - || ((target.Is(CustomRoles.Undead) || target.Is(CustomRoles.Necromancer) || target.Is(CustomRoles.Deathknight)) && CanKillUndead.GetBool()) - || (Main.LoversPlayers.Exists(x => x.PlayerId == target.PlayerId) && CanKillLovers.GetBool()) - || ((target.Is(CustomRoles.Romantic) || target.Is(CustomRoles.RuthlessRomantic) || target.Is(CustomRoles.VengefulRomantic) - || Romantic.PartnerId == target.PlayerId) && CanKillLovers.GetBool()) - || ((target.Is(CustomRoles.Sidekick) || target.Is(CustomRoles.Jackal) || target.Is(CustomRoles.Recruit)) && CanKillSidekicks.GetBool()) - || (target.Is(CustomRoles.Egoist) && CanKillEgoists.GetBool()) - || ((target.Is(CustomRoles.Contagious) || target.Is(CustomRoles.Virus)) && CanKillContagious.GetBool()) - ) + ((target.Is(CustomRoles.Madmate) || target.Is(CustomRoles.Gangster)) && CanKillMadmate.GetBool()) + || ((target.Is(CustomRoles.Charmed) || target.Is(CustomRoles.Succubus)) && CanKillCharmed.GetBool()) + || ((target.Is(CustomRoles.Undead) || target.Is(CustomRoles.Necromancer) || target.Is(CustomRoles.Deathknight)) && CanKillUndead.GetBool()) + || (Main.LoversPlayers.Exists(x => x.PlayerId == target.PlayerId) && CanKillLovers.GetBool()) + || ((target.Is(CustomRoles.Romantic) || target.Is(CustomRoles.RuthlessRomantic) || target.Is(CustomRoles.VengefulRomantic) + || Romantic.PartnerId == target.PlayerId) && CanKillLovers.GetBool()) + || ((target.Is(CustomRoles.Sidekick) || target.Is(CustomRoles.Jackal) || target.Is(CustomRoles.Recruit)) && CanKillSidekicks.GetBool()) + || (target.Is(CustomRoles.Egoist) && CanKillEgoists.GetBool()) + || ((target.Is(CustomRoles.Contagious) || target.Is(CustomRoles.Virus)) && CanKillContagious.GetBool()) + ) { if (killer.RpcCheckAndMurder(target)) IsWon = true; diff --git a/Roles/Neutral/Gaslighter.cs b/Roles/Neutral/Gaslighter.cs index 342853fdf..e92a3a081 100644 --- a/Roles/Neutral/Gaslighter.cs +++ b/Roles/Neutral/Gaslighter.cs @@ -50,7 +50,7 @@ public class Gaslighter : RoleBase On = true; Instances.Add(this); GaslighterId = playerId; - CurrentRound = default; + CurrentRound = default(Round); CursedPlayers = []; ShieldedPlayers = []; CycleFinished = false; @@ -85,8 +85,10 @@ public class Gaslighter : RoleBase foreach (Gaslighter instance in Instances) { foreach (byte id in exileIds) + { if (id == instance.GaslighterId) instance.CursedPlayers.Clear(); + } } List curseDeathList = []; diff --git a/Roles/Neutral/HexMaster.cs b/Roles/Neutral/HexMaster.cs index 536ae4540..4cfad0de6 100644 --- a/Roles/Neutral/HexMaster.cs +++ b/Roles/Neutral/HexMaster.cs @@ -7,7 +7,7 @@ namespace EHR.Neutral; public class HexMaster : RoleBase { private const int Id = 11900; - + public static OptionItem ModeSwitchAction; private static OptionItem CanVent; private static OptionItem HasImpostorVision; @@ -41,4 +41,4 @@ public class HexMaster : RoleBase { return CanVent.GetBool(); } -} +} \ No newline at end of file diff --git a/Roles/Neutral/Jackal.cs b/Roles/Neutral/Jackal.cs index d09802c6e..07ef8f403 100644 --- a/Roles/Neutral/Jackal.cs +++ b/Roles/Neutral/Jackal.cs @@ -174,7 +174,7 @@ public class Jackal : RoleBase sender.SetKillCooldown(killer, 3f); sender.RpcGuardAndKill(target, killer); sender.RpcGuardAndKill(target, target); - + sender.SendMessage(); Utils.NotifyRoles(SpecifySeer: killer, SpecifyTarget: target, ForceLoop: true); diff --git a/Roles/Neutral/Jester.cs b/Roles/Neutral/Jester.cs index 9925b28ac..3ba1d6ec1 100644 --- a/Roles/Neutral/Jester.cs +++ b/Roles/Neutral/Jester.cs @@ -27,12 +27,12 @@ internal class Jester : RoleBase .SetParent(CustomRoleSpawnChances[CustomRoles.Jester]); VentCooldown = new FloatOptionItem(10913, "VentCooldown", new(0f, 60f, 0.5f), 0f, TabGroup.NeutralRoles) - .SetParent(JesterCanVent) - .SetValueFormat(OptionFormat.Seconds); + .SetParent(JesterCanVent) + .SetValueFormat(OptionFormat.Seconds); MaxInVentTime = new FloatOptionItem(10914, "MaxInVentTime", new(0f, 60f, 0.5f), 30f, TabGroup.NeutralRoles) - .SetParent(JesterCanVent) - .SetValueFormat(OptionFormat.Seconds); + .SetParent(JesterCanVent) + .SetValueFormat(OptionFormat.Seconds); BlockVentMovement = new BooleanOptionItem(10916, "BlockVentMovement", false, TabGroup.NeutralRoles) .SetParent(JesterCanVent); @@ -41,8 +41,8 @@ internal class Jester : RoleBase .SetParent(CustomRoleSpawnChances[CustomRoles.Jester]); SunnyboyChance = new IntegerOptionItem(10915, "SunnyboyChance", new(0, 100, 5), 0, TabGroup.NeutralRoles) - .SetParent(CustomRoleSpawnChances[CustomRoles.Jester]) - .SetValueFormat(OptionFormat.Percent); + .SetParent(CustomRoleSpawnChances[CustomRoles.Jester]) + .SetValueFormat(OptionFormat.Percent); } public override void Add(byte playerId) diff --git a/Roles/Neutral/Magistrate.cs b/Roles/Neutral/Magistrate.cs index df4d21316..632ac0774 100644 --- a/Roles/Neutral/Magistrate.cs +++ b/Roles/Neutral/Magistrate.cs @@ -84,13 +84,13 @@ public class Magistrate : RoleBase return false; } - static void UseAbility(PlayerControl pc) + private static void UseAbility(PlayerControl pc) { pc.RpcRemoveAbilityUse(); CallCourtNextMeeting = true; } - enum AbilityTriggers + private enum AbilityTriggers { Vent, Pet, diff --git a/Roles/Neutral/Mario.cs b/Roles/Neutral/Mario.cs index 95472f19c..c5c995075 100644 --- a/Roles/Neutral/Mario.cs +++ b/Roles/Neutral/Mario.cs @@ -13,12 +13,12 @@ internal class Mario : RoleBase public static Dictionary MarioVentCount = []; public static bool On; - public override bool IsEnable => On; private static OptionItem MarioVentCD; private static Dictionary MapWinCounts = []; private static int MarioVentNumWin; + public override bool IsEnable => On; public override void SetupCustomOption() { diff --git a/Roles/Neutral/Mycologist.cs b/Roles/Neutral/Mycologist.cs index 867f79108..99dbd86a8 100644 --- a/Roles/Neutral/Mycologist.cs +++ b/Roles/Neutral/Mycologist.cs @@ -96,8 +96,10 @@ internal class Mycologist : RoleBase writer.Write(InfectedPlayers.Count); if (InfectedPlayers.Count > 0) + { foreach (byte x in InfectedPlayers) writer.Write(x); + } AmongUsClient.Instance.FinishRpcImmediately(writer); } diff --git a/Roles/Neutral/Necromancer.cs b/Roles/Neutral/Necromancer.cs index e4a62b667..c0dce3b23 100644 --- a/Roles/Neutral/Necromancer.cs +++ b/Roles/Neutral/Necromancer.cs @@ -92,7 +92,7 @@ internal class Necromancer : RoleBase if (Deathknight.DeathknightId == byte.MaxValue && !target.Is(CustomRoles.Loyal) && !target.Is(CustomRoles.Curser) && !target.IsConverted()) { var sender = CustomRpcSender.Create("Necromancer.OnCheckMurder", SendOption.Reliable); - + target.RpcChangeRoleBasis(CustomRoles.Deathknight, sender: sender); target.RpcSetCustomRole(CustomRoles.Deathknight); @@ -102,7 +102,7 @@ internal class Necromancer : RoleBase sender.SetKillCooldown(target); sender.Notify(target, GetString("RecruitedToDeathknight")); - + sender.SendMessage(); Utils.NotifyRoles(SpecifySeer: killer, SpecifyTarget: target); @@ -226,7 +226,7 @@ internal class Deathknight : RoleBase sender.SetKillCooldown(killer); sender.RpcGuardAndKill(target, killer); sender.RpcGuardAndKill(target, target); - + sender.SendMessage(); Utils.NotifyRoles(SpecifySeer: killer, SpecifyTarget: target); diff --git a/Roles/Neutral/NoteKiller.cs b/Roles/Neutral/NoteKiller.cs index 94ba9d411..70b013152 100644 --- a/Roles/Neutral/NoteKiller.cs +++ b/Roles/Neutral/NoteKiller.cs @@ -53,7 +53,7 @@ public class NoteKiller : RoleBase public override void SetupCustomOption() { - StartSetup(645950, single: true) + StartSetup(645950, true) .AutoSetupOption(ref AbilityCooldown, 15f, new FloatValueRule(0f, 90f, 0.5f), OptionFormat.Seconds) .AutoSetupOption(ref MinLettersRevealed, 1, new IntegerValueRule(1, Names.Max(x => x.Length), 1)) .AutoSetupOption(ref MaxLettersRevealed, 4, new IntegerValueRule(1, Names.Max(x => x.Length), 1)) @@ -75,12 +75,12 @@ public class NoteKiller : RoleBase LateTask.New(() => { - var names = Names.ToList(); + List names = Names.ToList(); foreach (PlayerControl pc in Main.AllAlivePlayerControls) { if (pc.Is(CustomRoles.NoteKiller)) continue; - var name = names.RandomElement(); + string name = names.RandomElement(); RealNames[pc.PlayerId] = name; names.Remove(name); Logger.Info($"{pc.GetRealName()}'s real name is {name}", "NoteKiller.Init"); @@ -118,15 +118,15 @@ public class NoteKiller : RoleBase Dictionary> revealedPositions = []; int numLettersRevealed = IRandom.Instance.Next(MinLettersRevealed.GetInt(), MaxLettersRevealed.GetInt() + 1); - for (int i = 0; i < numLettersRevealed; i++) + for (var i = 0; i < numLettersRevealed; i++) { foreach (KeyValuePair kvp in RealNames) { - var range = Enumerable.Range(0, Names.Max(x => x.Length) - 1); - var hasExceptions = revealedPositions.TryGetValue(kvp.Key, out var exceptions); + IEnumerable range = Enumerable.Range(0, Names.Max(x => x.Length) - 1); + bool hasExceptions = revealedPositions.TryGetValue(kvp.Key, out List exceptions); if (hasExceptions) range = range.Except(exceptions); - var position = range.RandomElement(); + int position = range.RandomElement(); if (!hasExceptions) revealedPositions[kvp.Key] = [position]; else exceptions.Add(position); @@ -206,11 +206,11 @@ public class NoteKiller : RoleBase public override string GetSuffix(PlayerControl seer, PlayerControl target, bool hud = false, bool meeting = false) { - if (seer.PlayerId == target.PlayerId && CustomRoles.NoteKiller.RoleExist() && seer.PlayerId != NoteKillerID && !meeting && RealNames.TryGetValue(seer.PlayerId, out var ownName)) + if (seer.PlayerId == target.PlayerId && CustomRoles.NoteKiller.RoleExist() && seer.PlayerId != NoteKillerID && !meeting && RealNames.TryGetValue(seer.PlayerId, out string ownName)) return MeetingStates.FirstMeeting ? string.Format(Translator.GetString("NoteKiller.OthersSelfSuffix"), CustomRoles.NoteKiller.ToColoredString(), ownName) : string.Format(Translator.GetString("NoteKiller.OthersSelfSuffixShort"), ownName); if (seer.PlayerId != NoteKillerID || meeting || ShowClueEndTimeStamp == 0 || ShownClues.Count == 0) return string.Empty; - if (ShownClues.TryGetValue(target.PlayerId, out var clue)) return clue; + if (ShownClues.TryGetValue(target.PlayerId, out string clue)) return clue; return seer.PlayerId == target.PlayerId ? $"\u25a9 ({ShowClueEndTimeStamp - Utils.TimeStamp}s)" : string.Empty; } } \ No newline at end of file diff --git a/Roles/Neutral/Pelican.cs b/Roles/Neutral/Pelican.cs index 4b72e73b6..869237d12 100644 --- a/Roles/Neutral/Pelican.cs +++ b/Roles/Neutral/Pelican.cs @@ -111,14 +111,16 @@ public class Pelican : RoleBase public static bool IsEaten(PlayerControl pc, byte id) { - return EatenList.TryGetValue(pc.PlayerId, out var list) && list.Contains(id); + return EatenList.TryGetValue(pc.PlayerId, out List list) && list.Contains(id); } public static bool IsEaten(byte id) { foreach (KeyValuePair> el in EatenList) + { if (el.Value.Contains(id)) return true; + } return false; } diff --git a/Roles/Neutral/PlagueDoctor.cs b/Roles/Neutral/PlagueDoctor.cs index 1833aa13f..d40800263 100644 --- a/Roles/Neutral/PlagueDoctor.cs +++ b/Roles/Neutral/PlagueDoctor.cs @@ -280,8 +280,10 @@ public class PlagueDoctor : RoleBase var 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()); } diff --git a/Roles/Neutral/QuizMaster.cs b/Roles/Neutral/QuizMaster.cs index 64a9c4d9b..f299d1530 100644 --- a/Roles/Neutral/QuizMaster.cs +++ b/Roles/Neutral/QuizMaster.cs @@ -40,7 +40,7 @@ internal class QuizMaster : RoleBase SystemTypes.HeliSabotage ]; - public static ((string ColorString, PlayerControl Player) LastReportedPlayer, string LastPlayerPressedButtonName, SystemTypes LastSabotage, string LastReporterName, int NumPlayersVotedLastMeeting, string FirstReportedBodyPlayerName, int NumEmergencyMeetings, int NumPlayersDeadThisRound, int NumPlayersDeadFirstRound, int NumSabotages, int NumMeetings) Data = ((string.Empty, null), string.Empty, default, string.Empty, 0, string.Empty, 0, 0, 0, 0, 0); + public static ((string ColorString, PlayerControl Player) LastReportedPlayer, string LastPlayerPressedButtonName, SystemTypes LastSabotage, string LastReporterName, int NumPlayersVotedLastMeeting, string FirstReportedBodyPlayerName, int NumEmergencyMeetings, int NumPlayersDeadThisRound, int NumPlayersDeadFirstRound, int NumSabotages, int NumMeetings) Data = ((string.Empty, null), string.Empty, default(SystemTypes), string.Empty, 0, string.Empty, 0, 0, 0, 0, 0); private Question CurrentQuestion; public byte QuizMasterId; @@ -85,7 +85,7 @@ internal class QuizMaster : RoleBase QuizMasters = []; - Data = ((string.Empty, null), string.Empty, default, string.Empty, 0, string.Empty, 0, 0, 0, 0, 0); + Data = ((string.Empty, null), string.Empty, default(SystemTypes), string.Empty, 0, string.Empty, 0, 0, 0, 0, 0); AllColors = []; @@ -194,7 +194,7 @@ internal class QuizMaster : RoleBase { case 1 when Data.LastReportedPlayer.ColorString != string.Empty: case 2 when Data.LastPlayerPressedButtonName != string.Empty: - case 3 when Data.LastSabotage != default: + case 3 when Data.LastSabotage != default(SystemTypes): case 4 when Main.LastVotedPlayerInfo != null: case 5 when Data.LastReporterName != string.Empty: case 6 when Data.NumPlayersVotedLastMeeting != 0: @@ -266,15 +266,9 @@ internal class QuizMaster : RoleBase return new(title, allAnswersList.ToArray(), correctIndex); - IEnumerable GetTwoRandomNames(string except) - { - return Main.AllPlayerControls.Select(x => x?.GetRealName()).Without(except).Shuffle().TakeLast(2); - } + IEnumerable GetTwoRandomNames(string except) => Main.AllPlayerControls.Select(x => x?.GetRealName()).Without(except).Shuffle().TakeLast(2); - IEnumerable GetTwoRandomNumbers(params int[] nums) - { - return IRandom.SequenceUnique(3, nums[1], nums[2] + 1).Without(nums[0]).Take(2).Select(x => x.ToString()); - } + IEnumerable GetTwoRandomNumbers(params int[] nums) => IRandom.SequenceUnique(3, nums[1], nums[2] + 1).Without(nums[0]).Take(2).Select(x => x.ToString()); } public override void OnReportDeadBody() diff --git a/Roles/Neutral/Revolutionist.cs b/Roles/Neutral/Revolutionist.cs index a73679f11..251840c64 100644 --- a/Roles/Neutral/Revolutionist.cs +++ b/Roles/Neutral/Revolutionist.cs @@ -16,13 +16,13 @@ internal class Revolutionist : RoleBase public static byte CurrentDrawTarget = byte.MaxValue; public static bool On; - public override bool IsEnable => On; public static OptionItem RevolutionistDrawTime; public static OptionItem RevolutionistCooldown; public static OptionItem RevolutionistDrawCount; public static OptionItem RevolutionistKillProbability; public static OptionItem RevolutionistVentCountDown; + public override bool IsEnable => On; public override void SetupCustomOption() { diff --git a/Roles/Neutral/Rogue.cs b/Roles/Neutral/Rogue.cs index 88482aa65..5739f809a 100644 --- a/Roles/Neutral/Rogue.cs +++ b/Roles/Neutral/Rogue.cs @@ -61,7 +61,7 @@ public class Rogue : RoleBase RoguePC = Utils.GetPlayerById(playerId); GotObjectives = []; GotRewards = []; - CurrentTask = (default, default, null, false); + CurrentTask = (default(Objective), default(Reward), null, false); AllTasksCompleted = false; SendRPC(); diff --git a/Roles/Neutral/Romantic.cs b/Roles/Neutral/Romantic.cs index 8f2b68f8d..c34c62121 100644 --- a/Roles/Neutral/Romantic.cs +++ b/Roles/Neutral/Romantic.cs @@ -185,7 +185,7 @@ public class Romantic : RoleBase else if (!IsPartnerProtected) { IsPartnerProtected = true; - + var sender = CustomRpcSender.Create("Romantic.OnCheckMurder - 1", SendOption.Reliable); RomanticPC.ResetKillCooldown(); @@ -194,7 +194,7 @@ public class Romantic : RoleBase sender.Notify(RomanticPC, GetString("RomanticProtectPartner")); sender.Notify(Partner, GetString("RomanticIsProtectingYou")); - + sender.SendMessage(); LateTask.New(() => @@ -211,7 +211,7 @@ public class Romantic : RoleBase sender2.Notify(Partner, GetString("ProtectingOver")); sender2.SetKillCooldown(RomanticPC); - + sender2.SendMessage(); }, ProtectDuration.GetFloat(), "RomanticProtecting"); } diff --git a/Roles/Neutral/RoomRusher.cs b/Roles/Neutral/RoomRusher.cs index fe1677b7a..df52dc035 100644 --- a/Roles/Neutral/RoomRusher.cs +++ b/Roles/Neutral/RoomRusher.cs @@ -80,7 +80,7 @@ public class RoomRusher : RoleBase AURoleOptions.EngineerInVentMaxTime = 300f; } - void StartNewRound(bool initial = false, bool dontCount = false, bool afterMeeting = false) + private void StartNewRound(bool initial = false, bool dontCount = false, bool afterMeeting = false) { MapNames map = Main.CurrentMap; @@ -110,7 +110,7 @@ public class RoomRusher : RoleBase bool involvesDecontamination = map switch { - MapNames.MiraHQ => (previous is SystemTypes.Laboratory or SystemTypes.Reactor) ^ (RoomGoal is SystemTypes.Laboratory or SystemTypes.Reactor), + MapNames.MiraHQ => previous is SystemTypes.Laboratory or SystemTypes.Reactor ^ RoomGoal is SystemTypes.Laboratory or SystemTypes.Reactor, MapNames.Polus => previous == SystemTypes.Specimens || RoomGoal == SystemTypes.Specimens, _ => false }; @@ -215,8 +215,8 @@ public class RoomRusher : RoleBase public override string GetProgressText(byte playerId, bool comms) { - var s1 = Utils.ColorString(Won ? Color.green : Color.white, $" {CompletedNum}"); - var s2 = Utils.ColorString(Won ? Color.white : Color.yellow, $"/{RoomsToWin.GetInt()}"); + string s1 = Utils.ColorString(Won ? Color.green : Color.white, $" {CompletedNum}"); + string s2 = Utils.ColorString(Won ? Color.white : Color.yellow, $"/{RoomsToWin.GetInt()}"); return base.GetProgressText(playerId, comms) + s1 + s2; } diff --git a/Roles/Neutral/Samurai.cs b/Roles/Neutral/Samurai.cs index 4a1031460..e3ff0ab25 100644 --- a/Roles/Neutral/Samurai.cs +++ b/Roles/Neutral/Samurai.cs @@ -103,8 +103,10 @@ internal class Samurai : RoleBase 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; diff --git a/Roles/Neutral/SchrodingersCat.cs b/Roles/Neutral/SchrodingersCat.cs index 1fce6e7ab..3f286f7f3 100644 --- a/Roles/Neutral/SchrodingersCat.cs +++ b/Roles/Neutral/SchrodingersCat.cs @@ -39,7 +39,7 @@ internal class SchrodingersCat : RoleBase if (!StealsExactImpostorRole.GetBool() && (killerRole.IsImpostor() || killerRole.IsMadmate())) killerRole = CustomRoles.Refugee; if (killerRole == CustomRoles.Jackal) killerRole = CustomRoles.Sidekick; if (Options.SingleRoles.Contains(killerRole)) killerRole = CustomRoles.Amnesiac; - + var sender = CustomRpcSender.Create("SchrodingersCat.OnCheckMurderAsTarget", SendOption.Reliable); target.RpcSetCustomRole(killerRole); @@ -51,7 +51,7 @@ internal class SchrodingersCat : RoleBase sender.Notify(target, string.Format(Translator.GetString("SchrodingersCat.Notify.RecruitedByKiller"), killer.GetRealName(), killerRole.ToColoredString()), setName: false); sender.SendMessage(); - + Utils.NotifyRoles(SpecifySeer: killer, ForceLoop: true); Utils.NotifyRoles(SpecifySeer: target, ForceLoop: true); diff --git a/Roles/Neutral/Seamstress.cs b/Roles/Neutral/Seamstress.cs index 296b2686d..78f914616 100644 --- a/Roles/Neutral/Seamstress.cs +++ b/Roles/Neutral/Seamstress.cs @@ -11,13 +11,13 @@ public class Seamstress : RoleBase public static bool On; private static List Instances = []; - public override bool IsEnable => On; - private static OptionItem ShapeshiftCooldown; private byte SeamstressID; public (byte, byte) SewedPlayers; + public override bool IsEnable => On; + public override void SetupCustomOption() { StartSetup(645800) @@ -47,7 +47,7 @@ public class Seamstress : RoleBase if (!firstIsSet && !secondIsSet) cd = ShapeshiftCooldown.GetFloat(); else if (firstIsSet ^ secondIsSet) cd = 1f; else cd = 300f; - + AURoleOptions.ShapeshifterCooldown = cd; } @@ -55,7 +55,7 @@ public class Seamstress : RoleBase { bool firstIsSet = SewedPlayers.Item1 != byte.MaxValue; bool secondIsSet = SewedPlayers.Item2 != byte.MaxValue; - + switch (firstIsSet) { case true when secondIsSet: @@ -67,7 +67,7 @@ public class Seamstress : RoleBase SewedPlayers.Item1 = target.PlayerId; break; } - + shapeshifter.SyncSettings(); target.Notify(string.Format(Translator.GetString("SewedBySeamstress"), CustomRoles.Seamstress.ToColoredString())); Utils.NotifyRoles(SpecifySeer: shapeshifter, SpecifyTarget: target); @@ -101,8 +101,8 @@ public class Seamstress : RoleBase { byte[] tuple = [SewedPlayers.Item1, SewedPlayers.Item2]; if (tuple.All(x => x == byte.MaxValue)) return; - - var sewed = tuple.ToValidPlayers().ToList(); + + List sewed = tuple.ToValidPlayers().ToList(); if (sewed.Count != 2 || sewed.Exists(x => !x.IsAlive())) { @@ -110,8 +110,8 @@ public class Seamstress : RoleBase Utils.SendRPC(CustomRPC.SyncRoleData, SeamstressID, SewedPlayers.Item1, SewedPlayers.Item2); pc.SyncSettings(); pc.RpcResetAbilityCooldown(); - - if (sewed.Count > 0 && sewed.FindFirst(x => x.IsAlive(), out var alive)) + + if (sewed.Count > 0 && sewed.FindFirst(x => x.IsAlive(), out PlayerControl alive)) Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: alive); } } diff --git a/Roles/Neutral/Spirit.cs b/Roles/Neutral/Spirit.cs index da188efea..199091e34 100644 --- a/Roles/Neutral/Spirit.cs +++ b/Roles/Neutral/Spirit.cs @@ -95,7 +95,7 @@ public class Spirit : RoleBase { newTarget = null; - if (!Instances.FindFirst(x => x.Targets.Item1 == originalTarget.PlayerId || x.Targets.Item2 == originalTarget.PlayerId, out var spirit)) + if (!Instances.FindFirst(x => x.Targets.Item1 == originalTarget.PlayerId || x.Targets.Item2 == originalTarget.PlayerId, out Spirit spirit)) return false; if (spirit.Targets.Item1 == originalTarget.PlayerId) @@ -111,7 +111,7 @@ public class Spirit : RoleBase byte[] tuple = [Targets.Item1, Targets.Item2]; if (tuple.All(x => x == byte.MaxValue)) return; - var sewed = tuple.ToValidPlayers().ToList(); + List sewed = tuple.ToValidPlayers().ToList(); if (sewed.Count != 2 || sewed.Exists(x => !x.IsAlive())) { @@ -120,7 +120,7 @@ public class Spirit : RoleBase pc.SetAbilityUseLimit(2); pc.RpcResetAbilityCooldown(); - if (sewed.Count > 0 && sewed.FindFirst(x => x.IsAlive(), out var alive)) + if (sewed.Count > 0 && sewed.FindFirst(x => x.IsAlive(), out PlayerControl alive)) Utils.NotifyRoles(SpecifySeer: pc, SpecifyTarget: alive); } } diff --git a/Roles/Neutral/Spiritcaller.cs b/Roles/Neutral/Spiritcaller.cs index 0af80e353..879c3272a 100644 --- a/Roles/Neutral/Spiritcaller.cs +++ b/Roles/Neutral/Spiritcaller.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using AmongUs.GameOptions; using EHR.Modules; +using Hazel; using static EHR.Options; using static EHR.Translator; @@ -115,7 +116,7 @@ public class Spiritcaller : RoleBase target.RpcSetCustomRole(CustomRoles.EvilSpirit); - var writer = CustomRpcSender.Create("SpiritCallerSendMessage", Hazel.SendOption.Reliable); + var writer = CustomRpcSender.Create("SpiritCallerSendMessage", SendOption.Reliable); writer.StartMessage(target.GetClientId()); writer.StartRpc(target.NetId, (byte)RpcCalls.SetName) diff --git a/Roles/Neutral/Starspawn.cs b/Roles/Neutral/Starspawn.cs index 561f71ae3..824352f1b 100644 --- a/Roles/Neutral/Starspawn.cs +++ b/Roles/Neutral/Starspawn.cs @@ -10,15 +10,15 @@ public class Starspawn : RoleBase public static bool On; private static List Instances = []; - public override bool IsEnable => On; - private static OptionItem AbilityUseLimit; private static OptionItem AbilityCooldown; - public HashSet IsolatedPlayers = []; + public static bool IsDayBreak; public bool HasUsedDayBreak; - public static bool IsDayBreak; + public HashSet IsolatedPlayers = []; + + public override bool IsEnable => On; public override void SetupCustomOption() { diff --git a/Roles/Neutral/Succubus.cs b/Roles/Neutral/Succubus.cs index a47873d34..fdf21c637 100644 --- a/Roles/Neutral/Succubus.cs +++ b/Roles/Neutral/Succubus.cs @@ -108,7 +108,7 @@ public class Succubus : RoleBase killer.RpcRemoveAbilityUse(); target.RpcSetCustomRole(CustomRoles.Charmed); - + var sender = CustomRpcSender.Create("Succubus.OnCheckMurder", SendOption.Reliable); sender.Notify(killer, Utils.ColorString(Utils.GetRoleColor(CustomRoles.Succubus), GetString("SuccubusCharmedPlayer"))); @@ -117,7 +117,7 @@ public class Succubus : RoleBase sender.SetKillCooldown(killer); sender.RpcGuardAndKill(target, killer); sender.RpcGuardAndKill(target, target); - + sender.SendMessage(); Utils.NotifyRoles(SpecifySeer: killer, SpecifyTarget: target, ForceLoop: true); diff --git a/Roles/Neutral/Vengeance.cs b/Roles/Neutral/Vengeance.cs index c98ecc171..c15fd5663 100644 --- a/Roles/Neutral/Vengeance.cs +++ b/Roles/Neutral/Vengeance.cs @@ -119,7 +119,7 @@ public class Vengeance : RoleBase return; } - player.Notify(string.Format(GetString("VengeanceRevenge"), seconds), 3f, overrideAll: true); + player.Notify(string.Format(GetString("VengeanceRevenge"), seconds), 3f, true); Timer = seconds; LateTask.New(() => { Countdown(seconds - 1, player); }, 1.01f, log: false); diff --git a/Roles/Neutral/Weatherman.cs b/Roles/Neutral/Weatherman.cs index 9bfeff4af..9f6ebd5ee 100644 --- a/Roles/Neutral/Weatherman.cs +++ b/Roles/Neutral/Weatherman.cs @@ -1,4 +1,5 @@ -using AmongUs.GameOptions; +using System; +using AmongUs.GameOptions; namespace EHR.Neutral; @@ -66,8 +67,8 @@ public class Weatherman : RoleBase { LateTask.New(() => { - var disaster = NaturalDisasters.GetAllDisasters().RandomElement(); - var room = pc.GetPlainShipRoom(); + Type disaster = NaturalDisasters.GetAllDisasters().RandomElement(); + PlainShipRoom room = pc.GetPlainShipRoom(); NaturalDisasters.FixedUpdatePatch.AddPreparingDisaster(pc.Pos(), disaster.Name, room == null ? null : room.RoomId); }, 3f, "Weatherman.SpawnRandomDisaster"); } diff --git a/Roles/Neutral/Werewolf.cs b/Roles/Neutral/Werewolf.cs index e276ab310..add58a55d 100644 --- a/Roles/Neutral/Werewolf.cs +++ b/Roles/Neutral/Werewolf.cs @@ -141,7 +141,7 @@ public class Werewolf : RoleBase if (!player.IsModdedClient()) { long cooldown = lastTime + (long)RampageCD.GetFloat() - now; - if ((int)cooldown != CD) player.Notify(string.Format(GetString("CDPT"), cooldown + 1), 3f, overrideAll: true); + if ((int)cooldown != CD) player.Notify(string.Format(GetString("CDPT"), cooldown + 1), 3f, true); CD = (int)cooldown; } @@ -255,7 +255,7 @@ public class Werewolf : RoleBase { if (Medic.ProtectList.Contains(target.PlayerId) || !IsRampaging) return false; - if (killer.RpcCheckAndMurder(target, check: true)) + if (killer.RpcCheckAndMurder(target, true)) Main.PlayerStates[target.PlayerId].deathReason = PlayerState.DeathReason.Mauled; return true; diff --git a/Roles/Neutral/Wraith.cs b/Roles/Neutral/Wraith.cs index 372624655..1840d53c7 100644 --- a/Roles/Neutral/Wraith.cs +++ b/Roles/Neutral/Wraith.cs @@ -24,5 +24,8 @@ public class Wraith : RoleBase public override void Add(byte playerId) { } - public override void ApplyGameOptions(IGameOptions opt, byte id) => opt.SetVision(ImpostorVision.GetBool()); -} + public override void ApplyGameOptions(IGameOptions opt, byte id) + { + opt.SetVision(ImpostorVision.GetBool()); + } +} \ No newline at end of file diff --git a/Roles/RoleBase.cs b/Roles/RoleBase.cs index b29877fbb..6167ace52 100644 --- a/Roles/RoleBase.cs +++ b/Roles/RoleBase.cs @@ -180,7 +180,7 @@ public abstract class RoleBase : IComparable protected bool IsThisRole(byte id) { - var role = Main.PlayerStates.TryGetValue(id, out var state) ? state.MainRole : CustomRoles.NotAssigned; + CustomRoles role = Main.PlayerStates.TryGetValue(id, out PlayerState state) ? state.MainRole : CustomRoles.NotAssigned; return role == Enum.Parse(GetType().Name, true); }