Decompiled source of CardSabotage v0.3.0

CardSabotage.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using InControl;
using Photon.Pun;
using RWF.GameModes;
using TMPro;
using UnboundLib;
using UnboundLib.GameModes;
using UnboundLib.Networking;
using UnboundLib.Utils.UI;
using UnityEngine;
using UnityEngine.Events;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("0.0.0.0")]
namespace CardSabotage;

[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInPlugin("com.cardsabotage.rounds", "Card Sabotage", "0.3.0")]
[BepInProcess("Rounds.exe")]
public class CardSabotagePlugin : BaseUnityPlugin
{
	[Serializable]
	[CompilerGenerated]
	private sealed class <>c
	{
		public static readonly <>c <>9 = new <>c();

		public static UnityAction <>9__7_0;

		public static Func<Contestant, int> <>9__13_0;

		public static Func<IGrouping<int, Contestant>, Contestant> <>9__13_1;

		public static Func<PickAssignment, int> <>9__13_2;

		public static Func<PickAssignment, int> <>9__13_3;

		public static Func<PickAssignment, bool> <>9__13_4;

		internal void <Start>b__7_0()
		{
		}

		internal int <OnPickStart>b__13_0(Contestant c)
		{
			return c.TeamId;
		}

		internal Contestant <OnPickStart>b__13_1(IGrouping<int, Contestant> g)
		{
			return new Contestant(g.Key, g.Key, g.First().WonRound);
		}

		internal int <OnPickStart>b__13_2(PickAssignment a)
		{
			return a.PickerId;
		}

		internal int <OnPickStart>b__13_3(PickAssignment a)
		{
			return a.RecipientId;
		}

		internal bool <OnPickStart>b__13_4(PickAssignment a)
		{
			return a.Skip;
		}
	}

	public const string ModId = "com.cardsabotage.rounds";

	public const string ModName = "Card Sabotage";

	public const string Version = "0.3.0";

	private static ManualLogSource logger;

	internal static ConfigEntry<bool> ConfigEveryoneReceives;

	private static readonly Random rng = new Random();

	private void Awake()
	{
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		logger = ((BaseUnityPlugin)this).Logger;
		ConfigEveryoneReceives = ((BaseUnityPlugin)this).Config.Bind<bool>("Card Sabotage", "BothPlayersPick", false, "Revenge modes only: the player who isn't being sabotaged still gets a card they pick for themselves.");
		new Harmony("com.cardsabotage.rounds").PatchAll();
	}

	private void Start()
	{
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_0100: Expected O, but got Unknown
		//IL_0100: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Expected O, but got Unknown
		SabotageState.Mode = SabotageMode.Off;
		SabotageState.EveryoneReceivesCard = ConfigEveryoneReceives.Value;
		if (Chainloader.PluginInfos.ContainsKey("io.olavim.rounds.rwf"))
		{
			SabotageGameModes.Register();
		}
		else
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"Rounds With Friends not found: the Sabotage game modes need it to appear in the lobby.");
		}
		Unbound.RegisterCredits("Card Sabotage", new string[1] { "Card Sabotage contributors" }, new string[0], new string[0]);
		object obj = <>c.<>9__7_0;
		if (obj == null)
		{
			UnityAction val = delegate
			{
			};
			<>c.<>9__7_0 = val;
			obj = (object)val;
		}
		Unbound.RegisterMenu("Card Sabotage", (UnityAction)obj, (Action<GameObject>)SabotageMenu.Build, (GameObject)null, true);
		Unbound.RegisterHandshake("com.cardsabotage.rounds", (Action)OnHandShakeCompleted);
		GameModeManager.AddHook("GameStart", (Func<IGameModeHandler, IEnumerator>)OnGameStart);
		GameModeManager.AddHook("PickStart", (Func<IGameModeHandler, IEnumerator>)OnPickStart);
		GameModeManager.AddHook("PickEnd", (Func<IGameModeHandler, IEnumerator>)OnPickEnd);
		GameObject val2 = new GameObject("CardSabotageBanner");
		Object.DontDestroyOnLoad((Object)val2);
		val2.AddComponent<SabotageBanner>();
		val2.AddComponent<TeamVoteController>();
	}

	internal static void Log(string msg)
	{
		if (logger != null)
		{
			logger.LogInfo((object)msg);
		}
	}

	private static void OnHandShakeCompleted()
	{
		if (PhotonNetwork.IsMasterClient)
		{
			PushSettings();
		}
	}

	internal static void PushSettings()
	{
		if (PhotonNetwork.IsMasterClient)
		{
			NetworkingManager.RPC_Others(typeof(CardSabotagePlugin), "RPC_SyncSettings", new object[1] { SabotageState.EveryoneReceivesCard });
		}
	}

	[UnboundRPC]
	public static void RPC_SyncSettings(bool everyoneReceives)
	{
		SabotageState.EveryoneReceivesCard = everyoneReceives;
	}

	private static IEnumerator OnGameStart(IGameModeHandler gm)
	{
		SabotageState.Mode = SabotageGameModes.ModeForHandler(GameModeManager.CurrentHandlerID, out var teamVote);
		SabotageState.TeamVote = teamVote;
		Log("Game started in '" + GameModeManager.CurrentHandlerID + "', sabotage mode: " + SabotageState.Mode.ToString() + (teamVote ? " (team vote)" : ""));
		SabotageState.ResetPickPhase();
		RoundTracker.Reset(gm);
		yield break;
	}

	private static IEnumerator OnPickStart(IGameModeHandler gm)
	{
		if (!SabotageState.Active)
		{
			yield break;
		}
		if (PhotonNetwork.IsMasterClient)
		{
			List<Contestant> list = RoundTracker.BuildContestants(gm);
			if (SabotageState.TeamVote)
			{
				list = (from c in list
					group c by c.TeamId into g
					select new Contestant(g.Key, g.Key, g.First().WonRound)).ToList();
			}
			List<PickAssignment> list2 = SabotagePlanner.Plan(SabotageState.Mode, list, SabotageState.EveryoneReceivesCard, rng);
			SabotageState.SetAssignments(list2);
			NetworkingManager.RPC_Others(typeof(CardSabotagePlugin), "RPC_SyncPlan", new object[3]
			{
				list2.Select((PickAssignment a) => a.PickerId).ToArray(),
				list2.Select((PickAssignment a) => a.RecipientId).ToArray(),
				list2.Select((PickAssignment a) => a.Skip).ToArray()
			});
		}
		else
		{
			float waited = 0f;
			while (!SabotageState.AssignmentsReady && waited < 3f)
			{
				waited += Time.unscaledDeltaTime;
				yield return null;
			}
			if (!SabotageState.AssignmentsReady)
			{
				logger.LogWarning((object)"Host's sabotage plan never arrived; this pick phase will be vanilla on this client.");
			}
		}
	}

	[UnboundRPC]
	public static void RPC_SyncPlan(int[] pickers, int[] recipients, bool[] skips)
	{
		List<PickAssignment> list = new List<PickAssignment>();
		for (int i = 0; i < pickers.Length; i++)
		{
			list.Add(new PickAssignment
			{
				PickerId = pickers[i],
				RecipientId = recipients[i],
				Skip = skips[i]
			});
		}
		SabotageState.SetAssignments(list);
	}

	private static IEnumerator OnPickEnd(IGameModeHandler gm)
	{
		SabotageState.ResetPickPhase();
		RoundTracker.Snapshot(gm);
		yield break;
	}
}
internal static class RoundTracker
{
	private static readonly Dictionary<int, int> lastRounds = new Dictionary<int, int>();

