Decompiled source of MathstormCoopExams v1.0.0

plugins/Mathstorm.dll

Decompiled 4 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using Microsoft.CodeAnalysis;
using R2API.Networking;
using R2API.Networking.Interfaces;
using R2API.Utils;
using RoR2;
using UnityEngine;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Mathstorm")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Mathstorm")]
[assembly: AssemblyTitle("Mathstorm")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Mathstorm
{
	public enum SubjectMode
	{
		Mixed,
		Calculus,
		LinearAlgebra
	}
	[BepInPlugin("com.mathstormcoopexams.ror2", "Mathstorm Co-op Exams", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public sealed class MathstormPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.mathstormcoopexams.ror2";

		public const string PluginName = "Mathstorm Co-op Exams";

		public const string PluginVersion = "1.0.0";

		private ConfigEntry<bool> automaticExams;

		private ConfigEntry<float> firstExamDelay;

		private ConfigEntry<float> intervalSeconds;

		private ConfigEntry<float> timeLimitSeconds;

		private ConfigEntry<float> barrierFraction;

		private ConfigEntry<KeyCode> practiceKey;

		private ConfigEntry<SubjectMode> subjectMode;

		private ConfigEntry<bool> showHud;

		private Run activeRun;

		private MathQuestion displayedQuestion;

		private bool displayedIsPractice;

		private bool displayedOpen;

		private bool submitted;

		private int displayedRoundId;

		private float displayedDeadline;

		private float dismissAt;

		private string resultLine = "";

		private MathQuestion serverQuestion;

		private bool serverRoundOpen;

		private int serverRoundId;

		private float serverDeadline;

		private float nextServerExamAt;

		private float nextSyncAt;

		private bool nextCalculus = true;

		private int teamStreak;

		private int teamCorrect;

		private int teamAttempts;

		private float nextExamAtClient;

		private bool hostAutomaticEnabled = true;

		private Texture2D darkBackground;

		private GUIStyle panelStyle;

		private GUIStyle headerStyle;

		private GUIStyle promptStyle;

		private GUIStyle optionStyle;

		private GUIStyle smallStyle;

		private GUIStyle resultStyle;

		internal static MathstormPlugin Instance { get; private set; }

		private void Awake()
		{
			Instance = this;
			automaticExams = ((BaseUnityPlugin)this).Config.Bind<bool>("Host Rules", "AutomaticExams", true, "HOST SETTING: Enable timed shared team challenges in runs.");
			firstExamDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Host Rules", "FirstExamDelaySeconds", 45f, "HOST SETTING: Delay after the start of a run before the first challenge (minimum 10s).");
			intervalSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Host Rules", "IntervalSeconds", 90f, "HOST SETTING: Delay between completed challenges (minimum 20s).");
			timeLimitSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Host Rules", "TimeLimitSeconds", 25f, "HOST SETTING: Seconds everyone has to solve each team question (minimum 5s).");
			subjectMode = ((BaseUnityPlugin)this).Config.Bind<SubjectMode>("Host Rules", "Subject", SubjectMode.Mixed, "HOST SETTING: Mixed alternates calculus/linear algebra. Other modes lock the subject.");
			barrierFraction = ((BaseUnityPlugin)this).Config.Bind<float>("Host Rules", "BaseBarrierFraction", 0.2f, "HOST SETTING: Each living teammate gets this fraction of max combined health as barrier on success. Streaks increase reward to 1.75x.");
			practiceKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Local Controls", "PracticeKey", (KeyCode)288, "Open a local, unrewarded practice question when no team question is open.");
			showHud = ((BaseUnityPlugin)this).Config.Bind<bool>("Local Display", "ShowExamHud", true, "Show the Mathstorm information panel.");
			NetworkingAPI.RegisterMessageType<TeamQuestionMessage>();
			NetworkingAPI.RegisterMessageType<TeamAnswerMessage>();
			NetworkingAPI.RegisterMessageType<TeamResultMessage>();
			NetworkingAPI.RegisterMessageType<TeamStatusMessage>();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Mathstorm multiplayer loaded. Shared team challenges; LeftAlt+1/2/3/4 to answer, F7 to practice.");
		}

		private void Update()
		{
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			Run instance = Run.instance;
			if ((Object)(object)instance == (Object)null)
			{
				if ((Object)(object)activeRun != (Object)null)
				{
					ResetRun();
				}
				return;
			}
			if ((Object)(object)activeRun != (Object)(object)instance)
			{
				ResetRun();
				activeRun = instance;
				if (NetworkServer.active)
				{
					nextServerExamAt = Time.unscaledTime + Mathf.Max(10f, firstExamDelay.Value);
				}
			}
			if (NetworkServer.active)
			{
				ServerUpdate();
			}
			if (displayedQuestion != null)
			{
				if (displayedOpen && displayedIsPractice && Time.unscaledTime >= displayedDeadline)
				{
					FinishLocalPractice(-1);
				}
				else if (!displayedOpen && Time.unscaledTime >= dismissAt)
				{
					displayedQuestion = null;
				}
			}
			if (displayedQuestion == null && Input.GetKeyDown(practiceKey.Value))
			{
				BeginLocalPractice();
			}
			else if (displayedOpen && !submitted && Time.unscaledTime < displayedDeadline && (Input.GetKey((KeyCode)308) || Input.GetKey((KeyCode)307)))
			{
				int num = -1;
				if (Input.GetKeyDown((KeyCode)49) || Input.GetKeyDown((KeyCode)257))
				{
					num = 0;
				}
				if (Input.GetKeyDown((KeyCode)50) || Input.GetKeyDown((KeyCode)258))
				{
					num = 1;
				}
				if (Input.GetKeyDown((KeyCode)51) || Input.GetKeyDown((KeyCode)259))
				{
					num = 2;
				}
				if (Input.GetKeyDown((KeyCode)52) || Input.GetKeyDown((KeyCode)260))
				{
					num = 3;
				}
				if (num >= 0)
				{
					SubmitAnswer(num);
				}
			}
		}

		private void ResetRun()
		{
			activeRun = null;
			displayedQuestion = null;
			displayedOpen = false;
			displayedIsPractice = false;
			submitted = false;
			displayedRoundId = 0;
			resultLine = "";
			serverQuestion = null;
			serverRoundOpen = false;
			serverRoundId = 0;
			serverDeadline = 0f;
			nextServerExamAt = 0f;
			nextSyncAt = 0f;
			nextExamAtClient = 0f;
			nextCalculus = true;
			teamStreak = 0;
			teamCorrect = 0;
			teamAttempts = 0;
			hostAutomaticEnabled = true;
		}

		private void ServerUpdate()
		{
			float unscaledTime = Time.unscaledTime;
			if (serverRoundOpen && unscaledTime >= serverDeadline)
			{
				FinishServerRound(solved: false);
			}
			if (!serverRoundOpen && automaticExams.Value && unscaledTime >= nextServerExamAt)
			{
				StartServerRound();
			}
			if (unscaledTime >= nextSyncAt)
			{
				nextSyncAt = unscaledTime + 5f;
				BroadcastStatus();
				if (serverRoundOpen)
				{
					BroadcastQuestion();
				}
			}
		}

		private void StartServerRound()
		{
			bool flag;
			if (subjectMode.Value == SubjectMode.Calculus)
			{
				flag = true;
			}
			else if (subjectMode.Value == SubjectMode.LinearAlgebra)
			{
				flag = false;
			}
			else
			{
				flag = nextCalculus;
				nextCalculus = !nextCalculus;
			}
			serverQuestion = (flag ? QuestionFactory.CreateCalculus() : QuestionFactory.CreateLinearAlgebra());
			serverRoundId++;
			serverRoundOpen = true;
			serverDeadline = Time.unscaledTime + Mathf.Max(5f, timeLimitSeconds.Value);
			nextServerExamAt = float.PositiveInfinity;
			DisplayIncomingQuestion(serverRoundId, serverQuestion.Subject, serverQuestion.Category, serverQuestion.Prompt, serverQuestion.Choices, serverDeadline - Time.unscaledTime);
			BroadcastQuestion();
			BroadcastStatus();
		}

		private void BroadcastQuestion()
		{
			if (NetworkServer.active && serverRoundOpen && serverQuestion != null)
			{
				NetMessageExtensions.Send((INetMessage)(object)new TeamQuestionMessage(serverRoundId, serverQuestion, Mathf.Max(0f, serverDeadline - Time.unscaledTime)), (NetworkDestination)1);
			}
		}

		private void BroadcastStatus()
		{
			if (NetworkServer.active && !((Object)(object)activeRun == (Object)null))
			{
				NetMessageExtensions.Send((INetMessage)(object)new TeamStatusMessage((automaticExams.Value && !serverRoundOpen) ? Mathf.Max(0f, nextServerExamAt - Time.unscaledTime) : (-1f), automaticExams.Value, teamStreak, teamCorrect, teamAttempts), (NetworkDestination)1);
			}
		}

		internal void TryServerAnswer(int roundId, int choice)
		{
			if (NetworkServer.active && !((Object)(object)activeRun == (Object)null) && serverRoundOpen && roundId == serverRoundId && !(Time.unscaledTime >= serverDeadline) && choice >= 0 && choice <= 3 && choice == serverQuestion.CorrectIndex)
			{
				FinishServerRound(solved: true);
			}
		}

		private void FinishServerRound(bool solved)
		{
			if (NetworkServer.active && serverRoundOpen && serverQuestion != null)
			{
				serverRoundOpen = false;
				teamAttempts++;
				float multiplier = 1f;
				if (solved)
				{
					teamStreak++;
					teamCorrect++;
					multiplier = Mathf.Min(1.75f, 1f + 0.15f * (float)(teamStreak - 1));
					GiveTeamBarrier(multiplier);
				}
				else
				{
					teamStreak = 0;
				}
				nextServerExamAt = Time.unscaledTime + Mathf.Max(20f, intervalSeconds.Value);
				string text = (solved ? ("Solved! Every living teammate gained barrier (x" + multiplier.ToString("0.00") + "). Team streak: " + teamStreak) : "Time expired. No team barrier this round; team streak reset.");
				ApplyResult(serverRoundId, solved, serverQuestion.CorrectIndex, text, serverQuestion.Explanation, teamStreak, teamCorrect, teamAttempts);
				NetMessageExtensions.Send((INetMessage)(object)new TeamResultMessage(serverRoundId, solved, serverQuestion.CorrectIndex, text, serverQuestion.Explanation, teamStreak, teamCorrect, teamAttempts), (NetworkDestination)1);
				BroadcastStatus();
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Team question #" + serverRoundId + ": " + text));
			}
		}

		private void GiveTeamBarrier(float multiplier)
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Invalid comparison between Unknown and I4
			float num = Mathf.Clamp(barrierFraction.Value, 0f, 1f);
			foreach (NetworkUser readOnlyInstances in NetworkUser.readOnlyInstancesList)
			{
				if (!((Object)(object)readOnlyInstances == (Object)null))
				{
					CharacterBody currentBody = readOnlyInstances.GetCurrentBody();
					if (!((Object)(object)currentBody == (Object)null) && !((Object)(object)currentBody.healthComponent == (Object)null) && currentBody.healthComponent.alive && !((Object)(object)currentBody.teamComponent == (Object)null) && (int)currentBody.teamComponent.teamIndex == 1)
					{
						currentBody.healthComponent.AddBarrier(currentBody.healthComponent.fullCombinedHealth * num * multiplier);
					}
				}
			}
		}

		internal void DisplayIncomingQuestion(int id, string subject, string category, string prompt, string[] choices, float remainingSeconds)
		{
			if ((Object)(object)activeRun == (Object)null || choices == null || choices.Length != 4)
			{
				return;
			}
			if (!displayedIsPractice && displayedQuestion != null && displayedRoundId == id)
			{
				if (displayedOpen)
				{
					displayedDeadline = Mathf.Min(displayedDeadline, Time.unscaledTime + Mathf.Max(0f, remainingSeconds));
				}
				return;
			}
			displayedRoundId = id;
			displayedQuestion = new MathQuestion(subject, category, prompt, (string[])choices.Clone(), -1, "");
			displayedIsPractice = false;
			displayedOpen = true;
			submitted = false;
			displayedDeadline = Time.unscaledTime + Mathf.Max(0f, remainingSeconds);
			resultLine = "";
		}

		internal void ApplyResult(int id, bool solved, int correctIndex, string summary, string explanation, int streak, int correct, int attempts)
		{
			if (!((Object)(object)activeRun == (Object)null))
			{
				teamStreak = streak;
				teamCorrect = correct;
				teamAttempts = attempts;
				if (displayedQuestion != null && !displayedIsPractice && displayedRoundId == id)
				{
					displayedQuestion = new MathQuestion(displayedQuestion.Subject, displayedQuestion.Category, displayedQuestion.Prompt, displayedQuestion.Choices, correctIndex, explanation);
					displayedOpen = false;
					submitted = true;
					dismissAt = Time.unscaledTime + 8f;
					resultLine = summary;
				}
			}
		}

		internal void ApplyStatus(float remainingToNext, bool enabled, int streak, int correct, int attempts)
		{
			if (!((Object)(object)activeRun == (Object)null))
			{
				hostAutomaticEnabled = enabled;
				teamStreak = streak;
				teamCorrect = correct;
				teamAttempts = attempts;
				nextExamAtClient = ((remainingToNext < 0f) ? (-1f) : (Time.unscaledTime + remainingToNext));
			}
		}

		private void SubmitAnswer(int selectedIndex)
		{
			if (displayedQuestion == null || !displayedOpen || submitted || Time.unscaledTime >= displayedDeadline || selectedIndex < 0 || selectedIndex >= 4)
			{
				return;
			}
			submitted = true;
			if (displayedIsPractice)
			{
				FinishLocalPractice(selectedIndex);
				return;
			}
			resultLine = "Answer submitted. Waiting for the team or the timer...";
			if (NetworkServer.active)
			{
				TryServerAnswer(displayedRoundId, selectedIndex);
			}
			else
			{
				NetMessageExtensions.Send((INetMessage)(object)new TeamAnswerMessage(displayedRoundId, selectedIndex), (NetworkDestination)2);
			}
		}

		private void BeginLocalPractice()
		{
			displayedIsPractice = true;
			displayedQuestion = QuestionFactory.CreateCalculus();
			if (subjectMode.Value == SubjectMode.LinearAlgebra || (subjectMode.Value == SubjectMode.Mixed && Random.value < 0.5f))
			{
				displayedQuestion = QuestionFactory.CreateLinearAlgebra();
			}
			displayedOpen = true;
			submitted = false;
			displayedDeadline = Time.unscaledTime + Mathf.Max(5f, timeLimitSeconds.Value);
			resultLine = "";
		}

		private void FinishLocalPractice(int selectedIndex)
		{
			if (displayedQuestion != null && displayedIsPractice && displayedOpen)
			{
				bool flag = selectedIndex == displayedQuestion.CorrectIndex;
				displayedOpen = false;
				submitted = true;
				dismissAt = Time.unscaledTime + 8f;
				resultLine = ((selectedIndex < 0) ? "Practice timed out." : (flag ? "Correct! Practice only: no reward." : "Not quite. Practice only: no penalty."));
			}
		}

		private void OnGUI()
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_032e: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)activeRun == (Object)null)
			{
				return;
			}
			InitializeStyles();
			if (displayedQuestion == null)
			{
				if (showHud.Value)
				{
					DrawHud();
				}
				return;
			}
			float num = Mathf.Min(590f, (float)Screen.width - 24f);
			float num2 = Mathf.Min(455f, (float)Screen.height - 32f);
			float num3 = 12f;
			float num4 = 38f;
			GUI.Box(new Rect(num3, num4, num, num2), GUIContent.none, panelStyle);
			float num5 = 15f;
			float num6 = num - num5 * 2f;
			GUI.Label(new Rect(num3 + num5, num4 + 7f, num6, 28f), "MATHSTORM  |  " + displayedQuestion.Subject, headerStyle);
			GUI.Label(new Rect(num3 + num5, num4 + 36f, num6, 27f), displayedQuestion.Category + (displayedIsPractice ? "  |  LOCAL PRACTICE" : "  |  CO-OP TEAM CHALLENGE"), smallStyle);
			GUI.Label(new Rect(num3 + num5, num4 + 70f, num6, 71f), displayedQuestion.Prompt, promptStyle);
			float num7 = num4 + 145f;
			float num8 = Mathf.Min(43f, Mathf.Max(27f, (num2 - 260f) / 4f));
			for (int i = 0; i < displayedQuestion.Choices.Length; i++)
			{
				string text = i + 1 + ". " + displayedQuestion.Choices[i];
				if (!displayedOpen && i == displayedQuestion.CorrectIndex)
				{
					text += "  [CORRECT]";
				}
				bool enabled = GUI.enabled;
				GUI.enabled = displayedOpen && !submitted && Time.unscaledTime < displayedDeadline;
				if (GUI.Button(new Rect(num3 + num5, num7, num6, num8), text, optionStyle))
				{
					SubmitAnswer(i);
				}
				GUI.enabled = enabled;
				num7 += num8 + 4f;
			}
			if (displayedOpen)
			{
				GUI.Label(new Rect(num3 + num5, num7 + 1f, num6, 23f), (submitted ? "Submitted | " : "LeftAlt + 1/2/3/4 to answer | ") + "Time: " + Mathf.CeilToInt(Mathf.Max(0f, displayedDeadline - Time.unscaledTime)) + "s", smallStyle);
				if (submitted)
				{
					GUI.Label(new Rect(num3 + num5, num7 + 24f, num6, 24f), resultLine, smallStyle);
				}
			}
			else
			{
				GUI.Label(new Rect(num3 + num5, num7, num6, 43f), resultLine, resultStyle);
				GUI.Label(new Rect(num3 + num5, num7 + 42f, num6, Mathf.Max(38f, num2 - (num7 - num4) - 45f)), displayedQuestion.Explanation, smallStyle);
			}
		}

		private void DrawHud()
		{
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Min(365f, (float)Screen.width - 24f);
			float num2 = (float)Screen.width - num - 12f;
			string text = ((!NetworkServer.active) ? ((!hostAutomaticEnabled) ? "off" : ((nextExamAtClient < 0f) ? "in progress / waiting" : ((nextExamAtClient == 0f) ? "syncing" : (Mathf.CeilToInt(Mathf.Max(0f, nextExamAtClient - Time.unscaledTime)) + "s")))) : ((!automaticExams.Value) ? "off" : (serverRoundOpen ? "in progress" : (Mathf.CeilToInt(Mathf.Max(0f, nextServerExamAt - Time.unscaledTime)) + "s"))));
			GUI.Box(new Rect(num2, 12f, num, 68f), GUIContent.none, panelStyle);
			GUI.Label(new Rect(num2 + 9f, 15f, num - 18f, 24f), "MATHSTORM CO-OP  |  Next: " + text, smallStyle);
			GUI.Label(new Rect(num2 + 9f, 39f, num - 18f, 29f), "Team " + teamCorrect + "/" + teamAttempts + "  |  Streak " + teamStreak + "  |  " + ((object)practiceKey.Value/*cast due to .constrained prefix*/).ToString() + " practice", smallStyle);
		}

		private void InitializeStyles()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: 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_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			//IL_0090: Expected O, but got Unknown
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Expected O, but got Unknown
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Expected O, but got Unknown
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Expected O, but got Unknown
			//IL_0150: Expected O, but got Unknown
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Expected O, but got Unknown
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Expected O, but got Unknown
			if (panelStyle == null)
			{
				darkBackground = new Texture2D(1, 1, (TextureFormat)4, false);
				darkBackground.SetPixel(0, 0, new Color(0.06f, 0.09f, 0.14f, 0.94f));
				darkBackground.Apply();
				GUIStyle val = new GUIStyle(GUI.skin.box);
				val.normal.background = darkBackground;
				val.normal.textColor = Color.white;
				val.padding = new RectOffset(9, 9, 6, 6);
				panelStyle = val;
				GUIStyle val2 = new GUIStyle(GUI.skin.label)
				{
					fontSize = 20,
					fontStyle = (FontStyle)1,
					alignment = (TextAnchor)3
				};
				val2.normal.textColor = new Color(0.5f, 0.91f, 1f);
				headerStyle = val2;
				GUIStyle val3 = new GUIStyle(GUI.skin.label)
				{
					fontSize = 18,
					wordWrap = true,
					alignment = (TextAnchor)3
				};
				val3.normal.textColor = Color.white;
				promptStyle = val3;
				optionStyle = new GUIStyle(GUI.skin.button)
				{
					fontSize = 16,
					wordWrap = true,
					alignment = (TextAnchor)3,
					padding = new RectOffset(11, 8, 3, 3)
				};
				GUIStyle val4 = new GUIStyle(GUI.skin.label)
				{
					fontSize = 13,
					wordWrap = true,
					alignment = (TextAnchor)3
				};
				val4.normal.textColor = Color.white;
				smallStyle = val4;
				GUIStyle val5 = new GUIStyle(GUI.skin.label)
				{
					fontSize = 15,
					fontStyle = (FontStyle)1,
					wordWrap = true
				};
				val5.normal.textColor = new Color(0.45f, 1f, 0.66f);
				resultStyle = val5;
			}
		}

		private void OnDestroy()
		{
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
			if ((Object)(object)darkBackground != (Object)null)
			{
				Object.Destroy((Object)(object)darkBackground);
			}
		}
	}
	public sealed class TeamQuestionMessage : INetMessage, ISerializableObject
	{
		private int roundId;

		private float remaining;

		private string subject;

		private string category;

		private string prompt;

		private string[] choices;

		public TeamQuestionMessage()
		{
		}

		internal TeamQuestionMessage(int id, MathQuestion q, float timeLeft)
		{
			roundId = id;
			remaining = timeLeft;
			subject = q.Subject;
			category = q.Category;
			prompt = q.Prompt;
			choices = q.Choices;
		}

		public void Serialize(NetworkWriter writer)
		{
			writer.Write(roundId);
			writer.Write(remaining);
			writer.Write(subject);
			writer.Write(category);
			writer.Write(prompt);
			for (int i = 0; i < 4; i++)
			{
				writer.Write(choices[i]);
			}
		}

		public void Deserialize(NetworkReader reader)
		{
			roundId = reader.ReadInt32();
			remaining = reader.ReadSingle();
			subject = reader.ReadString();
			category = reader.ReadString();
			prompt = reader.ReadString();
			choices = new string[4];
			for (int i = 0; i < 4; i++)
			{
				choices[i] = reader.ReadString();
			}
		}

		public void OnReceived()
		{
			if (!NetworkServer.active)
			{
				MathstormPlugin.Instance?.DisplayIncomingQuestion(roundId, subject, category, prompt, choices, remaining);
			}
		}
	}
	public sealed class TeamAnswerMessage : INetMessage, ISerializableObject
	{
		private int roundId;

		private int choice;

		public TeamAnswerMessage()
		{
		}

		public TeamAnswerMessage(int id, int index)
		{
			roundId = id;
			choice = index;
		}

		public void Serialize(NetworkWriter writer)
		{
			writer.Write(roundId);
			writer.Write(choice);
		}

		public void Deserialize(NetworkReader reader)
		{
			roundId = reader.ReadInt32();
			choice = reader.ReadInt32();
		}

		public void OnReceived()
		{
			if (NetworkServer.active)
			{
				MathstormPlugin.Instance?.TryServerAnswer(roundId, choice);
			}
		}
	}
	public sealed class TeamResultMessage : INetMessage, ISerializableObject
	{
		private int id;

		private bool solved;

		private int correctIndex;

		private string summary;

		private string explanation;

		private int streak;

		private int correct;

		private int attempts;

		public TeamResultMessage()
		{
		}

		public TeamResultMessage(int id, bool solved, int correctIndex, string summary, string explanation, int streak, int correct, int attempts)
		{
			this.id = id;
			this.solved = solved;
			this.correctIndex = correctIndex;
			this.summary = summary;
			this.explanation = explanation;
			this.streak = streak;
			this.correct = correct;
			this.attempts = attempts;
		}

		public void Serialize(NetworkWriter w)
		{
			w.Write(id);
			w.Write(solved);
			w.Write(correctIndex);
			w.Write(summary);
			w.Write(explanation);
			w.Write(streak);
			w.Write(correct);
			w.Write(attempts);
		}

		public void Deserialize(NetworkReader r)
		{
			id = r.ReadInt32();
			solved = r.ReadBoolean();
			correctIndex = r.ReadInt32();
			summary = r.ReadString();
			explanation = r.ReadString();
			streak = r.ReadInt32();
			correct = r.ReadInt32();
			attempts = r.ReadInt32();
		}

		public void OnReceived()
		{
			if (!NetworkServer.active)
			{
				MathstormPlugin.Instance?.ApplyResult(id, solved, correctIndex, summary, explanation, streak, correct, attempts);
			}
		}
	}
	public sealed class TeamStatusMessage : INetMessage, ISerializableObject
	{
		private float remaining;

		private bool enabled;

		private int streak;

		private int correct;

		private int attempts;

		public TeamStatusMessage()
		{
		}

		public TeamStatusMessage(float remaining, bool enabled, int streak, int correct, int attempts)
		{
			this.remaining = remaining;
			this.enabled = enabled;
			this.streak = streak;
			this.correct = correct;
			this.attempts = attempts;
		}

		public void Serialize(NetworkWriter w)
		{
			w.Write(remaining);
			w.Write(enabled);
			w.Write(streak);
			w.Write(correct);
			w.Write(attempts);
		}

		public void Deserialize(NetworkReader r)
		{
			remaining = r.ReadSingle();
			enabled = r.ReadBoolean();
			streak = r.ReadInt32();
			correct = r.ReadInt32();
			attempts = r.ReadInt32();
		}

		public void OnReceived()
		{
			if (!NetworkServer.active)
			{
				MathstormPlugin.Instance?.ApplyStatus(remaining, enabled, streak, correct, attempts);
			}
		}
	}
	internal sealed class MathQuestion
	{
		public readonly string Subject;

		public readonly string Category;

		public readonly string Prompt;

		public readonly string[] Choices;

		public readonly int CorrectIndex;

		public readonly string Explanation;

		public MathQuestion(string subject, string category, string prompt, string[] choices, int correctIndex, string explanation)
		{
			Subject = subject;
			Category = category;
			Prompt = prompt;
			Choices = choices;
			CorrectIndex = correctIndex;
			Explanation = explanation;
		}
	}
	internal static class QuestionFactory
	{
		private static readonly Random Random = new Random();

		private static int lastCalc = -1;

		private static int lastLinear = -1;

		private static int Between(int minInclusive, int maxInclusive)
		{
			return Random.Next(minInclusive, maxInclusive + 1);
		}

		private static int NextKind(int count, ref int previous)
		{
			int num = Between(0, count - 1);
			if (count > 1 && num == previous)
			{
				num = (num + Between(1, count - 1)) % count;
			}
			previous = num;
			return num;
		}

		public static MathQuestion CreateCalculus()
		{
			return NextKind(7, ref lastCalc) switch
			{
				0 => PolynomialDerivative(), 
				1 => ChainRule(), 
				2 => DefiniteIntegral(), 
				3 => ProductRule(), 
				4 => PartialDerivative(), 
				5 => ExponentialDerivative(), 
				_ => TrigDerivative(), 
			};
		}

		public static MathQuestion CreateLinearAlgebra()
		{
			return NextKind(8, ref lastLinear) switch
			{
				0 => DotProduct(), 
				1 => Determinant(), 
				2 => MatrixVector(), 
				3 => Trace(), 
				4 => MatrixRank(), 
				5 => LinearSystem(), 
				6 => Eigenvalues(), 
				_ => Nullity(), 
			};
		}

		private static MathQuestion PolynomialDerivative()
		{
			int num = Between(2, 6);
			int num2 = Between(2, 4);
			int num3 = Between(1, 3);
			int num4 = num * num2 * Power(num3, num2 - 1);
			return Numeric("CALCULUS", "Power rule", $"f(x) = {num}x^{num2}. What is f'({num3})?", num4, new int[3]
			{
				num * Power(num3, num2),
				num * num2 * Power(num3, num2),
				num2 * Power(num3, num2 - 1)
			}, $"f'(x) = {num * num2}x^{num2 - 1}; substitute x = {num3} to get {num4}.");
		}

		private static MathQuestion ChainRule()
		{
			int num = Between(2, 5);
			int num2 = Between(1, 5);
			int num3 = Between(1, 4);
			int num4 = num * num3 + num2;
			int num5 = 2 * num * num4;
			return Numeric("CALCULUS", "Chain rule", $"f(x) = ({num}x + {num2})^2. What is f'({num3})?", num5, new int[3]
			{
				2 * num4,
				num4 * num4,
				num * num4
			}, string.Format("The outer derivative is 2({0}x + {1}); multiply by the inner derivative {0}. At x = {2}, the result is {3}.", num, num2, num3, num5));
		}

		private static MathQuestion DefiniteIntegral()
		{
			int num = 2 * Between(1, 5);
			int num2 = Between(2, 6);
			int num3 = num * num2 * num2 / 2;
			return Numeric("CALCULUS", "Definite integrals", $"Evaluate the integral from 0 to {num2} of {num}x dx.", num3, new int[3]
			{
				num * num2,
				num * num2 * num2,
				num * num2 * num2 / 2 + num
			}, $"An antiderivative is ({num}/2)x^2. Evaluate at {num2} and subtract its value at 0: {num3}.");
		}

		private static MathQuestion ProductRule()
		{
			int num = Between(1, 6);
			int num2 = Between(1, 4);
			int num3 = 3 * num2 * num2 + 2 * num * num2;
			return Numeric("CALCULUS", "Product rule", $"f(x) = x^2(x + {num}). What is f'({num2})?", num3, new int[3]
			{
				2 * num2 * (num2 + num),
				num2 * num2 + num,
				3 * num2 * num2 + num * num2
			}, $"By the product rule, f'(x) = 2x(x + {num}) + x^2 = 3x^2 + {2 * num}x. At x = {num2}, f' = {num3}.");
		}

		private static MathQuestion PartialDerivative()
		{
			int num = Between(1, 4);
			int num2 = Between(2, 6);
			int num3 = Between(1, 4);
			int num4 = Between(1, 3);
			int num5 = Between(1, 3);
			int num6 = 2 * num * num4 + num2 * num5;
			return Numeric("CALCULUS", "Partial derivatives", $"f(x,y) = {num}x^2 + {num2}xy + {num3}y^2. Find df/dx at ({num4},{num5}).", num6, new int[3]
			{
				2 * num * num4 + num2 * num4,
				2 * num3 * num5 + num2 * num4,
				num * num4 + num2 * num5
			}, $"Treat y as constant: df/dx = {2 * num}x + {num2}y. Plug in ({num4},{num5}) to get {num6}.");
		}

		private static MathQuestion ExponentialDerivative()
		{
			int num = (new int[4] { 2, 3, 5, 7 })[Between(0, 3)];
			return Symbolic("CALCULUS", "Exponential derivatives", $"If f(x) = {num}^x, which expression is f'(x)?", string.Format("{0}^x * ln({0})", num), new string[3]
			{
				$"x * {num}^(x-1)",
				$"{num}^x",
				$"ln({num}) * x"
			}, $"For any constant a > 0, d(a^x)/dx = a^x ln(a). Here a = {num}.");
		}

		private static MathQuestion TrigDerivative()
		{
			int num = Between(2, 7);
			return Symbolic("CALCULUS", "Trigonometric chain rule", $"Find d/dx of sin({num}x). (Angles in radians.)", string.Format("{0}cos({0}x)", num), new string[3]
			{
				$"cos({num}x)",
				string.Format("-{0}sin({0}x)", num),
				string.Format("{0}sin({0}x)", num)
			}, string.Format("The derivative of sin(u) is cos(u) * u'. With u = {0}x, u' = {0}.", num));
		}

		private static MathQuestion DotProduct()
		{
			int num = Between(-4, 5);
			int num2 = Between(-4, 5);
			int num3 = Between(-4, 5);
			int num4 = Between(-4, 5);
			int num5 = Between(-4, 5);
			int num6 = Between(-4, 5);
			int num7 = num * num4 + num2 * num5 + num3 * num6;
			return Numeric("LINEAR ALGEBRA", "Dot product", $"Find ({num}, {num2}, {num3}) dot ({num4}, {num5}, {num6}).", num7, new int[3]
			{
				num + num4 + num2 + num5 + num3 + num6,
				num * num4 + num2 * num5 - num3 * num6,
				num * num4 - num2 * num5 + num3 * num6
			}, $"Multiply matching coordinates and add: ({num})({num4}) + ({num2})({num5}) + ({num3})({num6}) = {num7}.");
		}

		private static MathQuestion Determinant()
		{
			int num = Between(-4, 6);
			int num2 = Between(-4, 6);
			int num3 = Between(-4, 6);
			int num4 = Between(-4, 6);
			int num5 = num * num4 - num2 * num3;
			return Numeric("LINEAR ALGEBRA", "2x2 determinant", $"Find det(A) for A = [[{num}, {num2}], [{num3}, {num4}]].", num5, new int[3]
			{
				num * num4 + num2 * num3,
				num + num4,
				num * num3 - num2 * num4
			}, $"det(A) = ad - bc = ({num})({num4}) - ({num2})({num3}) = {num5}.");
		}

		private static MathQuestion MatrixVector()
		{
			int num = Between(1, 5);
			int num2 = Between(-4, 4);
			int num3 = Between(-4, 4);
			int num4 = Between(1, 5);
			int num5 = Between(-3, 4);
			int num6 = Between(-3, 4);
			int num7 = num * num5 + num2 * num6;
			return Numeric("LINEAR ALGEBRA", "Matrix-vector multiplication", $"A = [[{num}, {num2}], [{num3}, {num4}]], v = ({num5}, {num6}). What is the FIRST entry of Av?", num7, new int[3]
			{
				num3 * num5 + num4 * num6,
				num * num5 + num3 * num6,
				num + num2 + num5 + num6
			}, $"The first row dotted with v is ({num})({num5}) + ({num2})({num6}) = {num7}.");
		}

		private static MathQuestion Trace()
		{
			int num = Between(-6, 7);
			int num2 = Between(-6, 7);
			int num3 = Between(-6, 7);
			int num4 = Between(-6, 7);
			int num5 = num + num4;
			return Numeric("LINEAR ALGEBRA", "Matrix trace", $"Find tr(A) for A = [[{num}, {num2}], [{num3}, {num4}]].", num5, new int[3]
			{
				num * num4 - num2 * num3,
				num2 + num3,
				num + num2 + num3 + num4
			}, $"The trace is the sum of the diagonal entries: {num} + {num4} = {num5}.");
		}

		private static MathQuestion MatrixRank()
		{
			int num = Between(1, 5);
			int num2 = Between(1, 5);
			int num3 = Between(2, 4);
			return Numeric("LINEAR ALGEBRA", "Rank and dependence", $"What is the rank of A = [[{num}, {num * num3}], [{num2}, {num2 * num3}]]?", 1, new int[3] { 0, 2, 3 }, $"Column 2 is {num3} times column 1, and column 1 is nonzero. There is exactly one pivot.");
		}

		private static MathQuestion LinearSystem()
		{
			int num = Between(-4, 6);
			int num2 = Between(-4, 6);
			int num3 = num + num2;
			int num4 = num - num2;
			return Numeric("LINEAR ALGEBRA", "Linear systems", $"Solve for x: x + y = {num3}, x - y = {num4}.", num, new int[3] { num2, num3, num4 }, $"Add both equations: 2x = {num3} + ({num4}) = {2 * num}, so x = {num}.");
		}

		private static MathQuestion Eigenvalues()
		{
			int num = Between(-4, 5);
			int num2 = Between(-4, 5);
			if (num2 == num)
			{
				num2 = num + 1;
			}
			string answer = $"{num} and {num2}";
			return Symbolic("LINEAR ALGEBRA", "Eigenvalues", $"What are the eigenvalues of A = [[{num}, 0], [0, {num2}]]?", answer, new string[3]
			{
				$"{num + 1} and {num2 + 1}",
				$"{num - 1} and {num2 - 1}",
				$"{num + 2} and {num2 + 2}"
			}, $"The eigenvalues of a diagonal matrix are its diagonal entries: {num} and {num2}.");
		}

		private static MathQuestion Nullity()
		{
			int num = Between(1, 3);
			int num2 = ((num < 1) ? Between(1, 5) : 0);
			int num3 = ((num < 2) ? Between(1, 5) : 0);
			int num4 = ((num < 3) ? Between(1, 5) : 0);
			return Numeric("LINEAR ALGEBRA", "Null space and nullity", $"What is nullity(A) for the 3x3 diagonal matrix diag({num2}, {num3}, {num4})?", num, new int[3]
			{
				0,
				4 - num,
				3 - num
			}, string.Format("Each zero diagonal entry contributes a free variable. There are {0} free variables, so nullity = {0}.", num));
		}

		private static int Power(int value, int exponent)
		{
			int num = 1;
			for (int i = 0; i < exponent; i++)
			{
				num *= value;
			}
			return num;
		}

		private static MathQuestion Numeric(string subject, string category, string prompt, int answer, int[] distractors, string explanation)
		{
			string text = answer.ToString(CultureInfo.InvariantCulture);
			List<string> list = new List<string> { text };
			HashSet<string> hashSet = new HashSet<string> { text };
			foreach (int num in distractors)
			{
				string item = num.ToString(CultureInfo.InvariantCulture);
				if (hashSet.Add(item))
				{
					list.Add(item);
				}
				if (list.Count == 4)
				{
					break;
				}
			}
			int num2 = 0;
			while (list.Count < 4 && num2++ < 100)
			{
				int num3 = Between(-12, 12);
				if (num3 != 0)
				{
					string item2 = (answer + num3).ToString(CultureInfo.InvariantCulture);
					if (hashSet.Add(item2))
					{
						list.Add(item2);
					}
				}
			}
			return Shuffled(subject, category, prompt, list, text, explanation);
		}

		private static MathQuestion Symbolic(string subject, string category, string prompt, string answer, string[] distractors, string explanation)
		{
			List<string> list = new List<string> { answer };
			string[] array = distractors;
			foreach (string item in array)
			{
				if (!list.Contains(item))
				{
					list.Add(item);
				}
			}
			array = new string[5] { "0 and 0", "1 and 1", "-1 and -1", "2 and 2", "3 and 3" };
			foreach (string item2 in array)
			{
				if (list.Count >= 4)
				{
					break;
				}
				if (!list.Contains(item2))
				{
					list.Add(item2);
				}
			}
			return Shuffled(subject, category, prompt, list, answer, explanation);
		}

		private static MathQuestion Shuffled(string subject, string category, string prompt, List<string> options, string answer, string explanation)
		{
			if (options.Count > 4)
			{
				options.RemoveRange(4, options.Count - 4);
			}
			for (int num = options.Count - 1; num > 0; num--)
			{
				int index = Between(0, num);
				string value = options[num];
				options[num] = options[index];
				options[index] = value;
			}
			return new MathQuestion(subject, category, prompt, options.ToArray(), options.IndexOf(answer), explanation);
		}
	}
}