Decompiled source of BetterBasBoule v0.5.0
BasBoule.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.Json; using BasBoule.Sim; using BasBoule.Sim.League; using BasBouleMod.App; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using HarmonyLib; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem.Collections.Generic; using Microsoft.CodeAnalysis; using SOD.Common; using SOD.Common.Helpers; using SOD.Common.Helpers.DialogObjects; using TMPro; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("BasBoule")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+b2c6067481cefb001beeb78de3a2eae72e214ddf")] [assembly: AssemblyProduct("BasBoule")] [assembly: AssemblyTitle("BasBoule")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [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 BasBouleMod { internal sealed class LiveMatch { public LeagueEngine Engine; public MatchSetup Setup; public BroadcastPlan Plan; public float SlotTime; public Daypart Daypart; public Weather Weather; public bool Started; public bool Committed; public int Steered; public int LastCursor = -1; public int StallCount; } internal static class Director { internal sealed class LiveSnapshot { public MatchSetup Setup; public int Half; public int Score1; public int Score2; public PlayRecord LastPlay; public int Outs; public bool Final; public List<PlayRecord> Called = new List<PlayRecord>(); public PlayRecord Upcoming; public int[] HalfRuns = new int[4] { -1, -1, -1, -1 }; } private sealed class ClipView : IClipView { private readonly DynamicClip _clip; private readonly List<List<string>> _audio = new List<List<string>>(); public int EventCount => _clip.possibleEvents.Count; public ClipView(DynamicClip clip) { _clip = clip; for (int i = 0; i < clip.possibleEvents.Count; i++) { List<string> list = new List<string>(); List<AudioEvent> audioEvents = clip.possibleEvents[i].audioEvents; for (int j = 0; j < audioEvents.Count; j++) { list.Add(((Object)audioEvents[j]).name); } _audio.Add(list); } } public string EventName(int i) { return _clip.possibleEvents[i].name; } public IReadOnlyList<string> EventAudio(int i) { return _audio[i]; } public IReadOnlyList<(string type, float value)> EventParams(int i) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) List<DynamicShowParam> applyParameters = _clip.possibleEvents[i].applyParameters; List<(string, float)> list = new List<(string, float)>(); for (int j = 0; j < applyParameters.Count; j++) { list.Add((((object)applyParameters[j].paramType/*cast due to .constrained prefix*/).ToString(), applyParameters[j].value)); } return list; } public AudioEvent FindAudio(string name) { for (int i = 0; i < _clip.possibleEvents.Count; i++) { List<AudioEvent> audioEvents = _clip.possibleEvents[i].audioEvents; for (int j = 0; j < audioEvents.Count; j++) { if (((Object)audioEvents[j]).name == name) { return audioEvents[j]; } } } return null; } } private const string ChannelName = "FilmNoirChannel"; private const string ShowName = "BasBoule"; internal static LiveMatch Live; private static readonly Dictionary<int, float> _originalChance = new Dictionary<int, float>(); private static BroadcastPreset _show; private static readonly Dictionary<string, DynamicClipEvent> _pinned = new Dictionary<string, DynamicClipEvent>(); private static LoopingSoundInfo _cruncherSound; private static float _cruncherSoundWanted = -10f; private static bool _cruncherSoundFailed; private static TelevisionChannel FindChannel() { SessionData instance = SessionData.Instance; List<TelevisionChannel> val = ((instance != null) ? instance.televisionChannels : null); if (val == null) { return null; } for (int i = 0; i < val.Count; i++) { TelevisionChannel val2 = val[i]; if ((SoCustomComparison)(object)((val2 != null) ? val2.currentBroadcastSchedule : null) != (SoCustomComparison)null && ((SoCustomComparison)val2.currentBroadcastSchedule).presetName == "FilmNoirChannel") { return val2; } } return null; } private static bool IsOurs(TelevisionChannel ch) { if ((SoCustomComparison)(object)((ch != null) ? ch.currentBroadcastSchedule : null) != (SoCustomComparison)null) { return ((SoCustomComparison)ch.currentBroadcastSchedule).presetName == "FilmNoirChannel"; } return false; } private static int ShowIndex(TelevisionChannel ch) { List<BroadcastPreset> broadcasts = ch.currentBroadcastSchedule.broadcasts; for (int i = 0; i < broadcasts.Count; i++) { if ((SoCustomComparison)(object)broadcasts[i] != (SoCustomComparison)null && ((Object)broadcasts[i]).name == "BasBoule") { return i; } } return -1; } internal static bool CanBroadcast() { TelevisionChannel val = FindChannel(); if (val != null) { return ShowIndex(val) >= 0; } return false; } internal static void Start(LeagueEngine engine, float slot, SessionData sd) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: 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_017c: Unknown result type (might be due to invalid IL or missing references) TelevisionChannel obj = FindChannel(); int num = ShowIndex(obj); MatchSetup val = engine.Prepare(engine.Next()); float num2 = ((sd.decimalClock - (sd.gameTime - slot)) % 24f + 24f) % 24f; Daypart val2 = (Daypart)((num2 >= 17f) ? 1 : ((num2 < 6f) ? 2 : 0)); Weather val3 = (Weather)((sd.currentFog > 0.35f) ? 1 : ((sd.currentSnow > 0.35f) ? 2 : ((sd.currentRain > 0.35f) ? 3 : 0))); List<Call> list = Commentary.Narrate(val.Result, val.Facts, val3, val.Fixture.MatchSeed, val2); Live = new LiveMatch { Engine = engine, Setup = val, Plan = new BroadcastPlan(list), SlotTime = slot, Daypart = val2, Weather = val3 }; _show = obj.currentBroadcastSchedule.broadcasts[num]; int count = obj.currentBroadcastSchedule.broadcasts.Count; obj.currentScheduleIndex = (num - 1 + count) % count; ResetShow(obj); Plugin.Out($"FIRST LOB {Plugin.Clock(num2)}: {LeagueHost.Describe(val)} [result is pre-simulated]; {val2}, {val3}; {list.Count} lines planned"); } private static void ResetShow(TelevisionChannel ch) { ch.currentShow = null; ch.dynamicShowActive = false; ch.clipIndex = 0; ch.currentDynamicClip = null; ch.currentDynamicEvent = null; ch.currentDynamicAudio = null; ch.appliedParameters?.Clear(); } private static void Finish(string how) { LiveMatch live = Live; Live = null; StopCruncherSound(); RestoreChances(); if (live.Engine == LeagueHost.Engine) { if (!live.Committed) { live.Engine.Commit(live.Setup); } string value = ((live.Plan.Warnings.Count > 0) ? $"; {live.Plan.Warnings.Count} warning(s): {string.Join(" | ", live.Plan.Warnings.Take(3))}" : ""); Plugin.Out($"FULL TIME ({how}): {LeagueHost.Describe(live.Setup)}; {live.Plan.Cursor}/{live.Plan.Calls.Count} planned lines played, {live.Steered} steps steered{value}"); } } internal static void CommitNow() { LiveMatch live = Live; if (live != null && !live.Committed && live.Engine == LeagueHost.Engine) { live.Engine.Commit(live.Setup); live.Committed = true; } } internal static void Abort(string why) { if (Live != null) { Plugin.Out("Broadcast dropped (" + why + "); the fixture will be played at a later first lob."); Live = null; StopCruncherSound(); RestoreChances(); } } internal static void SkipToEnd(string why) { LiveMatch live = Live; if (live == null) { return; } TelevisionChannel val = FindChannel(); if (!live.Started || val == null || (SoCustomComparison)(object)val.currentShow == (SoCustomComparison)null || ((Object)val.currentShow).name != "BasBoule") { Plugin.Out("Match resolved before it went on air (" + why + ")."); if (val != null && !live.Started) { int count = val.currentBroadcastSchedule.broadcasts.Count; val.currentScheduleIndex = ShowIndex(val) % count; } Finish("skipped"); } else if (live.Plan.Peek != null && live.Plan.Peek.Step < 35) { SetParam(val, (ShowParamType)2, live.Setup.Result.Score1); SetParam(val, (ShowParamType)3, live.Setup.Result.Score2); SetParam(val, (ShowParamType)14, 0f); SetParam(val, (ShowParamType)16, 3f); live.Plan.SkipToEnd(); CommitNow(); val.clipIndex = 35; val.currentDynamicClip = null; val.currentDynamicEvent = null; val.currentDynamicAudio = null; Plugin.Out("Skipping to the end of the broadcast (" + why + ")."); } } public static void BroadcastPrefix(TelevisionChannel __instance) { try { if (!IsOurs(__instance)) { return; } int num = ShowIndex(__instance); if (num < 0) { return; } int count = __instance.currentBroadcastSchedule.broadcasts.Count; if ((SoCustomComparison)(object)__instance.currentShow == (SoCustomComparison)null) { int num2 = (__instance.currentScheduleIndex + 1) % count; if (Live != null && !Live.Started) { __instance.currentScheduleIndex = (num - 1 + count) % count; } else if (num2 == num) { __instance.currentScheduleIndex = num2; } } else if (((Object)__instance.currentShow).name == "BasBoule" && Live == null) { ResetShow(__instance); __instance.currentScheduleIndex = num; } } catch (Exception ex) { Plugin.Out("!! BroadcastPrefix: " + ex.Message); } } public static void BroadcastPostfix(TelevisionChannel __instance) { try { if (Live != null && IsOurs(__instance)) { bool flag = (SoCustomComparison)(object)__instance.currentShow != (SoCustomComparison)null && ((Object)__instance.currentShow).name == "BasBoule"; if (!Live.Started && flag) { EnsureStarted(__instance); } else if (Live.Started && !flag) { Finish("broadcast ended"); } } } catch (Exception ex) { Plugin.Out("!! BroadcastPostfix: " + ex.Message); } } private static void EnsureStarted(TelevisionChannel ch) { if (Live != null && !Live.Started && (SoCustomComparison)(object)ch.currentShow != (SoCustomComparison)null && ((Object)ch.currentShow).name == "BasBoule") { Live.Started = true; Plugin.Out("On air."); } } public static void DynamicShowPrefix(TelevisionChannel __instance) { try { if (Live == null || !IsOurs(__instance)) { return; } EnsureStarted(__instance); if (!Live.Started || (SoCustomComparison)(object)__instance.currentShow == (SoCustomComparison)null || ((Object)__instance.currentShow).name != "BasBoule" || __instance.currentDynamicClip != null) { return; } int clipIndex = __instance.clipIndex; List<DynamicClip> dynamicClips = __instance.currentShow.dynamicClips; if (clipIndex >= 0 && clipIndex < dynamicClips.Count) { DynamicClip val = dynamicClips[clipIndex]; if (!_originalChance.ContainsKey(clipIndex)) { _originalChance[clipIndex] = val.chance; } val.chance = Live.Plan.ChanceOverride(clipIndex) ?? _originalChance[clipIndex]; } } catch (Exception ex) { Plugin.Out("!! DynamicShowPrefix: " + ex.Message); } } public static void GetEventPostfix(TelevisionChannel __instance, ref DynamicClipEvent __result) { //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Expected I4, but got Unknown try { if (Live == null || !IsOurs(__instance)) { return; } EnsureStarted(__instance); if (!Live.Started || (SoCustomComparison)(object)__instance.currentShow == (SoCustomComparison)null || ((Object)__instance.currentShow).name != "BasBoule") { return; } DynamicClip currentDynamicClip = __instance.currentDynamicClip; if (currentDynamicClip == null) { return; } int clipIndex = __instance.clipIndex; DynamicClipEvent obj = __result; string value = ((obj != null) ? obj.name : null) ?? "<none>"; if (Live.Plan.Cursor != Live.LastCursor) { Live.LastCursor = Live.Plan.Cursor; Live.StallCount = 0; } else if (++Live.StallCount == 80) { Plugin.Out($"!! the broadcast stopped following the plan at #{clipIndex} (plan expects #{Live.Plan.Peek?.Step}); skipping to the result"); SkipToEnd("stall"); } else if (Live.StallCount == 200) { Plugin.Out("!! still stalled; ending the broadcast"); ResetShow(__instance); return; } Call val2 = default(Call); StepAction val = Live.Plan.OnEvent(clipIndex, ref val2); switch ((int)val) { case 0: return; case 1: __result = null; if (Plugin.VerboseLog.Value) { Plugin.Out($" #{clipIndex} silent (vanilla picked {value})"); } return; case 3: __result = currentDynamicClip.possibleEvents[0]; if (Plugin.VerboseLog.Value) { Plugin.Out($" #{clipIndex} gate open (vanilla picked {value})"); } return; } ClipView clipView = new ClipView(currentDynamicClip); int num = default(int); string text = default(string); string value2 = default(string); if (!BroadcastPlan.Resolve(val2, (IClipView)(object)clipView, ref num, ref text, ref value2)) { Plugin.Out($"!! #{clipIndex}: {value2}; keeping the game's pick"); return; } AudioEvent line = clipView.FindAudio(text); __result = Pinned(currentDynamicClip.name, num, currentDynamicClip.possibleEvents[num], line); Live.Steered++; if (Plugin.VerboseLog.Value) { Plugin.Out($" #{clipIndex} {text}{((val2.Note != null) ? (" (" + val2.Note + ")") : "")}"); } } catch (Exception ex) { Plugin.Out("!! GetEventPostfix: " + ex); } } internal static LiveSnapshot Snapshot() { LiveMatch live = Live; if (live == null) { return null; } LiveSnapshot liveSnapshot = new LiveSnapshot { Setup = live.Setup }; MatchResult result = live.Setup.Result; int num = 0; int num2 = 0; for (int i = 0; i < live.Plan.Cursor && i < live.Plan.Calls.Count; i++) { Call val = live.Plan.Calls[i]; if (val.Step == 19) { num2++; } else if (val.Step == 24) { num++; num2 = 0; } else if (val.Step >= 35) { num = 4; } } if (live.Committed || (live.Plan.Peek?.Step ?? 99) >= 35) { num = 4; } liveSnapshot.Half = Math.Min(num, 4); liveSnapshot.Final = num >= 4; for (int j = 0; j < num && j < 4; j++) { if (j % 2 == 0) { liveSnapshot.Score1 += result.Halves[j].Score; } else { liveSnapshot.Score2 += result.Halves[j].Score; } liveSnapshot.HalfRuns[j] = result.Halves[j].Score; } if (!liveSnapshot.Final && liveSnapshot.Half < 4) { List<PlayRecord> plays = result.Halves[liveSnapshot.Half].Plays; int num3 = Math.Min(num2, plays.Count); for (int k = 0; k < num3; k++) { liveSnapshot.Called.Add(plays[k]); } liveSnapshot.Upcoming = ((num3 < plays.Count) ? plays[num3] : null); liveSnapshot.HalfRuns[liveSnapshot.Half] = liveSnapshot.Called.Sum((PlayRecord p) => p.Scored.Count); } if (!liveSnapshot.Final && num2 > 0 && liveSnapshot.Half < 4) { List<PlayRecord> plays2 = result.Halves[liveSnapshot.Half].Plays; int num4 = Math.Min(num2, plays2.Count); liveSnapshot.LastPlay = plays2[num4 - 1]; int num5 = 0; for (int num6 = 0; num6 < num4; num6++) { num5 += plays2[num6].Scored.Count; if (plays2[num6].StrikerOut) { liveSnapshot.Outs++; } } if (liveSnapshot.Half % 2 == 0) { liveSnapshot.Score1 += num5; } else { liveSnapshot.Score2 += num5; } } return liveSnapshot; } internal static void KeepCruncherSound(Interactable cruncher) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) try { if (!Plugin.LiveAudio.Value || _cruncherSoundFailed || cruncher == null) { return; } _cruncherSoundWanted = Time.unscaledTime; if (_cruncherSound != null || !OnAirNow(out var ch)) { return; } AudioController instance = AudioController.Instance; AudioEvent audioEvent = ch.currentShow.audioEvent; if ((Object)(object)instance == (Object)null || (SoCustomComparison)(object)audioEvent == (SoCustomComparison)null) { return; } _cruncherSound = instance.PlayWorldLooping(audioEvent, (Actor)null, cruncher.node, cruncher.wPos, (Interactable)null, (List<FMODParam>)null, 1f, false, ch, (IfSwitchStateSFX)null); if (_cruncherSound == null) { _cruncherSoundFailed = true; Plugin.Out("!! the game would not start the match sound at the cruncher"); return; } try { _cruncherSound.UpdateDynamicClip(); } catch { } Plugin.Out("Match sound on at the cruncher."); } catch (Exception ex) { _cruncherSoundFailed = true; _cruncherSound = null; Plugin.Out("!! cruncher sound: " + ex.Message + " (turned off for this session)"); } } internal static void TickCruncherSound() { if (_cruncherSound != null && (!(Time.unscaledTime - _cruncherSoundWanted < 0.75f) || !OnAirNow(out var _))) { StopCruncherSound(); } } internal static void StopCruncherSound() { LoopingSoundInfo cruncherSound = _cruncherSound; _cruncherSound = null; if (cruncherSound == null) { return; } try { cruncherSound.isBroadcast = null; AudioController instance = AudioController.Instance; if ((Object)(object)instance == (Object)null) { return; } instance.StopSound(cruncherSound, (StopType)0); List<LoopingSoundInfo> loopingSounds = instance.loopingSounds; if (loopingSounds != null) { for (int num = loopingSounds.Count - 1; num >= 0; num--) { if (loopingSounds[num] != null && ((Il2CppObjectBase)loopingSounds[num]).Pointer == ((Il2CppObjectBase)cruncherSound).Pointer) { loopingSounds.RemoveAt(num); } } } Plugin.Out("Match sound off at the cruncher."); } catch (Exception ex) { Plugin.Out("!! stopping the cruncher sound: " + ex.Message); } } private static bool OnAirNow(out TelevisionChannel ch) { ch = null; if (Live == null || !Live.Started) { return false; } ch = FindChannel(); if (ch != null && (SoCustomComparison)(object)ch.currentShow != (SoCustomComparison)null) { return ((Object)ch.currentShow).name == "BasBoule"; } return false; } private static void RestoreChances() { try { BroadcastPreset show = _show; if (((show != null) ? show.dynamicClips : null) != null) { foreach (KeyValuePair<int, float> item in _originalChance) { if (item.Key < _show.dynamicClips.Count) { _show.dynamicClips[item.Key].chance = item.Value; } } } } catch { } _originalChance.Clear(); } private static DynamicClipEvent Pinned(string clipName, int eventIndex, DynamicClipEvent source, AudioEvent line) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0061: 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_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Expected O, but got Unknown string key = clipName + "|" + eventIndex + "|" + ((Object)line).name; if (_pinned.TryGetValue(key, out var value)) { return value; } DynamicClipEvent val = new DynamicClipEvent { name = source.name, conditionMode = source.conditionMode, OrConditions = new List<DynamicShowCondition>(), audioEvents = new List<AudioEvent>(), applyParameters = source.applyParameters, overrideCrowdNoiseParam = source.overrideCrowdNoiseParam, crowdLayerVolume = source.crowdLayerVolume, triggerCrowdReaction = source.triggerCrowdReaction }; val.audioEvents.Add(line); _pinned[key] = val; return val; } private static void SetParam(TelevisionChannel ch, ShowParamType type, float value) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown List<DynamicShowParam> appliedParameters = ch.appliedParameters; for (int i = 0; i < appliedParameters.Count; i++) { if (appliedParameters[i].paramType == type) { appliedParameters[i].value = value; return; } } appliedParameters.Add(new DynamicShowParam(type, value)); } } internal static class Fans { private sealed class AskLogic : IDialogLogic { public bool IsDialogShown(DialogPreset preset, Citizen saysTo, SideJob jobRef) { try { if (!Plugin.FanTalk.Value || LeagueHost.Engine == null || (Object)(object)saysTo == (Object)null || ((Actor)saysTo).isPlayer) { return false; } _asked = saysTo; return true; } catch { return false; } } public void OnDialogExecute(DialogController instance, Citizen saysTo, Interactable saysToInteractable, NewNode where, Actor saidBy, bool success, NewRoom roomRef, SideJob jobRef) { if ((Object)(object)saysTo != (Object)null) { _asked = saysTo; } } public ForceSuccess ShouldDialogSucceedOverride(DialogController instance, DialogOption dialog, Citizen saysTo, NewNode where, Actor saidBy) { if ((Object)(object)saysTo != (Object)null) { _asked = saysTo; } return (ForceSuccess)1; } } private static string _citySeed; private static ulong _cityKey; private static int[] _counts; private static int _counted; private static string _thenKey; private static string _nowKey; private static int[] _thenCounts; private static Citizen _asked; private static float _nextLook; private static float _nextTalk; private static float _replyAt = -1f; private static Citizen _replier; private static string _reply; private static readonly HashSet<string> _said = new HashSet<string>(); private static readonly Dictionary<int, float> _lastSpoke = new Dictionary<int, float>(); private static LeagueEngine _engine; private static double NeutralShare => Math.Clamp(Plugin.NonFanShare.Value, 0f, 0.9f); private static double Swing => Math.Clamp(Plugin.FanSwing.Value, 0f, 5f); private static double DieHards => Math.Clamp(Plugin.DieHardShare.Value, 0f, 1f); private static double[] Stock { get { LeagueEngine engine = LeagueHost.Engine; if (engine == null) { return null; } return engine.State.Stock; } } private static double Since { get { SessionData instance = SessionData.Instance; return ((instance != null) ? instance.gameTime : 0f) - Math.Max(1f, Plugin.FanTalkHours.Value); } } private static ulong CityKey() { string text = ""; try { CityData instance = CityData.Instance; text = ((instance != null) ? instance.seed : null) ?? ""; } catch { } if (text != _citySeed) { _citySeed = text; _cityKey = Fandom.CityKey(text); _counts = null; } return _cityKey; } internal static int TeamOf(Human h) { if (!((Object)(object)h == (Object)null)) { return Fandom.TeamOf(CityKey(), h.humanID, NeutralShare, Stock, Swing, DieHards); } return -1; } internal static bool IsDieHard(Human h) { if ((Object)(object)h != (Object)null) { return Fandom.IsDieHard(CityKey(), h.humanID, NeutralShare, DieHards); } return false; } internal static int ShareChange(int team) { try { LeagueEngine engine = LeagueHost.Engine; CityData instance = CityData.Instance; List<Citizen> val = ((instance != null) ? instance.citizenDirectory : null); if (engine == null || val == null || val.Count == 0 || engine.State.StockHistory.Count == 0) { return 0; } double[] stock = engine.State.StockHistory[engine.State.StockHistory.Count - 1].Stock; string text = _citySeed + "|" + val.Count + "|" + string.Join(",", stock.Select((double x) => x.ToString("0.00"))) + "|" + Swing + "|" + DieHards + "|" + NeutralShare; if (text != _thenKey) { _thenKey = text; _thenCounts = new int[6]; ulong num = CityKey(); for (int num2 = 0; num2 < val.Count; num2++) { Citizen val2 = val[num2]; if (!((Object)(object)val2 == (Object)null)) { int num3 = Fandom.TeamOf(num, ((Human)val2).humanID, NeutralShare, stock, Swing, DieHards); _thenCounts[(num3 < 0) ? 5 : num3]++; } } } float num4 = Share(team); return (!(num4 < 0f)) ? (Mathf.RoundToInt(num4 * 100f) - Mathf.RoundToInt(100f * (float)_thenCounts[team] / (float)val.Count)) : 0; } catch { return 0; } } internal static float Share(int team) { try { CityData instance = CityData.Instance; List<Citizen> val = ((instance != null) ? instance.citizenDirectory : null); if (val == null || val.Count == 0) { return -1f; } ulong num = CityKey(); double[] stock = Stock; string text = ((stock == null) ? "" : string.Join(",", stock.Select((double x) => x.ToString("0.00")))) + "|" + Swing + "|" + DieHards + "|" + NeutralShare; if (_counts == null || _counted != val.Count || text != _nowKey) { _nowKey = text; _counts = new int[6]; _counted = val.Count; for (int num2 = 0; num2 < val.Count; num2++) { Citizen val2 = val[num2]; if (!((Object)(object)val2 == (Object)null)) { int num3 = Fandom.TeamOf(num, ((Human)val2).humanID, NeutralShare, stock, Swing, DieHards); _counts[(num3 < 0) ? 5 : num3]++; } } } return (_counted == 0) ? (-1f) : ((float)_counts[team] / (float)_counted); } catch { return -1f; } } private static string Answer() { try { LeagueEngine engine = LeagueHost.Engine; Citizen asked = _asked; if (engine == null || (Object)(object)asked == (Object)null) { return "I don't follow it."; } int num = TeamOf((Human)(object)asked); Fixture val = ((num >= 0) ? Fandom.LastResult(engine.State, num, Since) : null); bool flag = IsDieHard((Human)(object)asked); int num2 = (flag ? (-1) : Fandom.FormerTeam(CityKey(), ((Human)asked).humanID, NeutralShare, engine.State, Swing, DieHards)); string text = Fandom.Answer(num, val, Plugin.FavouriteTeam.Value, CityKey() ^ (uint)((Human)asked).humanID, flag, num2); if (Plugin.VerboseLog.Value) { Plugin.Out($"[fans] asked {((Human)asked).GetCitizenName()} ({((num < 0) ? "no team" : Roster.ShortNames[num])}): {text}"); } return text; } catch (Exception ex) { Plugin.Out("!! fan answer: " + ex.Message); return "I don't follow it."; } } internal static void Register() { try { Lib.Dialogs.Builder("basboule_who_do_you_follow").SetText("Who do you follow in Bas-Boule?").SetDialogLogic((IDialogLogic)(object)new AskLogic()) .AddResponse((Func<string>)Answer, true, false) .CreateAndRegister(); } catch (Exception ex) { Plugin.Out("!! could not add the fan dialogue: " + ex.Message); } } private static bool Free(Citizen c) { if ((Object)(object)c == (Object)null || ((Actor)c).isPlayer || ((Actor)c).isDead || ((Actor)c).isAsleep || ((Actor)c).isStunned || ((Actor)c).isSpeaking || ((Actor)c).inConversation) { return false; } NewAIController ai = ((Actor)c).ai; if ((Object)(object)ai != (Object)null && (ai.inCombat || ai.persuit)) { return false; } return true; } internal static void Tick() { LeagueEngine engine = LeagueHost.Engine; SessionData instance = SessionData.Instance; if (engine == null || (Object)(object)instance == (Object)null || !instance.startedGame || !Plugin.FanTalk.Value || Time.timeScale <= 0f) { return; } if (engine != _engine) { _engine = engine; _said.Clear(); _lastSpoke.Clear(); _replier = null; _replyAt = -1f; } float time = Time.time; if ((Object)(object)_replier != (Object)null && time >= _replyAt) { Citizen replier = _replier; _replier = null; try { if (Free(replier)) { Lib.Dialogs.Speak(replier, _reply, false); } } catch (Exception ex) { Plugin.Out("!! fan reply: " + ex.Message); } } if (time < _nextLook || time < _nextTalk || (Object)(object)_replier != (Object)null) { return; } _nextLook = time + 5f; try { Look(engine, time); } catch (Exception ex2) { Plugin.Out("!! fan talk: " + ex2.Message); _nextLook = time + 60f; } } private static void Look(LeagueEngine e, float now) { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: 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_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: 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) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) Player instance = Player.Instance; CityData instance2 = CityData.Instance; List<Citizen> val = ((instance2 != null) ? instance2.citizenDirectory : null); if ((Object)(object)instance == (Object)null || val == null) { return; } double since = Since; if (!e.State.Fixtures.Any((Fixture f) => f.Played && f.PlayedAt >= since)) { return; } Vector3 position = ((Component)instance).transform.position; float num = Mathf.Max(3f, Plugin.FanTalkDistance.Value); List<(Citizen, Vector3, int)> list = new List<(Citizen, Vector3, int)>(); Vector3 val3; for (int num2 = 0; num2 < val.Count; num2++) { Citizen val2 = val[num2]; if (!((Object)(object)val2 == (Object)null)) { Vector3 position2 = ((Component)val2).transform.position; val3 = position2 - position; if (!(((Vector3)(ref val3)).sqrMagnitude > num * num) && Free(val2) && (!_lastSpoke.TryGetValue(((Human)val2).humanID, out var value) || !(now - value < 120f))) { list.Add((val2, position2, TeamOf((Human)(object)val2))); } } } if (list.Count < 2) { return; } ulong num3 = CityKey(); int num4 = 0; (Citizen, Citizen, string, string, string) tuple = default((Citizen, Citizen, string, string, string)); int num5 = default(int); foreach (var item in list) { if (item.Item3 < 0) { continue; } Fixture val4 = Fandom.LastResult(e.State, item.Item3, since); if (val4 == null) { continue; } foreach (var item2 in list) { if (((Human)item2.Item1).humanID == ((Human)item.Item1).humanID) { continue; } val3 = item.Item2 - item2.Item2; if (((Vector3)(ref val3)).sqrMagnitude > 16f || Mathf.Abs(item.Item2.y - item2.Item2.y) > 1.5f || ((Object)(object)((Actor)item.Item1).currentRoom != (Object)null && (Object)(object)((Actor)item2.Item1).currentRoom != (Object)null && ((Actor)item.Item1).currentRoom.roomID != ((Actor)item2.Item1).currentRoom.roomID)) { continue; } string text = $"{Math.Min(((Human)item.Item1).humanID, ((Human)item2.Item1).humanID)}-{Math.Max(((Human)item.Item1).humanID, ((Human)item2.Item1).humanID)}-{val4.Id}"; if (!_said.Contains(text)) { (string, string)? tuple2 = Fandom.Exchange(val4, item.Item3, item2.Item3, num3 ^ (uint)(((Human)item.Item1).humanID * 31 + ((Human)item2.Item1).humanID), ref num5); if (tuple2.HasValue && num5 > num4) { num4 = num5; tuple = (item.Item1, item2.Item1, tuple2.Value.Item1, tuple2.Value.Item2, text); } } } } if (num4 != 0) { Lib.Dialogs.Speak(tuple.Item1, tuple.Item3, false); _replier = tuple.Item2; _reply = tuple.Item4; _replyAt = now + 3.5f; _said.Add(tuple.Item5); _lastSpoke[((Human)tuple.Item1).humanID] = now; _lastSpoke[((Human)tuple.Item2).humanID] = now; _nextTalk = now + Mathf.Max(10f, Plugin.FanTalkSeconds.Value); Plugin.Out($"[fans] {((Human)tuple.Item1).GetCitizenName()}: \"{tuple.Item3}\" {((Human)tuple.Item2).GetCitizenName()}: \"{tuple.Item4}\""); } } } internal static class LeagueHost { private sealed class SaveFile { public int Version { get; set; } = 1; public float LastSlot { get; set; } public float LastCitySlot { get; set; } public string League { get; set; } } private const string FileName = "basboule-league.json"; internal static LeagueEngine Engine; private static float _lastSlot = float.NaN; private static float _lastTickTime = float.NaN; private static float _keptCitySlot; private static MethodInfo _ledgerContext; private static bool _ledgerLooked; internal static int Money { get { try { return ((Object)(object)GameplayController.Instance != (Object)null) ? GameplayController.Instance.money : 0; } catch { return 0; } } } internal static double BetEdge => Math.Clamp(Plugin.PlayerEdge.Value, -0.2f, 0.25f); internal static int LockedFixture { get { if (Director.Live == null || Director.Live.Committed) { return -1; } return Director.Live.Setup.Fixture.Id; } } internal static void Hook() { Lib.SaveGame.OnAfterNewGame += delegate { StartNewLeague("new game"); }; Lib.SaveGame.OnBeforeLoad += delegate { Director.Abort("loading a save"); Engine = null; }; Lib.SaveGame.OnAfterLoad += delegate(object? _, SaveGameArgs e) { LoadOrCreate(e); }; Lib.SaveGame.OnBeforeSave += delegate(object? _, SaveGameArgs e) { Save(e); }; Lib.SaveGame.OnBeforeDelete += delegate(object? _, SaveGameArgs e) { try { string saveGameDataPath = Lib.SaveGame.GetSaveGameDataPath(e, "basboule-league.json"); if (File.Exists(saveGameDataPath)) { File.Delete(saveGameDataPath); } } catch { } }; } private static void StartNewLeague(string why) { Director.Abort(why); ulong num = (ulong)(DateTime.Now.Ticks ^ 0xB0B0B0B0u); Engine = LeagueEngine.New(Plugin.LeagueConfigFromSettings(), num); _lastSlot = float.NaN; _lastTickTime = float.NaN; Plugin.Out($"New league started ({why}), seed {num}. Season {Engine.State.Season}: {Engine.State.Fixtures.Count} regular-season matches."); } private static void LoadOrCreate(SaveGameArgs e) { Director.Abort("save loaded"); string text = null; try { text = Lib.SaveGame.GetSaveGameDataPath(e, "basboule-league.json"); } catch { } if (text != null && File.Exists(text)) { try { SaveFile? saveFile = JsonSerializer.Deserialize<SaveFile>(File.ReadAllText(text)); Engine = LeagueEngine.Load(saveFile.League); ApplySettings(); _lastSlot = saveFile.LastSlot; _keptCitySlot = saveFile.LastCitySlot; _lastTickTime = float.NaN; Plugin.Out($"League loaded: season {Engine.State.Season}, {Engine.State.Fixtures.Count((Fixture f) => f.Played)} of {Engine.State.Fixtures.Count} fixtures played."); return; } catch (Exception ex) { Plugin.Out("!! could not read the saved league, starting a new one: " + ex.Message); } } StartNewLeague("no league in this save yet"); } private static void ApplySettings() { //IL_0023: 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_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) LeagueConfig val = Plugin.LeagueConfigFromSettings(); LeagueConfig config = Engine.State.Config; config.MeetingsPerPair = val.MeetingsPerPair; config.Playoffs = val.Playoffs; config.TieBreak = val.TieBreak; config.EventsPerRound = val.EventsPerRound; } private static void Save(SaveGameArgs e) { if (Engine == null) { return; } try { float num = ((Director.Live != null && !Director.Live.Committed) ? (Director.Live.SlotTime - 0.001f) : _lastSlot); float keptCitySlot = _keptCitySlot; SaveFile value = new SaveFile { LastSlot = (float.IsNaN(num) ? 0f : num), LastCitySlot = keptCitySlot, League = Engine.Save() }; File.WriteAllText(Lib.SaveGame.GetSaveGameDataPath(e, "basboule-league.json"), JsonSerializer.Serialize(value)); Plugin.Out($"League saved (season {Engine.State.Season})."); } catch (Exception ex) { Plugin.Out("!! could not save the league: " + ex.Message); } } private static List<float> Slots() { List<float> list = new List<float>(); string[] array = (Plugin.KickoffTimes.Value ?? "").Split(','); for (int i = 0; i < array.Length; i++) { if (TimeSpan.TryParseExact(array[i].Trim(), new string[2] { "h\\:mm", "hh\\:mm" }, CultureInfo.InvariantCulture, out var result)) { list.Add((float)result.TotalHours); } } if (list.Count == 0) { list.AddRange(new float[6] { 2f, 6f, 10f, 14f, 18f, 22f }); } list.Sort(); return list; } internal static void Tick() { SessionData instance = SessionData.Instance; if (Engine == null || (Object)(object)instance == (Object)null || !instance.startedGame) { return; } float gameTime = instance.gameTime; if (!float.IsNaN(_lastTickTime) && gameTime - _lastTickTime > 0.5f && Director.Live != null) { Director.SkipToEnd($"time jumped {gameTime - _lastTickTime:0.0} h"); } _lastTickTime = gameTime; Engine.BoostSize = Math.Clamp(Plugin.BoostSize.Value, 0f, 1f); PayBets(); foreach (Fixture fixture in Engine.State.Fixtures) { if (fixture.Played && fixture.PlayedAt < 0.0) { fixture.PlayedAt = gameTime; } } if (Director.Live != null && gameTime - Director.Live.SlotTime > 2.5f) { Director.SkipToEnd("the match overran"); } float num = gameTime - instance.decimalClock; if (float.IsNaN(_lastSlot)) { _lastSlot = gameTime; return; } List<float> list = new List<float>(); int[] array = new int[4] { -3, -2, -1, 0 }; foreach (int num2 in array) { foreach (float item in Slots()) { float num3 = num + (float)(num2 * 24) + item; if (num3 > _lastSlot + 0.02f && num3 <= gameTime) { list.Add(num3); } } } if (list.Count == 0) { return; } list.Sort(); if (list.Count > 18) { Plugin.Out($"{list.Count - 18} first lobs older than three days were dropped"); list = list.Skip(list.Count - 18).ToList(); } foreach (float item2 in list) { float num4 = (_lastSlot = item2); bool flag = gameTime - num4 > 0.25f; if (!flag && Director.Live == null && Director.CanBroadcast()) { Director.Start(Engine, num4, instance); } else { Resolve(flag ? ("the " + Plugin.Clock(num4) + " first lob was skipped") : "no broadcast available"); } } } internal static string PlaceBet(IList<BetLeg> picks, int stake, out Bet bet) { bet = null; if (Engine == null || !Plugin.BettingEnabled.Value) { return "THE BOOK IS CLOSED"; } if (Money < stake) { return "NOT ENOUGH CROWS"; } float num = (((Object)(object)SessionData.Instance != (Object)null) ? SessionData.Instance.gameTime : 0f); string text = Engine.PlaceBet(picks, stake, BetEdge, Math.Max(1, Plugin.MinStake.Value), Math.Max(1, Plugin.MaxStake.Value), Math.Max(1, Plugin.MaxOpenBets.Value), LockedFixture, (double)num, ref bet); if (text != null) { return text; } MoveMoney(-stake, $"Bas-Boule bet #{bet.Id}"); Plugin.Out($"Bet #{bet.Id} placed: {stake} cr at {Odds.Format(bet.Odds)} on {string.Join(" + ", bet.Legs.Select((BetLeg l) => BetsPage.LegText(l, match: true)))}"); return null; } private static void PayBets() { //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Invalid comparison between Unknown and I4 if (Engine == null || (Object)(object)GameplayController.Instance == (Object)null) { return; } List<Bet> list = null; foreach (Bet item in Engine.UnpaidBets()) { (list ?? (list = new List<Bet>())).Add(item); } if (list == null) { return; } foreach (Bet item2 in list) { item2.Paid = true; if (item2.Payout > 0) { MoveMoney(item2.Payout, ((int)item2.State == 3) ? $"Bas-Boule bet #{item2.Id} returned" : $"Bas-Boule bet #{item2.Id} won"); } Plugin.Out($"Bet #{item2.Id} {((object)Unsafe.As<BetState, BetState>(ref item2.State)/*cast due to .constrained prefix*/).ToString().ToLowerInvariant()}: {item2.Payout} cr paid (stake {item2.Stake})."); } } internal static void BetSound(string what) { //IL_0073: Unknown result type (might be due to invalid IL or missing references) try { if (!Plugin.BetSounds.Value) { return; } AudioControls instance = AudioControls.Instance; AudioController instance2 = AudioController.Instance; if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance2 == (Object)null)) { AudioEvent val = ((what == "stake") ? instance.payphoneMoneyIn : ((what == "win") ? instance.pickUpMoney : instance.purchaseItem)); if ((SoCustomComparison)(object)val != (SoCustomComparison)null) { instance2.Play2DSound(val, (List<FMODParam>)null, 1f); } } } catch (Exception ex) { Plugin.Out("!! bet sound: " + ex.Message); } } private static void MoveMoney(int amount, string memo) { IDisposable disposable = null; try { if (!_ledgerLooked) { _ledgerLooked = true; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { Type type = assemblies[i].GetType("Ledger.Bank", throwOnError: false); if (!(type == null)) { _ledgerContext = type.GetMethod("Context", new Type[2] { typeof(string), typeof(string) }); break; } } } disposable = _ledgerContext?.Invoke(null, new object[2] { "Gambling", memo }) as IDisposable; } catch { } try { GameplayController.Instance.AddMoney(amount, true, memo); } finally { try { disposable?.Dispose(); } catch { } } } private static void Resolve(string why) { Director.CommitNow(); MatchSetup s = Engine.PlayNext(); Plugin.Out("Resolved without broadcast (" + why + "): " + Describe(s)); } internal static string Describe(MatchSetup s) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 Fixture fixture = s.Fixture; string value = (((int)fixture.Stage == 0) ? $"round {fixture.Round}" : ((((int)fixture.Stage == 2) ? "Starch Series" : "District Series") + (fixture.IsReplay ? " replay" : ""))); string value2 = ((s.Absent1.Count + s.Absent2.Count > 0) ? (" (absent: " + string.Join(", ", from p in s.Absent1.Concat(s.Absent2) select p.Name) + ")") : ""); return $"season {fixture.Season} {value}: {s.Team1.Name} {s.Result.Score1}-{s.Result.Score2} {s.Team2.Name}{value2}"; } internal static List<float> NextKickoffs(int count) { List<float> list = new List<float>(); SessionData instance = SessionData.Instance; if ((Object)(object)instance == (Object)null) { return list; } float gameTime = instance.gameTime; float num = gameTime - instance.decimalClock; for (int i = 0; i < 8; i++) { if (list.Count >= count) { break; } foreach (float item in Slots()) { float num2 = num + (float)(i * 24) + item; if (num2 > gameTime + 0.001f && list.Count < count) { list.Add(num2); } } } return list; } internal static void Dump() { //IL_044f: Unknown result type (might be due to invalid IL or missing references) //IL_0458: Unknown result type (might be due to invalid IL or missing references) //IL_045e: Invalid comparison between Unknown and I4 if (Engine == null) { Plugin.Out("No league loaded."); return; } StringBuilder stringBuilder = new StringBuilder(); LeagueState st = Engine.State; StringBuilder stringBuilder2 = stringBuilder; StringBuilder stringBuilder3 = stringBuilder2; StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(53, 2, stringBuilder2); handler.AppendLiteral("===== BAS-BOULE: season "); handler.AppendFormatted(st.Season); handler.AppendLiteral(", defending champions: "); handler.AppendFormatted(Roster.FullNames[st.DefendingChampion]); handler.AppendLiteral(" ====="); stringBuilder3.AppendLine(ref handler); stringBuilder2 = stringBuilder; StringBuilder stringBuilder4 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(33, 1, stringBuilder2); handler.AppendLiteral(" "); handler.AppendFormatted<string>("Team", -26); handler.AppendLiteral(" P W D L RF RA RD Pts"); stringBuilder4.AppendLine(ref handler); int num = 1; foreach (StandingRow item in Engine.Standings(-1)) { stringBuilder2 = stringBuilder; StringBuilder stringBuilder5 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(14, 10, stringBuilder2); handler.AppendLiteral(" "); handler.AppendFormatted(num++); handler.AppendLiteral(". "); handler.AppendFormatted<string>(Roster.FullNames[item.Team], -26); handler.AppendFormatted(item.Played, 2); handler.AppendLiteral(" "); handler.AppendFormatted(item.Won, 2); handler.AppendLiteral(" "); handler.AppendFormatted(item.Drawn, 2); handler.AppendLiteral(" "); handler.AppendFormatted(item.Lost, 2); handler.AppendLiteral(" "); handler.AppendFormatted(item.RunsFor, 3); handler.AppendLiteral(" "); handler.AppendFormatted(item.RunsAgainst, 3); handler.AppendLiteral(" "); handler.AppendFormatted(item.RunDiff, 3, "+0;-0;0"); handler.AppendLiteral(" "); handler.AppendFormatted(item.Points, 3); stringBuilder5.AppendLine(ref handler); } SessionData instance = SessionData.Instance; List<Fixture> list = (from f in st.Fixtures where !f.Played orderby f.Id select f).Take(6).ToList(); if ((Object)(object)instance != (Object)null && list.Count > 0) { stringBuilder.AppendLine("Next fixtures:"); float gameTime = instance.gameTime; float num2 = gameTime - instance.decimalClock; List<float> list2 = new List<float>(); for (int num3 = 0; num3 < 4; num3++) { if (list2.Count >= list.Count) { break; } foreach (float item2 in Slots()) { float num4 = num2 + (float)(num3 * 24) + item2; if (num4 > gameTime && list2.Count < list.Count) { list2.Add(num4); } } } for (int num5 = 0; num5 < list.Count; num5++) { Fixture val = list[num5]; string value = ((num5 < list2.Count) ? $"day {Math.Floor(list2[num5] / 24f)} {Plugin.Clock(list2[num5])}" : "later"); stringBuilder2 = stringBuilder; StringBuilder stringBuilder6 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(10, 4, stringBuilder2); handler.AppendLiteral(" "); handler.AppendFormatted(value); handler.AppendLiteral(": "); handler.AppendFormatted(Roster.FullNames[val.Team1]); handler.AppendLiteral(" v "); handler.AppendFormatted(Roster.FullNames[val.Team2]); handler.AppendLiteral(" ("); handler.AppendFormatted(((int)val.Stage == 0) ? ("round " + val.Round) : (((int)val.Stage == 2) ? "Starch Series" : "District Series")); handler.AppendLiteral(")"); stringBuilder6.AppendLine(ref handler); } } List<Player> list3 = st.Players.Where((Player p) => (int)st.Statuses[p.Id].Absence > 0).ToList(); if (list3.Count > 0) { stringBuilder.AppendLine("Unavailable: " + string.Join(", ", list3.Select((Player p) => $"{p.Name} ({st.Statuses[p.Id].Absence}, {st.Statuses[p.Id].MatchesOut} more)"))); } stringBuilder.AppendLine("Latest news:"); foreach (Article item3 in st.Articles.Where((Article a) => a.Kind != "match").Reverse().Take(5)) { stringBuilder2 = stringBuilder; StringBuilder stringBuilder7 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(2, 1, stringBuilder2); handler.AppendLiteral(" "); handler.AppendFormatted(item3.Headline); stringBuilder7.AppendLine(ref handler); } stringBuilder.AppendLine("Latest results:"); foreach (Article item4 in st.Articles.Where((Article a) => a.Kind == "match").Reverse().Take(5)) { stringBuilder2 = stringBuilder; StringBuilder stringBuilder8 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(2, 1, stringBuilder2); handler.AppendLiteral(" "); handler.AppendFormatted(item4.Headline); stringBuilder8.AppendLine(ref handler); } if (Director.Live != null) { stringBuilder2 = stringBuilder; StringBuilder stringBuilder9 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(21, 3, stringBuilder2); handler.AppendLiteral("On air now: "); handler.AppendFormatted(Describe(Director.Live.Setup)); handler.AppendLiteral(" (plan "); handler.AppendFormatted(Director.Live.Plan.Cursor); handler.AppendLiteral("/"); handler.AppendFormatted(Director.Live.Plan.Calls.Count); handler.AppendLiteral(")"); stringBuilder9.AppendLine(ref handler); } Plugin.Out(stringBuilder.ToString()); } } [BepInPlugin("basboule.league", "BetterBasBoule", "0.5.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BasePlugin { public const string Guid = "basboule.league"; public const string Version = "0.5.0"; internal static ManualLogSource L; internal static ConfigEntry<int> MeetingsPerPair; internal static ConfigEntry<int> ReservesPerTeam; internal static ConfigEntry<PlayoffFormat> Playoffs; internal static ConfigEntry<PlayoffTieBreak> TieBreak; internal static ConfigEntry<float> EventsPerRound; internal static ConfigEntry<string> KickoffTimes; internal static ConfigEntry<KeyCode> DebugKey; internal static ConfigEntry<bool> VerboseLog; internal static ConfigEntry<int> FavouriteTeam; internal static ConfigEntry<bool> AnimatedAds; internal static ConfigEntry<float> AdSeconds; internal static ConfigEntry<float> TextWeight; internal static ConfigEntry<float> PlayerEdge; internal static ConfigEntry<bool> BettingEnabled; internal static ConfigEntry<bool> LiveAudio; internal static ConfigEntry<bool> FanTalk; internal static ConfigEntry<bool> BetSounds; internal static ConfigEntry<float> BoostSize; internal static ConfigEntry<float> NonFanShare; internal static ConfigEntry<float> FanTalkHours; internal static ConfigEntry<float> FanTalkSeconds; internal static ConfigEntry<float> FanTalkDistance; internal static ConfigEntry<float> FanSwing; internal static ConfigEntry<float> DieHardShare; internal static ConfigEntry<Ui.TextSmoothing> TextSmoothing; internal static ConfigEntry<int> MinStake; internal static ConfigEntry<int> MaxStake; internal static ConfigEntry<int> MaxOpenBets; private static StreamWriter _file; public override void Load() { //IL_04a6: Unknown result type (might be due to invalid IL or missing references) //IL_04ab: Unknown result type (might be due to invalid IL or missing references) //IL_04d2: Unknown result type (might be due to invalid IL or missing references) //IL_04e7: Unknown result type (might be due to invalid IL or missing references) //IL_04f4: Expected O, but got Unknown //IL_04f4: Expected O, but got Unknown //IL_04f5: Unknown result type (might be due to invalid IL or missing references) //IL_051c: Unknown result type (might be due to invalid IL or missing references) //IL_052a: Expected O, but got Unknown //IL_052b: Unknown result type (might be due to invalid IL or missing references) //IL_0553: Unknown result type (might be due to invalid IL or missing references) //IL_0560: Expected O, but got Unknown //IL_0566: Unknown result type (might be due to invalid IL or missing references) //IL_058d: Unknown result type (might be due to invalid IL or missing references) //IL_059b: Expected O, but got Unknown //IL_05c2: Unknown result type (might be due to invalid IL or missing references) //IL_05d0: Expected O, but got Unknown L = ((BasePlugin)this).Log; MeetingsPerPair = ((BasePlugin)this).Config.Bind<int>("League", "MeetingsPerPair", 2, "How many times each pair of teams meets in the regular season. Takes effect from the next season."); Playoffs = ((BasePlugin)this).Config.Bind<PlayoffFormat>("League", "Playoffs", (PlayoffFormat)0, "SemisAndFinal (top four play the District Series, then the winners meet in the Starch Series) or FinalOnly (the top two go straight to the Starch Series)."); TieBreak = ((BasePlugin)this).Config.Bind<PlayoffTieBreak>("League", "PlayoffTieBreak", (PlayoffTieBreak)0, "A drawn playoff match is replayed at the next first lob (Replay), or the higher seed goes through (HigherSeed)."); ReservesPerTeam = ((BasePlugin)this).Config.Bind<int>("League", "ReservesPerTeam", 2, "Unvoiced reserves per team. Takes effect in new leagues."); EventsPerRound = ((BasePlugin)this).Config.Bind<float>("League", "EventsPerRound", 1f, "Average number of league news events (injuries, suspensions, stories) after each round."); KickoffTimes = ((BasePlugin)this).Config.Bind<string>("Schedule", "KickoffTimes", "02:00,06:00,10:00,14:00,18:00,22:00", "First-lob times (when matches start), 24-hour clock, comma-separated."); DebugKey = ((BasePlugin)this).Config.Bind<KeyCode>("Debug", "DumpKey", (KeyCode)290, "Writes the standings, the next fixtures and the latest news to BepInEx/BasBoule.log."); VerboseLog = ((BasePlugin)this).Config.Bind<bool>("Debug", "VerboseLog", false, "Log every steered broadcast step."); AnimatedAds = ((BasePlugin)this).Config.Bind<bool>("LeagueNet", "AnimatedAds", true, "Flashing borders and blinking text in LeagueNet's ads. Turn this off if flashing images bother you (photosensitivity)."); AdSeconds = ((BasePlugin)this).Config.Bind<float>("LeagueNet", "AdSeconds", 8f, "How long each LeagueNet ad stays up before the next one, in real seconds. The ad copy is in BepInEx/config/basboule.ads.txt."); TextWeight = ((BasePlugin)this).Config.Bind<float>("LeagueNet", "TextWeight", 0.12f, "Has no effect with the game's current pixel font. Extra stroke thickness for LeagueNet's small text, 0 to 0.4 (0 = the font as it is). Raise it if small text breaks up on the cruncher screen; lower it if letters look blobby. Takes effect the next time the app is opened."); TextSmoothing = ((BasePlugin)this).Config.Bind<Ui.TextSmoothing>("LeagueNet", "TextSmoothing", Ui.TextSmoothing.Smooth, "The cruncher's pixel font breaks up at some viewing distances (letters lose strokes). Smooth draws LeagueNet's text with a smoothed copy of the font: a little soft, but even. SmoothMip also helps when the screen is small in view, but may show specks between letters. Off is the game's own look. Only LeagueNet is affected. Takes effect the next time the app is opened."); LiveAudio = ((BasePlugin)this).Config.Bind<bool>("LeagueNet", "LiveAudio", true, "Play the match commentary from the cruncher while LeagueNet is open (any page) and a match is on. The SOUND button at the top of LeagueNet changes this too."); FavouriteTeam = ((BasePlugin)this).Config.Bind<int>("LeagueNet", "FavouriteTeam", -1, "Your team (0 Bloodhounds, 1 Proteans, 2 Woodpeckers, 3 Blues, 4 Sugarbirds; -1 none). LeagueNet takes its colours. Set from the TEAMS page."); BettingEnabled = ((BasePlugin)this).Config.Bind<bool>("Betting", "Enabled", true, "The Starch Sportsbook on LeagueNet's BETS tab: moneylines, spreads, totals and parlays on league matches."); PlayerEdge = ((BasePlugin)this).Config.Bind<float>("Betting", "PlayerEdge", 0.05f, "How generous the book is. Prices are the fair odds (from simulating the match) improved by this much, so 0.05 means a bet returns 5% more than it costs on average, per leg. 0 is a fair book; a negative value gives the house an edge, as in real life. Range -0.2 to 0.25."); MinStake = ((BasePlugin)this).Config.Bind<int>("Betting", "MinStake", 10, "Smallest stake, in crows."); MaxStake = ((BasePlugin)this).Config.Bind<int>("Betting", "MaxStake", 250, "Largest stake on one bet, in crows. The book favours the player, so this is what keeps betting from being a money printer."); BoostSize = ((BasePlugin)this).Config.Bind<float>("Betting", "BoostSize", 0.25f, "The book's specials: about one match in three has one price boosted to pay this much more (0.25 = a quarter more). 0 turns specials off."); BetSounds = ((BasePlugin)this).Config.Bind<bool>("Betting", "Sounds", true, "Coins when you place a bet, and a payout sound when the sportsbook shows a win."); MaxOpenBets = ((BasePlugin)this).Config.Bind<int>("Betting", "MaxOpenBets", 6, "How many unsettled bets the player can have at once."); FanTalk = ((BasePlugin)this).Config.Bind<bool>("Fans", "Enabled", true, "Every citizen supports a team (or none). You can ask them who they follow, and fans standing together talk about recent results."); NonFanShare = ((BasePlugin)this).Config.Bind<float>("Fans", "NonFanShare", 0.2f, "Share of citizens who do not follow the sport (0 to 0.9). Changing it changes who supports whom."); FanSwing = ((BasePlugin)this).Config.Bind<float>("Fans", "Swing", 1f, "How strongly results, streaks, titles and news move people between teams (0 = fandoms never change; 2 = a fickle city)."); DieHardShare = ((BasePlugin)this).Config.Bind<float>("Fans", "DieHardShare", 0.3f, "Share of fans who never change team, whatever happens (0 to 1)."); FanTalkHours = ((BasePlugin)this).Config.Bind<float>("Fans", "TalkForHours", 24f, "For how many game hours after a match fans still talk about it."); FanTalkSeconds = ((BasePlugin)this).Config.Bind<float>("Fans", "SecondsBetweenTalks", 90f, "Shortest gap between two fan conversations near you, in real seconds."); FanTalkDistance = ((BasePlugin)this).Config.Bind<float>("Fans", "HearingDistance", 12f, "Fans only talk when they are within this many metres of you."); string text = Path.Combine(Paths.BepInExRootPath, "BasBoule.log"); try { FileInfo fileInfo = new FileInfo(text); if (fileInfo.Exists && fileInfo.Length > 2097152) { string text2 = Path.Combine(Paths.BepInExRootPath, "BasBoule.prev.log"); if (File.Exists(text2)) { File.Delete(text2); } File.Move(text, text2); } } catch { } _file = new StreamWriter(text, append: true, Encoding.UTF8) { AutoFlush = true }; _file.WriteLine(); _file.WriteLine("================================================================"); Out($"BasBoule {"0.5.0"} loaded at {DateTime.Now:yyyy-MM-dd HH:mm:ss}"); LeagueHost.Hook(); Fans.Register(); Harmony val = new Harmony("basboule.league"); val.Patch((MethodBase)AccessTools.Method(typeof(TelevisionChannel), "ProcessTelevisionBroadcast", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Director), "BroadcastPrefix", (Type[])null), new HarmonyMethod(typeof(Director), "BroadcastPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.Method(typeof(TelevisionChannel), "ProcessDynamicShow", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Director), "DynamicShowPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.Method(typeof(TelevisionChannel), "GetEvent", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Director), "GetEventPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); ClassInjector.RegisterTypeInIl2Cpp<LeagueNetApp>(); val.Patch((MethodBase)AccessTools.Method(typeof(MainMenuController), "Start", (Type[])null, (Type[])null), new HarmonyMethod(typeof(AppInstaller), "MainMenuStartPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.Method(typeof(DesktopApp), "OnSetup", (Type[])null, (Type[])null), new HarmonyMethod(typeof(AppInstaller), "DesktopOnSetupPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); ((BasePlugin)this).AddComponent<Ticker>(); } internal static LeagueConfig LeagueConfigFromSettings() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown return new LeagueConfig { MeetingsPerPair = Math.Max(1, MeetingsPerPair.Value), Playoffs = Playoffs.Value, TieBreak = TieBreak.Value, ReservesPerTeam = Math.Max(1, ReservesPerTeam.Value), EventsPerRound = Math.Max(0f, EventsPerRound.Value) }; } internal static void Out(string msg) { string text; try { SessionData instance = SessionData.Instance; text = (((Object)(object)instance != (Object)null) ? $"{Time.realtimeSinceStartup,7:0.0}s day {Math.Floor(instance.gameTime / 24f)} {Clock(instance.decimalClock)}" : $"{Time.realtimeSinceStartup,7:0.0}s"); } catch { text = "--"; } try { _file?.WriteLine("[" + text + "] " + msg); } catch { } ManualLogSource l = L; if (l != null) { l.LogInfo((object)msg); } } internal static string Clock(float hours) { hours = (hours % 24f + 24f) % 24f; int num = (int)hours; int num2 = (int)Math.Round((hours - (float)num) * 60f); if (num2 == 60) { num = (num + 1) % 24; num2 = 0; } return $"{num:00}:{num2:00}"; } } public class Ticker : MonoBehaviour { public Ticker(IntPtr ptr) : base(ptr) { } private void Update() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) try { try { if (Input.GetKeyDown(Plugin.DebugKey.Value)) { LeagueHost.Dump(); } } catch { } LeagueHost.Tick(); Director.TickCruncherSound(); Fans.Tick(); } catch (Exception ex) { Plugin.Out("!! tick: " + ex); } } } } namespace BasBouleMod.App { internal static class Ads { private sealed class Style { public string Id; public string Ink; public string Shadow; public string Border; public string Alt; public string Ribbon; } private sealed class Copy { public Style Style; public string Brand; public string Slogan; public string Burst; } private static readonly Style[] Styles = new Style[11] { S("starchkola", "FFFFFF", "000000", "FFFF55", "55FFFF", "FFFF55"), S("gemsteader", "FFFFFF", "000000", "FFFF55", "FF5555", "FFFF55"), S("yellowbeaks", "FFFF55", "000000", "FFFF55", "FF55FF", "FF5555"), S("holysmokes", "FFFFFF", "000000", "FFFF55", "55FFFF", "FFFF55"), S("synthmilk", "0000AA", "FFFFFF", "55FFFF", "FFFF55", "FF55FF"), S("elgen", "FFFFFF", "000000", "FF55FF", "FFFF55", "FFFF55"), S("kaizen", "FFFFFF", "000000", "FF55FF", "55FFFF", "55FFFF"), S("candor", "FFFFFF", "000000", "55FF55", "FF55FF", "55FF55"), S("kensington", "FFFF55", "000000", "FFFF55", "FF5555", "FF5555"), S("krueger", "FFFFFF", "000000", "FFFF55", "55FFFF", "FFFF55"), S("synthbeef", "FFFFFF", "000000", "FF5555", "55FF55", "55FF55") }; internal const int BrandMax = 18; internal const int SloganMax = 22; internal const int BurstMax = 16; internal const string FileName = "basboule.ads.txt"; private const string DefaultFile = "# LeagueNet ad copy. One ad per line:\n#\n# sponsor | brand | slogan | burst\n#\n# The sponsor sets the logo and the colours. It must be one of:\n# starchkola, gemsteader, yellowbeaks, holysmokes, synthmilk, elgen, kaizen, candor, kensington, krueger, synthbeef\n# A sponsor may have several lines. The ads rotate through every line, top to bottom.\n# Holy Smokes has no slot of its own: it takes over about 3 in 8 of the Yellow Beaks slots.\n#\n# Limits: brand 18 characters, slogan 22, burst 16. Longer text is cut. Text is shown in capitals.\n# Use plain letters, digits and basic punctuation; other symbols may be missing from the cruncher's fonts.\n# Lines starting with # are ignored. The file is read again whenever it changes, even while the game runs.\n# Delete the file to get the defaults back.\n\nstarchkola | STARCH KOLA | PUT SOME LIFE INTO IT! | GRAB A STARCH\ngemsteader | GEMSTEADER | WHATEVER THE WEATHER | REAL HOPS!\nyellowbeaks | YELLOW BEAKS | FOR THE LONG NIGHTS | UNFILTERED!\nholysmokes | HOLY SMOKES | A PILLAR OF FIRE | HOSANNA!\nsynthmilk | SYNTHMILK | DON'T HAVE A COW, MAN | NOW 15% MILK!\nelgen | ELLIOT GENETICS | YOU, BUT BETTER | NEW SYNCDISKS!\nkaizen | KAIZEN-6 V-LOVE | LOVE OPTIMISED | FIND YOUR MATCH!\ncandor | CANDOR NEWS | WE KNOW WHAT YOU WATCH | LIVE 24/7\nkensington | KENSINGTON INDIGO | YOUR MONEY, OUR FUTURE | 0% APR*\nkrueger | KRUEGER MUSTARD | SPREAD THE WORD | EXTRA HOT!\nsynthbeef | SYNTH BEEF | TASTES LIKE YESTERDAY | LAB FRESH!\n"; private static List<Copy> _main = new List<Copy>(); private static List<Copy> _holy = new List<Copy>(); private static DateTime _stamp = DateTime.MinValue; private static float _nextCheck; private static bool _loaded; internal static string FilePath => Path.Combine(Paths.ConfigPath, "basboule.ads.txt"); internal static int Rotation => (int)(Time.unscaledTime / Mathf.Max(2f, Plugin.AdSeconds.Value)); private static Style S(string id, string ink, string shadow, string border, string alt, string ribbon) { return new Style { Id = id, Ink = ink, Shadow = shadow, Border = border, Alt = alt, Ribbon = ribbon }; } private static void Refresh() { if (_loaded && Time.unscaledTime < _nextCheck) { return; } _nextCheck = Time.unscaledTime + 2f; try { string filePath = FilePath; if (!File.Exists(filePath)) { File.WriteAllText(filePath, "# LeagueNet ad copy. One ad per line:\n#\n# sponsor | brand | slogan | burst\n#\n# The sponsor sets the logo and the colours. It must be one of:\n# starchkola, gemsteader, yellowbeaks, holysmokes, synthmilk, elgen, kaizen, candor, kensington, krueger, synthbeef\n# A sponsor may have several lines. The ads rotate through every line, top to bottom.\n# Holy Smokes has no slot of its own: it takes over about 3 in 8 of the Yellow Beaks slots.\n#\n# Limits: brand 18 characters, slogan 22, burst 16. Longer text is cut. Text is shown in capitals.\n# Use plain letters, digits and basic punctuation; other symbols may be missing from the cruncher's fonts.\n# Lines starting with # are ignored. The file is read again whenever it changes, even while the game runs.\n# Delete the file to get the defaults back.\n\nstarchkola | STARCH KOLA | PUT SOME LIFE INTO IT! | GRAB A STARCH\ngemsteader | GEMSTEADER | WHATEVER THE WEATHER | REAL HOPS!\nyellowbeaks | YELLOW BEAKS | FOR THE LONG NIGHTS | UNFILTERED!\nholysmokes | HOLY SMOKES | A PILLAR OF FIRE | HOSANNA!\nsynthmilk | SYNTHMILK | DON'T HAVE A COW, MAN | NOW 15% MILK!\nelgen | ELLIOT GENETICS | YOU, BUT BETTER | NEW SYNCDISKS!\nkaizen | KAIZEN-6 V-LOVE | LOVE OPTIMISED | FIND YOUR MATCH!\ncandor | CANDOR NEWS | WE KNOW WHAT YOU WATCH | LIVE 24/7\nkensington | KENSINGTON INDIGO | YOUR MONEY, OUR FUTURE | 0% APR*\nkrueger | KRUEGER MUSTARD | SPREAD THE WORD | EXTRA HOT!\nsynthbeef | SYNTH BEEF | TASTES LIKE YESTERDAY | LAB FRESH!\n".Replace("\r\n", "\n").Replace("\n", Environment.NewLine)); } DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(filePath); if (_loaded && lastWriteTimeUtc == _stamp) { return; } _stamp = lastWriteTimeUtc; List<string> list = new List<string>(); Parse(File.ReadAllText(filePath), list); if (_main.Count == 0) { list.Add("no usable ads in the file; using the built-in ones"); Parse("# LeagueNet ad copy. One ad per line:\n#\n# sponsor | brand | slogan | burst\n#\n# The sponsor sets the logo and the colours. It must be one of:\n# starchkola, gemsteader, yellowbeaks, holysmokes, synthmilk, elgen, kaizen, candor, kensington, krueger, synthbeef\n# A sponsor may have several lines. The ads rotate through every line, top to bottom.\n# Holy Smokes has no slot of its own: it takes over about 3 in 8 of the Yellow Beaks slots.\n#\n# Limits: brand 18 characters, slogan 22, burst 16. Longer text is cut. Text is shown in capitals.\n# Use plain letters, digits and basic punctuation; other symbols may be missing from the cruncher's fonts.\n# Lines starting with # are ignored. The file is read again whenever it changes, even while the game runs.\n# Delete the file to get the defaults back.\n\nstarchkola | STARCH KOLA | PUT SOME LIFE INTO IT! | GRAB A STARCH\ngemsteader | GEMSTEADER | WHATEVER THE WEATHER | REAL HOPS!\nyellowbeaks | YELLOW BEAKS | FOR THE LONG NIGHTS | UNFILTERED!\nholysmokes | HOLY SMOKES | A PILLAR OF FIRE | HOSANNA!\nsynthmilk | SYNTHMILK | DON'T HAVE A COW, MAN | NOW 15% MILK!\nelgen | ELLIOT GENETICS | YOU, BUT BETTER | NEW SYNCDISKS!\nkaizen | KAIZEN-6 V-LOVE | LOVE OPTIMISED | FIND YOUR MATCH!\ncandor | CANDOR NEWS | WE KNOW WHAT YOU WATCH | LIVE 24/7\nkensington | KENSINGTON INDIGO | YOUR MONEY, OUR FUTURE | 0% APR*\nkrueger | KRUEGER MUSTARD | SPREAD THE WORD | EXTRA HOT!\nsynthbeef | SYNTH BEEF | TASTES LIKE YESTERDAY | LAB FRESH!\n", new List<string>()); } Plugin.Out($"Ads: {_main.Count + _holy.Count} lines read from {"basboule.ads.txt"}." + ((list.Count > 0) ? (" Problems: " + string.Join("; ", list.Take(8))) : "")); } catch (Exception ex) { if (_main.Count == 0) { Parse("# LeagueNet ad copy. One ad per line:\n#\n# sponsor | brand | slogan | burst\n#\n# The sponsor sets the logo and the colours. It must be one of:\n# starchkola, gemsteader, yellowbeaks, holysmokes, synthmilk, elgen, kaizen, candor, kensington, krueger, synthbeef\n# A sponsor may have several lines. The ads rotate through every line, top to bottom.\n# Holy Smokes has no slot of its own: it takes over about 3 in 8 of the Yellow Beaks slots.\n#\n# Limits: brand 18 characters, slogan 22, burst 16. Longer text is cut. Text is shown in capitals.\n# Use plain letters, digits and basic punctuation; other symbols may be missing from the cruncher's fonts.\n# Lines starting with # are ignored. The file is read again whenever it changes, even while the game runs.\n# Delete the file to get the defaults back.\n\nstarchkola | STARCH KOLA | PUT SOME LIFE INTO IT! | GRAB A STARCH\ngemsteader | GEMSTEADER | WHATEVER THE WEATHER | REAL HOPS!\nyellowbeaks | YELLOW BEAKS | FOR THE LONG NIGHTS | UNFILTERED!\nholysmokes | HOLY SMOKES | A PILLAR OF FIRE | HOSANNA!\nsynthmilk | SYNTHMILK | DON'T HAVE A COW, MAN | NOW 15% MILK!\nelgen | ELLIOT GENETICS | YOU, BUT BETTER | NEW SYNCDISKS!\nkaizen | KAIZEN-6 V-LOVE | LOVE OPTIMISED | FIND YOUR MATCH!\ncandor | CANDOR NEWS | WE KNOW WHAT YOU WATCH | LIVE 24/7\nkensington | KENSINGTON INDIGO | YOUR MONEY, OUR FUTURE | 0% APR*\nkrueger | KRUEGER MUSTARD | SPREAD THE WORD | EXTRA HOT!\nsynthbeef | SYNTH BEEF | TASTES LIKE YESTERDAY | LAB FRESH!\n", new List<string>()); } if (!_loaded) { Plugin.Out("!! ads file: " + ex.Message + " (using the built-in ads)"); } } _loaded = true; } private static void Parse(string text, List<string> problems) { List<Copy> list = new List<Copy>(); List<Copy> list2 = new List<Copy>(); int n = 0; string[] array = text.Split('\n'); foreach (string obj in array) { n++; string text2 = obj.Trim(); if (text2.Length == 0 || text2[0] == '#') { continue; } string[] parts = text2.Split('|'); if (parts.Length < 2) { problems.Add($"line {n}: expected sponsor | brand | slogan | burst"); continue; } string id = parts[0].Trim().ToLowerInvariant(); Style style = Styles.FirstOrDefault((Style s) => s.Id == id); if (style == null) { problems.Add($"line {n}: unknown sponsor '{id}'"); continue; } Copy copy = new Copy { Style = style, Brand = Field(1, 18, "brand"), Slogan = Field(2, 22, "slogan"), Burst = Field(3, 16, "burst") }; if (copy.Brand.Length == 0) { problems.Add($"line {n}: no brand"); } else { ((id == "holysmokes") ? list2 : list).Add(copy); } string Field(int num, int max, string what) { string text3 = ((num < parts.Length) ? Clean(parts[num]) : ""); if (text3.Length > max) { problems.Add($"line {n}: {what} cut to {max} characters"); text3 = text3.Substring(0, max).TrimEnd(); } return text3; } } _main = list; _holy = list2; } private static string Clean(string s) { return new string((from c in s.Trim().ToUpperInvariant() where c >= ' ' && c <= '~' && c != '<' && c != '>' select c).ToArray()); } private static Copy Pick(int key) { Refresh(); if (_main.Count == 0) { return null; } int index = (key % _main.Count + _main.Count) % _main.Count; Copy copy = _main[index]; if (copy.Style.Id == "yellowbeaks" && _holy.Count > 0 && ((key * 7919) & 7) < 3) { copy = _holy[(key & 0x7FFFFFFF) % _holy.Count]; } return copy; } internal static void Draw(Transform parent, int key, float x0, float y0, float x1, float y1) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) Copy copy = Pick(key); if (copy == null) { return; } Style style = copy.Style; Color border = Ui.Hex(style.Border); Color alt = Ui.Hex(style.Alt); RectTransform val = Ui.Panel(parent, "Ad", border, x0, y0, x1, y1); Image frameImg = ((Component)val).GetComponent<Image>(); Ui.Blinkers.Add(delegate(bool on) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) ((Graphic)frameImg).color = (on ? alt : border); }); RectTransform val2 = Ui.Picture((Transform)(object)val, "ad_" + style.Id + ".png", 0f, 0f, 1f, 1f); float num = Ui.Size(0.009f); val2.offsetMin = new Vector2(num, num); val2.offsetMax = new Vector2(0f - num, 0f - num); Color colour = Ui.Hex(style.Ink); Color shadow = Ui.Hex(style.Shadow); Ui.Shadowed((Transform)(object)val2, "<b>" + copy.Brand + "</b>", 0.044f, colour, shadow, 0.28f, 0.66f, 0.985f, 0.99f, (TextAlignmentOptions)4097, Ui.Title, 0.032f); if (copy.Slogan.Length > 0) { Ui.Shadowed((Transform)(object)val2, copy.Slogan, 0.04f, colour, shadow, 0.28f, 0.37f, 0.985f, 0.66f, (TextAlignmentOptions)4097, Ui.Caps, 0.03f); } if (copy.Burst.Length > 0) { RectTransform val3 = Ui.Picture((Transform)(object)val2, "ad_ribbon.png", 0.33f, 0f, 0.995f, 0.38f, Ui.Hex(style.Ribbon)); Ui.ShrinkToFit(Ui.Label((Transform)(object)val3, "<b>" + copy.Burst + "</b>", 0.04f, Color.black, 0.04f, 0.15f, 0.94f, 1f, (TextAlignmentOptions)514, Ui.Caps), 0.04f, 0.03f); GameObject ribbonGo = ((Component)val3).gameObject; Ui.Blinkers.Add(delegate(bool on) { ribbonGo.SetActive(!on); }); } } } internal static class AppInstaller { internal const string AppName = "LeagueNet"; private static bool _done; public static void MainMenuStartPrefix() { if (_done) { return; } _done = true; try { Install(); } catch (Exception ex) { Plugin.Out("!! could not install LeagueNet: " + ex); } } public static void DesktopOnSetupPrefix() { try { SetLabel(); } catch { } } private static void Install() { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Expected O, but got Unknown CruncherAppPreset val = ((IEnumerable<CruncherAppPreset>)Resources.FindObjectsOfTypeAll<CruncherAppPreset>()).FirstOrDefault((Func<CruncherAppPreset, bool>)((CruncherAppPreset a) => ((Object)a).name == "VMail")); GameObject val2 = ((((val != null) ? val.appContent : null) != null && val.appContent.Count > 0) ? val.appContent[0] : null); if ((SoCustomComparison)(object)val == (SoCustomComparison)null || (Object)(object)val2 == (Object)null) { Plugin.Out("!! VMail app not found; LeagueNet not installed"); return; } GameObject val3 = new GameObject("LeagueNetTemplates"); val3.SetActive(false); Object.DontDestroyOnLoad((Object)(object)val3); ((Object)val3).hideFlags = (HideFlags)61; GameObject val4 = Object.Instantiate<GameObject>(val2, val3.transform); ((Object)val4).name = "LeagueNetApp"; Strip(val4); val4.AddComponent<LeagueNetApp>(); CruncherAppPreset val5 = Object.Instantiate<CruncherAppPreset>(val); ((Object)val5).name = "LeagueNet"; ((Object)val5).hideFlags = (HideFlags)32; val5.appContent = new List<GameObject>(); val5.appContent.Add(val4); val5.onlyInAddresses = new List<AddressPreset>(); Sprite val6 = Ui.MakeIcon(); if ((Object)(object)val6 != (Object)null) { val5.desktopIcon = val6; } int num = 0; foreach (InteractablePreset item in Resources.FindObjectsOfTypeAll<InteractablePreset>()) { List<CruncherAppPreset> additionalApps = item.additionalApps; if (additionalApps == null || additionalApps.Count == 0 || !((Object)item).name.Contains("Cruncher")) { continue; } bool flag = false; for (int num2 = 0; num2 < additionalApps.Count; num2++) { CruncherAppPreset obj = additionalApps[num2]; if (((obj != null) ? ((Object)obj).name : null) == "LeagueNet") { flag = true; } } if (flag) { continue; } int num3 = -1; for (int num4 = 0; num4 < additionalApps.Count; num4++) { CruncherAppPreset obj2 = additionalApps[num4]; if (((obj2 != null) ? ((Object)obj2).name : null) == "Login") { num3 = num4; } } additionalApps.Insert((num3 >= 0) ? num3 : additionalApps.Count, val5); num++; } SetLabel(); Plugin.Out($"LeagueNet installed on {num} cruncher presets."); } private static void SetLabel() { Lib.DdsStrings.AddOrUpdate("computer", "LeagueNet".ToLowerInvariant(), "LeagueNet"); } private static void Strip(GameObject app) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Expected O, but got Unknown VMailApp component = app.GetComponent<VMailApp>(); if ((Object)(object)component != (Object)null) { Object.DestroyImmediate((Object)(object)component); } foreach (ComputerAutoTextController componentsInChild in app.GetComponentsInChildren<ComputerAutoTextController>(true)) { Object.DestroyImmediate((Object)(object)componentsInChild); } foreach (Button componentsInChild2 in app.GetComponentsInChildren<Button>(true)) { if (!((Object)componentsInChild2).name.StartsWith("Scroll")) { componentsInChild2.onClick = new ButtonClickedEvent(); } } } } internal static class BetsPage { private const float S = 0.04f; private const float T = 0.044f; private const int PerPage = 2; private const int Offered = 6; private const int BetsPerPage = 4; private static readonly List<BetLeg> Slip = new List<BetLeg>(); private static int _stakeIndex = 2; private static bool _myBets; private static string _message; private static LeagueEngine _engine; private static int _splashSounded = -1; private static readonly HashSet<int> Seen = new HashSet<int>(); internal static int Revision; private static readonly Color Pink = Ui.Hex("FF1F7A"); private static readonly Color DeepRed = Ui.Hex("AA0000"); private static readonly Color Yellow = Ui.Hex("FFFF55"); private static readonly Color Amber = Ui.Hex("FFB000"); private static readonly Color Green = Ui.Hex("55FF55"); private static readonly Color Red = Ui.Hex("FF5555"); private static readonly Color Navy = Ui.Hex("000060"); private static readonly Color Magenta = Ui.Hex("FF55FF"); private static readonly Color Ticket = Ui.Hex("FFF3A0"); private static readonly Color Cyan = Ui.Hex("55FFFF"); private static readonly Color Boost = Ui.Hex("AA00AA"); private static readonly int[] StakeSteps = new int[10] { 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000 }; private static readonly string[] Hype = new string[6] { "WIN BIG!", "EASY MONEY!", "BET NOW!", "ODDS BOOSTS!", "FEEL LUCKY?", "BEST PRICES!" }; private static readonly string[] ComeOns = new string[6] { "PICK A PRICE. ANY PRICE. YOU CAN'T LOSE!*", "TWO PICKS PAY MORE. THREE PAY MORE STILL!", "YOUR LUCK IS DUE. WE CAN FEEL IT.", "WHY WATCH WHEN YOU COULD WIN?", "A PARLAY TODAY, A PENTHOUSE TOMORROW!", "THE ODDS HAVE NEVER BEEN THIS GOOD!" }; private static List<int> Stakes() { int min = Math.Max(1, Plugin.MinStake.Value); int max = Math.Max(min, Plugin.MaxStake.Value); List<int> list = StakeSteps.Where((int s) => s >= min && s <= max).ToList(); if (list.Count == 0 || list[0] != min) { list.Insert(0, min); } if (list[list.Count - 1] != max) { list.Add(max); } return list; } private static string N(long n) { return n.ToString("N0", CultureInfo.InvariantCulture); } private static string L(double x) { return x.ToString("0.0", CultureInfo.InvariantCulture); } private static string Code(int team) { if (team < 0 || team >= Roster.Codes.Length) { return "?"; } return Roster.Codes[team]; } internal static string LegText(BetLeg leg, bool match = false) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 BetKind kind = leg.Kind; if ((int)kind != 0) { if ((int)kind == 1) { return Code(leg.Team) + " " + ((leg.Line > 0.0) ? "+" : "") + L(leg.Line); } return (leg.Over ? "O" : "U") + " " + L(leg.Line) + (match ? (" " + Code(leg.Team1) + "/" + Code(leg.Team2)) : ""); } return Code(leg.Team) + " ML"; } private static void Touch(string message = null) { _message = message; Revision++; } internal static string TickerText(LeagueEngine e) { int num = Ads.Rotation / 8; return Line(num * 4) + " · " + Line(1) + " · " + Line(num * 4 + 2) + " · " + Line(3); } private static string Line(int r) { switch (r % 4) { case 0: case 2: { string value = "A CITIZEN"; try { CityData instance = CityData.Instance; List<Citizen> val = ((instance != null) ? instance.citizenDirectory : null); if (val != null && val.Count > 0) { Citizen obj = val[(int)((uint)(r * 7919 + 13) % (uint)val.Count)]; string text = ((obj != null) ? ((Human)obj).GetCitizenName() : null); if (!string.IsNullOrEmpty(text) && text.All((char c) => c >= ' ' && c <= '~' && c != '<')) { value = text.ToUpperInvariant(); } } } catch { } int num = (int)(400 + (uint)(r * 2654435761u) % 90 * 50); int value2 = 2 + r % 3; return $"<color=#FFFF55>JUST IN</color> {value} WON {N(num)} CR ON {value2} PICKS · YOU'RE NEXT!"; } case 1: return "<color=#FF55FF>STARCH SPORTSBOOK</color> · WHERE EVERYBODY WINS* · PARLAYS PAY MORE!"; default: return "*NOT EVERYBODY WINS. STARCH KOLA ACCEPTS NO LIABILITY FOR LOSSES."; } } internal static void Draw(LeagueNetApp app, Transform body, LeagueEngine e, int page) { //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_022c: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) if (e != _engine) { _engine = e; Slip.Clear(); _message = null; Seen.Clear(); foreach (Bet bet in e.State.Book.Bets) { if ((int)bet.State != 0) { Seen.Add(bet.Id); } } } int locked = LeagueHost.LockedFixture; Slip.RemoveAll((BetLeg l) => l.FixtureId == locked || !e.State.Fixtures.Any((Fixture f) => f.Id == l.FixtureId && !f.Played)); Marquee(body); if (!Plugin.BettingEnabled.Value) { Ui.Label(body, "THE BOOK IS CLOSED", 0.044f, Ui.Grey, 0f, 0.4f, 1f, 0.6f, (TextAlignmentOptions)514, Ui.Caps); return; } int num = e.State.Book.Bets.Count((Bet b) => (int)b.State == 0); Ui.Button(body, "BOARD", delegate { _myBets = false; app.Turn(-999); Touch(); }, 0f, 0.785f, 0.17f, 0.875f, !_myBets, 0.04f); Ui.Button(body, (num > 0) ? $"MY BETS ({num})" : "MY BETS", delegate { _myBets = true; app.Turn(-999); Touch(); }, 0.18f, 0.785f, 0.45f, 0.875f, _myBets, 0.04f); RectTransform val = Ui.Picture(body, "ad_ribbon.png", 0.47f, 0.785f, 0.77f, 0.875f, Yellow); Ui.ShrinkToFit(Ui.Label((Transform)(object)val, "<b>" + Hype[Ads.Rotation % Hype.Length] + "</b>", 0.04f, Color.black, 0.04f, 0.15f, 0.94f, 1f, (TextAlignmentOptions)514, Ui.Caps), 0.04f, 0.03f); Image hypeImg = ((Component)val).GetComponent<Image>(); if ((Object)(object)hypeImg != (Object)null) { Ui.Blinkers.Add(delegate(bool on) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) ((Graphic)hypeImg).color = (on ? Cyan : Yellow); }); } if (_myBets) { MyBets(app, body, e, page); } else { Board(app, body, e, page, locked); } } private static void Marquee(Transform body) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: 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_00c6: 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_013f: 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_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) RectTransform parent = Ui.Dither(body, "Marquee", Pink, DeepRed, 0f, 0.885f, 1f, 1f); Ui.Icon((Transform)(object)parent, "sponsor_starchkola.png", 0.005f, 0.12f, 0.05f, 0.88f); Ui.Shadowed((Transform)(object)parent, "<b>STARCH SPORTSBOOK</b>", 0.044f, Yellow, Color.black, 0.06f, 0.1f, 0.6f, 0.9f, (TextAlignmentOptions)4097, Ui.Title); Ui.Icon((Transform)(object)parent, "bet_coin.png", 0.945f, 0.14f, 0.99f, 0.86f); Ui.Shadowed((Transform)(object)parent, "<b>" + N(LeagueHost.Money) + " CR</b>", 0.044f, Color.white, Color.black, 0.6f, 0.1f, 0.94f, 0.9f, (TextAlignmentOptions)4100, Ui.Caps); for (int i = 0; i < 2; i++) { for (int j = 0; j < 40; j++) { float num = ((float)j + 0.5f) / 40f; float num2 = ((i == 0) ? 0f : 0.86f); float y = num2 + 0.14f; Image img = ((Component)Ui.Panel((Transform)(object)parent, "Bulb", Color.white, num - 0.006f, num2, num + 0.006f, y)).GetComponent<Image>(); bool even = (j + i) % 2 == 0; Color lit = Yellow; Color dim = Ui.Hex("AA5500"); ((Graphic)img).color = (even ? lit : dim); Ui.Blinkers.Add(delegate(bool on) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) ((Graphic)img).color = ((even != on) ? lit : dim); }); } } } private static void Pager(LeagueNetApp app, Transform body, int page, int pages) { //IL_008e: Unknown result type (might be due to invalid IL or missing references) if (pages <= 1) { return; } if (page > 0) { Ui.Button(body, "<", delegate { app.Turn(-1); }, 0.79f, 0.785f, 0.86f, 0.875f, pressed: false, 0.04f); } Ui.Label(body, $"{page + 1}/{pages}", 0.04f, Ui.Grey, 0.86f, 0.785f, 0.93f, 0.875f, (TextAlignmentOptions)514, Ui.Caps); if (page < pages - 1) { Ui.Button(body, ">", delegate { app.Turn(1); }, 0.93f, 0.785f, 1f, 0.875f, pressed: false, 0.04f); } } private static void Board(LeagueNetApp app, Transform body, LeagueEngine e, int page, int locked) { //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_04ca: Unknown result type (might be due to invalid IL or missing references) //IL_051f: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_087b: Unknown result type (might be due to invalid IL or missing references) //IL_05ca: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_0767: Unknown result type (might be due to invalid IL or missing references) //IL_0935: Unknown result type (might be due to invalid IL or missing references) //IL_092e: Unknown result type (might be due to invalid IL or missing references) //IL_0678: Unknown result type (might be due to invalid IL or missing references) //IL_06fc: Unknown result type (might be due to invalid IL or missing references) //IL_072c: Unknown result type (might be due to invalid IL or missing references) //IL_0731: Unknown result type (might be due to invalid IL or missing references) //IL_073d: Unknown result type (might be due to invalid IL or missing references) //IL_0742: Unknown result type (might be due to invalid IL or missing references) //IL_093f: Unknown result type (might be due to invalid IL or missing references) //IL_07bc: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: Unknown result type (might be due to invalid IL or missing references) //IL_02e8: Unknown result type (might be due to invalid IL or missing references) //IL_0991: Unknown result type (might be due to invalid IL or missing references) //IL_0996: Unknown result type (might be due to invalid IL or missing references) //IL_099d: Unknown result type (might be due to invalid IL or missing references) //IL_09a2: Unknown result type (might be due to invalid IL or missing references) double betEdge = LeagueHost.BetEdge; List<Fixture> list = (from f in e.State.Fixtures where !f.Played && f.Id != locked orderby f.Id select f).Take(6).ToList(); List<float> list2 = LeagueHost.NextKickoffs(list.Count); int num = Math.Max(1, (list.Count + 2 - 1) / 2); page = Math.Min(page, num - 1); Pager(app, body, page, num); List<Bet> list3 = e.State.Book.Bets.Where((Bet val5) => (int)val5.State != 0 && !Seen.Contains(val5.Id)).ToList(); if (list3.Count > 0) { Splash(body, list3); } else if (list.Count == 0) { Ui.Label((Transform)(object)Ui.Framed(body, "Lamps", Color.black, raised: false, 0f, 0.26f, 1f, 0.775f).field, "NEW PRICES SOON. DON'T GO ANYWHERE!", 0.04f, Amber, 0f, 0.3f, 1f, 0.7f, (TextAlignmentOptions)514, Ui.Caps); } else { for (int num2 = 0; num2 < 2; num2++) { int num3 = page * 2 + num2; if (num3 >= list.Count) { break; } Fixture val = list[num3]; Market val2 = e.MarketFor(val, betEdge); float num4 = 0.775f - (float)num2 * 0.26f; RectTransform item = Ui.Framed(body, "Lamps", Color.black, raised: false, 0f, num4 - 0.255f, 1f, num4).field; string text = ((num3 < list2.Count) ? Pages.Kickoff(list2[num3]) : "LATER"); Ui.Label((Transform)(object)item, $"<b>{Roster.ShortNames[val.Team1].ToUpperInvariant()} v {Roster.ShortNames[val.Team2].ToUpperInvariant()}</b>", 0.04f, Green, 0.012f, 0.68f, 0.7f, 1f, (TextAlignmentOptions)4097, Ui.Caps); bool flag = val2.All.Any((BetLeg o) => o.Boosted); TextMeshProUGUI whenText = Ui.Label((Transform)(object)item, flag ? "<b>ODDS BOOST!</b>" : text, 0.04f, flag ? Magenta : Amber, 0.6f, 0.68f, 0.988f, 1f, (TextAlignmentOptions)4100, Ui.Caps); if (flag) { string w = text; Ui.Blinkers.Add(delegate(bool flag3) { //IL_
BasBoule.Sim.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text.Json; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("BasBoule.Sim")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+b2c6067481cefb001beeb78de3a2eae72e214ddf")] [assembly: AssemblyProduct("BasBoule.Sim")] [assembly: AssemblyTitle("BasBoule.Sim")] [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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [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 BasBoule.Sim { public interface IClipView { int EventCount { get; } string EventName(int i); IReadOnlyList<string> EventAudio(int i); IReadOnlyList<(string type, float value)> EventParams(int i); } public enum StepAction { Pass, Silence, Play, Open } public sealed class BroadcastPlan { public readonly List<Call> Calls; public readonly List<string> Warnings = new List<string>(); public static readonly HashSet<int> OptionalSteps = new HashSet<int> { 7, 9, 13, 15, 20, 21, 31 }; public static readonly HashSet<int> LogicSteps = new HashSet<int> { 28, 29, 30, 36, 37 }; public static readonly Dictionary<int, int> Gates = new Dictionary<int, int> { { 22, 24 }, { 26, 35 } }; public static readonly HashSet<int> MaySkip = new HashSet<int> { 6, 8, 10, 12, 14, 16, 23, 25, 27, 32, 33, 39, 41 }; private static readonly string[] TeamNames = new string[5] { "Bloodhounds", "Proteans", "Woodpeckers", "Blues", "Sugarbirds" }; private static readonly string[] PlayEventNames = new string[6] { "Cheer Small", "Cheer Medium", "Cheer Large", "Boo", "Near Miss", "Strike" }; public int Cursor { get; private set; } public Call Peek { get { if (Cursor >= Calls.Count) { return null; } return Calls[Cursor]; } } public bool Finished => Cursor >= Calls.Count; public BroadcastPlan(List<Call> calls) { Calls = calls; } public float? ChanceOverride(int step) { if (!OptionalSteps.Contains(step)) { return null; } Call peek = Peek; return (peek != null && peek.Step == step) ? 1f : 0f; } public StepAction OnEvent(int step, out Call call) { call = null; if (LogicSteps.Contains(step)) { return StepAction.Pass; } if (Gates.TryGetValue(step, out var value)) { Call peek = Peek; if (peek == null || peek.Step != value) { return StepAction.Silence; } return StepAction.Open; } if (Peek != null && Peek.Step == step) { call = Calls[Cursor++]; return StepAction.Play; } if (MaySkip.Contains(step)) { return StepAction.Silence; } int num = -1; for (int i = Cursor; i < Calls.Count && i < Cursor + 12; i++) { if (Calls[i].Step == step) { num = i; break; } } Warnings.Add($"desync: game asked for #{step}, plan expected #{Peek?.Step.ToString() ?? "end"}" + ((num >= 0) ? $"; skipped {num - Cursor} planned call(s)" : "; left silent")); if (num < 0) { return StepAction.Silence; } Cursor = num; call = Calls[Cursor++]; return StepAction.Play; } public void SkipToEnd() { int num = Calls.FindIndex(Cursor, (Call c) => c.Step == 35); if (num >= 0) { Cursor = num; } } public static bool Resolve(Call call, IClipView clip, out int eventIndex, out string audio, out string error) { eventIndex = -1; audio = call.LineId; error = null; switch (call.Step) { case 1: eventIndex = FindByParam(clip, "team1", call.Team); break; case 2: eventIndex = FindByParam(clip, "team2", call.Team); break; case 19: { eventIndex = (int)call.Kind; if (eventIndex >= clip.EventCount || clip.EventName(eventIndex) != PlayEventNames[eventIndex]) { error = $"#19 event {eventIndex} is not '{PlayEventNames[(int)call.Kind]}'"; return false; } string line = audio; if (!Enumerable.Range(0, clip.EventCount).Any((int i2) => clip.EventAudio(i2).Contains(line))) { error = "#19 has no line '" + line + "'"; return false; } return true; } case 24: eventIndex = FindByName(clip, (call.Score == 0) ? "No Score" : ("Score " + call.Score)); break; case 25: eventIndex = call.Score - 1; break; case 27: eventIndex = FindByName(clip, $"Team {call.Side} {TeamNames[call.Team]}"); break; case 39: eventIndex = FindByName(clip, $"Winning Team {call.Side}: {TeamNames[call.Team]}"); break; default: { for (int i = 0; i < clip.EventCount; i++) { if (eventIndex >= 0) { break; } if (clip.EventAudio(i).Contains(audio)) { eventIndex = i; } } break; } } if (eventIndex < 0 || eventIndex >= clip.EventCount) { error = $"#{call.Step}: no event for '{audio}'"; return false; } if (!clip.EventAudio(eventIndex).Contains(audio)) { error = $"#{call.Step}: event '{clip.EventName(eventIndex)}' has no line '{audio}'"; return false; } return true; } private static int FindByName(IClipView clip, string name) { for (int i = 0; i < clip.EventCount; i++) { if (clip.EventName(i) == name) { return i; } } return -1; } private static int FindByParam(IClipView clip, string type, int value) { for (int i = 0; i < clip.EventCount; i++) { foreach (var (text, num) in clip.EventParams(i)) { if (text == type && Math.Abs(num - (float)value) < 0.01f) { return i; } } } return -1; } } public sealed class Line { public string Id; public Func<Ctx, bool> When; public string Why; public double Weight = 1.0; public string Group; public string Family; public bool OncePerMatch; public bool OncePerPlayer; public bool CrossMatchCooldown; public bool MustSay; public Line(string id, Func<Ctx, bool> when = null, string why = null, double weight = -1.0, string group = null, string family = null, bool once = false, bool oncePerPlayer = false, bool cooldown = false, bool mustSay = false) { Id = id; When = when; Why = why; MustSay = mustSay; Weight = ((weight >= 0.0) ? weight : ((double)((when == null) ? 1 : 2))); Group = group ?? DefaultGroup(id); Family = family; OncePerMatch = once; OncePerPlayer = oncePerPlayer; CrossMatchCooldown = cooldown; } public static string DefaultGroup(string id) { Match match = Regex.Match(id, "^(.*? - \\d+)b?(\\s|$)"); if (!match.Success) { return id; } return match.Groups[1].Value; } } public sealed class Ctx { public int Step; public MatchResult Match; public int Half; public PlayRecord Play; public int BoosThisSpell; public bool EarlierBigPlay; public Player NextLobber; public Player NextStriker; public Player Named; public Weather Weather; public Daypart Daypart = Daypart.Evening; public LeagueFacts League; public int Margin; public bool DefendingChampionLost; public bool AfterDark => Daypart != Daypart.Day; public bool RunnerScores { get { if (Play != null) { return Play.Scored.Any((Player p) => p != Play.Striker); } return false; } } public bool Veteran(Player p) { return p?.Tags.Contains("veteran") ?? false; } } public enum Weather { Clear, Fog, Snow, Rain } public enum Daypart { Day, Evening, Night } public sealed class LeagueFacts { public Player BestLobber; public HashSet<Player> TopRouleurs = new HashSet<Player>(); public HashSet<Player> TopTireurs = new HashSet<Player>(); public HashSet<Player> TopFielders = new HashSet<Player>(); public HashSet<Player> Returning = new HashSet<Player>(); public HashSet<Player> ReturningSync = new HashSet<Player>(); public HashSet<Player> BackFromSuspension = new HashSet<Player>(); public HashSet<string> News = new HashSet<string>(); public int DefendingChampion = -1; public Player FanFavourite; public bool ChampionWonThreeToOneLastWeek; public HashSet<string> Cooldown = new HashSet<string>(); } public sealed class Call { public int Step; public string LineId; public string Group; public string Note; public Player Player; public int Team = -1; public int Side; public PlayKind Kind; public int Score = -1; } public sealed class CommentaryState { public readonly Dictionary<(Line[], int), string> LastGroup = new Dictionary<(Line[], int), string>(); public readonly HashSet<string> UsedGroups = new HashSet<string>(); public readonly HashSet<string> UsedFamilies = new HashSet<string>(); public readonly HashSet<(string, Player)> UsedPerPlayer = new HashSet<(string, Player)>(); public readonly Dictionary<string, int> Uses = new Dictionary<string, int>(); public readonly Dictionary<int, string> LastAtStep = new Dictionary<int, string>(); } public static class Commentary { private const string StrikeRightHander = "play - strike right-hander"; public static readonly Dictionary<PlayKind, Line[]> Plays = new Dictionary<PlayKind, Line[]> { [PlayKind.CheerSmall] = new Line[5] { new Line("play - 03 a high handed", (Ctx c) => c.Play.Turn == 0 && c.Play.LobInTurn == 0, "first lob of a half-inning: a soft single that drops near the jack, 8.5 m from the plates", 3.0), new Line("play - 06 its a curve ball swooping"), new Line("play - 08 and look at that", (Ctx c) => c.Veteran(c.Play.Striker) || c.Veteran(c.Play.Lobber), "backspin stops it short; a veteran is involved", 2.0), new Line("play - 12 here it rolls", (Ctx c) => c.RunnerScores, "a runner (pointer) races home to the circle", 3.0), new Line("play - 16 thats a fast ball", null, "snapping to the centre of the piste, short of the jack") }, [PlayKind.CheerMedium] = new Line[5] { new Line("play - 08 and look at that", (Ctx c) => c.Veteran(c.Play.Striker) || c.Veteran(c.Play.Lobber), "a veteran is involved", 2.0), new Line("play - 09 pumps once", null, "the struck boule kisses the jack"), new Line("play - 12 here it rolls", (Ctx c) => c.RunnerScores, "a runner races home to the circle", 3.0), new Line("play - 14 its right up against", null, "the struck boule stops against the jack"), new Line("play - 16 thats a fast ball") }, [PlayKind.CheerLarge] = new Line[4] { new Line("play - 09 pumps once"), new Line("play - 10 and its out and rolling", null, "rolls on past the jack; 'a perfect roule'"), new Line("play - 12 here it rolls", (Ctx c) => c.RunnerScores, "a runner races home to the circle", 3.0), new Line("play - 14 its right up against") }, [PlayKind.Boo] = new Line[4] { new Line("play - 02 curls all the way outside", (Ctx c) => c.BoosThisSpell == 0, "'Ball one': only the first dead lob of a lobber's spell", 2.0), new Line("play - 04 and heres the first"), new Line("play - 05 seven point three", (Ctx c) => c.Play.Lobber.Position == Position.Fielder, "'this long-armed fielder' is the lobber, and his lob falls short", 3.0), new Line("play - 15 fast ball into the edge") }, [PlayKind.NearMiss] = new Line[5] { new Line("play - 01 its a curve ball"), new Line("play - 11 and it flies"), new Line("play - 13 there it goes", (Ctx c) => c.Play.RunnersBefore == 2, "'risking two boules': exactly two runners on base when the striker is put out", 3.0), new Line("play - 15 fast ball into the edge", null, "struck into the edge of the piste: out"), new Line("play - 17 the distinguished", (Ctx c) => c.Play.Striker.LeftHanded, "a left-hander sends it flying", 2.0, null, null, once: false, oncePerPlayer: true) }, [PlayKind.Strike] = new Line[3] { new Line("play - 07 quick lob", (Ctx c) => !c.Play.Striker.LeftHanded, "'right-hander for a strike'", -1.0, "play - strike right-hander"), new Line("play - 18 its a booming strike"), new Line("play - 19 up to the line", (Ctx c) => !c.Play.Striker.LeftHanded, "'right-hander for a strike'", -1.0, "play - strike right-hander") } }; public static readonly Line[] NextPosition = new Line[21] { new Line("next position - 01 and the next player", NewStriker, "a different striker steps up"), new Line("next position - 01b and the next player", NewStriker), new Line("next position - 02 another player", NewStriker), new Line("next position - 02b another player", NewStriker), new Line("next position - 03 rivals coming out", (Ctx c) => c.Step == 34, "the other side takes the field"), new Line("next position - 04 the big rouleur", (Ctx c) => c.NextLobber.Position == Position.Rouleur, "the Rouleur lobs next (closing lob, or the first spell of a half-inning)"), new Line("next position - 04b the big rouleur", (Ctx c) => c.NextLobber.Position == Position.Rouleur), new Line("next position - 05 next lobber warming", (Ctx c) => c.Step == 23, "a new lobber's spell"), new Line("next position - 05b next lobber warming", (Ctx c) => c.Step == 23), new Line("next position - 06 next rouleur", (Ctx c) => c.Step == 34, "the new defence's Rouleur takes the first spell ('first position')"), new Line("next position - 06b next rouleur", (Ctx c) => c.Step == 34), new Line("next position - 07 the opposing side", (Ctx c) => c.Step == 34), new Line("next position - 07b the opposing side", (Ctx c) => c.Step == 34), new Line("next position - 08 the tireur", (Ctx c) => c.NextLobber.Position == Position.Tireur, "the Tireur lobs the second spell"), new Line("next position - 08b the tireur", (Ctx c) => c.NextLobber.Position == Position.Tireur), new Line("next position - 09 the opposing rouleur", (Ctx c) => c.NextLobber.Position == Position.Rouleur, "the fielding side's Rouleur warms up"), new Line("next position - 10 here comes the response", (Ctx c) => c.Step == 34), new Line("next position - 10b here comes the response", (Ctx c) => c.Step == 34), new Line("next position - 11 the opposition looking", null, "the fielding side, before any new lobber"), new Line("next position - 12 here comes the big", (Ctx c) => c.NextLobber.Position == Position.Rouleur, "the Rouleur lobs next"), new Line("next position - 12b the next tireur", (Ctx c) => c.NextStriker != null && c.NextStriker.Position == Position.Tireur && NewStriker(c), "the Tireur steps into the circle to strike", 2.0, "next position - 12b") }; public static readonly Line[] Interjections = new Line[15] { new Line("play interjection - 01 it looks like", (Ctx c) => Is(c, PlayKind.Boo, PlayKind.NearMiss, PlayKind.CheerSmall)), new Line("play interjection - 02 no-one saw", (Ctx c) => Is(c, PlayKind.Boo, PlayKind.CheerSmall)), new Line("play interjection - 02b no-one saw", (Ctx c) => Is(c, PlayKind.CheerLarge, PlayKind.Strike, PlayKind.CheerSmall)), new Line("play interjection - 03 what a play", (Ctx c) => Is(c, PlayKind.CheerMedium, PlayKind.CheerLarge, PlayKind.Strike), null, -1.0, "play interjection - what a play"), new Line("play interjection - 04 lets see", (Ctx c) => Is(c, PlayKind.Boo), "the lobber has slipped; the batting side may exploit it"), new Line("play interjection - 05 during last weeks", (Ctx c) => Hit(c) && c.League.ChampionWonThreeToOneLastWeek, "only true if the reigning champion won 3-1 last week", 4.0), new Line("play interjection - 06 to quote the boss", (Ctx c) => Is(c, PlayKind.CheerSmall, PlayKind.CheerMedium, PlayKind.CheerLarge, PlayKind.Strike)), new Line("play interjection - 07 what a play", (Ctx c) => Is(c, PlayKind.CheerMedium, PlayKind.CheerLarge, PlayKind.Strike), null, -1.0, "play interjection - what a play"), new Line("play interjection - 08 what a play what a game", (Ctx c) => Is(c, PlayKind.CheerMedium, PlayKind.CheerLarge, PlayKind.Strike)), new Line("play interjection - 09 cooler than a", (Ctx c) => Hit(c)), new Line("play interjection - 10 the corps are", (Ctx c) => Is(c, PlayKind.Boo)), new Line("play interjection - 11 never a dull"), new Line("play interjection - 12 how will the", (Ctx c) => Is(c, PlayKind.CheerMedium, PlayKind.CheerLarge)), new Line("play interjection - 12b how will the", (Ctx c) => Is(c, PlayKind.CheerMedium, PlayKind.CheerLarge)), new Line("play interjection - 13 we havent seen", (Ctx c) => Is(c, PlayKind.CheerLarge, PlayKind.Strike) && !c.EarlierBigPlay, "first triple or home run of the match", 2.0) }; public static readonly Line[] NameInterjections = new Line[14] { new Line("player name interjection - 01 a big day", (Ctx c) => !c.Named.LeftHanded, "right-hander", 1.0, null, null, once: true), new Line("player name interjection - 02 always ready"), new Line("player name interjection - 03 one of the best", (Ctx c) => c.League.TopRouleurs.Contains(c.Named), "one of the league's best rollers", 3.0), new Line("player name interjection - 04 the lean", (Ctx c) => c.Named.Position == Position.Rouleur && c.Named.Tags.Contains("lean"), null, 4.0), new Line("player name interjection - 05 the stocky", (Ctx c) => c.Named.LeftHanded && c.Named.Tags.Contains("stocky"), null, 4.0), new Line("player name interjection - 06 back fresh", (Ctx c) => c.League.Returning.Contains(c.Named), "back from injury", 4.0, null, null, once: false, oncePerPlayer: false, cooldown: false, mustSay: true), new Line("player name interjection - 07 fielding very well", (Ctx c) => c.League.TopFielders.Contains(c.Named), null, 3.0), new Line("player name interjection - 08 last seasons", (Ctx c) => c.League.FanFavourite == c.Named, null, 4.0), new Line("player name interjection - 09 back from a", (Ctx c) => c.League.BackFromSuspension.Contains(c.Named), "first match back after the cigarette suspension (in-game news)", 4.0, null, null, once: false, oncePerPlayer: false, cooldown: false, mustSay: true), new Line("player name interjection - 10 best lobber", (Ctx c) => c.League.BestLobber == c.Named, null, 4.0), new Line("player name interjection - 11 having a strong"), new Line("player name interjection - 12 star tirreur", (Ctx c) => c.League.TopTireurs.Contains(c.Named), null, 3.0), new Line("player name interjection - 13 back after a nasty case", (Ctx c) => c.League.ReturningSync.Contains(c.Named), "back from SyncDisk trouble", 4.0, null, null, once: false, oncePerPlayer: false, cooldown: false, mustSay: true), new Line("player name interjection - 14 fresh from", (Ctx c) => TeamOf(c).Index == 1 && c.League.News.Contains("proteanRumours"), "Proteans, while the SyncDisk rumours are in the news", 4.0) }; public static readonly Line[] OpeningEnd = new Line[11] { new Line("opening end - 01 it promises"), new Line("opening end - 02 old rivals"), new Line("opening end - 03 two great teams"), new Line("opening end - 04 what a match-up"), new Line("opening end - 05 folks this will"), new Line("opening end - 06 who will be victorius"), new Line("opening end - 07 its a foggy", (Ctx c) => c.Weather == Weather.Fog && c.AfterDark, "in-game weather; 'a foggy night'", 4.0), new Line("opening end - 08 the teams are", (Ctx c) => c.Weather == Weather.Fog, "in-game weather", 4.0), new Line("opening end - 09 quite the crowd", (Ctx c) => c.AfterDark, "'here tonight'"), new Line("opening end - 10 weve got a little snow", (Ctx c) => c.Weather == Weather.Snow && c.Daypart == Daypart.Evening, "in-game weather; 'this evening'", 6.0), new Line("opening end - 11 yes were expecting", (Ctx c) => c.AfterDark, "'fireworks tonight'") }; public static readonly Line[] Narrative = new Line[8] { new Line("narrative interjection - 01 and now a word"), new Line("narrative interjection - 01b and now a word"), new Line("narrative interjection - 02 excitement", null, null, -1.0, null, null, once: false, oncePerPlayer: false, cooldown: true), new Line("narrative interjection - 03 you can bet"), new Line("narrative interjection - 04 the weather", (Ctx c) => c.Weather == Weather.Fog && c.AfterDark, "'on the piste tonight. Foggy and getting foggier'", 3.0), new Line("narrative interjection - 04b the weather", (Ctx c) => c.Weather == Weather.Fog && c.AfterDark, null, 3.0), new Line("narrative interjection - 05 theres a dog", null, null, -1.0, null, null, once: false, oncePerPlayer: false, cooldown: true), new Line("narrative interjection - 06 were lucky", (Ctx c) => c.AfterDark, "'in the stands tonight'") }; public static readonly Line[] FinalWin = new Line[5] { new Line("final scores win - 01 and thats the game"), new Line("final scores win - 02 and there it is"), new Line("final scores win - 03 there we have it", (Ctx c) => c.Margin >= 3, "'a humiliating defeat'", 3.0), new Line("final scores win - 04 that brings the game", (Ctx c) => c.DefendingChampionLost, "'an upset for the defending champs'", 6.0), new Line("final scores win - 05 its a win", (Ctx c) => c.Margin >= 2, "'one that's decisive'", 2.0) }; public static readonly Line[] FinalDraw = new Line[4] { new Line("final scores draw - 01 there we have it bringing"), new Line("final scores draw - 02 a thrilling"), new Line("final scores draw - 03 that brings the"), new Line("final scores draw - 04 and there it is") }; private static readonly HashSet<Line[]> PreferFresh = new HashSet<Line[]> { NameInterjections, Narrative, OpeningEnd, FinalWin, FinalDraw }; public static readonly Line[] Intro = new Line[4] { new Line("intro - 01 good evening", (Ctx c) => c.Daypart == Daypart.Evening, "'Good evening, one and all'"), new Line("intro - 02 hello everyone", null, "'joining us today': fits any time"), new Line("intro - 03 good evening friends", (Ctx c) => c.Daypart == Daypart.Evening), new Line("intro - 04 good evening citizens", (Ctx c) => c.Daypart == Daypart.Evening) }; public static readonly string[] LineUp = new string[2] { "line-up intro - 01 playing in todays", "line-up intro - 01b playing in todays" }; public static readonly string[] FirstPlay = new string[7] { "first play - 01 excitement", "first play - 02 and here we go", "first play - 03 the first player", "first play - 04 and heres the first", "first play - 04b and heres the first", "first play - 05 were getting started", "first play - 06 no hanging around" }; public static readonly string[] Ads = new string[10] { "advert interjection - 01 gemsteader", "advert interjection - 01b gemsteader", "advert interjection - 02 no mam", "advert interjection - 02b no mam", "advert interjection - 03 thats right", "advert interjection - 03b thats right", "advert interjection - 04 whever youre listening", "advert interjection - 04b whever youre listening", "advert interjection - 05 thats right whether", "advert interjection - 05b thats right whether" }; public static readonly string[] FinalInnings = new string[4] { "final innings - 01 this is the final", "final innings - 01b this is the final", "final innings - 02 coming up", "final innings - 02b coming up" }; public static readonly string[] Ending = new string[3] { "ending - 01 join us again", "ending - 02 tune in", "ending - 03 well be back" }; public static readonly Line[] SignOff = new Line[3] { new Line("commentator sign off - 01 Im starch sam", (Ctx c) => c.AfterDark, null, -1.0, "sign off"), new Line("commentator sign off - 02 Im starch sam", (Ctx c) => c.AfterDark, null, -1.0, "sign off"), new Line("commentator sign off - 03 Im starch sam", (Ctx c) => c.AfterDark, null, -1.0, "sign off") }; private static readonly string[] TeamKeys = new string[5] { "bloodhounds", "proteans", "woodpeckers", "blues", "sugarbirds" }; private static bool NewStriker(Ctx c) { if (c.Step != 34 && c.Play != null) { return c.NextStriker != c.Play.Striker; } return true; } private static bool Hit(Ctx c) { if (c.Play != null && c.Play.Kind != PlayKind.Boo) { return c.Play.Kind != PlayKind.NearMiss; } return false; } private static bool Is(Ctx c, params PlayKind[] kinds) { if (c.Play != null) { return kinds.Contains(c.Play.Kind); } return false; } private static Team TeamOf(Ctx c) { if (!c.Match.Team1.Players.Contains(c.Named)) { return c.Match.Team2; } return c.Match.Team1; } public static Line Pick(Line[] pool, Ctx c, Rng rng, CommentaryState st) { List<Line> list = pool.Where((Line l) => l.When == null || l.When(c)).ToList(); if (list.Count == 0) { return null; } List<Line> list2 = list.Where((Line l) => l.MustSay).ToList(); if (list2.Count > 0) { list = list2; } List<Line> list3 = list.Where((Line l) => !Blocked(l)).ToList(); if (list3.Count == 0) { list3 = list; } List<IGrouping<string, Line>> list4 = (from l in list3 group l by l.Group).ToList(); if (list4.Count > 1 && st.LastGroup.TryGetValue((pool, c.Step), out var last)) { list4 = list4.Where((IGrouping<string, Line> g) => g.Key != last).ToList(); } if (list4.Count > 1 && st.LastAtStep.TryGetValue(c.Step, out var lastAny)) { list4 = list4.Where((IGrouping<string, Line> g) => g.Key != lastAny).ToList(); } if (list4.Count > 1 && PreferFresh.Contains(pool)) { List<IGrouping<string, Line>> list5 = list4.Where((IGrouping<string, Line> g) => !st.UsedGroups.Contains(g.Key)).ToList(); if (list5.Count > 0) { list4 = list5; } } List<Line> list6 = list4[rng.Pick(list4.Select(delegate(IGrouping<string, Line> x) { st.Uses.TryGetValue(x.Key, out var value2); return x.Max((Line l) => l.Weight) / ((1.0 + (double)value2) * (1.0 + (double)value2)); }).ToArray())].ToList(); Line line = list6[(int)(rng.NextU64() % (ulong)list6.Count)]; st.LastGroup[(pool, c.Step)] = line.Group; st.LastAtStep[c.Step] = line.Group; st.UsedGroups.Add(line.Group); st.Uses[line.Group] = ((!st.Uses.TryGetValue(line.Group, out var value)) ? 1 : (value + 1)); if (line.Family != null) { st.UsedFamilies.Add(line.Family); } if (line.OncePerPlayer && c.Play != null) { st.UsedPerPlayer.Add((line.Group, c.Play.Striker)); } return line; bool Blocked(Line l) { if ((!l.OncePerMatch || !st.UsedGroups.Contains(l.Group)) && (l.Family == null || !st.UsedFamilies.Contains(l.Family)) && (!l.OncePerPlayer || c.Play == null || !st.UsedPerPlayer.Contains((l.Group, c.Play.Striker)))) { if (l.CrossMatchCooldown) { return c.League.Cooldown.Contains(l.Group); } return false; } return true; } } private static string Any(string[] pool, Rng rng) { return pool[(uint)(rng.NextU64() % (ulong)pool.Length)]; } private static string Take(Rng rng) { if (!(rng.NextDouble() < 0.5)) { return "02"; } return "01"; } public static List<Call> Narrate(MatchResult m, LeagueFacts league, Weather weather, ulong seed, Daypart daypart = Daypart.Evening) { Rng rng = new Rng(seed ^ 0x5EEDC0FFEEL); CommentaryState st = new CommentaryState(); List<Call> calls = new List<Call>(); Ctx c = new Ctx { Match = m, League = league, Weather = weather, Daypart = daypart, Half = -1 }; c.Step = 0; SayLine(0, Pick(Intro, c, rng, st)); Say(1, "team 1 " + TeamFullKey(m.Team1)).Team = m.Team1.Index; Say(2, "team 2 " + TeamFullKey(m.Team2, second: true)).Team = m.Team2.Index; c.Step = 3; SayLine(3, Pick(OpeningEnd, c, rng, st)); Say(4, Any(LineUp, rng)); string text = null; (Team, int, int)[] array = new(Team, int, int)[2] { (m.Team1, 5, 6), (m.Team2, 11, 12) }; for (int i = 0; i < array.Length; i++) { var (team, step, num) = array[i]; Say(step, TeamIntroKey(team, rng)).Team = team.Index; Player[] array2 = (from p in team.Players where !p.Reserve orderby (!HasMustSayLine(p, c)) ? (HasRareNameLine(p, c) ? 1 : 0) : 2 descending select p).ThenBy((Player _) => rng.NextU64()).ToArray(); for (int num2 = 0; num2 < array2.Length; num2++) { Player player = array2[num2]; Say(num + 2 * num2, player.VoiceKey + " - " + Take(rng), player.Name).Player = player; if (num2 < 2 && (HasMustSayLine(player, c) || Chance(0.4))) { c.Named = player; c.Step = num + 2 * num2 + 1; Line line = Pick(NameInterjections, c, rng, st); if (line != null && line.Group != text) { SayLine(c.Step, line, player.Name).Player = player; text = line.Group; } } } } c.Named = null; Say(17, "organ match start"); Say(18, Any(FirstPlay, rng)); int num3 = 0; int num4 = 0; bool earlierBigPlay = false; for (int num5 = 0; num5 < 4; num5++) { c.Half = num5; HalfInningResult halfInningResult = m.Halves[num5]; int num6 = 0; for (int num7 = 0; num7 < halfInningResult.Plays.Count; num7++) { PlayRecord playRecord = halfInningResult.Plays[num7]; if (num7 > 0 && halfInningResult.Plays[num7 - 1].Turn != playRecord.Turn) { num6 = 0; } c.Play = playRecord; c.BoosThisSpell = num6; c.EarlierBigPlay = earlierBigPlay; c.Step = 19; SayLine(19, Pick(Plays[playRecord.Kind], c, rng, st), Describe(playRecord)).Kind = playRecord.Kind; if (playRecord.Kind == PlayKind.Boo) { num6++; } c.Step = 20; if (Chance((playRecord.Kind == PlayKind.CheerSmall) ? 0.25 : 0.5)) { SayLine(20, Pick(Interjections, c, rng, st)); } if (playRecord.Kind == PlayKind.CheerLarge || playRecord.Kind == PlayKind.Strike) { earlierBigPlay = true; } if (Chance(0.1)) { Say(21, Any(Ads, rng)); } if (playRecord.Turn < 3 && (num7 + 1 >= halfInningResult.Plays.Count || halfInningResult.Plays[num7 + 1].Turn != playRecord.Turn)) { PlayRecord playRecord2 = halfInningResult.Plays[num7 + 1]; c.Step = 23; c.NextLobber = playRecord2.Lobber; c.NextStriker = playRecord2.Striker; SayLine(23, Pick(NextPosition, c, rng, st)); } } int score = halfInningResult.Score; Say(24, (score == 0) ? ("score amount no score - " + Take(rng)) : ("score amount score - " + Take(rng))).Score = score; if (score > 0) { Say(25, score switch { 2 => "score amount thats two - " + Take(rng), 1 => "score amount thats one - " + Take(rng), _ => "score amount thats three - " + Take(rng), }).Score = score; } bool flag = num5 % 2 == 0; int num8 = (flag ? num3 : num4); int num9 = (flag ? num4 : num3); if (flag) { num3 += score; } else { num4 += score; } if (num5 == 3) { break; } if (score > 0 && num8 <= num9 && num8 + score > num9) { Call call = Say(27, "lead " + LeadKey(flag ? m.Team1 : m.Team2) + " - " + ((rng.NextDouble() < 0.5) ? "01" : "01b")); call.Team = (flag ? m.Team1 : m.Team2).Index; call.Side = (flag ? 1 : 2); } c.Play = null; c.Step = 31; if (Chance(0.85)) { SayLine(31, Pick(Narrative, c, rng, st)); } if (num5 == 2) { Say(32, "organ final innings"); Say(33, Any(FinalInnings, rng)); } HalfInningResult halfInningResult2 = m.Halves[num5 + 1]; c.Step = 34; c.NextLobber = halfInningResult2.Plays[0].Lobber; c.NextStriker = halfInningResult2.Plays[0].Striker; SayLine(34, Pick(NextPosition, c, rng, st)); } Say(35, "organ match end"); c.Step = 38; c.Margin = Math.Abs(m.Score1 - m.Score2); Team team2 = ((m.Score1 > m.Score2) ? m.Team1 : ((m.Score2 > m.Score1) ? m.Team2 : null)); c.DefendingChampionLost = team2 != null && league.DefendingChampion >= 0 && league.DefendingChampion != team2.Index && (m.Team1.Index == league.DefendingChampion || m.Team2.Index == league.DefendingChampion); SayLine(38, Pick((team2 == null) ? FinalDraw : FinalWin, c, rng, st)); if (team2 != null) { Call call2 = Say(39, "winning team signoff " + TeamKeys[team2.Index] + " - " + Take(rng)); call2.Team = team2.Index; call2.Side = ((team2 == m.Team1) ? 1 : 2); } Say(40, Any(Ending, rng)); c.Step = 41; SayLine(41, Pick(SignOff, c, rng, st)); return calls; bool Chance(double p) { return rng.NextDouble() < p; } Call Say(int step2, string id, string note = null, string group = null) { if (id == null) { return null; } Call call3 = new Call { Step = step2, LineId = id, Group = (group ?? Line.DefaultGroup(id)), Note = note }; calls.Add(call3); return call3; } Call SayLine(int step2, Line l, string note = null) { if (l != null) { return Say(step2, l.Id, note, l.Group); } return null; } } public static bool HasMustSayLine(Player p, Ctx c) { Player named = c.Named; c.Named = p; bool result = NameInterjections.Any((Line l) => l.MustSay && l.When(c)); c.Named = named; return result; } private static bool HasRareNameLine(Player p, Ctx c) { Player named = c.Named; c.Named = p; bool result = NameInterjections.Any((Line l) => l.Weight >= 3.0 && l.When != null && l.When(c)); c.Named = named; return result; } public static string Describe(PlayRecord p) { string value = $"{p.Lobber.Position} lobs to {p.Striker.Name}"; string value2 = p.Kind switch { PlayKind.CheerSmall => "single", PlayKind.CheerMedium => "double", PlayKind.CheerLarge => "triple", PlayKind.Strike => "home run along the ground", PlayKind.Boo => "dead lob", _ => "OUT", }; string value3 = ((p.Scored.Count > 0) ? ("; scores: " + string.Join(", ", p.Scored.Select((Player x) => x.Name))) : ""); string value4 = ((p.Turn == 3) ? "closing lob" : $"spell {p.Turn + 1}, lob {p.LobInTurn + 1}"); return $"{value4}: {value}: {value2}; runners on {p.RunnersBefore} before{value3}"; } private static string TeamFullKey(Team t, bool second = false) { return t.Index switch { 0 => "candor city bloodhounds", 1 => "el gen proteans", 2 => "kaizen woodpeckers", 3 => "kensington blues", _ => second ? "stark kola sugarbirds" : "starch kola sugarbirds", }; } private static string TeamIntroKey(Team t, Rng rng) { if (t.Index != 4) { return "team intro " + TeamKeys[t.Index] + " - " + Take(rng); } return "team intro - sugarbirds - " + Take(rng); } private static string LeadKey(Team t) { if (t.Index != 3) { return TeamKeys[t.Index]; } return "the blues"; } } public enum PlayKind { CheerSmall, CheerMedium, CheerLarge, Boo, NearMiss, Strike } public enum Position { Rouleur, Tireur, Fielder } public sealed class Player { public string Id; public string Name; public string Surname; public bool Reserve; public string VoiceKey; public int TeamIndex = -1; public int SeasonsPlayed; public Position Position; public int Lob = 50; public int Bat = 50; public int Field = 50; public bool LeftHanded; public HashSet<string> Tags = new HashSet<string>(); public override string ToString() { return Name; } } public sealed class Team { public int Index = -1; public string Name; public Player[] Players = new Player[3]; public double AverageField => (double)(Players[0].Field + Players[1].Field + Players[2].Field) / 3.0; public Player Get(Position p) { Player[] players = Players; foreach (Player player in players) { if (player.Position == p) { return player; } } throw new InvalidOperationException($"{Name} has no {p}"); } public static Team Average(string name, int bonus = 0) { Team team = new Team { Name = name }; Position[] array = new Position[3] { Position.Rouleur, Position.Tireur, Position.Fielder }; for (int i = 0; i < 3; i++) { team.Players[i] = new Player { Name = $"{name} {array[i]}", Position = array[i], Lob = 50 + bonus, Bat = 50 + bonus, Field = 50 + bonus }; } return team; } } public enum BankMode { Sum, Best, SumToLastPlate } public sealed class Rules { public string Name = "triangle"; public int Bases = 2; public bool StrikeIsHomeRun; public int StrikeBankLegs; public bool RunOnContact; public bool OutRetires; public BankMode Banking; public bool StrikeLocksBank = true; public Position[] BattingOrder = new Position[3] { Position.Fielder, Position.Rouleur, Position.Tireur }; public Position[] LobbingOrder = new Position[3] { Position.Rouleur, Position.Tireur, Position.Fielder }; public Position Closer; public const int Turns = 3; public const int LobsPerTurn = 3; public int HomeLegs => Bases + 1; public static Rules Triangle() { return new Rules { Name = "triangle", Bases = 2, StrikeIsHomeRun = false, StrikeBankLegs = 0 }; } public static Rules RunOnContactDiamond() { return new Rules { Name = "diamond, run on contact", Bases = 3, StrikeIsHomeRun = true, RunOnContact = true }; } public static Rules OneLifeDiamond() { return new Rules { Name = "diamond, run on contact, one life", Bases = 3, StrikeIsHomeRun = true, RunOnContact = true, OutRetires = true }; } public static Rules RunOnContactTriangle() { return new Rules { Name = "triangle, run on contact", Bases = 2, StrikeIsHomeRun = true, RunOnContact = true }; } public static Rules Diamond() { return new Rules { Name = "diamond", Bases = 3, StrikeIsHomeRun = true }; } } public sealed class OutcomeModel { public double[] Base = new double[6] { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; public double[] DuelSlope = new double[6] { 0.1, 0.3, 0.5, -0.35, -0.25, 0.6 }; public double[] FieldSlope = new double[6] { 0.0, 0.0, -0.1, 0.0, 0.35, -0.1 }; public double[] Weights(Player lobber, Player striker, Team defence) { double num = (double)(striker.Bat - lobber.Lob) / 25.0; double num2 = (defence.AverageField - 50.0) / 25.0; double[] array = new double[6]; for (int i = 0; i < 6; i++) { array[i] = Base[i] * Math.Exp(DuelSlope[i] * num + FieldSlope[i] * num2); } return array; } public static OutcomeModel Uniform() { return new OutcomeModel(); } public static OutcomeModel OneLifeTuned() { return WithBase(0.276, 0.09, 0.072, 0.175, 0.318, 0.069); } public static OutcomeModel WithBase(params double[] baseWeights) { return new OutcomeModel { Base = (double[])baseWeights.Clone() }; } } public sealed class Rng { private ulong _s; public ulong State { get { return _s; } set { _s = value; } } public Rng(ulong seed) { _s = seed; } public static ulong Mix(ulong a, ulong b) { Rng rng = new Rng(a ^ (ulong)((long)b * -7046029254386353131L)); rng.NextU64(); return rng.NextU64(); } public ulong NextU64() { ulong num = (_s += 11400714819323198485uL); long num2 = (long)(num ^ (num >> 30)) * -4658895280553007687L; long num3 = (num2 ^ (num2 >>> 27)) * -7723592293110705685L; return (ulong)(num3 ^ (num3 >>> 31)); } public double NextDouble() { return (double)(NextU64() >> 11) * 1.1102230246251565E-16; } public int Pick(double[] weights) { double num = 0.0; foreach (double num2 in weights) { num += num2; } double num3 = NextDouble() * num; for (int j = 0; j < weights.Length; j++) { num3 -= weights[j]; if (num3 < 0.0) { return j; } } return weights.Length - 1; } } public static class Roster { public static readonly string[] ShortNames = new string[5] { "Bloodhounds", "Proteans", "Woodpeckers", "Blues", "Sugarbirds" }; public static readonly string[] Codes = new string[5] { "BLD", "PRO", "WPK", "BLU", "SGB" }; public static readonly string[] Keys = new string[5] { "bloodhounds", "proteans", "woodpeckers", "blues", "sugarbirds" }; public static readonly string[] FullNames = new string[5] { "Candor City Bloodhounds", "El-Gen Proteans", "Kaizen Woodpeckers", "Kensington Blues", "Starch Kola Sugarbirds" }; public static readonly string[] Sponsors = new string[5] { "Candor", "Elliot Genetics", "Kaizen-6", "Kensington Indigo", "Starch Kola" }; private static readonly string[][] VoiceKeys = new string[5][] { new string[3] { "team players bloodhounds bill nosseross", "team players bloodhounds ohanna derrida", "team players bloodhounds tisha bannerjee" }, new string[3] { "team players proteans jean-luc trottoir", "team players proteans lyn tae-yeon", "team players proteans ray vargas" }, new string[3] { "team players woodpeckers sally al-hassem", "team players woodpeckers makuku watts", "team players woodpeckers quincy large" }, new string[3] { "team players blues enola jones", "team players blues micky esposito", "team players blues kristo mistry" }, new string[3] { "team players sugarbirds - 02 virginie de loof", "team players sugarbirds - 01 remmy caution", "team players sugarbirds - 03 sharky tannous" } }; public static Team[] Build() { return new Team[5] { T(0, "Bloodhounds", P("\"Bad\" Bill Nosseross", Position.Rouleur, 64, 48, 44, left: false, "fastBoule brawler"), P("Ohanna Derrida", Position.Tireur, 44, 62, 48, left: false, "strong"), P("Tisha Bannerjee", Position.Fielder, 46, 50, 54)), T(1, "Proteans", P("Jean-Luc \"Trotty\" Trottoir", Position.Rouleur, 56, 46, 58, left: false, "lean"), P("Lynn \"the Spin\" Tae-Yeon", Position.Tireur, 50, 56, 48, left: true), P("Ray \"the Play\" Vargas", Position.Fielder, 46, 52, 56, left: false, "veteran")), T(2, "Woodpeckers", P("Sally al-Hassem", Position.Rouleur, 62, 46, 46, left: false, "curveBall"), P("Makuku Watts", Position.Tireur, 46, 55, 50), P("Quincy Large", Position.Fielder, 44, 54, 50, left: true, "stocky")), T(3, "Blues", P("Eniola \"Roller\" Jones", Position.Rouleur, 58, 46, 50), P("Mickey Esposito", Position.Tireur, 44, 57, 48), P("Kristo Mistry", Position.Fielder, 46, 48, 57, left: true)), T(4, "Sugarbirds", P("Virginie \"Loop\" De Loof", Position.Rouleur, 60, 48, 48), P("Remmy Caution", Position.Tireur, 46, 60, 48, left: false, "suspended fanFavourite veteran"), P("Sharky Tannous", Position.Fielder, 46, 50, 58)) }; } private static Team T(int index, string name, params Player[] players) { foreach (Player player in players) { player.TeamIndex = index; player.Id = Keys[index] + "-" + player.Position.ToString().ToLowerInvariant(); player.VoiceKey = VoiceKeys[index][(int)player.Position]; } return new Team { Index = index, Name = name, Players = players }; } private static Player P(string name, Position pos, int lob, int bat, int field, bool left = false, string tags = "") { Player player = new Player { Name = name, Position = pos, Lob = lob, Bat = bat, Field = field, LeftHanded = left }; string[] array = name.Split(' '); player.Surname = (name.StartsWith("Sally") ? "al-Hassem" : (name.StartsWith("Virginie") ? "De Loof" : array[^1])); string[] array2 = tags.Split(' '); foreach (string text in array2) { if (text.Length > 0) { player.Tags.Add(text); } } return player; } } public sealed class PlayRecord { public int Half; public int Turn; public int LobInTurn; public Player Lobber; public Player Striker; public PlayKind Kind; public int Legs; public int BankAfter; public bool BankLocked; public bool StrikerOut; public bool GhostRunner; public int RunnersBefore; public int[] RunnersAfter; public List<Player> Scored = new List<Player>(); } public sealed class HalfInningResult { public Team Batting; public Team Fielding; public List<PlayRecord> Plays = new List<PlayRecord>(); public int Score; } public sealed class MatchResult { public Team Team1; public Team Team2; public HalfInningResult[] Halves = new HalfInningResult[4]; public int Score1; public int Score2; } public static class Simulator { public static MatchResult PlayMatch(Team team1, Team team2, Rules rules, OutcomeModel model, ulong seed) { Rng rng = new Rng(seed); MatchResult matchResult = new MatchResult { Team1 = team1, Team2 = team2 }; for (int i = 0; i < 4; i++) { bool flag = i % 2 == 0; HalfInningResult halfInningResult = PlayHalf(flag ? team1 : team2, flag ? team2 : team1, rules, model, rng, i); matchResult.Halves[i] = halfInningResult; if (flag) { matchResult.Score1 += halfInningResult.Score; } else { matchResult.Score2 += halfInningResult.Score; } } return matchResult; } private static HalfInningResult PlayHalfRunOnContact(Team batting, Team fielding, Rules rules, OutcomeModel model, Rng rng, int halfIndex) { HalfInningResult result = new HalfInningResult { Batting = batting, Fielding = fielding }; Player[] batters = new Player[3]; for (int i = 0; i < 3; i++) { batters[i] = batting.Get(rules.BattingOrder[i]); } int[] onBase = new int[3]; bool[] home = new bool[3]; bool[] retired = new bool[3]; int slot = 0; bool ghost = false; for (int j = 0; j < 3; j++) { Player lobber = fielding.Get(rules.LobbingOrder[j]); for (int k = 0; k < 3 && !Lob(j, k, lobber); k++) { } } Lob(3, 0, fielding.Get(rules.Closer)); for (int l = 0; l < 3; l++) { if (home[l]) { result.Score++; } } return result; bool Lob(int turn, int lobInTurn, Player lobber2) { Player player = batters[slot]; PlayKind playKind = (PlayKind)rng.Pick(model.Weights(lobber2, player, fielding)); PlayRecord playRecord = new PlayRecord { Half = halfIndex, Turn = turn, LobInTurn = lobInTurn, Lobber = lobber2, Striker = player, Kind = playKind, GhostRunner = ghost, RunnersBefore = Count(onBase) }; int num = (playRecord.Legs = playKind switch { PlayKind.Strike => rules.HomeLegs, PlayKind.CheerLarge => 3, PlayKind.CheerMedium => 2, PlayKind.CheerSmall => 1, _ => 0, }); if (num > 0) { for (int m = 0; m < 3; m++) { if (onBase[m] != 0) { onBase[m] += num; if (onBase[m] >= rules.HomeLegs) { onBase[m] = 0; if (!home[m]) { home[m] = true; playRecord.Scored.Add(batters[m]); } } } } if (!home[slot] && !retired[slot] && onBase[slot] == 0) { if (num >= rules.HomeLegs) { home[slot] = true; playRecord.Scored.Add(player); } else { onBase[slot] = num; } } NextStriker(); } else if (playKind == PlayKind.NearMiss) { playRecord.StrikerOut = true; if (rules.OutRetires) { retired[slot] = true; } NextStriker(); } playRecord.RunnersAfter = (int[])onBase.Clone(); result.Plays.Add(playRecord); return playRecord.StrikerOut; } void NextStriker() { ghost = false; for (int m = 1; m <= 3; m++) { int num = (slot + m) % 3; if (onBase[num] == 0) { slot = num; return; } } slot = (slot + 1) % 3; ghost = true; } } private static int Count(int[] onBase) { int num = 0; for (int i = 0; i < onBase.Length; i++) { if (onBase[i] > 0) { num++; } } return num; } public static HalfInningResult PlayHalf(Team batting, Team fielding, Rules rules, OutcomeModel model, Rng rng, int halfIndex = 0) { if (rules.RunOnContact) { return PlayHalfRunOnContact(batting, fielding, rules, model, rng, halfIndex); } HalfInningResult halfInningResult = new HalfInningResult { Batting = batting, Fielding = fielding }; Player[] batters = new Player[3]; for (int i = 0; i < 3; i++) { batters[i] = batting.Get(rules.BattingOrder[i]); } int[] onBase = new int[3]; bool[] home = new bool[3]; for (int j = 0; j < 3; j++) { Player player = batters[j]; Player lobber = fielding.Get(rules.LobbingOrder[j]); int num = 0; bool flag = false; for (int num2 = 0; num2 < 3; num2++) { PlayKind playKind = (PlayKind)rng.Pick(model.Weights(lobber, player, fielding)); PlayRecord playRecord = new PlayRecord { Half = halfIndex, Turn = j, LobInTurn = num2, Lobber = lobber, Striker = player, Kind = playKind, RunnersBefore = Count(onBase) }; switch (playKind) { case PlayKind.CheerSmall: case PlayKind.CheerMedium: case PlayKind.CheerLarge: playRecord.Legs = playKind switch { PlayKind.CheerMedium => 2, PlayKind.CheerSmall => 1, _ => 3, }; Advance(playRecord.Legs, playRecord); num = ((rules.Banking == BankMode.Best) ? Math.Max(num, playRecord.Legs) : ((rules.Banking == BankMode.SumToLastPlate) ? Math.Max(num, Math.Min(num + playRecord.Legs, rules.Bases)) : Math.Min(num + playRecord.Legs, rules.HomeLegs))); break; case PlayKind.Strike: playRecord.Legs = rules.HomeLegs; Advance(rules.HomeLegs, playRecord); num = (rules.StrikeIsHomeRun ? rules.HomeLegs : Math.Min(num + rules.StrikeBankLegs, rules.HomeLegs)); if (rules.StrikeLocksBank) { flag = true; } break; case PlayKind.NearMiss: playRecord.StrikerOut = true; if (!flag) { num = 0; } break; } int num3; if (!playRecord.StrikerOut) { num3 = ((num2 == 2) ? 1 : 0); if (num3 == 0) { goto IL_02ac; } } else { num3 = 1; } if (num >= rules.HomeLegs) { home[j] = true; playRecord.Scored.Add(player); } else if (num > 0) { onBase[j] = num; } goto IL_02ac; IL_02ac: playRecord.BankAfter = num; playRecord.BankLocked = flag; playRecord.RunnersAfter = (int[])onBase.Clone(); halfInningResult.Plays.Add(playRecord); if (num3 != 0) { break; } } } int num4 = -1; for (int k = 0; k < 3; k++) { if (onBase[k] == 0) { num4 = k; break; } } bool flag2 = num4 < 0; if (flag2) { num4 = 0; } Player lobber2 = fielding.Get(rules.Closer); Player striker = batters[num4]; PlayKind playKind2 = (PlayKind)rng.Pick(model.Weights(lobber2, striker, fielding)); PlayRecord playRecord2 = new PlayRecord { Half = halfIndex, Turn = 3, LobInTurn = 0, Lobber = lobber2, Striker = striker, Kind = playKind2, GhostRunner = flag2, RunnersBefore = Count(onBase) }; switch (playKind2) { case PlayKind.CheerSmall: playRecord2.Legs = 1; break; case PlayKind.CheerMedium: playRecord2.Legs = 2; break; case PlayKind.CheerLarge: playRecord2.Legs = 3; break; case PlayKind.Strike: playRecord2.Legs = rules.HomeLegs; break; case PlayKind.NearMiss: playRecord2.StrikerOut = true; break; } if (playRecord2.Legs > 0) { Advance(playRecord2.Legs, playRecord2); } playRecord2.RunnersAfter = (int[])onBase.Clone(); halfInningResult.Plays.Add(playRecord2); for (int l = 0; l < 3; l++) { if (home[l]) { halfInningResult.Score++; } } return halfInningResult; void Advance(int legs, PlayRecord rec) { for (int m = 0; m < 3; m++) { if (onBase[m] != 0) { onBase[m] += legs; if (onBase[m] >= rules.HomeLegs) { onBase[m] = 0; home[m] = true; rec.Scored.Add(batters[m]); } } } } } } } namespace BasBoule.Sim.League { public enum BetKind { Moneyline, Spread, Total } public enum LegResult { Open, Won, Lost, Push } public enum BetState { Open, Won, Lost, Void } public sealed class BetLeg { public int FixtureId; public BetKind Kind; public int Team = -1; public bool Over; public double Line; public double Odds; public LegResult Result; public bool Boosted; public int Team1 = -1; public int Team2 = -1; public double Combo; public double ComboDraw; public bool Same(BetLeg o) { if (o != null && FixtureId == o.FixtureId && Kind == o.Kind && Team == o.Team && Over == o.Over) { return Math.Abs(Line - o.Line) < 0.01; } return false; } } public sealed class Bet { public int Id; public int Season; public int Stake; public List<BetLeg> Legs = new List<BetLeg>(); public BetState State; public int Payout; public bool Paid; public double PlacedAt; public double Odds { get { double num = 1.0; foreach (IGrouping<int, BetLeg> item in from l in Legs group l by l.FixtureId) { List<BetLeg> list = item.ToList(); bool flag = list.Any((BetLeg l) => l.Result == LegResult.Push); if (list.Count == 1) { num *= (flag ? 1.0 : list[0].Odds); } else if (!flag) { num *= list[0].Combo; } else if (list.Any((BetLeg l) => l.Result != LegResult.Push)) { num *= list[0].ComboDraw; } } return num; } } } public sealed class BetBook { public int NextId = 1; public List<Bet> Bets = new List<Bet>(); public int Placed; public int Won; public int Lost; public int Void; public long Staked; public long Returned; } public sealed class Market { public Fixture Fixture; public BetLeg Money1; public BetLeg Money2; public BetLeg Spread1; public BetLeg Spread2; public BetLeg Over; public BetLeg Under; public double MeanTotal; public double MeanMargin; public double Win1; public double Draw; public double Win2; public int[] Margins; public int[] Totals; public IEnumerable<BetLeg> All { get { yield return Money1; yield return Money2; yield return Spread1; yield return Spread2; yield return Over; yield return Under; } } } public static class Odds { public static int ToAmerican(double dec) { if (dec >= 2.0) { return (int)Math.Ceiling((dec - 1.0) * 100.0 / 5.0 - 1E-09) * 5; } int num = (int)Math.Floor(100.0 / (dec - 1.0) / 5.0 + 1E-09) * 5; if (num > 100) { return -num; } return 100; } public static double FromAmerican(int am) { if (am <= 0) { return 1.0 + 100.0 / (double)(-am); } return 1.0 + (double)am / 100.0; } public static string Format(double dec) { int num = ToAmerican(dec); if (num <= 0) { return num.ToString(); } return "+" + num; } public static double Price(double p, double edge) { p = Math.Min(0.97, Math.Max(0.02, p)); double val = 1.0 / p * (1.0 + edge); val = Math.Min(51.0, Math.Max(1.02, val)); return FromAmerican(ToAmerican(val)); } public static LegResult Grade(BetLeg leg, int team1, int margin, int total) { switch (leg.Kind) { case BetKind.Moneyline: if (margin != 0) { if (leg.Team == team1 != margin > 0) { return LegResult.Lost; } return LegResult.Won; } return LegResult.Push; case BetKind.Spread: { double num2 = (double)((leg.Team == team1) ? margin : (-margin)) + leg.Line; if (!(num2 > 0.0)) { if (!(num2 < 0.0)) { return LegResult.Push; } return LegResult.Lost; } return LegResult.Won; } default: { double num = (double)total - leg.Line; if (num != 0.0) { if (num > 0.0 != leg.Over) { return LegResult.Lost; } return LegResult.Won; } return LegResult.Push; } } } public static LegResult Settle(BetLeg leg, int team1, int score1, int score2) { switch (leg.Kind) { case BetKind.Moneyline: { if (score1 == score2) { return LegResult.Push; } bool flag = score1 > score2; if (leg.Team == team1 != flag) { return LegResult.Lost; } return LegResult.Won; } case BetKind.Spread: { double num2 = (double)((leg.Team == team1) ? (score1 - score2) : (score2 - score1)) + leg.Line; if (!(num2 > 0.0)) { if (!(num2 < 0.0)) { return LegResult.Push; } return LegResult.Lost; } return LegResult.Won; } default: { double num = (double)(score1 + score2) - leg.Line; if (num == 0.0) { return LegResult.Push; } if (num > 0.0 != leg.Over) { return LegResult.Lost; } return LegResult.Won; } } } } public sealed class LeagueEngine { public const int MaxLegs = 4; public const int MarketSims = 4000; public const int KeepSettledBets = 40; public const int MinComboHits = 60; private readonly Dictionary<int, (string key, Market market)> _markets = new Dictionary<int, (string, Market)>(); public double BoostSize; public const int BoostOneIn = 3; private static readonly string[] Products = new string[6] { "Starch Kola", "Gemsteader", "SynthMilk", "Krueger Mustard", "Starch Ketchup", "Starch Candy" }; private static readonly List<EventTemplate> Templates = new List<EventTemplate> { new EventTemplate { Id = "inj-hamstring", MaxPerSeason = 3, Weight = 3.0, Effect = EventEffect.Injury, Matches = new int[5] { 1, 1, 2, 2, 3 }, Headline = "{SURNAME} PULLS UP LAME", Body = "{Name} limped off the piste clutching a hamstring after chasing down a loose boule. The {team} expect {n} on the sidelines." }, new EventTemplate { Id = "inj-wet-piste", Weight = 2.0, Effect = EventEffect.Injury, Matches = new int[2] { 1, 2 }, Headline = "SLICK PISTE CLAIMS {SURNAME}", Body = "Rainwater pooling on the Gemsteader piste has claimed another victim: {Name} turned an ankle on the way to the plates and will miss {n}. Groundskeepers blame the drains. The drains have not commented." }, new EventTemplate { Id = "inj-training", MaxPerSeason = 2, Weight = 2.0, Effect = EventEffect.Injury, Matches = new int[2] { 1, 2 }, Headline = "TRAINING MISHAP FOR THE {TEAM}", Body = "{Name} took a stray boule to the knee during a {team} training session. Club medics expect {n} out and no lasting damage." }, new EventTemplate { Id = "inj-concession", Weight = 1.0, Effect = EventEffect.Injury, Matches = new int[1] { 1 }, Headline = "CONCESSION STAND CLAIMS {SURNAME}", Body = "{Name} will miss {n} after a synth-pork sandwich from the Boulodrome concession stand. The vendor maintains the batch was 'within acceptable tolerances'." }, new EventTemplate { Id = "inj-smog", Weight = 0.7, Noir = true, Effect = EventEffect.Injury, Matches = new int[2] { 1, 2 }, Headline = "SMOG LUNG SIDELINES {SURNAME}", Body = "{Name} has been ordered to rest after training through a 'Hazardous' air-quality day. League officials declined to move practice indoors, citing the cost of air." }, new EventTemplate { Id = "inj-mugging", Weight = 0.7, Noir = true, Effect = EventEffect.Injury, Matches = new int[2] { 1, 2 }, Headline = "{SURNAME} ROUGHED UP NEAR THE BOULODROME", Body = "{Name} was found nursing bruised ribs in a service alley behind the Gemsteader Boulodrome. Enforcers took a statement, noted the missing wallet and closed the file before the ink was dry. Expected out: {n}." }, new EventTemplate { Id = "sync-drift", Weight = 1.2, Noir = true, Effect = EventEffect.SyncInjury, Matches = new int[2] { 1, 2 }, Cooldown = 6, Headline = "SYNC DISPLACEMENT FOR {SURNAME}", Body = "{Name} was admitted to a clinic in {city} after a reflex SyncDisk drifted out of alignment overnight. The {team} physician calls it a routine recalibration. The clinic's billing department calls it something else. Out: {n}." }, new EventTemplate { Id = "sync-bootleg", Weight = 0.7, Noir = true, Effect = EventEffect.SyncInjury, Matches = new int[1] { 2 }, Cooldown = 10, Headline = "{SURNAME}'S BACK-ALLEY UPGRADE GOES WRONG", Body = "{Name} is recovering after an unlicensed SyncDisk, installed in a back room above a pawnbroker's, rejected its new host. The {team} deny all knowledge. Out: {n}." }, new EventTemplate { Id = "susp-cigarette", Weight = 2.5, Effect = EventEffect.CigaretteSuspension, Matches = new int[1] { 1 }, Cooldown = 8, PlayerOk = (LeagueEngine _, Player p) => p.Tags.Contains("suspended"), Headline = "CAUTION TO THE WIND", Body = "{Name} has been handed a one-game suspension after being caught red-handed with a Yellow Beaks behind the Sugarbirds' dugout. A Starch Kola spokesperson reminded fans that nothing refreshes like an ice-cold Starch." }, new EventTemplate { Id = "susp-brawl", Weight = 1.0, Effect = EventEffect.Suspension, Matches = new int[2] { 1, 2 }, Cooldown = 10, PlayerOk = (LeagueEngine _, Player p) => p.Tags.Contains("brawler"), Headline = "BAD BILL, WORSE NIGHT", Body = "{Name} has been suspended for {n} after a bar brawl in {city} left five people injured and a jukebox beyond repair. One witness said Nosseross 'went for me with a bottle of ketchup'." }, new EventTemplate { Id = "susp-sponsor", Weight = 0.8, Noir = true, Effect = EventEffect.Suspension, Matches = new int[1] { 1 }, Cooldown = 8, Headline = "{SURNAME} BENCHED FOR WRONG LOGO", Body = "{Name} has been suspended for {n} after appearing in an advertisement for a rival of {sponsor}. League bylaws are clear: a player's likeness belongs to the sponsor, along with the rest of the player." }, new EventTemplate { Id = "susp-scan", Weight = 0.6, Noir = true, Effect = EventEffect.Suspension, Matches = new int[1] { 2 }, Cooldown = 10, Headline = "{SURNAME} FAILS SYNCDISK SCREENING", Body = "A routine League scan has found an unregistered SyncDisk in {Name}. The player's agent insists the implant is 'purely cosmetic'. Suspended: {n}." }, new EventTemplate { Id = "form-breakthrough", MaxPerSeason = 2, Weight = 1.5, Effect = EventEffect.FormUp, Headline = "{SURNAME} FINDS SOMETHING NEW", Body = "{Name} has been staying late at the Boulodrome working on {skill}, and the {team} coaches like what they see." }, new EventTemplate { Id = "form-fans", Weight = 1.0, Effect = EventEffect.FormUp, Headline = "{SURNAME} SIGNS CARDS IN THE RAIN", Body = "{Name} spent two hours outside the Boulodrome signing Bas-Boule cards for young fans in the rain, long after the floodlights went off. Team-mates say the mood in the {team} camp has never been better." }, new EventTemplate { Id = "form-upgrade", Weight = 1.0, Noir = true, Effect = EventEffect.BigFormUp, Cooldown = 8, PlayerOk = (LeagueEngine _, Player p) => p.TeamIndex == 1, NewsKey = "proteanRumours", NewsRounds = 2, Headline = "{SURNAME} UNVEILS 'LEAGUE-APPROVED' UPGRADE", Body = "{Name} has returned from an Elliot Genetics clinic with a reflex SyncDisk the League insists is fully approved. Opponents have asked to see the paperwork." }, new EventTemplate { Id = "form-slump", Weight = 0.7, Noir = true, Effect = EventEffect.FormDown, Cooldown = 8, Headline = "WHAT'S WRONG WITH {SURNAME}?", Body = "{Name} hasn't looked the same since a night out down at the docks in {city} that nobody at the {team} will talk about. The coaches call it 'a confidence thing'." }, new EventTemplate { Id = "form-slump-plain", MaxPerSeason = 2, Weight = 1.0, Effect = EventEffect.FormDown, Headline = "{SURNAME} IN A SLUMP", Body = "{Name} is going through a rough patch, and the {team} coaches have been working on {skill} in extra sessions. 'It'll come back,' said a team-mate. 'It always does.'" }, new EventTemplate { Id = "form-contract", Weight = 0.7, Effect = EventEffect.FormDown, Cooldown = 8, Headline = "{SURNAME} SKIPS TRAINING OVER CONTRACT", Body = "{Name} failed to report for training as contract talks with {sponsor} stalled. {sponsor} describes the offer as 'generous by any standard currently enforced'." }, new EventTemplate { Id = "form-face", Weight = 0.8, Effect = EventEffect.FormUp, Cooldown = 6, Headline = "{SURNAME} IS THE NEW FACE OF {PRODUCT}", Body = "{Name} has been named the new face of {product}. The adverts go up across the city this week; the photographer asked {surname} to smile more." }, new EventTemplate { Id = "news-protean-rumours", TeamEvent = true, Weight = 1.0, Effect = EventEffect.News, Cooldown = 10, TeamOk = (LeagueEngine _, int t) => t == 1, NewsKey = "proteanRumours", NewsRounds = 3, Headline = "PROTEANS DENY RUMOURS (AGAIN)", Body = "A spokesperson for the El-Gen Proteans has once again denied that players are receiving illegal SyncDisk upgrades. 'All of our treatments are League approved,' the spokesperson said, before ending the press conference." }, new EventTemplate { Id = "news-burglary", Weight = 0.6, Noir = true, Effect = EventEffect.None, Cooldown = 10, Headline = "{SURNAME} BURGLED; THIEF TAKES ONE THING", Body = "{Name}'s apartment was broken into overnight. The only item missing: a signed Bas-Boule card of {Name}. Enforcers believe the culprit 'may be a fan'." }, new EventTemplate { Id = "news-umpire", Weight = 0.8, Effect = EventEffect.None, Cooldown = 10, PlayerOk = (LeagueEngine _, Player p) => p.Tags.Contains("fastBoule"), Headline = "ANOTHER UMPIRE, ANOTHER ANKLE", Body = "An umpire was stretchered off at the Gemsteader Boulodrome after a fast boule from {Name} found an ankle on the way through. The League says it is reviewing umpires' footwear." }, new EventTemplate { Id = "news-body", TeamEvent = true, Weight = 0.3, Noir = true, Effect = EventEffect.None, Cooldown = 15, Headline = "BODY FOUND NEAR BOULODROME", Body = "A {team} season-ticket holder was found dead in the Boulodrome parking structure in the early hours. Enforcers have ruled out any connection to the night's result. The League asks fans to celebrate responsibly." }, new EventTemplate { Id = "news-illegal-book", TeamEvent = true, Weight = 0.5, Noir = true, Effect = EventEffect.None, Cooldown = 12, Headline = "ENFORCERS RAID BAS-BOULE BOOK", Body = "Enforcers have shut down an illegal Bas-Boule book run out of a laundrette in {city}. The seized ledger shows a suspicious number of bets on the {teamfull} to lose. The club calls the timing 'a coincidence'." }, new EventTemplate { Id = "news-memo", TeamEvent = true, Weight = 0.9, Noir = true, Effect = EventEffect.None, Cooldown = 8, TeamOk = (LeagueEngine e, int t) => e.State.Fixtures.Count((Fixture f) => f.Played && f.Stage == Stage.Regular) >= 6 && e.Standings()[4].Team == t, Headline = "LEAKED MEMO: {SPONSOR} UNIMPRESSED", Body = "A leaked {sponsor} memo describes the {teamfull} as 'an under-performing marketing asset' and asks managers to 'explore synergies'. The club insists morale is high." }, new EventTemplate { Id = "news-seawall", TeamEvent = true, Weight = 0.4, Noir = true, Effect = EventEffect.None, Cooldown = 12, Headline = "SEA WALL WORKS CLOSE {TEAM} TRAINING GROUND", Body = "Emergency sea wall repairs have closed the {teamfull} training ground for the week. The water was up another few millimetres this month; the team will train in a multi-storey car park." }, new EventTemplate { Id = "news-floodlights", TeamEvent = true, Weight = 0.6, Effect = EventEffect.None, Cooldown = 12, Headline = "BOULODROME GETS NEW FLOODLIGHTS", Body = "The Gemsteader Boulodrome has switched on its new floodlights, paid for by Gemsteader and, according to the small print, by a modest surcharge on every bottle. The {team} were the first to train under them." } }; private static readonly string[] ColourLines = new string[5] { "Attendance was down after an evening smog warning.", "The floodlights flickered twice in the fourth half-inning. The Boulodrome blames the grid; the grid blames the Boulodrome.", "Enforcers cleared a crowd of ticketless fans from the turnstiles before the first lob.", "A Starch Kola blimp circled the Boulodrome throughout, as it does every night, whether anyone is playing or not.", "Fog rolled in from the harbour during the third half-inning, and the far plate was briefly a matter of faith." }; private Rng _rng; private Dictionary<string, Player> _byId; public static readonly Rules MatchRules = Rules.OneLifeDiamond(); public static readonly OutcomeModel MatchModel = OutcomeModel.OneLifeTuned(); private static readonly JsonSerializerOptions Json = new JsonSerializerOptions { IncludeFields = true, WriteIndented = false }; public const double StockWin = 0.12; public const double StockStreak = 0.1; public const double StockFade = 0.93; public const double StockTitle = 1.0; public const double StockRunnerUp = 0.4; public const double StockLast = -0.4; public const double StockLimit = 2.5; public const int StreakFrom = 3; private const double MoodOn = 0.9; private const double MoodOff = 0.4; public LeagueState State { get; private set; } public CityLeague City { get; private set; } public Market MarketFor(Fixture f, double edge) { Team team = MatchdayTeam(f.Team1, new List<Player>()); Team team2 = MatchdayTeam(f.Team2, new List<Player>()); string text = edge.ToString("0.0000") + "|" + BoostSize.ToString("0.000") + "|" + string.Join(",", from p in team.Players.Concat(team2.Players) select $"{p.Id}:{p.Lob}:{p.Bat}:{p.Field}"); if (_markets.TryGetValue(f.Id, out (string, Market) value) && value.Item1 == text) { return value.Item2; } ulong a = Rng.Mix(State.BaseSeed ^ 0x5B00C0FFEEL, (ulong)f.Id + 36864uL); int[] array = new int[4000]; int[] array2 = new int[4000]; int num = 0; int num2 = 0; for (int num3 = 0; num3 < 4000; num3++) { MatchResult matchResult = Simulator.PlayMatch(team, team2, MatchRules, MatchModel, Rng.Mix(a, (ulong)num3)); array[num3] = matchResult.Score1 - matchResult.Score2; array2[num3] = matchResult.Score1 + matchResult.Score2; if (matchResult.Score1 > matchResult.Score2) { num++; } else if (matchResult.Score2 > matchResult.Score1) { num2++; } } double num4 = 4000.0; Market market = new Market { Fixture = f, Win1 = (double)num / num4, Win2 = (double)num2 / num4, Draw = (num4 - (double)num - (double)num2) / num4, MeanMargin = array.Average(), MeanTotal = array2.Average(), Margins = array, Totals = array2 }; double num5 = Math.Max(1, num + num2); market.Money1 = Leg(BetKind.Moneyline, f.Team1, over: false, 0.0, (double)num / num5); market.Money2 = Leg(BetKind.Moneyline, f.Team2, over: false, 0.0, (double)num2 / num5); bool fav1 = market.MeanMargin >= 0.0; double num6 = 0.5; double num7 = 0.5; double num8 = double.MaxValue; double[] array3 = new double[4] { 0.5, 1.5, 2.5, 3.5 }; foreach (double line in array3) { double num10 = (double)array.Count((int x) => (double)(fav1 ? x : (-x)) > line) / num4; if (Math.Abs(num10 - 0.5) < num8) { num8 = Math.Abs(num10 - 0.5); num6 = line; num7 = num10; } } market.Spread1 = Leg(BetKind.Spread, f.Team1, over: false, fav1 ? (0.0 - num6) : num6, fav1 ? num7 : (1.0 - num7)); market.Spread2 = Leg(BetKind.Spread, f.Team2, over: false, fav1 ? num6 : (0.0 - num6), fav1 ? (1.0 - num7) : num7); num8 = double.MaxValue; double line2 = 5.5; double num11 = 0.5; double line3; for (line3 = 1.5; line3 <= 12.5; line3 += 1.0) { double num12 = (double)array2.Count((int x) => (double)x > line3) / num4; if (Math.Abs(num12 - 0.5) < num8) { num8 = Math.Abs(num12 - 0.5); line2 = line3; num11 = num12; } } market.Over = Leg(BetKind.Total, -1, over: true, line2, num11); market.Under = Leg(BetKind.Total, -1, over: false, line2, 1.0 - num11); if (BoostSize > 0.0) { ulong num13 = Rng.Mix(State.BaseSeed ^ 0xB0057ED, (ulong)f.Id); if (num13 % 3 == 0L) { BetLeg betLeg = market.All.ElementAt((int)((num13 >> 8) % 6)); betLeg.Odds = Odds.FromAmerican(Odds.ToAmerican(Math.Min(51.0, betLeg.Odds * (1.0 + BoostSize)))); betLeg.Boosted = true; } } _markets[f.Id] = (text, market); return market; BetLeg Leg(BetKind kind, int team3, bool over, double line4, double p) { return new BetLeg { FixtureId = f.Id, Kind = kind, Team = team3, Over = over, Line = line4, Odds = Odds.Price(p, edge), Team1 = f.Team1, Team2 = f.Team2 }; } } public string PlaceBet(IList<BetLeg> picks, int stake, double edge, int minStake, int maxStake, int maxOpenBets, int lockedFixture, double gameTime, out Bet bet) { bet = null; if (stake < minStake) { return $"MINIMUM STAKE {minStake}"; } if (stake > maxStake) { return $"MAXIMUM STAKE {maxStake}"; } if (State.Book.Bets.Count((Bet b) => b.State == BetState.Open) >= maxOpenBets) { return $"{maxOpenBets} OPEN BETS AT MOST"; } List<BetLeg> legs; double odds; string text = Quote(picks, edge, lockedFixture, out legs, out odds); if (text != null) { return text; } BetBook book = State.Book; bet = new Bet { Id = book.NextId++, Season = State.Season, Stake = stake, Legs = legs, PlacedAt = gameTime }; book.Bets.Add(bet); book.Placed++; return null; } public string Quote(IList<BetLeg> picks, double edge, int lockedFixture, out List<BetLeg> legs, out double odds) { legs = new List<BetLeg>(); odds = 1.0; if (picks == null || picks.Count == 0) { return "PICK SOMETHING FIRST"; } if (picks.Count > 4) { return $"{4} PICKS AT MOST"; } foreach (IGrouping<int, BetLeg> match in from p in picks group p by p.FixtureId) { Fixture f = State.Fixtures.FirstOrDefault((Fixture x) => x.Id == match.Key); if (f == null || f.Played || f.Id == lockedFixture) { return "BETTING HAS CLOSED ON A MATCH"; } if (match.Select((BetLeg p) => p.Kind).Distinct().Count() != match.Count()) { return "ONE PICK PER MARKET"; } Market market = MarketFor(f, edge); List<BetLeg> list = new List<BetLeg>(); foreach (BetLeg pick in match) { BetLeg betLeg = market.All.FirstOrDefault((BetLeg o) => o.Same(pick)); if (betLeg == null) { return "THE LINE HAS MOVED"; } list.Add(new BetLeg { FixtureId = betLeg.FixtureId, Kind = betLeg.Kind, Team = betLeg.Team, Over = betLeg.Over, Line = betLeg.Line, Odds = betLeg.Odds, Boosted = betLeg.Boosted, Team1 = f.Team1, Team2 = f.Team2 }); } if (list.Count == 1) { odds *= list[0].Odds; } else { List<BetLeg> list2 = list.Where((BetLeg l) => l.Kind != BetKind.Moneyline).ToList(); bool flag = list2.Count < list.Count; int num = 0; int num2 = 0; int num3 = 0; for (int num4 = 0; num4 < market.Margins.Length; num4++) { int margin = market.Margins[num4]; int total = market.Totals[num4]; if (list2.All((BetLeg l) => Odds.Grade(l, f.Team1, margin, total) == LegResult.Won)) { num2++; if (!flag) { num++; } else if (margin == 0) { num3++; } else if (list.All((BetLeg l) => Odds.Grade(l, f.Team1, margin, total) == LegResult.Won)) { num++; } } } if (num < 60) { return "NO PRICE ON THAT COMBINATION"; } double num5 = market.Margins.Length; double num6 = 0.0; double dec; if (!flag) { dec = Math.Pow(1.0 + edge, list.Count) * num5 / (double)num; } else { num6 = Snap(Math.Pow(1.0 + edge, list2.Count) * num5 / (double)num2); dec = (Math.Pow(1.0 + edge, list.Count) - (double)num3 / num5 * num6) / ((double)num / num5); } dec = Snap(dec); foreach (BetLeg item in list) { item.Combo = dec; item.ComboDraw = num6; } odds *= dec; } legs.AddRange(list); } return null; static double Snap(double val) { return Odds.FromAmerican(Odds.ToAmerican(Math.Min(101.0, Math.Max(1.02, val)))); } } private void SettleBets(Fixture f) { BetBook book = State.Book; foreach (Bet bet in book.Bets) { if (bet.State != BetState.Open) { continue; } bool flag = false; foreach (BetLeg leg in bet.Legs) { if (leg.FixtureId == f.Id && leg.Result == LegResult.Open) { leg.Result = Odds.Settle(leg, f.Team1, f.Score1, f.Score2); flag = true; } } if (!flag) { continue; } if (bet.Legs.Any((BetLeg l) => l.Result == LegResult.Lost)) { bet.State = BetState.Lost; bet.Payout = 0; bet.Paid = true; book.Lost++; } else { if (!bet.Legs.All((BetLeg l) => l.Result != LegResult.Open)) { continue; } if (bet.Legs.All((BetLeg l) => l.Result == LegResult.Push)) { bet.State = BetState.Void; bet.Payout = bet.Stake; book.Void++; } else { bet.State = BetState.Won; bet.Payout = (int)Math.Round((double)bet.Stake * bet.Odds, MidpointRounding.AwayFromZero); book.Won++; } } book.Staked += bet.Stake; book.Returned += bet.Payout; } int num = book.Bets.Count((Bet b) => b.State != BetState.Open && b.Paid); for (int num2 = 0; num2 < book.Bets.Count; num2++) { if (num <= 40) { break; } if (book.Bets[num2].State != BetState.Open && book.Bets[num2].Paid) { book.Bets.RemoveAt(num2--); num--; } } } public IEnumerable<Bet> UnpaidBets() { return State.Book.Bets.Where((Bet b) => b.State != BetState.Open && !b.Paid); } private void RunEvents(Stage stage) { double num = State.Config.EventsPerRound * ((stage == Stage.Regular) ? 1.0 : 0.5); int num2 = 0; for (int i = 0; i < 3; i++) { if (_rng.NextDouble() < num / 3.0) { num2++; } } for (int j = 0; j < num2; j++) { FireOne(); } } private bool OnCooldown(EventTemplate t) { if (State.TemplateLastUsed.TryGetValue(t.Id, out var value)) { return State.GlobalRound - value < t.Cooldown; } return false; } private int AbsentCount(int team) { return Starters(team).Count((Player p) => !Available(p)); } private bool IsAbsence(EventEffect e) { if (e != EventEffect.Injury && e != EventEffect.SyncInjury && e != EventEffect.Suspension) { return e == EventEffect.CigaretteSuspension; } return true; } private bool HadStoryThisSeason(EventTemplate t, Player p) { return State.Articles.Any((Article a) => a.Season == State.Season && a.Template == t.Id && a.PlayerId == p.Id); } private List<Player> Targets(EventTemplate t) { return State.Players.Where((Player p) => !p.Reserve && Available(p) && t.PlayerOk(this, p) && !HadStoryThisSeason(t, p) && (!IsAbsence(t.Effect) || AbsentCount(p.TeamIndex) < State.Config.ReservesPerTeam)).ToList(); } private void FireOne() { List<EventTemplate> list = Templates.Where((EventTemplate t) => !OnCooldown(t) && State.Articles.Count((Article a) => a.Season == State.Season && a.Template == t.Id) < t.MaxPerSeason && ((!t.TeamEvent) ? (Targets(t).Count > 0) : Enumerable.Range(0, 5).Any((int x) => t.TeamOk(this, x)))).ToList(); if (list.Count == 0) { return; } EventTemplate tpl = list[_rng.Pick(list.Select((EventTemplate t) => t.Weight).ToArray())]; Player p = null; int team; if (tpl.TeamEvent) { List<int> list2 = (from x in Enumerable.Range(0, 5) where tpl.TeamOk(this, x) select x).ToList(); team = list2[(int)(_rng.NextU64() % (ulong)list2.Count)]; } else { List<Player> list3 = Targets(tpl); p = list3[(int)(_rng.NextU64() % (ulong)list3.Count)]; team = p.TeamIndex; } int n = tpl.Matches[(uint)(_rng.NextU64() % (ulong)tpl.Matches.Length)]; string skill = ""; switch (tpl.Effect) { case EventEffect.Injury: Absent(p, AbsenceKind.Injury, n); break; case EventEffect.SyncInjury: Absent(p, AbsenceKind.SyncInjury, n); break; case EventEffect.Suspension: Absent(p, AbsenceKind.Suspension, n); break; case EventEffect.CigaretteSuspension: Absent(p, AbsenceKind.CigaretteSuspension, 1); n = 1; break; case EventEffect.FormUp: skill = Adjust(p, 2); break; case EventEffect.BigFormUp: skill = Adjust(p, 3); break; case EventEffect.FormDown: skill = Adjust(p, -2); break; } if (tpl.NewsKey != null) { State.News.RemoveAll((NewsFlag x) => x.Key == tpl.NewsKey); State.News.Add(new NewsFlag { Key = tpl.NewsKey, RoundsLeft = tpl.NewsRounds }); } State.TemplateLastUsed[tpl.Id] = State.GlobalRound; string product = Products[(uint)(_rng.NextU64() % (ulong)Products.Length)]; AddArticle(new Article { Kind = "event", Template = tpl.Id, PlayerId = p?.Id, TeamIndex = team, Noir = tpl.Noir, Headline = Fill(tpl.Headline), Body = Fill(tpl.Body) }); string Fill(string s) { return s.Replace("{Name}", p?.Name ?? "").Replace("{name}", p?.Name ?? "").Replace("{SURNAME}", (p?.Surname ?? "").ToUpperInvariant()) .Replace("{surname}", p?.Surname ?? "") .Replace("{TEAM}", Short(team).ToUpperInvariant()) .Replace("{team}", Short(team)) .Replace("{teamfull}", Roster.FullNames[team]) .Replace("{SPONSOR}", Roster.Sponsors[team].ToUpperInvariant()) .Replace("{sponsor}", Roster.Sponsors[team]) .Replace("{PRODUCT}", product.ToUpperInvariant()) .Replace("{product}", product) .Replace("{skill}", skill) .Replace("{n}", (n == 1) ? "one match" : (Words(n) + " matches")); } } private void Absent(Player p, AbsenceKind kind, int matches) { Status status = State.Statuses[p.Id]; status.Absence = kind; status.MatchesOut = matches; status.ReturningFrom = AbsenceKind.None; } private static string Adjust(Player p, int delta) { switch (p.Position) { case Position.Rouleur: p.Lob = Clamp(p.Lob); return "a new curve on the lob"; case Position.Tireur: p.Bat = Clamp(p.Bat); return "a shorter, flatter swing"; default: p.Field = Clamp(p.Field); return "the throw back to the circle"; } int Clamp(int v) { return Math.Max(35, Math.Min(75, v + delta)); } } private static string Words(int n) { return n switch { 1 => "one", 2 => "two", 3 => "three", 4 => "four", _ => n.ToString(), }; } private Article MatchReport(Fixture f, MatchSetup s) { int winner = f.Winner; int team = ((winner == f.Team1) ? f.Team2 : f.Team1); int num = Math.Max(f.Score1, f.Score2); int num2 = Math.Min(f.Score1, f.Score2); string headline; string text; if (f.Score1 == f.Score2) { headline = Short(f.Team1).ToUpperInvariant() + " AND " + Short(f.Team2).ToUpperInvariant() + " SHARE THE SPOILS"; text = $"{Cap(Name(f.Team1))} and {Name(f.Team2)} finished level at {f.Score1}-{f.Score2} at the Gemsteader Boulodrome."; if (f.Stage != Stage.Regular) { text += ((State.Config.TieBreak == PlayoffTieBreak.Replay) ? " With a playoff place at stake, the match will be replayed." : (" The " + Short(f.Winner) + " go through as the higher seed.")); } } else { string value = ((num - num2 == 1) ? "EDGE" : ((num - num2 >= 4) ? "ROUT" : "BEAT")); headline = $"{Short(winner).ToUpperInvariant()} {value} {Short(team).ToUpperInvariant()} {num}-{num2}"; text = $"{Cap(Name(winner))} beat {Name(team)} {num}-{num2} at the Gemsteader Boulodrome."; if (f.Stage == Stage.Semi) { text = $"{Cap(Name(winner))} beat {Name(team)} {num}-{num2} in the District Series and go through to the Starch Series."; } if (f.Stage == Stage.Final) { text = $"{Cap(Name(winner))} won the Starch Series, beating {Name(team)} {num}-{num2} at the Gemsteader Boulodrome."; } } (Player, int, int) tuple = (from p in s.Team1.Players.Concat(s.Team2.Players) select (p: p, rbi: (from x in s.Result.Halves.SelectMany((HalfInningResult h) => h.Plays) where x.Striker == p select x).Sum((PlayRecord x) => x.Scored.Count), runs: s.Result.Halves.SelectMany((HalfInningResult h) => h.Plays).Sum((PlayRecord x) => x.Scored.Count((Player y) => y == p))) into x orderby x.rbi descending, x.runs descending select x).First(); if (tuple.Item2 >= 2) { text += $" {tuple.Item1.Name} drove in {Words(tuple.Item2)}."; } foreach (Player item in s.Absent1.Concat(s.Absent2)) { text = text + " " + item.Name + " sat out; a reserve took the place."; } if (_rng.NextDouble() < 0.12) { text = text + " " + ColourLines[(uint)(_rng.NextU64() % (ulong)ColourLines.Length)]; } return new Article { Kind = "match", Template = "match", Headline = headline, Body = text, TeamIndex = winner }; } private static string Cap(string s) { if (s.Length != 0) { return char.ToUpperInvariant(s[0]) + s.Substring(1); } return s; } public static LeagueEngine New(LeagueConfig config, ulong seed) { LeagueState leagueState = new LeagueState { Config = (config ?? new LeagueConfig()), BaseSeed = seed, RngState = seed }; Team[] array = Roster.Build(); foreach (Team team in array) { Player[] players = team.Players; foreach (Player item in players) { leagueState.Players.Add(item); } for (int k = 0; k < leagueState.Config.ReservesPerTeam; k++) { leagueState.Players.Add(ReserveNames.Make(team.Index, k)); } } foreach (Player player in leagueState.Players) { leagueState.Statuses[player.Id] = new Status(); } LeagueEngine leagueEngine = new LeagueEngine(leagueState); leagueEngine.StartSeason(); return leagueEngine; } public string Save() { State.RngState = _rng.State; City?.BeforeSave(); return JsonSerializer.Serialize(State, Json); } public static LeagueEngine Load(string json) { return new LeagueEngine(JsonSerializer.Deserialize<LeagueState>(json, Json)); } private LeagueEngine(LeagueState state) { State = state; _rng = new Rng(state.RngState); _byId = state.Players.ToDictionary((Player p) => p.Id); if (state.City != null) { City = new CityLeague(state.City); } } public bool FoundCity(IList<CityTeamSpec> specs, int teams) { CityLeague cityLeague = CityLeague.Create(Rng.Mix(State.BaseSeed, 49534uL), specs, teams); if (cityLeague == null) { return false; } City = cityLeague; State.City = cityLeague.State; return true; } public Player PlayerById(string id) { if (!_byId.TryGetValue(id, out var value)) { return null; } return value; } public IEnumerable<Player> Starters(int team) { return State.Players.Where((Player p) => p.TeamIndex == team && !p.Reserve); } public IEnumerable<Player> TeamPlayers(int team) { return State.Players.Where((Player p) => p.TeamIndex == team); } private bool Available(Player p) { return State.Statuses[p.Id].Absence == AbsenceKind.None; } private void StartSeason() { State.Fixtures = new List<Fixture>(); State.Stats = new Dictionary<string, PlayerSeasonStats>(); foreach (var item in Schedule.RoundRobin(5, State.Config.MeetingsPerPair, _rng)) { AddFixture(Stage.Regular, item.round, item.t1, item.t2); } int count = State.Fixtures.Count; AddArticle(new Article { Kind = "season", Template = "season-start", Headline = $"SEASON {State.Season} OPENS AT THE GEMSTEADER BOULODROME", Body = $"The U.A.S. League's season {State.Season} gets under way tonight: {count} regular-season matches, then the playoffs. The {Roster.FullNames[State.DefendingChampion]} defend the title." }); } private Fixture AddFixture(Stage stage, int round, int t1, int t2, int seed1 = -1, int seed2 = -1, bool replay = false) { Fixture fixture = new Fixture { Id = State.NextFixtureId++, Season = State.Season, Round = round, Stage = stage, IsReplay = replay, Team1 = t1, Team2 = t2, Seed1 = seed1, Seed2 = seed2 }; fixture.MatchSeed = Rng.Mix(State.BaseSeed, (ulong)fixture.Id); State.Fixtures.Add(fixture); return fixture; } public Fixture Next() { Fixture fixture; while (true) { fixture = (from x in State.Fixtures where !x.Played orderby x.Id select x).FirstOrDefault(); if (fixture != null) { break; } if (!AdvanceStage()) { if (!State.SeasonClosed) { EndSeason(); } State.SeasonClosed = false; State.Season++; StartSeason(); } } return fixture; } private bool AdvanceStage() { List<Fixture> fixtures = State.Fixtures; bool flag = fixtures.Any((Fixture x) => x.Stage == Stage.Semi); bool flag2 = fixtures.Any((Fixture x) => x.Stage == Stage.Final); List<StandingRow> list = Standings(); if (!flag && !flag2) { if (State.Config.Playoffs == PlayoffFormat.SemisAndFinal) { AddFixture(Stage.Semi, 1, list[0].Team, list[3].Team, 1, 4); AddFixture(Stage.Semi, 1, list[1].Team, list[2].Team, 2, 3); AddArticle(new Article { Kind = "playoff", Template = "semis-set", Headline = "DISTRICT SERIES SET", Body = $"{Name(list[0].Team)} meet {Name(list[3].Team)}, and {Name(list[1].Team)} take on {Name(list[2].Team)}, " + "in the District Series, with places in the Starch Series at stake. Top seeds bat first." }); } else { AddFixture(Stage.Final, 1, list[0].Team, list[1].Team, 1, 2); AddArticle(new Article { Kind = "playoff", Template = "final-set", Headline = "IT'S " + Short(list[0].Team).ToUpperInvariant() + " AGAINST " + Short(list[1].Team).ToUpperInvariant(), Body = $"The top two meet in the Starch Series: {Name(list[0].Team)} against {Name(list[1].Team)}." }); } return true; } if (flag && !flag2) { List<(int, int)> list2 = (from x in fixtures where x.Stage == Stage.Semi && x.Played && x.Winner >= 0 select (team: x.Winner, seed: (x.Winner == x.Team1) ? x.Seed1 : x.Seed2) into x orderby x.seed select x).ToList(); AddFixture(Stage.Final, 2, list2[0].Item1, list2[1].Item1, list2[0].Item2, list2[1].Item2); AddArticle(new Article { Kind = "playoff", Template = "final-set", Headline = "IT'S " + Short(list2[0].Item1).ToUpperInvariant() + " AGAINST " + Short(list2[1].Item1).ToUpperInvariant(), Body = Name(list2[0].Item1) + " and " + Name(list2[1].Item1) + " will contest the Starch Series at the Gemsteader Boulodrome." }); return true; } return false; } private void EndSeason() { Fixture fixture = (from x in State.Fixtures where x.Stage == Stage.Final && x.Played && x.Winner >= 0 orderby x.Id select x).Last(); int winner = fixture.Winner; int num = ((fixture.Winner == fixture.Team1) ? fixture.Team2 : fixture.Team1); SeasonRecord seasonRecord = new SeasonRecord { Season = State.Season, Champion = winner, RunnerUp = num, FinalTable = (from r in Standings() select r.Team).ToList(), Table = Standings(), Stats = State.Stats }; string text = (seasonRecord.FanFavourite = (from kv in State.Stats where !PlayerById(kv.Key).Reserve orderby (double)(kv.Value.Batting.HomeRuns * 2 + kv.Value.Batting.Triples) + (double)kv.Value.Batting.RunsBattedIn * 0.1 descending select kv.Key).FirstOrDefault()); State.History.Add(seasonRecord); State.DefendingChampion = winner; if (text != null) { State.FanFavourite = text; } foreach (Player item in State.Players.Where((Player p) => State.Stats.ContainsKey(p.Id))) { item.SeasonsPlayed++; } RegressRatings(); AddArticle(new Article { Kind = "season", Template = "champions", TeamIndex = winner, Headline = Short(winner).ToUpperInvariant() + " ARE CHAMPIONS", Body = $"The {Roster.FullNames[winner]} are the U.A.S. League champions for season {State.Season}, beating the {Roster.FullNames[num]} {Math.Max(fixture.Score1, fixture.Score2)}-{Math.Min(fixture.Score1, fixture.Score2)} in the Starch Series. {Roster.Sponsors[winner]} has declared a company holiday; attendance will be taken.", Noir = true }); StockFromSeason(winner, num, seasonRecord.FinalTable[seasonRecord.FinalTable.Count - 1]); State.SeasonClosed = true; SnapshotStock(State.Season + 1); } private void RegressRatings() { Dictionary<string, Player> baseline = Roster.Build().SelectMany((Team t) => t.Players).ToDictionary((Player p) => p.Id); foreach (Player item in State.Players.Where((Player p) => !p.Reserve && baseline.ContainsKey(p.Id))) { Player player = baseline[item.Id]; item.Lob = Pull(item.Lob, player.Lob); item.Bat = Pull(item.Bat, player.Bat); item.Field = Pull(item.Field, player.Field); } static int Pull(int now, int orig) { return now + (int)Math.Round((double)(orig - now) * 0.4, MidpointRounding.AwayFromZero); } } public MatchSetup Prepare(Fixture f) { MatchSetup matchSetup = new MatchSetup { Fixture = f }; matchSetup.Team1 = MatchdayTeam(f.Team1, matchSetup.Absent1); matchSetup.Team2 = MatchdayTeam(f.Team2, matchSetup.Absent2); matchSetup.Result = Simulator.PlayMatch(matchSetup.Team1, matchSetup.Team2, MatchRules, MatchModel, f.MatchSeed); matchSetup.Facts = Facts(); return matchSetup; } public MatchSetup PlayNext() { MatchSetup matchSetup = Prepare(Next()); Commit(matchSetup); return matchSetup; } private Team MatchdayTeam(int index, List<Player> absent) { List<Player> list = (from p in TeamPlayers(index) where p.Reserve orderby p.Id select p).ToList(); Player[] array = new Player[3]; Position[] order = new Position[3] { Position.Rouleur, Position.Tireur, Position.Fielder }; int num = 0; int i; for (i = 0; i < 3; i++) { Player player = Starters(index).First((Player p) => p.Position == order[i]); if (Available(player)) { array[i] = player; continue; } absent.Add(player); Player player2 = list[Math.Min(num++, list.Count - 1)]; array[i] = new Player { Id = player2.Id, Name = player2.Name, Surname = player2.Surname, Reserve = true, TeamIndex = player2.TeamIndex, Position = order[i], Lob = player2.Lob, Bat = player2.Bat, Field = player2.Field, LeftHanded = player2.LeftHanded, Tags = new HashSet<string>(player2.Tags), SeasonsPlayed = player2.SeasonsPlayed }; } return new Team { Index = index, Name = Roster.Build()[index].Name, Players = array }; } public void Commit(MatchSetup s) { Fixture f = s.Fixture; if (f.Played) { throw new InvalidOperationException($"fixture {f.Id} already played"); } MatchResult result = s.Result; f.Played = true; f.Score1 = result.Score1; f.Score2 = result.Score2; f.HalfScores = result.Halves.Select((HalfInningResult h) => h.Score).ToArray(); f.Lineup1 = s.Team1.Players.Select((Player p) => p.Id).ToList(); f.Lineup2 = s.Team2.Players.Select((Player p) => p.Id).ToList(); f.Winner = ((result.Score1 > result.Score2) ? f.Team1 : ((result.Score2 > result.Score1) ? f.Team2 : (-1))); SettleBets(f); StockFromResult(f); RecordStats(s); UpdateStatuses(s); if (f.Stage != Stage.Regular && f.Winner < 0) { if (State.Config.TieBreak == PlayoffTieBreak.Replay) { AddFixture(f.Stage, f.Round, f.Team1, f.Team2, f.Seed1, f.Seed2, replay: true); } else { f.Winner = ((f.Seed1 <= f.Seed2) ? f.Team1 : f.Team2); } } AddArticle(MatchReport(f, s)); if (!State.Fixtures.Any((Fixture x) => !x.Played && x.Stage == f.Stage && x.Round == f.Round)) { State.GlobalRound++; StockAfterRound(); foreach (NewsFlag item in State.News) { item.RoundsLeft--; } State.News.RemoveAll((NewsFlag n) => n.RoundsLeft <= 0); RunEvents(f.Stage); } if (!State.Fixtures.Any((Fixture x) => !x.Played) && !AdvanceStage() && !State.SeasonClosed) { EndSeason(); } } private void RecordStats(MatchSetup s) { foreach (Player item in s.Team1.Players.Concat(s.Team2.Players)) { S(item).Matches++; } HalfInningResult[] halves = s.Result.Halves; foreach (HalfInningResult obj in halves) { HashSet<(Player, int)> hashSet = new HashSet<(Player, int)>(); foreach (PlayRecord play in obj.Plays) { BattingLine batting = S(play.Striker).Batting; LobbingLine lobbing = S(play.Lobber).Lobbing; batting.Lobs++; lobbing.Lobs++; if (hashSet.Add((play.Lobber, play.Turn))) { lobbing.Spells++; } switch (play.Kind) { case PlayKind.CheerSmall: batting.Singles++; lobbing.HitsAllowed++; break; case PlayKind.CheerMedium: batting.Doubles++; lobbing.HitsAllowed++; break; case PlayKind.CheerLarge: batting.Triples++; lobbing.HitsAllowed++; break; case PlayKind.Strike: batting.HomeRuns++; lobbing.HitsAllowed++; lobbing.HomeRunsAllowed++; break; case PlayKind.Boo: batting.DeadLobs++; lobbing.DeadLobs++; break; case PlayKind.NearMiss: batting.Outs++; lobbing.OutsInduced++; break; } batting.RunsBattedIn += play.Scored.Count; lobbing.RunsAllowed += play.Scored.Count; foreach (Player item2 in play.Scored) { S(item2).Batting.Runs++; } } } PlayerSeasonStats S(Player p) { if (!State.Stats.TryGetValue(p.Id, out var value)) { value = (State.Stats[p.Id] = new PlayerSeasonStats()); } return value; } } private void UpdateStatuses(MatchSetup s) { foreach (Player item in s.Team1.Players.Concat(s.Team2.Players)) { State.Statuses[item.Id].ReturningFrom = AbsenceKind.None; } foreach (Player item2 in s.Absent1.Concat(s.Absent2)) { Status status = State.Statuses[item2.Id]; if (--status.MatchesOut <= 0) { status.ReturningFrom = status.Absence; status.Absence = AbsenceKind.None; status.MatchesOut = 0; } } } public List<StandingRow> Standings(int season = -1) { List<Fixture> fixtures = ((season < 0 || season == State.Season) ? State.Fixtures : new List<Fixture>()); List<StandingRow> list = (from t in Enumerable.Range(0, 5) select new StandingRow { Team = t }).ToList(); foreach (Fixture item in fixtures.Where((Fixture x) => x.Stage == Stage.Regular && x.Played)) { StandingRow standingRow = list[item.Team1]; StandingRow standingRow2 = list[item.Team2]; standingRow.Played++; standingRow2.Played++; standingRow.RunsFor += item.Score1; standingRow.RunsAgainst += item.Score2; standingRow2.RunsFor += item.Score2; standingRow2.RunsAgainst += item.Score1; if (item.Score1 > item.Score2) { standingRow.Won++; standingRow2.Lost++; standingRow.Points += State.Config.PointsForWin; } else if (item.Score2 > item.Score1) { standingRow2.Won++; standingRow.Lost++; standingRow2.Points += State.Config.PointsForWin; } else { standingRow.Drawn++; standingRow2.Drawn++; st