	public static void Reset(IGameModeHandler gm)
	{
		lastRounds.Clear();
	}

	public static void Snapshot(IGameModeHandler gm)
	{
		lastRounds.Clear();
		foreach (int item in TeamIds())
		{
			lastRounds[item] = RoundsOf(gm, item);
		}
	}

	public static List<Contestant> BuildContestants(IGameModeHandler gm)
	{
		HashSet<int> winningTeams = new HashSet<int>();
		foreach (int item in TeamIds())
		{
			lastRounds.TryGetValue(item, out var value);
			if (RoundsOf(gm, item) > value)
			{
				winningTeams.Add(item);
			}
		}
		return PlayerManager.instance.players.Select((Player p) => new Contestant(p.playerID, p.teamID, winningTeams.Contains(p.teamID))).ToList();
	}

	private static IEnumerable<int> TeamIds()
	{
		return PlayerManager.instance.players.Select((Player p) => p.teamID).Distinct();
	}

	private static int RoundsOf(IGameModeHandler gm, int teamId)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		return gm.GetTeamScore(teamId).rounds;
	}
}
internal static class SabotageUtil
{
	public static Player GetPlayer(int playerId)
	{
		return ((IEnumerable<Player>)PlayerManager.instance.players).FirstOrDefault((Func<Player, bool>)((Player p) => p.playerID == playerId));
	}

	public static int CurrentPickerId()
	{
		try
		{
			return (int)Traverse.Create((object)CardChoice.instance).Field("pickrID").GetValue();
		}
		catch (Exception ex)
		{
			CardSabotagePlugin.Log("Could not read CardChoice.pickrID: " + ex.Message);
			return -1;
		}
	}
}
[HarmonyPatch(typeof(ApplyCardStats), "Pick")]
internal static class ApplyCardStatsPickPatch
{
	private static void Prefix(ref int pickerID, ref PickerType pickerType)
	{
		if (!SabotageState.Active || !SabotageState.PickInProgress || (int)pickerType != 1 || pickerID != SabotageState.CurrentPickerId)
		{
			return;
		}
		if (SabotageState.RecipientIsTeam)
		{
			CardSabotagePlugin.Log("Team vote card from picker " + pickerID + " goes to every player on team " + SabotageState.CurrentRecipientId);
			pickerID = SabotageState.CurrentRecipientId;
			pickerType = (PickerType)0;
		}
		else if (SabotageState.CurrentRecipientId != SabotageState.CurrentPickerId)
		{
			Player player = SabotageUtil.GetPlayer(SabotageState.CurrentRecipientId);
			if (!((Object)(object)player == (Object)null))
			{
				CardSabotagePlugin.Log("Redirecting card from picker " + pickerID + " to recipient " + player.playerID);
				pickerID = player.playerID;
			}
		}
	}
}
[HarmonyPatch(typeof(CardChoiceVisuals), "Show")]
internal static class CardChoiceVisualsShowPatch
{
	private static bool Prefix()
	{
		if (SabotageState.RunningOwnPicks)
		{
			return true;
		}
		return !SabotageState.TakesOverPhase;
	}
}
[HarmonyPatch(typeof(CardChoice), "DoPick")]
internal static class CardChoiceDoPickPatch
{
	private static bool Prefix(PickerType __2, ref IEnumerator __result)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Invalid comparison between Unknown and I4
		if (SabotageState.RunningOwnPicks)
		{
			return true;
		}
		if ((int)__2 != 1)
		{
			return true;
		}
		if (!SabotageState.TakesOverPhase)
		{
			return true;
		}
		if (SabotageState.PhaseHandled)
		{
			__result = Empty();
			return false;
		}
		SabotageState.PhaseHandled = true;
		__result = RunPlan();
		return false;
	}

	private static IEnumerator RunPlan()
	{
		SabotageState.RunningOwnPicks = true;
		try
		{
			PickAssignment[] array = SabotageState.Plan.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				PickAssignment pickAssignment = array[i];
				if (!pickAssignment.Skip)
				{
					if (SabotageState.TeamVote)
					{
						int pickerId = pickAssignment.PickerId;
						string text = pickerId.ToString();
						pickerId = pickAssignment.RecipientId;
						CardSabotagePlugin.Log("Team vote: team " + text + " votes on a card for team " + pickerId);
						yield return TeamVoteController.Run(pickAssignment.PickerId, pickAssignment.RecipientId);
						yield return (object)new WaitForSecondsRealtime(0.3f);
					}
					else if (!((Object)(object)SabotageUtil.GetPlayer(pickAssignment.PickerId) == (Object)null))
					{
						SabotageState.CurrentPickerId = pickAssignment.PickerId;
						SabotageState.CurrentRecipientId = pickAssignment.RecipientId;
						SabotageState.PickInProgress = true;
						int pickerId = pickAssignment.PickerId;
						string text2 = pickerId.ToString();
						pickerId = pickAssignment.RecipientId;
						CardSabotagePlugin.Log("Sabotage pick: player " + text2 + " picks for player " + pickerId);
						CardChoiceVisuals.instance.Show(pickAssignment.PickerId, true);
						yield return CardChoice.instance.DoPick(1, pickAssignment.PickerId, (PickerType)1);
						yield return (object)new WaitForSecondsRealtime(0.3f);
						SabotageState.PickInProgress = false;
						SabotageState.CurrentPickerId = -1;
						SabotageState.CurrentRecipientId = -1;
					}
				}
			}
		}
		finally
		{
			SabotageState.RunningOwnPicks = false;
			SabotageState.PickInProgress = false;
		}
	}

	private static IEnumerator Empty()
	{
		yield break;
	}
}
[HarmonyPatch(typeof(CardChoice), "DoPlayerSelect")]
internal static class CardChoiceDoPlayerSelectPatch
{
	private static bool Prefix()
	{
		return TeamVoteController.Session == null;
	}
}
internal class SabotageBanner : MonoBehaviour
{
	private GUIStyle style;

	private void OnGUI()
	{
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_011c: Unknown result type (might be due to invalid IL or missing references)
		if (!SabotageState.Active || !SabotageState.PickInProgress)
		{
			return;
		}
		if (SabotageState.RecipientIsTeam)
		{
			VoteSession session = TeamVoteController.Session;
			if (session != null)
			{
				EnsureStyle();
				string text = ((session.PickerTeam == session.RecipientTeam) ? $"TEAM {session.PickerTeam + 1} IS VOTING ON ITS OWN CARD" : $"TEAM {session.PickerTeam + 1} IS SABOTAGING TEAM {session.RecipientTeam + 1}");
				GUI.Label(new Rect(0f, 20f, (float)Screen.width, 50f), text, style);
			}
			return;
		}
		Player player = SabotageUtil.GetPlayer(SabotageState.CurrentPickerId);
		Player player2 = SabotageUtil.GetPlayer(SabotageState.CurrentRecipientId);
		if (!((Object)(object)player == (Object)null) && !((Object)(object)player2 == (Object)null))
		{
			EnsureStyle();
			string text2 = ((player.playerID == player2.playerID) ? "PICK YOUR OWN CARD" : $"PLAYER {player.playerID + 1} IS SABOTAGING PLAYER {player2.playerID + 1}");
			GUI.Label(new Rect(0f, 20f, (float)Screen.width, 50f), text2, style);
		}
	}

	private void EnsureStyle()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Expected O, but got Unknown
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		if (style == null)
		{
			style = new GUIStyle(GUI.skin.label)
			{
				alignment = (TextAnchor)4,
				fontSize = 28,
				fontStyle = (FontStyle)1
			};
			style.normal.textColor = new Color(1f, 0.35f, 0.3f);
		}
	}
}
public class SabotageDeathmatchHandler : RWFGameModeHandler<GM_Deathmatch>
{
	private const string DeathmatchVideo = "https://github.com/olavim/RoundsWithFriends/raw/main/Media/Deathmatch.mp4";

	public SabotageDeathmatchHandler(SabotageMode mode)
		: base(SabotageGameModes.LobbyName(mode, teamVote: false), SabotageGameModes.IdFor(mode, teamVote: false), false, 2, 5, (int?)null, (int?)null, (int?)null, (int?)null, "CARD SABOTAGE: " + SabotageModeInfo.Description(mode) + ". Free for all, last player standing wins.", (int?)null, "https://github.com/olavim/RoundsWithFriends/raw/main/Media/Deathmatch.mp4")
	{
	}
}
public class SabotageTeamDeathmatchHandler : RWFGameModeHandler<GM_TeamDeathmatch>
{
	private const string TeamDeathmatchVideo = "https://github.com/olavim/RoundsWithFriends/raw/main/Media/TeamDeathmatch.mp4";

	public SabotageTeamDeathmatchHandler(SabotageMode mode)
		: base(SabotageGameModes.LobbyName(mode, teamVote: true), SabotageGameModes.IdFor(mode, teamVote: true), true, 2, 5, (int?)null, (int?)null, (int?)null, (int?)null, "CARD SABOTAGE (TEAMS): " + SabotageModeInfo.TeamDescription(mode) + ". The picking team votes, ties are rolled. Last team standing wins.", (int?)null, "https://github.com/olavim/RoundsWithFriends/raw/main/Media/TeamDeathmatch.mp4")
	{
	}
}
public static class SabotageGameModes
{
	private const string IdPrefix = "CardSabotage_";

	private const string TeamIdPrefix = "CardSabotageTeam_";

	public static string IdFor(SabotageMode mode, bool teamVote)
	{
		return (teamVote ? "CardSabotageTeam_" : "CardSabotage_") + mode;
	}

	public static string LobbyName(SabotageMode mode, bool teamVote)
	{
		return (teamVote ? "Team Sabotage: " : "Sabotage: ") + SabotageModeInfo.DisplayName(mode);
	}

	public static SabotageMode ModeForHandler(string handlerId, out bool teamVote)
	{
		teamVote = false;
		if (handlerId == null)
		{
			return SabotageMode.Off;
		}
		SabotageMode[] selectable = SabotageModeInfo.Selectable;
		foreach (SabotageMode sabotageMode in selectable)
		{
			if (handlerId == IdFor(sabotageMode, teamVote: false))
			{
				return sabotageMode;
			}
			if (handlerId == IdFor(sabotageMode, teamVote: true))
			{
				teamVote = true;
				return sabotageMode;
			}
		}
		return SabotageMode.Off;
	}

	[MethodImpl(MethodImplOptions.NoInlining)]
	public static void Register()
	{
		SabotageMode[] selectable = SabotageModeInfo.Selectable;
		foreach (SabotageMode mode in selectable)
		{
			GameModeManager.AddHandler<GM_Deathmatch>(IdFor(mode, teamVote: false), (IGameModeHandler)(object)new SabotageDeathmatchHandler(mode));
		}
		selectable = SabotageModeInfo.Selectable;
		foreach (SabotageMode mode2 in selectable)
		{
			GameModeManager.AddHandler<GM_TeamDeathmatch>(IdFor(mode2, teamVote: true), (IGameModeHandler)(object)new SabotageTeamDeathmatchHandler(mode2));
		}
	}
}
internal static class SabotageMenu
{
	public static void Build(GameObject menu)
	{
		TextMeshProUGUI val = default(TextMeshProUGUI);
		MenuHandler.CreateText("CARD SABOTAGE", menu, ref val, 60, true, (Color?)null, (TMP_FontAsset)null, (Material)null, (TextAlignmentOptions?)null);
		TextMeshProUGUI val2 = default(TextMeshProUGUI);
		MenuHandler.CreateText("Choose a mode in the lobby's game mode list: the \"Sabotage: ...\" entries.", menu, ref val2, 28, true, (Color?)null, (TMP_FontAsset)null, (Material)null, (TextAlignmentOptions?)null);
		TextMeshProUGUI val3 = default(TextMeshProUGUI);
		MenuHandler.CreateText("Only the host can change the setting below. Everyone uses the host's value.", menu, ref val3, 24, true, (Color?)null, (TMP_FontAsset)null, (Material)null, (TextAlignmentOptions?)null);
		MenuHandler.CreateToggle(SabotageState.EveryoneReceivesCard, "Both Players Pick - in Winner's/Loser's Revenge, the other player still picks a card for themselves", menu, (UnityAction<bool>)delegate(bool isOn)
		{
			SabotageState.EveryoneReceivesCard = isOn;
			CardSabotagePlugin.ConfigEveryoneReceives.Value = isOn;
			CardSabotagePlugin.PushSettings();
		}, 24, true, (Color?)null, (TMP_FontAsset)null, (Material)null, (TextAlignmentOptions?)null);
	}
}
public enum SabotageMode
{
	Off,
	SwapPicks,
	WinnersRevenge,
	LosersRevenge,
	SabotageEveryone,
	LosersChoice
}
public static class SabotageModeInfo
{
	public static readonly SabotageMode[] Selectable = new SabotageMode[5]
	{
		SabotageMode.SwapPicks,
		SabotageMode.WinnersRevenge,
		SabotageMode.LosersRevenge,
		SabotageMode.SabotageEveryone,
		SabotageMode.LosersChoice
	};

	public static string DisplayName(SabotageMode mode)
	{
		return mode switch
		{
			SabotageMode.SwapPicks => "Swap Picks", 
			SabotageMode.WinnersRevenge => "Winner's Revenge", 
			SabotageMode.LosersRevenge => "Loser's Revenge", 
			SabotageMode.SabotageEveryone => "Sabotage Everyone", 
			SabotageMode.LosersChoice => "Loser's Choice", 
			_ => "Off", 
		};
	}

	public static string Description(SabotageMode mode)
	{
		return mode switch
		{
			SabotageMode.SwapPicks => "Everyone picks a card for an opponent", 
			SabotageMode.WinnersRevenge => "The round winner picks the loser's card", 
			SabotageMode.LosersRevenge => "The round loser picks the winner's card", 
			SabotageMode.SabotageEveryone => "Random opponents pick each other's cards", 
			SabotageMode.LosersChoice => "The round loser picks their own card, then picks the winner's card", 
			_ => "Vanilla picking", 
		};
	}

	public static string TeamDescription(SabotageMode mode)
	{
		return mode switch
		{
			SabotageMode.SwapPicks => "Every team votes on a card for an opposing team", 
			SabotageMode.WinnersRevenge => "The winning team votes on the losing team's card", 
			SabotageMode.LosersRevenge => "The losing team votes on the winning team's card", 
			SabotageMode.SabotageEveryone => "Teams vote on a card for a random opposing team", 
			SabotageMode.LosersChoice => "The losing team votes on its own card, then on the winning team's card", 
			_ => "Vanilla picking", 
		};
	}
}
public struct Contestant
{
	public int PlayerId;

	public int TeamId;

	public bool WonRound;

	public Contestant(int playerId, int teamId, bool wonRound)
	{
		PlayerId = playerId;
		TeamId = teamId;
		WonRound = wonRound;
	}
}
public struct PickAssignment
{
	public int PickerId;

	public int RecipientId;

	public bool Skip;
}
public static class SabotagePlanner
{
	public static List<PickAssignment> Plan(SabotageMode mode, IList<Contestant> players, bool everyoneReceivesCard, Random rng)
	{
		List<PickAssignment> list = new List<PickAssignment>();
		if (mode == SabotageMode.Off || players == null || players.Count < 2)
		{
			return list;
		}
		List<Contestant> list2 = players.OrderBy((Contestant p) => p.PlayerId).ToList();
		List<Contestant> list3 = list2.Where((Contestant p) => p.WonRound).ToList();
		List<Contestant> list4 = list2.Where((Contestant p) => !p.WonRound).ToList();
		switch (mode)
		{
		case SabotageMode.SwapPicks:
			foreach (KeyValuePair<int, int> item in SwapTargets(list2))
			{
				list.Add(new PickAssignment
				{
					PickerId = item.Key,
					RecipientId = item.Value
				});
			}
			break;
		case SabotageMode.SabotageEveryone:
			foreach (KeyValuePair<int, int> item2 in RandomTargets(list2, rng))
			{
				list.Add(new PickAssignment
				{
					PickerId = item2.Key,
					RecipientId = item2.Value
				});
			}
			break;
		case SabotageMode.WinnersRevenge:
			AddRevenge(list, list2, list3, list4, everyoneReceivesCard);
			break;
		case SabotageMode.LosersRevenge:
			AddRevenge(list, list2, list4, list3, everyoneReceivesCard);
			break;
		case SabotageMode.LosersChoice:
			AddLosersChoice(list, list4, list3, everyoneReceivesCard);
			break;
		}
		return list;
	}

	private static void AddRevenge(List<PickAssignment> result, List<Contestant> everyone, List<Contestant> pickers, List<Contestant> victims, bool everyoneReceivesCard)
	{
		if (pickers.Count == 0 || victims.Count == 0)
		{
			return;
		}
		HashSet<int> hashSet = new HashSet<int>(pickers.Select((Contestant p) => p.PlayerId));
		for (int num = 0; num < pickers.Count; num++)
		{
			result.Add(new PickAssignment
			{
				PickerId = pickers[num].PlayerId,
				RecipientId = victims[num % victims.Count].PlayerId
			});
		}
		foreach (Contestant item in everyone)
		{
			if (!hashSet.Contains(item.PlayerId))
			{
				result.Add(new PickAssignment
				{
					PickerId = item.PlayerId,
					RecipientId = item.PlayerId,
					Skip = !everyoneReceivesCard
				});
			}
		}
	}

	private static void AddLosersChoice(List<PickAssignment> result, List<Contestant> losers, List<Contestant> winners, bool everyoneReceivesCard)
	{
		if (losers.Count == 0 || winners.Count == 0)
		{
			return;
		}
		for (int i = 0; i < losers.Count; i++)
		{
			int playerId = losers[i].PlayerId;
			result.Add(new PickAssignment
			{
				PickerId = playerId,
				RecipientId = playerId
			});
			result.Add(new PickAssignment
			{
				PickerId = playerId,
				RecipientId = winners[i % winners.Count].PlayerId
			});
		}
		foreach (Contestant winner in winners)
		{
			result.Add(new PickAssignment
			{
				PickerId = winner.PlayerId,
				RecipientId = winner.PlayerId,
				Skip = !everyoneReceivesCard
			});
		}
	}

	public static Dictionary<int, int> SwapTargets(List<Contestant> ordered)
	{
		Dictionary<int, int> dictionary = new Dictionary<int, int>();
		bool flag = ordered.Select((Contestant contestant) => contestant.TeamId).Distinct().Count() == ordered.Count;
		for (int num = 0; num < ordered.Count; num++)
		{
			Contestant p = ordered[num];
			if (flag)
			{
				dictionary[p.PlayerId] = ordered[(num + 1) % ordered.Count].PlayerId;
				continue;
			}
			List<Contestant> list = ordered.Where((Contestant e) => e.TeamId != p.TeamId).ToList();
			if (list.Count == 0)
			{
				dictionary[p.PlayerId] = p.PlayerId;
				continue;
			}
			int num2 = ordered.Where((Contestant t) => t.TeamId == p.TeamId).ToList().FindIndex((Contestant t) => t.PlayerId == p.PlayerId);
			dictionary[p.PlayerId] = list[num2 % list.Count].PlayerId;
		}
		return dictionary;
	}

	public static Dictionary<int, int> RandomTargets(List<Contestant> ordered, Random rng)
	{
		for (int i = 0; i < 64; i++)
		{
			List<Contestant> list = ordered.OrderBy((Contestant _) => rng.Next()).ToList();
			Dictionary<int, int> dictionary = new Dictionary<int, int>();
			bool flag = true;
			for (int num = 0; num < ordered.Count; num++)
			{
				if (ordered[num].TeamId == list[num].TeamId)
				{
					flag = false;
					break;
				}
				dictionary[ordered[num].PlayerId] = list[num].PlayerId;
			}
			if (flag)
			{
				return dictionary;
			}
		}
		return SwapTargets(ordered);
	}
}
public static class SabotageState
{
	public static SabotageMode Mode = SabotageMode.Off;

	public static bool TeamVote = false;

	public static bool RecipientIsTeam;

	public static bool EveryoneReceivesCard = false;

	private static readonly Dictionary<int, PickAssignment> bySlot = new Dictionary<int, PickAssignment>();

	public static readonly List<PickAssignment> Plan = new List<PickAssignment>();

	public static bool AssignmentsReady;

	public static bool PhaseHandled;

	public static bool RunningOwnPicks;

	public static bool PickInProgress;

	public static int CurrentPickerId = -1;

	public static int CurrentRecipientId = -1;

	public static bool TakesOverPhase
	{
		get
		{
			if (Active && AssignmentsReady)
			{
				return Plan.Count > 0;
			}
			return false;
		}
	}

	public static bool Active => Mode != SabotageMode.Off;

	public static void SetAssignments(IList<PickAssignment> list)
	{
		bySlot.Clear();
		Plan.Clear();
		foreach (PickAssignment item in list)
		{
			bySlot[item.PickerId] = item;
			Plan.Add(item);
		}
		PhaseHandled = false;
		AssignmentsReady = true;
	}

	public static bool TryGet(int pickerId, out PickAssignment assignment)
	{
		return bySlot.TryGetValue(pickerId, out assignment);
	}

	public static bool ShouldSkip(int pickerId)
	{
		if (Active && AssignmentsReady && bySlot.TryGetValue(pickerId, out var value))
		{
			return value.Skip;
		}
		return false;
	}

	public static void ResetPickPhase()
	{
		bySlot.Clear();
		Plan.Clear();
		AssignmentsReady = false;
		PhaseHandled = false;
		RunningOwnPicks = false;
		PickInProgress = false;
		RecipientIsTeam = false;
		TeamVoteController.ClearPending();
		CurrentPickerId = -1;
		CurrentRecipientId = -1;
	}
}
internal class VoteSession
{
	public int PickerTeam;

	public int RecipientTeam;

	public int LeadId;

	public List<int> Voters;

	public List<GameObject> Cards;

	public float CardsReadyTime;

	public readonly Dictionary<int, int> Votes = new Dictionary<int, int>();

	public readonly Dictionary<int, int> Cursors = new Dictionary<int, int>();

	public readonly Dictionary<int, int> LastStick = new Dictionary<int, int>();

	public bool ResolveSent;

	public bool Resolved;

	public int[] Tied;

	public int Winner = -1;

	public int RollIndex = -1;

	public bool Rolling;

	public bool Finished;

	public bool CardsReady => Cards != null;
}
internal class TeamVoteController : MonoBehaviour
{
	public const float VoteSeconds = 20f;

	internal static TeamVoteController Instance;

	internal static VoteSession Session;

	private static int[] pendingCardIds;

	private static readonly List<KeyValuePair<int, int>> pendingVotes = new List<KeyValuePair<int, int>>();

	private static int[] pendingTied;

	private static int pendingWinner = -1;

	private static readonly Random rng = new Random();

	private GUIStyle labelStyle;

	private GUIStyle headerStyle;

	private static bool IsHost
	{
		get
		{
			if (!PhotonNetwork.OfflineMode)
			{
				return PhotonNetwork.IsMasterClient;
			}
			return true;
		}
	}

	private void Awake()
	{
		Instance = this;
	}

	internal static void ClearPending()
	{
		pendingCardIds = null;
		pendingVotes.Clear();
		pendingTied = null;
		pendingWinner = -1;
	}

	public static IEnumerator Run(int pickerTeam, int recipientTeam)
	{
		List<int> list = (from p in PlayerManager.instance.players
			where p.teamID == pickerTeam
			select p.playerID into id
			orderby id
			select id).ToList();
		if (list.Count == 0)
		{
			yield break;
		}
		VoteSession s = (Session = new VoteSession
		{
			PickerTeam = pickerTeam,
			RecipientTeam = recipientTeam,
			LeadId = list[0],
			Voters = list
		});
		SabotageState.CurrentPickerId = s.LeadId;
		SabotageState.CurrentRecipientId = recipientTeam;
		SabotageState.RecipientIsTeam = true;
		SabotageState.PickInProgress = true;
		if (pendingCardIds != null)
		{
			ApplyCards(s, pendingCardIds);
		}
		foreach (KeyValuePair<int, int> pendingVote in pendingVotes)
		{
			s.Votes[pendingVote.Key] = pendingVote.Value;
		}
		if (pendingTied != null)
		{
			ApplyResult(s, pendingTied, pendingWinner);
		}
		ClearPending();
		try
		{
			CardChoiceVisuals.instance.Show(s.LeadId, true);
			yield return CardChoice.instance.DoPick(1, s.LeadId, (PickerType)1);
		}
		finally
		{
			s.Finished = true;
			Session = null;
			SabotageState.RecipientIsTeam = false;
			SabotageState.PickInProgress = false;
			SabotageState.CurrentPickerId = -1;
			SabotageState.CurrentRecipientId = -1;
		}
	}

	private static bool IsLocal(int playerId)
	{
		Player player = SabotageUtil.GetPlayer(playerId);
		if ((Object)(object)player != (Object)null && (Object)(object)player.data != (Object)null && (Object)(object)player.data.view != (Object)null)
		{
			return player.data.view.IsMine;
		}
		return false;
	}

	private void Update()
	{
		VoteSession session = Session;
		if (session == null || session.Finished)
		{
			return;
		}
		if (!session.CardsReady && IsLocal(session.LeadId))
		{
			TryAnnounceCards();
		}
		if (!session.CardsReady)
		{
			return;
		}
		if (!session.Resolved)
		{
			HandleLocalInput(session);
			if (IsHost)
			{
				TryResolve(session);
			}
		}
		UpdateHighlights(session);
	}

	private static void TryAnnounceCards()
	{
		Traverse obj = Traverse.Create((object)CardChoice.instance);
		List<GameObject> value = obj.Field("spawnedCards").GetValue<List<GameObject>>();
		Transform[] value2 = obj.Field("children").GetValue<Transform[]>();
		bool value3 = obj.Field("isPlaying").GetValue<bool>();
		if (!(value == null || value2 == null || value3) && value.Count != 0 && value.Count >= value2.Length && !value.Any((GameObject c) => (Object)(object)c == (Object)null))
		{
			int[] array = value.Select((GameObject c) => c.GetComponent<PhotonView>().ViewID).ToArray();
			NetworkingManager.RPC_Others(typeof(TeamVoteController), "RPC_VoteCards", new object[1] { array });
			RPC_VoteCards(array);
		}
	}

	private static void HandleLocalInput(VoteSession s)
	{
		int count = s.Cards.Count;
		foreach (int voter in s.Voters)
		{
			if (!IsLocal(voter))
			{
				continue;
			}
			PlayerActions playerActions = SabotageUtil.GetPlayer(voter).data.playerActions;
			if (playerActions != null)
			{
				if (!s.Cursors.TryGetValue(voter, out var value))
				{
					value = count / 2;
				}
				int num = 0;
				if (((OneAxisInputControl)playerActions.Right).Value > 0.7f)
				{
					num = 1;
				}
				if (((OneAxisInputControl)playerActions.Left).Value > 0.7f)
				{
					num = -1;
				}
				s.LastStick.TryGetValue(voter, out var value2);
				if (num != 0 && num != value2)
				{
					value = Mathf.Clamp(value + num, 0, count - 1);
				}
				s.LastStick[voter] = num;
				s.Cursors[voter] = value;
				if (((OneAxisInputControl)playerActions.Jump).WasPressed && (!s.Votes.TryGetValue(voter, out var value3) || value3 != value))
				{
					NetworkingManager.RPC_Others(typeof(TeamVoteController), "RPC_CastVote", new object[2] { voter, value });
					RPC_CastVote(voter, value);
				}
			}
		}
	}

	private static void TryResolve(VoteSession s)
	{
		if (s.ResolveSent)
		{
			return;
		}
		bool num = s.Voters.Where((int v) => (Object)(object)SabotageUtil.GetPlayer(v) != (Object)null).ToList().All((int v) => s.Votes.ContainsKey(v));
		bool flag = Time.unscaledTime - s.CardsReadyTime > 20f;
		if (!num && !flag)
		{
			return;
		}
		s.ResolveSent = true;
		int count = s.Cards.Count;
		int[] counts = new int[count];
		foreach (KeyValuePair<int, int> vote in s.Votes)
		{
			if (vote.Value >= 0 && vote.Value < count)
			{
				counts[vote.Value]++;
			}
		}
		int max = counts.Max();
		int[] array = (from i in Enumerable.Range(0, count)
			where counts[i] == max
			select i).ToArray();
		int num2 = array[rng.Next(array.Length)];
		NetworkingManager.RPC_Others(typeof(TeamVoteController), "RPC_VoteResult", new object[2] { array, num2 });
		RPC_VoteResult(array, num2);
	}

	[UnboundRPC]
	public static void RPC_VoteCards(int[] viewIds)
	{
		if (Session == null)
		{
			pendingCardIds = viewIds;
		}
		else
		{
			ApplyCards(Session, viewIds);
		}
	}

	private static void ApplyCards(VoteSession s, int[] viewIds)
	{
		if (!s.CardsReady)
		{
			s.Cards = viewIds.Select(delegate(int id)
			{
				PhotonView photonView = PhotonNetwork.GetPhotonView(id);
				return (!((Object)(object)photonView != (Object)null)) ? null : ((Component)photonView).gameObject;
			}).ToList();
			s.CardsReadyTime = Time.unscaledTime;
		}
	}

	[UnboundRPC]
	public static void RPC_CastVote(int voterId, int cardIndex)
	{
		if (Session == null)
		{
			pendingVotes.Add(new KeyValuePair<int, int>(voterId, cardIndex));
		}
		else if (!Session.Resolved)
		{
			Session.Votes[voterId] = cardIndex;
		}
	}

	[UnboundRPC]
	public static void RPC_VoteResult(int[] tied, int winner)
	{
		if (Session == null)
		{
			pendingTied = tied;
			pendingWinner = winner;
		}
		else
		{
			ApplyResult(Session, tied, winner);
		}
	}

	private static void ApplyResult(VoteSession s, int[] tied, int winner)
	{
		if (!s.Resolved)
		{
			s.Resolved = true;
			s.Tied = tied;
			s.Winner = winner;
			((MonoBehaviour)Instance).StartCoroutine(Instance.RollAndPick(s));
		}
	}

	private IEnumerator RollAndPick(VoteSession s)
	{
		float waited = 0f;
		while (!s.CardsReady && waited < 5f && !s.Finished)
		{
			waited += Time.unscaledDeltaTime;
			yield return null;
		}
		s.Rolling = true;
		if (s.Tied.Length > 1)
		{
			int len = s.Tied.Length;
			int num = Array.IndexOf(s.Tied, s.Winner);
			int num2 = Mathf.Max(3, Mathf.CeilToInt(16f / (float)len));
			int steps = num2 * len + num;
			for (int k = 0; k <= steps; k++)
			{
				if (s.Finished)
				{
					yield break;
				}
				s.RollIndex = s.Tied[k % len];
				Tick(s.RollIndex);
				float num3 = (float)k / (float)steps;
				yield return (object)new WaitForSecondsRealtime(Mathf.Lerp(0.035f, 0.55f, num3 * num3 * num3));
			}
		}
		s.RollIndex = s.Winner;
		Tick(s.Winner);
		yield return (object)new WaitForSecondsRealtime((s.Tied.Length > 1) ? 1.1f : 0.7f);
		s.Rolling = false;
		if (s.Finished || Session != s || !IsLocal(s.LeadId))
		{
			yield break;
		}
		GameObject val = ((s.Winner >= 0 && s.Winner < s.Cards.Count) ? s.Cards[s.Winner] : null);
		if ((Object)(object)val == (Object)null)
		{
			val = ((IEnumerable<GameObject>)s.Cards).FirstOrDefault((Func<GameObject, bool>)((GameObject c) => (Object)(object)c != (Object)null));
		}
		if (!((Object)(object)val == (Object)null))
		{
			SetHighlight(s, -1);
			CardChoice.instance.Pick(val, false);
			CardChoice.instance.pickrID = -1;
		}
	}

	private static void Tick(int index)
	{
		try
		{
			Traverse.Create((object)CardChoiceVisuals.instance).Method("RPCA_SetCurrentSelected", new object[1] { index }).GetValue();
		}
		catch (Exception ex)
		{
			CardSabotagePlugin.Log("Roll tick failed: " + ex.Message);
		}
	}

	private static void UpdateHighlights(VoteSession s)
	{
		if (s.Resolved)
		{
			SetHighlight(s, s.RollIndex);
			return;
		}
		HashSet<int> hashSet = new HashSet<int>(s.Cursors.Values);
		for (int i = 0; i < s.Cards.Count; i++)
		{
			SetSelected(s.Cards[i], hashSet.Contains(i));
		}
	}

	private static void SetHighlight(VoteSession s, int index)
	{
		for (int i = 0; i < s.Cards.Count; i++)
		{
			SetSelected(s.Cards[i], i == index);
		}
	}

	private static void SetSelected(GameObject card, bool on)
	{
		if (!((Object)(object)card == (Object)null))
		{
			CardVisuals componentInChildren = card.GetComponentInChildren<CardVisuals>();
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.ChangeSelected(on);
			}
		}
	}

	private void OnGUI()
	{
		//IL_00de: Unknown result type (might be due to invalid IL or missing references)
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		//IL_017d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0182: Unknown result type (might be due to invalid IL or missing references)
		//IL_0184: Unknown result type (might be due to invalid IL or missing references)
		//IL_029f: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
		VoteSession session = Session;
		if (session == null || session.Finished)
		{
			return;
		}
		EnsureStyles();
		string text;
		if (!session.CardsReady)
		{
			text = "TEAM " + (session.PickerTeam + 1) + " IS VOTING...";
		}
		else if (session.Rolling && session.Tied != null && session.Tied.Length > 1)
		{
			text = "TIE! ROLLING...";
		}
		else if (session.Resolved)
		{
			text = "CARD CHOSEN";
		}
		else
		{
			int num = Mathf.Max(0, Mathf.CeilToInt(20f - (Time.unscaledTime - session.CardsReadyTime)));
			text = $"VOTE: LEFT/RIGHT TO MOVE, JUMP TO VOTE   {session.Votes.Count}/{session.Voters.Count} VOTED   {num}s";
		}
		GUI.Label(new Rect(0f, 70f, (float)Screen.width, 40f), text, headerStyle);
		if (!session.CardsReady || session.Resolved)
		{
			return;
		}
		Camera val = (((Object)(object)MainCam.instance != (Object)null && (Object)(object)MainCam.instance.cam != (Object)null) ? MainCam.instance.cam : Camera.main);
		if ((Object)(object)val == (Object)null)
		{
			return;
		}
		int i;
		for (i = 0; i < session.Cards.Count; i++)
		{
			GameObject val2 = session.Cards[i];
			if ((Object)(object)val2 == (Object)null)
			{
				continue;
			}
			Vector3 val3 = val.WorldToScreenPoint(val2.transform.position);
			if (!(val3.z < 0f))
			{
				List<string> list = (from kv in session.Votes
					where kv.Value == i
					select "P" + (kv.Key + 1)).ToList();
				List<string> list2 = (from kv in session.Cursors
					where kv.Value == i
					select "P" + (kv.Key + 1)).ToList();
				string text2 = list.Count + ((list.Count == 1) ? " VOTE" : " VOTES");
				if (list.Count > 0)
				{
					text2 = text2 + "\n" + string.Join(" ", list.ToArray());
				}
				if (list2.Count > 0)
				{
					text2 = text2 + "\n^ " + string.Join(" ", list2.ToArray());
				}
				float num2 = (float)Screen.height - val3.y + (float)Screen.height * 0.2f;
				GUI.Label(new Rect(val3.x - 110f, num2, 220f, 90f), text2, labelStyle);
			}
		}
	}

	private void EnsureStyles()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Expected O, but got Unknown
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Expected O, but got Unknown
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		if (labelStyle == null)
		{
			labelStyle = new GUIStyle(GUI.skin.label)
			{
				alignment = (TextAnchor)1,
				fontSize = 22,
				fontStyle = (FontStyle)1
			};
			labelStyle.normal.textColor = new Color(1f, 0.85f, 0.3f);
			headerStyle = new GUIStyle(labelStyle)
			{
				fontSize = 24,
				alignment = (TextAnchor)4
			};
			headerStyle.normal.textColor = Color.white;
		}
	}
}