add missing files
This commit is contained in:
@@ -0,0 +1,788 @@
|
||||
#if UNITY_EDITOR || DEVELOPMENT_BUILD
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using KernelPanic.UI;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace KernelPanic.Run
|
||||
{
|
||||
/// <summary>Opt-in standalone development-build integration check with an isolated save.</summary>
|
||||
public sealed class PlayerSmokeRunner : MonoBehaviour
|
||||
{
|
||||
private string _output;
|
||||
private string _failure;
|
||||
private string _campaignSuccess;
|
||||
private string _stage = "startup";
|
||||
private float _deadline;
|
||||
|
||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
|
||||
private static void Install()
|
||||
{
|
||||
string[] args = Environment.GetCommandLineArgs();
|
||||
int flag = Array.IndexOf(args, "--kernel-panic-smoke");
|
||||
if (flag < 0) return;
|
||||
int saveFlag = Array.IndexOf(args, "--kernel-panic-save-path");
|
||||
if (saveFlag < 0 || saveFlag + 1 >= args.Length || !Path.IsPathRooted(args[saveFlag + 1]) || File.Exists(args[saveFlag + 1]) || File.Exists(args[saveFlag + 1] + ".bak"))
|
||||
{
|
||||
Debug.LogError("Smoke check requires an absolute, unused --kernel-panic-save-path.");
|
||||
Application.Quit(2);
|
||||
return;
|
||||
}
|
||||
// Install before the menu's OnEnable can schedule the animated boot sequence.
|
||||
UIPreferences.ReducedMotion = true; // Session only; never writes preferences.
|
||||
var owner = new GameObject("Player smoke verification");
|
||||
Application.runInBackground = true;
|
||||
DontDestroyOnLoad(owner);
|
||||
var runner = owner.AddComponent<PlayerSmokeRunner>();
|
||||
runner._output = Path.GetDirectoryName(args[saveFlag + 1]);
|
||||
Directory.CreateDirectory(runner._output);
|
||||
runner._deadline = Time.realtimeSinceStartup + 900;
|
||||
Application.logMessageReceived += runner.ObserveLog;
|
||||
}
|
||||
|
||||
private void ObserveLog(string message, string trace, LogType type)
|
||||
{
|
||||
if (type == LogType.Exception || type == LogType.Error || type == LogType.Assert)
|
||||
_failure ??= message + "\n" + trace;
|
||||
}
|
||||
|
||||
private IEnumerator Start()
|
||||
{
|
||||
// Pump manually so an exception writes a useful result and exits instead of hanging CI.
|
||||
var scenario = Scenario();
|
||||
while (true)
|
||||
{
|
||||
bool next = false;
|
||||
object yielded = null;
|
||||
try
|
||||
{
|
||||
if (_failure != null) throw new InvalidOperationException(_failure);
|
||||
if (Time.realtimeSinceStartup > _deadline) throw new TimeoutException("Smoke check timed out at " + _stage);
|
||||
next = scenario.MoveNext();
|
||||
if (next) yielded = scenario.Current;
|
||||
}
|
||||
catch (Exception ex) { _failure = ex.ToString(); }
|
||||
if (_failure != null || !next) break;
|
||||
yield return yielded;
|
||||
}
|
||||
Application.logMessageReceived -= ObserveLog;
|
||||
if (_failure == null && _campaignSuccess != null)
|
||||
{
|
||||
File.WriteAllText(Path.Combine(_output, "player-smoke-result.txt"), _campaignSuccess);
|
||||
Debug.Log("PLAYER_SMOKE_PASS");
|
||||
Application.Quit(0);
|
||||
yield break;
|
||||
}
|
||||
File.WriteAllText(Path.Combine(_output, "player-smoke-result.txt"), _failure == null ? "PASS: starter selection -> configured run -> pile tabs/search/grouping/cost details/keyboard focus -> combat -> repository purchase -> save and exit without payout -> exact repository resume -> next wave -> shutdown -> run archive command/navigation -> original build details/copy seed/load setup -> saved rewards/history -> same-seed retry -> new-seed retry -> natural defeat with attributed damage" : "FAIL at " + _stage + "\n" + _failure);
|
||||
Debug.Log(_failure == null ? "PLAYER_SMOKE_PASS" : "PLAYER_SMOKE_FAIL: " + _failure);
|
||||
Application.Quit(_failure == null ? 0 : 1);
|
||||
}
|
||||
|
||||
private IEnumerator Scenario()
|
||||
{
|
||||
// Preference loading is also a BeforeSceneLoad callback; reapply the session
|
||||
// override after all such callbacks, regardless of their registration order.
|
||||
UIPreferences.ReducedMotion = true;
|
||||
_stage = "starter selection";
|
||||
yield return new WaitForSecondsRealtime(2);
|
||||
var menu = FindFirstObjectByType<MainMenuController>();
|
||||
Require(menu != null, "Main menu scene did not initialize.");
|
||||
var starter = Field<StarterSelectionController>(menu, "starterSelection");
|
||||
if (!starter.IsActive)
|
||||
{
|
||||
// Exercise the normal "any key" boot skip; hidden windows need not run
|
||||
// the animated panel scheduler at the same cadence as a visible window.
|
||||
var startupRoot = menu.GetComponent<UIDocument>().rootVisualElement;
|
||||
using var skipIntro = KeyDownEvent.GetPooled(' ', KeyCode.Space, EventModifiers.None);
|
||||
skipIntro.target = startupRoot;
|
||||
startupRoot.SendEvent(skipIntro);
|
||||
}
|
||||
float starterDeadline = Time.realtimeSinceStartup + 30;
|
||||
while (!starter.IsActive && Time.realtimeSinceStartup < starterDeadline) yield return null;
|
||||
Require(starter.IsActive, $"Fresh profile did not show starter selection; boot elapsed={Field<float>(menu, "_bootIntroElapsed")}, starterChosen={new SaveService().Load().starterChosen}.");
|
||||
var choices = Field<System.Collections.Generic.IReadOnlyList<DistroDefinition>>(starter, "_activeStarters");
|
||||
int ubuntuIndex = choices.ToList().FindIndex(distro => distro.Id == "ubuntu");
|
||||
Require(ubuntuIndex >= 0, "Ubuntu starter not available.");
|
||||
Call(starter, "Select", ubuntuIndex);
|
||||
using (var key = KeyDownEvent.GetPooled('\n', KeyCode.Return, EventModifiers.None)) starter.HandleKeyDown(key);
|
||||
using (var key = KeyDownEvent.GetPooled('y', KeyCode.Y, EventModifiers.None)) starter.HandleKeyDown(key);
|
||||
yield return null;
|
||||
Require(new SaveService().Load().IsUnitOwned("ubuntu"), "Starter choice was not persisted.");
|
||||
var training = TutorialScenario();
|
||||
while (training.MoveNext()) yield return training.Current;
|
||||
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-tutorial-smoke"))
|
||||
{
|
||||
_campaignSuccess = "PASS: two-wave guided tutorial, real targeting/revival/queue/stack, full clears, shop purchase, same-run resume, one-time 1000 Bandwidth + 1000 Entropy, clean normal-run workspace.";
|
||||
yield break;
|
||||
}
|
||||
menu = FindFirstObjectByType<MainMenuController>();
|
||||
_stage = "run setup";
|
||||
ConfigureMenu(menu);
|
||||
yield return null;
|
||||
Call(menu, "BootSelectedPackage");
|
||||
CombatManager combat = null;
|
||||
while (combat == null || !combat.CanSurrenderRun)
|
||||
{
|
||||
yield return null;
|
||||
combat = FindFirstObjectByType<CombatManager>();
|
||||
}
|
||||
Require(combat.RunConfig.RunSeed == 12345, "Run seed was not handed off.");
|
||||
string originalBuild = BuildSignature(combat.RunConfig);
|
||||
var view = FindFirstObjectByType<CombatSceneController>();
|
||||
var previewRoot = view.GetComponent<UIDocument>().rootVisualElement;
|
||||
var executionPreview = previewRoot.Q<Foldout>("ExecutionPreview");
|
||||
int drawsBeforePreview = RandomRoll.DrawCount;
|
||||
executionPreview.value = true;
|
||||
yield return null;
|
||||
var previewContents = previewRoot.Q("ExecutionPreviewPopup") ?? executionPreview;
|
||||
Require(RandomRoll.DrawCount == drawsBeforePreview && previewContents.Q<Label>(className: "terminal-body") != null,
|
||||
"Execution preview changed RNG or did not render its explanation.");
|
||||
executionPreview.value = false;
|
||||
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-campaign-smoke"))
|
||||
{
|
||||
var campaign = CampaignScenario(combat, view);
|
||||
while (campaign.MoveNext()) yield return campaign.Current;
|
||||
yield break;
|
||||
}
|
||||
var guide = Field<FirstBattleGuide>(view, "_firstBattleGuide");
|
||||
guide.Begin(combat.RunConfig, true);
|
||||
var capture = CapturePanel(view.GetComponent<UIDocument>(), "first-battle");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
_stage = "pile inspection";
|
||||
var inspection = InspectPiles(view, combat);
|
||||
while (inspection.MoveNext()) yield return inspection.Current;
|
||||
_stage = "combat";
|
||||
int actions = 0;
|
||||
while (!combat.AwaitingWaveContinue && !combat.RunLost)
|
||||
{
|
||||
if (combat.CanSurrenderRun)
|
||||
{
|
||||
bool played = false;
|
||||
for (int i = 0; i < combat.Enemies.Count; i++)
|
||||
{
|
||||
if (!combat.Enemies[i].State.IsDefeated) { combat.SelectEnemy(i); break; }
|
||||
}
|
||||
foreach (var card in combat.HandController.Cards.ToArray())
|
||||
{
|
||||
if (combat.PlayCard(card)) { played = true; break; }
|
||||
}
|
||||
if (!played) combat.EndPlayerTurn();
|
||||
Require(++actions < 500, "Bot exceeded action budget before clearing wave one.");
|
||||
}
|
||||
yield return null;
|
||||
}
|
||||
Require(!combat.RunLost, "Seeded starter bot died before repository.");
|
||||
yield return null;
|
||||
_stage = "repository";
|
||||
var run = combat.GetComponent<RunManager>();
|
||||
Require(run.WavesCleared == 1 && run.RepositoryVisitActive, "Wave completion did not open repository.");
|
||||
Submit(view.GetComponent<UIDocument>().rootVisualElement.Q<Button>("RouteChallenge"));
|
||||
Require(run.Journey.selectedRoute == WaveRoute.Challenge, "Elite route selection did not reach the run model.");
|
||||
var offer = run.RepositoryOffers.FirstOrDefault(item => item.Price <= run.Bits);
|
||||
Require(offer != null, "No affordable repository offer.");
|
||||
int bits = run.Bits;
|
||||
Require(run.BuyOffer(offer, combat.PlayerState), "Repository purchase failed.");
|
||||
Require(run.Bits == bits - offer.Price, "Purchase charged incorrect Bits.");
|
||||
capture = CapturePanel(view.GetComponent<UIDocument>(), "repository");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
yield return null;
|
||||
|
||||
_stage = "repository checkpoint and suspension";
|
||||
string runId = run.RunId;
|
||||
string deckBefore = DeckSignature(run);
|
||||
string offersBefore = OfferSignature(run);
|
||||
RunCheckpoint beforeSuspend = run.CaptureCheckpoint(combat);
|
||||
string combatBefore = JsonUtility.ToJson(beforeSuspend.combat);
|
||||
int bankedBits = run.Bits;
|
||||
var beforeSave = new SaveService().Load();
|
||||
Call(view, "SaveAndExitRun");
|
||||
menu = null;
|
||||
while (menu == null) { yield return null; menu = FindFirstObjectByType<MainMenuController>(); }
|
||||
var suspended = new SaveService().Load();
|
||||
Require(suspended.activeRun != null && suspended.activeRun.runId == runId, "Repository checkpoint was not persisted.");
|
||||
Require(suspended.bandwidthBalance == beforeSave.bandwidthBalance && suspended.entropyBalance == beforeSave.entropyBalance,
|
||||
"Suspending the run paid out rewards.");
|
||||
Require(suspended.recentRuns.Count == beforeSave.recentRuns.Count, "Suspending created a completed-run history entry.");
|
||||
Require(JsonUtility.ToJson(suspended.activeRun.combat) == combatBefore, "Saved checkpoint changed carried combat state or RNG cursor.");
|
||||
_stage = "repository resume";
|
||||
Call(menu, "ResumeSavedRun");
|
||||
combat = null;
|
||||
while (combat == null || !combat.AwaitingWaveContinue)
|
||||
{
|
||||
yield return null;
|
||||
combat = FindFirstObjectByType<CombatManager>();
|
||||
}
|
||||
view = FindFirstObjectByType<CombatSceneController>();
|
||||
run = combat.GetComponent<RunManager>();
|
||||
Require(run.RepositoryVisitActive && run.RunId == runId && run.CurrentWaveNumber == beforeSuspend.wave
|
||||
&& run.WavesCleared == beforeSuspend.wavesCleared && run.Bits == bankedBits, "Resume changed run identity, wave or currency.");
|
||||
Require(DeckSignature(run) == deckBefore && OfferSignature(run) == offersBefore, "Resume changed cards, upgrades or repository offers.");
|
||||
Require(JsonUtility.ToJson(run.CaptureCheckpoint(combat).combat) == combatBefore, "Resume changed carried combat state or RNG cursor.");
|
||||
Require(BuildSignature(combat.RunConfig) == originalBuild, "Resume changed the original build.");
|
||||
Require(run.Journey.selectedRoute == WaveRoute.Challenge, "Resume lost the selected elite route.");
|
||||
Require(new SaveService().Load().activeRun == null, "Resumed checkpoint was not claimed exactly once.");
|
||||
capture = CapturePanel(view.GetComponent<UIDocument>(), "repository-resumed");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
combat.ContinueToNextWave();
|
||||
while (!combat.CanSurrenderRun) yield return null;
|
||||
Require(run.CurrentWaveNumber == 2, "Next wave failed to start.");
|
||||
_stage = "defeat and reward settlement";
|
||||
int reward = run.AccruedBandwidth + TutorialCampaign.BandwidthReward;
|
||||
Call(view, "ConfirmSurrender");
|
||||
yield return null;
|
||||
Require(combat.RunLost && run.RewardsSettled, "Defeat did not settle rewards.");
|
||||
var saved = new SaveService().Load();
|
||||
Require(saved.bandwidthBalance == reward && saved.GetBestWave("ubuntu") == 2, "Run rewards/stats were not persisted exactly once.");
|
||||
Require(saved.activeRun == null && saved.recentRuns.Count == 1 && saved.recentRuns[0].runId == runId
|
||||
&& saved.recentRuns[0].surrendered && !string.IsNullOrWhiteSpace(saved.recentRuns[0].cause), "Completed resumed run did not save a single useful history entry.");
|
||||
Require(saved.recentRuns[0].finalRound >= 1, "Next wave accepted shutdown before its first round was ready.");
|
||||
capture = CapturePanel(view.GetComponent<UIDocument>(), "run-report");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
yield return null;
|
||||
_stage = "return to menu and run archive";
|
||||
SceneLoader.LoadMainMenu(view.GetComponent<UIDocument>().rootVisualElement);
|
||||
menu = null;
|
||||
while (menu == null) { yield return null; menu = FindFirstObjectByType<MainMenuController>(); }
|
||||
Require(!Field<StarterSelectionController>(menu, "starterSelection").IsActive, "Returning profile unexpectedly needs a starter.");
|
||||
Require(new SaveService().Load().bandwidthBalance == reward, "Scene unload paid rewards twice.");
|
||||
var menuRoot = menu.GetComponent<UIDocument>().rootVisualElement;
|
||||
yield return null;
|
||||
var homePanel = menuRoot.Q("MainMenuPanel");
|
||||
Require(homePanel != null && homePanel.resolvedStyle.display != DisplayStyle.None, "Returning profile did not show the main menu.");
|
||||
Require(homePanel.Q("RetrySameSeedButton") == null && homePanel.Q("RetryNewSeedButton") == null
|
||||
&& homePanel.Q("RecentRunsButton") == null, "Archived run actions still appear on the main menu.");
|
||||
var archiveCommand = menuRoot.Q("CommandRunArchive");
|
||||
Require(archiveCommand != null && archiveCommand.parent.IndexOf(archiveCommand) == archiveCommand.parent.IndexOf(menuRoot.Q("CommandSettings")) + 1
|
||||
&& archiveCommand.parent.IndexOf(menuRoot.Q("CommandQuit")) == archiveCommand.parent.IndexOf(archiveCommand) + 1,
|
||||
"Run archive command is not between Settings and Quit.");
|
||||
capture = CapturePanel(menu.GetComponent<UIDocument>(), "home-menu");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
OpenRunArchive(menuRoot);
|
||||
yield return null;
|
||||
RequireArchiveVisible(menuRoot);
|
||||
capture = CapturePanel(menu.GetComponent<UIDocument>(), "run-archive");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
_stage = "recent runs within archive";
|
||||
Submit(menuRoot.Q<Button>("RecentRunsButton"));
|
||||
yield return null;
|
||||
Require(menuRoot.Q("RunHistoryOverlay") != null, "Recent runs did not open.");
|
||||
var archived = new SaveService().Load().recentRuns[0];
|
||||
Require(RunHistory.HasBuildSnapshot(archived) && archived.build.seed == 12345
|
||||
&& archived.build.startingDeckCardIds.Count > 4, "Run history did not preserve the original starting build.");
|
||||
menuRoot.Q<Foldout>("ArchivedBuildDetails_0").value = true;
|
||||
string previousClipboard = GUIUtility.systemCopyBuffer;
|
||||
try
|
||||
{
|
||||
Submit(menuRoot.Q<Button>("CopyRunSeed_0"));
|
||||
Require(GUIUtility.systemCopyBuffer == "12345", "Archive copy-seed action copied the wrong seed.");
|
||||
}
|
||||
finally { GUIUtility.systemCopyBuffer = previousClipboard; }
|
||||
capture = CapturePanel(menu.GetComponent<UIDocument>(), "run-history");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
string retryBeforeLoad = JsonUtility.ToJson(new SaveService().Load().lastRunLoadout);
|
||||
Submit(menuRoot.Q<Button>("LoadArchivedBuild_0"));
|
||||
yield return null;
|
||||
Require(menuRoot.Q("RunSetupPanel").resolvedStyle.display != DisplayStyle.None
|
||||
&& !Field<bool>(menu, "_runLaunchPending") && Field<string>(menu, "_runSeedText") == "12345",
|
||||
"Archive load did not open setup without launching a run.");
|
||||
Require(JsonUtility.ToJson(new SaveService().Load().lastRunLoadout) == retryBeforeLoad,
|
||||
"Loading an archived build changed the frozen retry build.");
|
||||
Submit(menuRoot.Q("RunSetupPanel").Q<Button>(className: "screen-back"));
|
||||
yield return null;
|
||||
OpenRunArchive(menuRoot);
|
||||
yield return null;
|
||||
Submit(menuRoot.Q<Button>("RecentRunsButton"));
|
||||
Submit(menuRoot.Q<Button>("CloseRunHistory"));
|
||||
Require(menuRoot.Q("RunHistoryOverlay") == null, "Recent runs did not close.");
|
||||
RequireArchiveVisible(menuRoot);
|
||||
_stage = "run archive back navigation";
|
||||
using (var escape = KeyDownEvent.GetPooled('\0', KeyCode.Escape, EventModifiers.None))
|
||||
{
|
||||
escape.target = menuRoot.Q("RunArchivePanel");
|
||||
menuRoot.Q("RunArchivePanel").SendEvent(escape);
|
||||
}
|
||||
yield return null;
|
||||
Require(homePanel.resolvedStyle.display != DisplayStyle.None && menuRoot.Q("RunArchivePanel").resolvedStyle.display == DisplayStyle.None,
|
||||
"Escape did not return from run archive to the main menu.");
|
||||
using (var click = ClickEvent.GetPooled())
|
||||
{
|
||||
click.target = archiveCommand;
|
||||
archiveCommand.SendEvent(click);
|
||||
}
|
||||
yield return null;
|
||||
RequireArchiveVisible(menuRoot);
|
||||
Submit(menuRoot.Q("RunArchivePanel").Q<Button>(className: "screen-back"));
|
||||
yield return null;
|
||||
Require(homePanel.resolvedStyle.display != DisplayStyle.None && menuRoot.Q("RunArchivePanel").resolvedStyle.display == DisplayStyle.None,
|
||||
"Archive Back button did not return to the main menu.");
|
||||
OpenRunArchive(menuRoot);
|
||||
yield return null;
|
||||
RequireArchiveVisible(menuRoot);
|
||||
_stage = "same-seed retry";
|
||||
Submit(menuRoot.Q<Button>("RetrySameSeedButton"));
|
||||
combat = null;
|
||||
while (combat == null || !combat.CanSurrenderRun) { yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
||||
Require(combat.CurrentWaveNumber == 1 && combat.RunConfig.RunSeed == 12345, "Restart did not produce a fresh seeded run.");
|
||||
Require(BuildSignature(combat.RunConfig) == originalBuild && combat.GetComponent<RunManager>().RunId != runId,
|
||||
"Same-seed retry lost the saved build or reused the completed run identity.");
|
||||
Call(FindFirstObjectByType<CombatSceneController>(), "ConfirmSurrender");
|
||||
yield return null;
|
||||
SceneLoader.LoadMainMenu(combat.GetComponent<UIDocument>().rootVisualElement);
|
||||
menu = null;
|
||||
while (menu == null) { yield return null; menu = FindFirstObjectByType<MainMenuController>(); }
|
||||
Require(new SaveService().Load().bandwidthBalance == reward, "Empty second run changed earned rewards.");
|
||||
_stage = "new-seed retry";
|
||||
menuRoot = menu.GetComponent<UIDocument>().rootVisualElement;
|
||||
OpenRunArchive(menuRoot);
|
||||
yield return null;
|
||||
RequireArchiveVisible(menuRoot);
|
||||
Submit(menuRoot.Q<Button>("RetryNewSeedButton"));
|
||||
combat = null;
|
||||
while (combat == null || !combat.CanSurrenderRun) { yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
||||
Require(combat.CurrentWaveNumber == 1 && combat.RunConfig.RunSeed != 12345 && BuildSignature(combat.RunConfig) == originalBuild,
|
||||
"New-seed retry did not preserve the build with a fresh seed.");
|
||||
Require(new SaveService().Load().lastRunLoadout.runSeed == combat.RunConfig.RunSeed, "New seed was not persisted for the next retry.");
|
||||
_stage = "natural defeat and damage attribution";
|
||||
string finalRunId = combat.GetComponent<RunManager>().RunId;
|
||||
int idleTurns = 0;
|
||||
while (!combat.RunLost)
|
||||
{
|
||||
if (combat.CanSurrenderRun)
|
||||
{
|
||||
combat.EndPlayerTurn();
|
||||
Require(++idleTurns < 200, "Enemies did not defeat the idle starter within 200 turns.");
|
||||
}
|
||||
yield return null;
|
||||
}
|
||||
yield return null;
|
||||
saved = new SaveService().Load();
|
||||
var naturalDefeat = saved.recentRuns.FirstOrDefault(entry => entry.runId == finalRunId);
|
||||
Require(naturalDefeat != null && !naturalDefeat.surrendered && naturalDefeat.finalRound >= 1
|
||||
&& naturalDefeat.damageTaken > 0 && naturalDefeat.finalHits.Count > 0, "Natural defeat did not persist incoming damage and final-round history.");
|
||||
Require(!string.IsNullOrWhiteSpace(naturalDefeat.cause)
|
||||
&& naturalDefeat.cause.IndexOf("Uptime reached 0", StringComparison.OrdinalIgnoreCase) < 0
|
||||
&& naturalDefeat.cause.IndexOf("Unattributed", StringComparison.OrdinalIgnoreCase) < 0
|
||||
&& naturalDefeat.cause.IndexOf("Shutdown", StringComparison.OrdinalIgnoreCase) < 0,
|
||||
"Natural defeat did not identify the killing action: " + naturalDefeat.cause);
|
||||
capture = CapturePanel(combat.GetComponent<UIDocument>(), "natural-defeat");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
// Exercise scene-unload settlement after both retry modes before reporting PASS.
|
||||
SceneLoader.LoadMainMenu(combat.GetComponent<UIDocument>().rootVisualElement);
|
||||
while (FindFirstObjectByType<MainMenuController>() == null) yield return null;
|
||||
saved = new SaveService().Load();
|
||||
Require(saved.bandwidthBalance == reward && saved.recentRuns.Count == 3 && saved.activeRun == null,
|
||||
"Retry settlement duplicated rewards/history or resurrected the consumed checkpoint.");
|
||||
}
|
||||
|
||||
private IEnumerator TutorialScenario()
|
||||
{
|
||||
var save = new SaveService();
|
||||
var initial = save.Load();
|
||||
Require(TutorialCampaign.Required(initial), "Starter did not enroll in required training.");
|
||||
CombatManager combat = null;
|
||||
while (combat == null || combat.CurrentPhase != TurnPhase.Execute)
|
||||
{ yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
||||
Require(combat.RunConfig.IsTutorial, "Fresh starter bypassed training.");
|
||||
var view = FindFirstObjectByType<CombatSceneController>();
|
||||
var flow = Field<TutorialFlow>(view, "_tutorial");
|
||||
var document = view.GetComponent<UIDocument>();
|
||||
var capture = CapturePanel(document, "tutorial-intro");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
int actions = 0;
|
||||
bool resumed = false;
|
||||
var capturedSteps = new System.Collections.Generic.HashSet<string>();
|
||||
while (TutorialCampaign.Required(save.Load()))
|
||||
{
|
||||
_stage = "training wave " + flow.Lesson + " / " + flow.Guide.Step?.Id;
|
||||
Require(!combat.RunLost, "Training bot lost: " + _stage);
|
||||
if (flow.Guide.Active)
|
||||
{
|
||||
if (!combat.TutorialInputReady) { yield return null; continue; }
|
||||
var step = flow.Guide.Step;
|
||||
if (capturedSteps.Add(flow.Lesson + step.Id) && step.Id is "select-attack" or "target-zombie" or "pending-revival" or "revived" or "queued-haskell")
|
||||
{
|
||||
capture = CapturePanel(document, "tutorial-" + step.Id);
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
}
|
||||
var root = document.rootVisualElement;
|
||||
if (flow.Reading)
|
||||
{
|
||||
var before = combat.CurrentPhase; combat.EndPlayerTurn();
|
||||
Require(combat.CurrentPhase == before, "Reading allowed combat input.");
|
||||
Submit(root.Q<Button>("TutorialNext"));
|
||||
}
|
||||
else if (step.Action is TutorialAction.SelectCard or TutorialAction.PlayShield)
|
||||
{
|
||||
int cycles = combat.PlayerState.Cycles;
|
||||
var button = root.Query<Button>(className: "hand-card").ToList().FirstOrDefault(b => b.userData == flow.Guide.Card);
|
||||
Require(button != null && button.enabledInHierarchy, "Guided card unavailable: " + step.Id);
|
||||
Submit(button);
|
||||
if (combat.PendingTargetCard != null) Require(combat.PlayerState.Cycles == cycles, "Selection spent Cycles before targeting.");
|
||||
}
|
||||
else if (step.Action == TutorialAction.TargetEnemy)
|
||||
{
|
||||
var button = root.Query<Button>(className: "enemy-card").ToList().FirstOrDefault(b => b.userData == flow.Guide.Enemy);
|
||||
Require(button != null && button.enabledInHierarchy, "Guided target unavailable: " + step.Id);
|
||||
Submit(button);
|
||||
}
|
||||
else if (step.Action == TutorialAction.EndTurn)
|
||||
Submit(root.Q<Button>("TutorialEndTurn"));
|
||||
}
|
||||
else if (combat.AwaitingWaveContinue)
|
||||
{
|
||||
Require(combat.Enemies.All(enemy => enemy.State.IsDefeated && !enemy.PendingRevive), "Shop opened with surviving enemies.");
|
||||
var root = document.rootVisualElement;
|
||||
var shopNext = root.Q<Button>("TutorialShopNext");
|
||||
var buy = root.Q<Button>("TutorialBuy");
|
||||
if (shopNext != null) Submit(shopNext);
|
||||
else if (buy?.enabledSelf == true)
|
||||
{
|
||||
capture = CapturePanel(document, "tutorial-shop");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
Submit(buy);
|
||||
}
|
||||
else
|
||||
{
|
||||
string runId = FindFirstObjectByType<RunManager>().RunId;
|
||||
int uptime = combat.PlayerState.CurrentUptime;
|
||||
var next = root.Q<Button>("TutorialContinue");
|
||||
Require(next != null && next.enabledSelf, "Tutorial progression blocked.");
|
||||
Submit(next);
|
||||
if (!resumed && save.Load().tutorialCheckpoint != null)
|
||||
{
|
||||
resumed = true;
|
||||
Require(save.Load().tutorialCheckpoint.offers.Any(offer => offer.sold), "Shop purchase was not saved.");
|
||||
SceneLoader.LoadMainMenu(document.rootVisualElement);
|
||||
while (FindFirstObjectByType<MainMenuController>() == null) yield return null;
|
||||
combat = null;
|
||||
while (combat == null || combat.CurrentPhase != TurnPhase.Execute)
|
||||
{ yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
||||
view = FindFirstObjectByType<CombatSceneController>();
|
||||
document = view.GetComponent<UIDocument>(); flow = Field<TutorialFlow>(view, "_tutorial");
|
||||
Require(flow.Lesson == 2 && flow.Reading && FindFirstObjectByType<RunManager>().RunId == runId,
|
||||
"Restart did not resume the same run at wave two.");
|
||||
Require(combat.PlayerState.CurrentUptime == uptime, "Resume reset remaining Uptime.");
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (combat.CanSurrenderRun)
|
||||
{
|
||||
int target = -1;
|
||||
for (int i = 0; i < combat.Enemies.Count; i++)
|
||||
if (!combat.Enemies[i].State.IsDefeated && !combat.Enemies[i].PendingRevive
|
||||
&& (target < 0 || combat.Enemies[i].CurrentUptime < combat.Enemies[target].CurrentUptime)) target = i;
|
||||
if (target >= 0) combat.SelectEnemy(target);
|
||||
var card = combat.HandController.Cards.Where(card => !card.Definition.IsToken && !card.IsBroken && !card.IsLocked
|
||||
&& combat.GetDisplayedPlayCost(card) <= combat.PlayerState.Cycles)
|
||||
.OrderByDescending(card =>
|
||||
{
|
||||
var p = CardPreviewService.Build(combat, card);
|
||||
return (p.MinimumDamage + p.MaximumDamage + p.Shield + p.Heal + 1f) / (p.Cost + 1);
|
||||
}).FirstOrDefault();
|
||||
if (card == null || combat.CardsPlayedThisRound >= 64 || !combat.PlayCard(card)) combat.EndPlayerTurn();
|
||||
}
|
||||
Require(++actions < 1500, "Tutorial exceeded action budget: " + _stage);
|
||||
yield return null;
|
||||
}
|
||||
while (FindFirstObjectByType<MainMenuController>() == null) yield return null;
|
||||
var final = save.Load();
|
||||
Require(final.recentRuns.Count == 0 && final.activeRun == null && final.tutorialCheckpoint == null && final.tutorialRewardClaimed
|
||||
&& final.bandwidthBalance == initial.bandwidthBalance + TutorialCampaign.BandwidthReward
|
||||
&& final.entropyBalance == initial.entropyBalance + TutorialCampaign.EntropyReward
|
||||
&& final.lastRunLoadout.cardIds.Count == initial.lastRunLoadout.cardIds.Count,
|
||||
"Training rewards or isolation are incorrect.");
|
||||
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-tutorial-smoke"))
|
||||
{
|
||||
var menu = FindFirstObjectByType<MainMenuController>();
|
||||
ConfigureMenu(menu); Call(menu, "BootSelectedPackage");
|
||||
combat = null;
|
||||
while (combat == null || !combat.CanSurrenderRun) { yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
||||
view = FindFirstObjectByType<CombatSceneController>(); document = view.GetComponent<UIDocument>();
|
||||
Require(!combat.RunConfig.IsTutorial && document.rootVisualElement.Q("EncounterBrief").resolvedStyle.display == DisplayStyle.None
|
||||
&& !Field<FirstBattleGuide>(view, "_firstBattleGuide").Visible, "Normal run still has automatic instructional text.");
|
||||
capture = CapturePanel(document, "normal-run-clean");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
Require(save.Load().bandwidthBalance == final.bandwidthBalance && save.Load().entropyBalance == final.entropyBalance,
|
||||
"Scene change paid the tutorial reward again.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void OpenRunArchive(VisualElement root)
|
||||
{
|
||||
var commandInput = root.Q<TextField>("CommandInput");
|
||||
Require(commandInput != null && commandInput.enabledInHierarchy, "Main menu command prompt is unavailable.");
|
||||
commandInput.value = "history --runs";
|
||||
using var enter = KeyDownEvent.GetPooled('\n', KeyCode.Return, EventModifiers.None);
|
||||
enter.target = commandInput;
|
||||
commandInput.SendEvent(enter);
|
||||
}
|
||||
|
||||
private IEnumerator CampaignScenario(CombatManager combat, CombatSceneController view)
|
||||
{
|
||||
var run = combat.GetComponent<RunManager>();
|
||||
var document = view.GetComponent<UIDocument>();
|
||||
int actions = 0;
|
||||
bool capturedBoss = false;
|
||||
bool capturedPreview = false;
|
||||
while (!run.CampaignChoicePending && !combat.RunFinished)
|
||||
{
|
||||
_stage = "campaign wave " + run.CurrentWaveNumber;
|
||||
if (combat.AwaitingWaveContinue)
|
||||
{
|
||||
foreach (var offer in run.RepositoryOffers.Where(offer => !offer.Sold)
|
||||
.OrderByDescending(offer => offer.Kind == RepositoryOfferKind.StatUpgrade && offer.StatUpgradeKind == RunStatUpgradeKind.Heal
|
||||
&& combat.PlayerState.CurrentUptime < combat.PlayerState.MaxUptime / 2 ? 100
|
||||
: offer.Kind == RepositoryOfferKind.CardUpgrade && offer.CardUpgradeKind == CardUpgradeKind.DrawRider ? 90
|
||||
: offer.Kind == RepositoryOfferKind.CardUpgrade ? 80 : 10).ToArray())
|
||||
if (offer.Price <= run.Bits) run.BuyOffer(offer, combat.PlayerState);
|
||||
Submit(document.rootVisualElement.Q<Button>("RouteRepair"));
|
||||
combat.ContinueToNextWave();
|
||||
}
|
||||
else if (combat.CanSurrenderRun)
|
||||
{
|
||||
if (!capturedPreview && combat.InterpreterQueue.Count > 0)
|
||||
{
|
||||
capturedPreview = true;
|
||||
var preview = document.rootVisualElement.Q<Foldout>("ExecutionPreview");
|
||||
preview.value = true;
|
||||
var capture = CapturePanel(document, "execution-preview");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
preview.value = false;
|
||||
}
|
||||
if (run.CurrentWaveNumber == RunJourney.BossWave && !capturedBoss)
|
||||
{
|
||||
capturedBoss = true;
|
||||
Require(combat.Enemies.Any(enemy => enemy.Archetype.Tier == EnemyTier.Boss), "Boss encounter did not spawn.");
|
||||
var capture = CapturePanel(document, "boss-encounter");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
}
|
||||
int target = -1;
|
||||
for (int i = 0; i < combat.Enemies.Count; i++)
|
||||
if (!combat.Enemies[i].State.IsDefeated && (target < 0 || combat.Enemies[i].CurrentUptime < combat.Enemies[target].CurrentUptime)) target = i;
|
||||
if (target >= 0) combat.SelectEnemy(target);
|
||||
var card = combat.HandController.Cards.Where(card => card.Definition != null && !card.Definition.IsToken
|
||||
&& !card.IsBroken && !card.IsLocked && combat.GetDisplayedPlayCost(card) <= combat.PlayerState.Cycles)
|
||||
.OrderByDescending(card =>
|
||||
{
|
||||
var preview = CardPreviewService.Build(combat, card);
|
||||
return ((preview.MinimumDamage + preview.MaximumDamage) * 0.5 + preview.Shield * 0.7 + preview.Heal * 1.5 + 1) / (preview.Cost + 1);
|
||||
}).FirstOrDefault();
|
||||
if (card == null || combat.CardsPlayedThisRound >= 64 || !combat.PlayCard(card)) combat.EndPlayerTurn();
|
||||
Require(++actions < 2000, "Campaign bot exceeded action budget.");
|
||||
}
|
||||
yield return null;
|
||||
}
|
||||
Require(!combat.RunLost && run.WavesCleared == 5 && capturedBoss, "Seeded campaign bot did not clear the boss.");
|
||||
_stage = "campaign milestone";
|
||||
var milestone = CapturePanel(document, "campaign-milestone");
|
||||
while (milestone.MoveNext()) yield return milestone.Current;
|
||||
int expectedBandwidth = run.AccruedBandwidth + TutorialCampaign.BandwidthReward;
|
||||
int expectedEntropy = run.AccruedEntropy + TutorialCampaign.EntropyReward;
|
||||
string runId = run.RunId;
|
||||
bool endless = Environment.GetCommandLineArgs().Contains("--kernel-panic-endless-smoke");
|
||||
if (endless)
|
||||
{
|
||||
Submit(document.rootVisualElement.Q<Button>("ContinueEndlessButton"));
|
||||
while (!combat.CanSurrenderRun) yield return null;
|
||||
Require(run.Journey.endless && run.CurrentWaveNumber == 6 && run.RunId == runId && !run.RewardsSettled,
|
||||
"Endless continuation reset the build/run or settled rewards early.");
|
||||
var capture = CapturePanel(document, "endless-encounter");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
combat.SurrenderRun();
|
||||
}
|
||||
else Submit(document.rootVisualElement.Q<Button>("FinishCampaignButton"));
|
||||
yield return null;
|
||||
var saved = new SaveService().Load();
|
||||
Require(run.RewardsSettled && saved.recentRuns.Count == 1 && saved.recentRuns[0].victory == !endless,
|
||||
"Campaign outcome did not settle a single correct history record.");
|
||||
Require(saved.bandwidthBalance == expectedBandwidth && saved.entropyBalance == expectedEntropy, "Campaign reward settlement mismatch.");
|
||||
var report = CapturePanel(document, "campaign-report");
|
||||
while (report.MoveNext()) yield return report.Current;
|
||||
SceneLoader.LoadMainMenu(document.rootVisualElement);
|
||||
while (FindFirstObjectByType<MainMenuController>() == null) yield return null;
|
||||
saved = new SaveService().Load();
|
||||
Require(saved.recentRuns.Count == 1 && saved.bandwidthBalance == expectedBandwidth, "Scene unload duplicated campaign rewards.");
|
||||
_campaignSuccess = "PASS: real five-wave campaign, repair route, purchases, boss, "
|
||||
+ (endless ? "endless continuation, surrender" : "victory") + ", saved rewards/history exactly once, menu return.";
|
||||
}
|
||||
|
||||
private static void RequireArchiveVisible(VisualElement root)
|
||||
{
|
||||
var archive = root.Q("RunArchivePanel");
|
||||
Require(archive != null && archive.resolvedStyle.display != DisplayStyle.None
|
||||
&& root.Q("MainMenuPanel").resolvedStyle.display == DisplayStyle.None, "Run archive did not become the active screen.");
|
||||
Require(archive.Q<Button>("RetrySameSeedButton") != null && archive.Q<Button>("RetryNewSeedButton") != null
|
||||
&& archive.Q<Button>("RecentRunsButton") != null, "Run archive does not contain all three run actions.");
|
||||
}
|
||||
|
||||
private static void ConfigureMenu(MainMenuController menu)
|
||||
{
|
||||
Call(menu, "HandleStartRunClicked");
|
||||
var distro = Field<DistroDatabase>(menu, "distroDatabase").FindById("ubuntu");
|
||||
var loadout = Field<CardLoadout>(menu, "_cardLoadout");
|
||||
foreach (var card in distro.ExclusiveCards.Take(4))
|
||||
if (!loadout.GetEquippedCardIds(distro.Id).Contains(card.Id)) Call(menu, "ToggleCardInSelectedLoadout", distro, card);
|
||||
var languages = Field<System.Collections.Generic.List<Language>>(menu, "_selectedRunLanguages");
|
||||
if (!languages.Contains(Language.Python)) Call(menu, "ToggleRunLanguage", Language.Python);
|
||||
if (!languages.Contains(Language.JavaScript)) Call(menu, "ToggleRunLanguage", Language.JavaScript);
|
||||
var root = menu.GetComponent<UIDocument>().rootVisualElement;
|
||||
var seed = root.Q<TextField>("RunSeedInput");
|
||||
Require(seed != null, "Seed input is missing.");
|
||||
seed.value = "12345";
|
||||
Require(root.Q<Button>("BootRunButton").enabledSelf, "Configured boot button is disabled.");
|
||||
}
|
||||
|
||||
private IEnumerator InspectPiles(CombatSceneController view, CombatManager combat)
|
||||
{
|
||||
var root = view.GetComponent<UIDocument>().rootVisualElement;
|
||||
var originalOrder = combat.DeckController.DrawPile.ToArray();
|
||||
Require(originalOrder.Length > 0, "Smoke setup needs a non-empty draw pile.");
|
||||
Submit(root.Q<Button>("InspectPile_draw"));
|
||||
yield return null;
|
||||
var inspector = root.Q("CardPileInspector");
|
||||
Require(inspector != null, "Draw pile inspector did not open.");
|
||||
var overlay = inspector.parent;
|
||||
Require(overlay.ClassListContains("pile-overlay"), "Pile inspector did not use its centered overlay layout.");
|
||||
var grid = inspector.Q("PileCardGrid");
|
||||
Require(grid != null, "Pile inspector card grid is missing.");
|
||||
var names = grid.Query<VisualElement>("PileCard").ToList()
|
||||
.Select(card => card.Q<Label>(className: "software-name").text).ToArray();
|
||||
Require(names.SequenceEqual(CardPileView.GroupIdenticalCopies(originalOrder, combat.GetPileCostDetails).Select(group => group[0].Definition.DisplayName)),
|
||||
"Draw pile inspector did not present an alphabetically sorted inventory.");
|
||||
Require(grid.Query<VisualElement>("PileCard").ToList().Sum(face => (int)face.userData) == originalOrder.Length,
|
||||
"Grouping did not preserve the actual card count.");
|
||||
inspector.Q<Toggle>("PileGroupCopies").value = false;
|
||||
var search = inspector.Q<TextField>("PileSearch");
|
||||
var clear = inspector.Q<Button>("ClearPileSearch");
|
||||
Require(clear != null && !clear.enabledSelf, "Empty pile search should have a disabled Clear button.");
|
||||
search.value = "__no_matching_card__";
|
||||
Require(grid.Query<VisualElement>("PileCard").ToList().Count == 0, "Pile search did not filter cards.");
|
||||
Require(grid.Q<Label>("PileEmptyState")?.text.StartsWith("No matching cards.", StringComparison.Ordinal) == true,
|
||||
"Nonmatching pile search did not explain how to recover.");
|
||||
Submit(clear);
|
||||
for (int frame = 0; frame < 3; frame++) yield return null;
|
||||
Require(search.value.Length == 0 && grid.Query<VisualElement>("PileCard").ToList().Count == originalOrder.Length
|
||||
&& grid.Q("PileEmptyState") == null && !clear.enabledSelf, "Clearing pile search did not restore every card.");
|
||||
var focused = root.focusController.focusedElement as VisualElement;
|
||||
Require(focused == search || (focused != null && search.Contains(focused)), "Clearing pile search did not restore search focus.");
|
||||
search.value = originalOrder[0].Definition.Id;
|
||||
Require(grid.Query<VisualElement>("PileCard").ToList().Count > 0, "Pile search could not find an existing card.");
|
||||
Submit(inspector.Q<Button>("PileTab_discard"));
|
||||
Require(search.value.Length == 0 && inspector.Q<Label>("PileEmptyState")?.text == "This pile is empty.",
|
||||
"Discard tab did not retain its own empty search and pile.");
|
||||
Submit(inspector.Q<Button>("PileTab_exhaust"));
|
||||
Require(inspector.Q<Button>("PileTab_exhaust").ClassListContains("selected"), "Exhaust tab did not become selected.");
|
||||
Submit(inspector.Q<Button>("PileTab_draw"));
|
||||
Require(search.value == originalOrder[0].Definition.Id && !inspector.Q<Toggle>("PileGroupCopies").value,
|
||||
"Returning to Draw did not preserve its search and grouping preference.");
|
||||
Submit(clear);
|
||||
inspector.Q<Toggle>("PileGroupCopies").value = true;
|
||||
var costDetails = grid.Q<Foldout>("PileCostDetails");
|
||||
Require(costDetails != null, "Current cost explanation is missing.");
|
||||
costDetails.value = true;
|
||||
var languageFilter = inspector.Q<DropdownField>("PileLanguageFilter");
|
||||
var costFilter = inspector.Q<DropdownField>("PileCostFilter");
|
||||
languageFilter.Focus();
|
||||
yield return null;
|
||||
using (var next = NavigationMoveEvent.GetPooled(NavigationMoveEvent.Direction.Next))
|
||||
{
|
||||
next.target = languageFilter;
|
||||
languageFilter.SendEvent(next);
|
||||
}
|
||||
yield return null;
|
||||
var filterFocus = root.focusController.focusedElement as VisualElement;
|
||||
Require(filterFocus == costFilter || costFilter.Contains(filterFocus), "Runtime modal navigation skipped the cost filter.");
|
||||
var capture = CapturePanel(view.GetComponent<UIDocument>(), "pile-inspector");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
Require(Mathf.Abs(inspector.worldBound.center.x - overlay.worldBound.center.x) <= 2
|
||||
&& Mathf.Abs(inspector.worldBound.center.y - overlay.worldBound.center.y) <= 2,
|
||||
"Pile inspector is not centered in the combat overlay.");
|
||||
var faces = grid.Query<VisualElement>("PileCard").ToList();
|
||||
if (Screen.width >= 1200)
|
||||
Require(faces.Count >= 2 && Mathf.Abs(faces[0].worldBound.yMin - faces[1].worldBound.yMin) <= 2
|
||||
&& faces[1].worldBound.xMin > faces[0].worldBound.xMax,
|
||||
"Wide-screen pile inspector did not display multiple card columns with a gutter.");
|
||||
Submit(inspector.Q<Button>("ClosePileInspector"));
|
||||
Require(root.Q("CardPileInspector") == null && !overlay.ClassListContains("pile-overlay")
|
||||
&& combat.DeckController.DrawPile.SequenceEqual(originalOrder),
|
||||
"Inspecting or closing the draw pile changed its live order.");
|
||||
foreach (string pile in new[] { "discard", "exhaust" })
|
||||
{
|
||||
Submit(root.Q<Button>("InspectPile_" + pile));
|
||||
yield return null;
|
||||
inspector = root.Q("CardPileInspector");
|
||||
Require(inspector != null, pile + " inspector did not open.");
|
||||
Require(inspector.Q("PileCardGrid").Query<VisualElement>("PileCard").ToList().Count == 0
|
||||
&& inspector.Q<Label>("PileEmptyState")?.text == "This pile is empty.",
|
||||
pile + " did not display its empty state before any cards were played.");
|
||||
capture = CapturePanel(view.GetComponent<UIDocument>(), "pile-" + pile + "-empty");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
Submit(inspector.Q<Button>("ClosePileInspector"));
|
||||
Require(root.Q("CardPileInspector") == null && !overlay.ClassListContains("pile-overlay"),
|
||||
"Closing the " + pile + " inspector left its modal layout active.");
|
||||
}
|
||||
Require(combat.DeckController.DrawPile.SequenceEqual(originalOrder), "Pile inspection changed the original draw order.");
|
||||
}
|
||||
|
||||
private static string BuildSignature(RunConfig config) => $"{config.Distro.Id}|{config.DistroVersion}|{config.PrimaryLanguage}|{config.SecondaryLanguage}|"
|
||||
+ string.Join(",", config.StartingDeck.Select(card => card.Id)) + "|"
|
||||
+ string.Join(",", config.EquippedPackages.Select(package => package.Definition.Id + ":" + package.UpgradeLevel));
|
||||
|
||||
private static string DeckSignature(RunManager run) => string.Join("|", run.RunDeck.Select(card =>
|
||||
$"{card.InstanceId}:{card.Definition.Id}:{card.PermanentCostDelta}:{card.MagnitudeBonus}:{card.DrawRider}:{card.UpgradeLevel}"));
|
||||
|
||||
private static string OfferSignature(RunManager run) => string.Join("|", run.RepositoryOffers.Select(offer =>
|
||||
$"{offer.Kind}:{offer.CardDefinition?.Id}:{offer.TargetCard?.InstanceId}:{offer.CardUpgradeKind}:{offer.StatUpgradeKind}:{offer.Price}:{offer.Sold}"));
|
||||
|
||||
private static void Submit(Button button)
|
||||
{
|
||||
Require(button != null && button.enabledInHierarchy, "Expected enabled UI command is unavailable.");
|
||||
using var submit = NavigationSubmitEvent.GetPooled();
|
||||
submit.target = button;
|
||||
button.SendEvent(submit);
|
||||
}
|
||||
|
||||
private IEnumerator CapturePanel(UIDocument document, string name)
|
||||
{
|
||||
// A hidden Windows swap chain can return black screenshots. Render the actual
|
||||
// runtime panel to a texture for deterministic visual inspection of the same UI.
|
||||
var settings = document.panelSettings;
|
||||
var previous = settings.targetTexture;
|
||||
var target = new RenderTexture(Screen.width, Screen.height, 24);
|
||||
target.Create();
|
||||
settings.targetTexture = target;
|
||||
try
|
||||
{
|
||||
for (int frame = 0; frame < 8; frame++) yield return null;
|
||||
var root = document.rootVisualElement;
|
||||
File.WriteAllText(Path.Combine(_output, name + "-panel.txt"),
|
||||
$"panel={root.panel != null}; bounds={root.worldBound}; opacity={root.resolvedStyle.opacity}; display={root.resolvedStyle.display}; visibility={root.resolvedStyle.visibility}; children={root.childCount}; renderedFrames={Time.renderedFrameCount}; graphics={SystemInfo.graphicsDeviceType}; focused={Application.isFocused}");
|
||||
var previousActive = RenderTexture.active;
|
||||
var pixels = new Texture2D(target.width, target.height, TextureFormat.RGB24, false);
|
||||
try
|
||||
{
|
||||
RenderTexture.active = target;
|
||||
pixels.ReadPixels(new Rect(0, 0, target.width, target.height), 0, 0);
|
||||
pixels.Apply();
|
||||
File.WriteAllBytes(Path.Combine(_output, name + ".png"), pixels.EncodeToPNG());
|
||||
Require(pixels.GetPixels32().Any(pixel => pixel.r > 20 || pixel.g > 20 || pixel.b > 20), "Runtime panel rendered an empty image: " + name);
|
||||
}
|
||||
finally { RenderTexture.active = previousActive; Destroy(pixels); }
|
||||
}
|
||||
finally { settings.targetTexture = previous; target.Release(); Destroy(target); }
|
||||
}
|
||||
|
||||
private static T Field<T>(object owner, string name) => (T)owner.GetType().GetField(name, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(owner);
|
||||
private static void Call(object owner, string name, params object[] args) => owner.GetType().GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance).Invoke(owner, args);
|
||||
private static void Require(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d7286c6e49724ab183243caac5f05945
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
|
||||
namespace KernelPanic.Run
|
||||
{
|
||||
/// <summary>Retains System.Random's existing sequence, with a portable seed/cursor checkpoint.</summary>
|
||||
public sealed class ReplayableRandom
|
||||
{
|
||||
private Random _random;
|
||||
public int Seed { get; }
|
||||
public int Draws { get; private set; }
|
||||
|
||||
public ReplayableRandom(int seed, int draws = 0)
|
||||
{
|
||||
if (draws < 0 || draws > 10000000) throw new ArgumentOutOfRangeException(nameof(draws));
|
||||
Seed = seed;
|
||||
_random = new Random(seed);
|
||||
for (int i = 0; i < draws; i++) _random.Next();
|
||||
Draws = draws;
|
||||
}
|
||||
|
||||
public int Next(int min, int max)
|
||||
{
|
||||
// Large-range Next consumes two samples; combat/shop ranges use one.
|
||||
int value = _random.Next(min, max);
|
||||
Draws += (long)max - min > int.MaxValue ? 2 : 1;
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 41d0b7e13bb879d42944d340610f5b69
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b1200000000000000000000000000001
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a06eada6fbafd6e44ae1d21238a64750
|
||||
@@ -0,0 +1,224 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using UnityEngine;
|
||||
|
||||
namespace KernelPanic.Run
|
||||
{
|
||||
/// <summary>A repository-boundary snapshot, never an in-flight combat serialization.</summary>
|
||||
[Serializable]
|
||||
public sealed class RunCheckpoint
|
||||
{
|
||||
public int version = 1;
|
||||
public string runId;
|
||||
public string savedUtc;
|
||||
public string distroId;
|
||||
public int distroVersion;
|
||||
public Language primaryLanguage;
|
||||
public Language secondaryLanguage;
|
||||
public int seed;
|
||||
public List<string> startingCards = new();
|
||||
public List<RunBuildPackageSaveEntry> packages = new();
|
||||
public List<CheckpointCard> deck = new();
|
||||
public List<CheckpointOffer> offers = new();
|
||||
public List<string> soldKeys = new();
|
||||
public int wave;
|
||||
public int wavesCleared;
|
||||
public int bits;
|
||||
public int bandwidth;
|
||||
public int entropy;
|
||||
public int maxUptimeBonus;
|
||||
public int maxCyclesBonus;
|
||||
public int ramBonus;
|
||||
public int rerolls;
|
||||
public int shopRandomDraws;
|
||||
public CheckpointCombat combat;
|
||||
public RunJourney journey;
|
||||
|
||||
public ResolvedRunCheckpoint Resolve(DistroDatabase distros, CardDatabase cards,
|
||||
LanguageDeckDatabase languages, PackageDatabase packageDatabase)
|
||||
{
|
||||
Require(version == 1 || version == 2, "This checkpoint needs a different game version.");
|
||||
Require(version < 2 || journey != null, "Missing saved route decisions.");
|
||||
journey?.Validate(wave);
|
||||
Require(Guid.TryParseExact(runId, "N", out _), "Invalid run identity.");
|
||||
Require(wave >= 2 && wave <= 100000 && wavesCleared == wave - 1, "Invalid checkpoint wave.");
|
||||
Require(bits >= 0 && bandwidth >= 0 && entropy >= 0 && rerolls >= 0, "Invalid checkpoint balances.");
|
||||
Require(maxUptimeBonus >= 0 && maxCyclesBonus >= 0 && ramBonus >= 0, "Invalid run upgrades.");
|
||||
Require(shopRandomDraws >= 0 && shopRandomDraws <= 10000000, "Invalid shop random cursor.");
|
||||
Require(Enum.IsDefined(typeof(Language), primaryLanguage) && Enum.IsDefined(typeof(Language), secondaryLanguage)
|
||||
&& primaryLanguage != secondaryLanguage, "Invalid checkpoint languages.");
|
||||
Require(distroVersion >= 1 && distroVersion <= GachaTuning.MaxVersion, "Invalid distro version.");
|
||||
DistroDefinition distro = distros == null ? null : distros.FindById(distroId);
|
||||
Require(distro != null, $"Checkpoint distro '{distroId}' is unavailable. Save was left unchanged.");
|
||||
Require(deck != null && deck.Count > 0 && deck.Count <= 10000 && startingCards != null
|
||||
&& startingCards.Count > 0 && startingCards.Count <= 10000, "Invalid checkpoint deck.");
|
||||
Require(packages != null && packages.Count <= 3 && offers != null && offers.Count <= 100
|
||||
&& soldKeys != null && soldKeys.Count <= 10000, "Invalid repository snapshot.");
|
||||
Require(combat != null, "Missing combat checkpoint.");
|
||||
combat.Validate();
|
||||
|
||||
CardDefinition FindCard(string id)
|
||||
{
|
||||
CardDefinition result = cards == null ? null : cards.FindById(id);
|
||||
result ??= distro.ExclusiveCards.FirstOrDefault(card => card != null && string.Equals(card.Id, id, StringComparison.OrdinalIgnoreCase));
|
||||
foreach (Language language in new[] { primaryLanguage, secondaryLanguage })
|
||||
{
|
||||
LanguageDeckDefinition languageDeck = languages == null ? null : languages.FindByLanguage(language);
|
||||
if (result == null && languageDeck != null)
|
||||
result = languageDeck.Entries.Select(entry => entry.Card).FirstOrDefault(card => card != null && string.Equals(card.Id, id, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
Require(result != null, $"Checkpoint card '{id}' is unavailable. Save was left unchanged.");
|
||||
return result;
|
||||
}
|
||||
|
||||
List<PackageInstance> equipped = new();
|
||||
HashSet<PackageSlot> slots = new();
|
||||
foreach (RunBuildPackageSaveEntry entry in packages)
|
||||
{
|
||||
PackageDefinition package = entry == null || packageDatabase == null ? null : packageDatabase.FindById(entry.packageId);
|
||||
Require(package != null && package.Slot == entry.slot && slots.Add(entry.slot), "A checkpoint package is missing or invalid.");
|
||||
Require(entry.upgradeLevel >= 0 && entry.upgradeLevel <= 5, "Invalid package level.");
|
||||
equipped.Add(new PackageInstance(package, entry.upgradeLevel));
|
||||
}
|
||||
var config = new RunConfig(distro, primaryLanguage, secondaryLanguage, startingCards.Select(FindCard).ToList(), equipped, seed, distroVersion);
|
||||
List<CardInstance> restoredDeck = deck.Select(entry => RestoreCard(entry, FindCard)).ToList();
|
||||
Require(restoredDeck.Select(card => card.InstanceId).Distinct().Count() == restoredDeck.Count, "Duplicate run card identity.");
|
||||
List<RepositoryOffer> restoredOffers = new();
|
||||
foreach (CheckpointOffer entry in offers)
|
||||
{
|
||||
Require(entry != null && entry.price >= 0 && Enum.IsDefined(typeof(RepositoryOfferKind), entry.kind), "Invalid repository offer.");
|
||||
RepositoryOffer offer;
|
||||
switch (entry.kind)
|
||||
{
|
||||
case RepositoryOfferKind.NewCard:
|
||||
offer = RepositoryOffer.NewCard(FindCard(entry.cardId), entry.price);
|
||||
break;
|
||||
case RepositoryOfferKind.CardUpgrade:
|
||||
Require(Enum.IsDefined(typeof(CardUpgradeKind), entry.cardUpgrade), "Invalid card upgrade.");
|
||||
CardInstance target = restoredDeck.FirstOrDefault(card => card.InstanceId == entry.targetId)
|
||||
?? RestoreCard(entry.detachedTarget, FindCard);
|
||||
offer = RepositoryOffer.CardUpgrade(target, entry.cardUpgrade, entry.price);
|
||||
break;
|
||||
default:
|
||||
Require(Enum.IsDefined(typeof(RunStatUpgradeKind), entry.statUpgrade), "Invalid stat upgrade.");
|
||||
offer = RepositoryOffer.StatUpgrade(entry.statUpgrade, entry.price);
|
||||
break;
|
||||
}
|
||||
if (entry.sold) offer.MarkSold();
|
||||
restoredOffers.Add(offer);
|
||||
}
|
||||
return new ResolvedRunCheckpoint(this, config, restoredDeck, restoredOffers);
|
||||
}
|
||||
|
||||
private static CardInstance RestoreCard(CheckpointCard entry, Func<string, CardDefinition> find)
|
||||
{
|
||||
Require(entry != null && Guid.TryParseExact(entry.instanceId, "N", out _), "Invalid run card.");
|
||||
Require(entry.costDelta <= 0 && entry.magnitude >= 0 && entry.drawRider >= 0 && entry.upgradeLevel >= 0,
|
||||
"Invalid card upgrades.");
|
||||
CardInstance card = new(find(entry.cardId));
|
||||
card.RestoreRunState(entry.instanceId, entry.costDelta, entry.magnitude, entry.drawRider, entry.upgradeLevel);
|
||||
return card;
|
||||
}
|
||||
|
||||
internal static void Require(bool valid, string message)
|
||||
{
|
||||
if (!valid) throw new InvalidDataException(message);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ResolvedRunCheckpoint
|
||||
{
|
||||
public RunCheckpoint Snapshot { get; }
|
||||
public RunConfig Config { get; }
|
||||
public IReadOnlyList<CardInstance> Deck { get; }
|
||||
public IReadOnlyList<RepositoryOffer> Offers { get; }
|
||||
internal ResolvedRunCheckpoint(RunCheckpoint snapshot, RunConfig config, List<CardInstance> deck, List<RepositoryOffer> offers)
|
||||
{ Snapshot = snapshot; Config = config; Deck = deck; Offers = offers; }
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class CheckpointCard
|
||||
{
|
||||
public string cardId, instanceId;
|
||||
public int costDelta, magnitude, drawRider, upgradeLevel;
|
||||
public static CheckpointCard Capture(CardInstance card) => new()
|
||||
{
|
||||
cardId = card.Definition.Id, instanceId = card.InstanceId, costDelta = card.PermanentCostDelta,
|
||||
magnitude = card.MagnitudeBonus, drawRider = card.DrawRider, upgradeLevel = card.UpgradeLevel
|
||||
};
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class CheckpointOffer
|
||||
{
|
||||
public RepositoryOfferKind kind;
|
||||
public string cardId, targetId;
|
||||
public CheckpointCard detachedTarget;
|
||||
public CardUpgradeKind cardUpgrade;
|
||||
public RunStatUpgradeKind statUpgrade;
|
||||
public int price;
|
||||
public bool sold;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class CheckpointCombat
|
||||
{
|
||||
public int uptime, shield, cycles;
|
||||
public int randomSeed, randomDraws;
|
||||
public bool ubuntuRefillUsed, interpreterShieldUsed, nativeDamageUsed;
|
||||
public float fedoraCrashChance;
|
||||
public int javaCardsPlayed, rawhideCharges, repeatCharges, nextTurnCycles;
|
||||
public List<CheckpointDelayedEffect> delayed = new();
|
||||
|
||||
internal void Validate()
|
||||
{
|
||||
RunCheckpoint.Require(uptime > 0 && shield >= 0 && cycles >= 0 && randomDraws >= 0 && randomDraws <= 10000000,
|
||||
"Invalid combat boundary state.");
|
||||
RunCheckpoint.Require(!float.IsNaN(fedoraCrashChance) && !float.IsInfinity(fedoraCrashChance)
|
||||
&& fedoraCrashChance >= 0 && fedoraCrashChance <= 100 && javaCardsPlayed >= 0 && rawhideCharges >= 0
|
||||
&& repeatCharges >= 0 && nextTurnCycles >= 0 && delayed != null && delayed.Count <= 10000, "Invalid carried combat effects.");
|
||||
foreach (CheckpointDelayedEffect effect in delayed)
|
||||
RunCheckpoint.Require(effect != null && (effect.kind == 0 || effect.kind == 1) && effect.rounds > 0
|
||||
&& effect.amount >= 0, "Invalid delayed effect.");
|
||||
}
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class CheckpointDelayedEffect { public int kind, amount, rounds; }
|
||||
|
||||
public static class RunCheckpointService
|
||||
{
|
||||
public static void SaveAndSuspend(SaveService saves, RunManager run, CombatManager combat)
|
||||
{
|
||||
RunCheckpoint.Require(run.CurrentConfig?.IsTutorial != true, "Training uses its separate shop checkpoint.");
|
||||
RunCheckpoint snapshot = run.CaptureCheckpoint(combat);
|
||||
SaveData data = saves.Load();
|
||||
data.activeRun = snapshot;
|
||||
saves.Save(data);
|
||||
run.MarkSuspended(); // Never suppress settlement or leave the scene on a failed save.
|
||||
}
|
||||
|
||||
public static ResolvedRunCheckpoint PrepareResume(SaveService saves, DistroDatabase distros, CardDatabase cards,
|
||||
LanguageDeckDatabase languages, PackageDatabase packages)
|
||||
{
|
||||
RunCheckpoint snapshot = saves.Load().activeRun;
|
||||
RunCheckpoint.Require(snapshot != null, "No saved run is available.");
|
||||
return snapshot.Resolve(distros, cards, languages, packages);
|
||||
}
|
||||
|
||||
public static void Consume(SaveService saves, ResolvedRunCheckpoint resume)
|
||||
{
|
||||
SaveData data = saves.Load();
|
||||
RunCheckpoint.Require(data.activeRun != null && data.activeRun.runId == resume.Snapshot.runId
|
||||
&& data.activeRun.savedUtc == resume.Snapshot.savedUtc, "The saved run changed. Return to the menu and retry.");
|
||||
data.activeRun = null;
|
||||
saves.Save(data); // Claim once before play, preventing replaying the same banked rewards.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c74add9056068a2458a5f6c4b494fc6d
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0c3d34a2ce0e53b4b8f9a77feb60fb95
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b1100000000000000000000000000002
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,32 @@
|
||||
using System;
|
||||
|
||||
namespace KernelPanic.Run
|
||||
{
|
||||
public enum WaveRoute { Repair, Challenge }
|
||||
|
||||
/// <summary>Serializable route decisions, independent of combat and repository presentation.</summary>
|
||||
[Serializable]
|
||||
public sealed class RunJourney
|
||||
{
|
||||
public const int BossWave = 5;
|
||||
public const int RepairUptime = 6;
|
||||
public const int ChallengeBits = 4;
|
||||
public bool campaign;
|
||||
public bool endless;
|
||||
public WaveRoute selectedRoute;
|
||||
public WaveRoute activeRoute;
|
||||
public string lastReward;
|
||||
|
||||
public bool AtMilestone(int wavesCleared) => campaign && !endless && wavesCleared >= BossWave;
|
||||
public static RunJourney NewCampaign() => new() { campaign = true };
|
||||
public RunJourney Copy() => (RunJourney)MemberwiseClone();
|
||||
|
||||
public void Validate(int wave)
|
||||
{
|
||||
RunCheckpoint.Require(Enum.IsDefined(typeof(WaveRoute), selectedRoute)
|
||||
&& Enum.IsDefined(typeof(WaveRoute), activeRoute), "Invalid saved route.");
|
||||
RunCheckpoint.Require(!endless || (campaign && wave > BossWave), "Invalid endless-mode checkpoint.");
|
||||
RunCheckpoint.Require(!campaign || endless || wave <= BossWave + 1, "Missing campaign completion choice.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c0a22d93857c4b64a8b4bdc1c802250a
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 234cc6c5ca577b64ea44020f5514cebe
|
||||
@@ -0,0 +1,54 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
|
||||
namespace KernelPanic.Run
|
||||
{
|
||||
public static class TutorialCampaign
|
||||
{
|
||||
public const int LessonCount = 2;
|
||||
public const int BandwidthReward = 1000;
|
||||
public const int EntropyReward = GachaService.StandardTenPullCost * GachaService.EntropyPerCommit;
|
||||
public static bool Required(SaveData save) => save != null && save.starterChosen && save.tutorialRequired;
|
||||
public static int Lesson(SaveData save) => save?.tutorialCheckpoint != null ? 2 : 1;
|
||||
|
||||
public static void Enroll(SaveData save, string distroId)
|
||||
{
|
||||
save.tutorialRequired = true; save.tutorialLesson = 1;
|
||||
save.tutorialDistroId = distroId; save.tutorialCheckpoint = null;
|
||||
}
|
||||
|
||||
// Commit balances and the claimed flag together. Re-enrollment never grants a second payout.
|
||||
public static void Complete(SaveData save)
|
||||
{
|
||||
if (!Required(save) || save.tutorialLesson != 2)
|
||||
throw new InvalidOperationException("Complete both training waves before claiming the reward.");
|
||||
if (!save.tutorialRewardClaimed)
|
||||
{
|
||||
save.bandwidthBalance = checked(Math.Max(0, save.bandwidthBalance) + BandwidthReward);
|
||||
save.entropyBalance = checked(Math.Max(0, save.entropyBalance) + EntropyReward);
|
||||
save.tutorialRewardClaimed = true;
|
||||
}
|
||||
save.tutorialRequired = false; save.tutorialCheckpoint = null;
|
||||
}
|
||||
|
||||
public static EncounterPlan Plan(int wave) => wave switch
|
||||
{
|
||||
1 => new("Targeting and revival", "", 0, "zombie_process", "orphan_process"),
|
||||
2 => new("Queue, stack and finish", "", 0, "memory_leak", "firewalld"),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(wave))
|
||||
};
|
||||
|
||||
public static RunConfig CreateConfig(DistroDefinition distro, CardDatabase cards, int lesson)
|
||||
{
|
||||
if (distro == null || cards == null) throw new InvalidOperationException("Tutorial content is unavailable.");
|
||||
_ = Plan(lesson);
|
||||
var deck = new List<CardDefinition>();
|
||||
foreach (string id in new[] { "lang_rs_unwrap", "lang_rs_fn_main", "lang_rs_borrow", "lang_py_print", "lang_hs_thunk" })
|
||||
deck.Add(cards.FindById(id) ?? throw new InvalidOperationException("Missing tutorial card: " + id));
|
||||
return RunConfig.ForTutorial(distro, deck, lesson);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cb33ab352e4340c4b362209cf671d92b
|
||||
@@ -0,0 +1,151 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
|
||||
namespace KernelPanic.Run
|
||||
{
|
||||
public enum TutorialAction { Read, SelectCard, TargetEnemy, EndTurn, PlayShield, Free }
|
||||
|
||||
public sealed class TutorialStep
|
||||
{
|
||||
public readonly string Id, Title, Copy, Anchor;
|
||||
public readonly TutorialAction Action;
|
||||
public TutorialStep(string id, string title, string copy, string anchor, TutorialAction action = TutorialAction.Read)
|
||||
{ Id = id; Title = title; Copy = copy; Anchor = anchor; Action = action; }
|
||||
}
|
||||
|
||||
/// <summary>Advances from observed combat state, never from fabricated damage or a Next button on action steps.</summary>
|
||||
public sealed class TutorialGuide
|
||||
{
|
||||
private readonly int _lesson;
|
||||
private readonly IReadOnlyList<TutorialStep> _steps;
|
||||
private bool _played, _resolved, _ended;
|
||||
public int Index { get; private set; }
|
||||
public int Count => _steps.Count;
|
||||
public TutorialStep Step => Active ? _steps[Index] : null;
|
||||
public bool Active => Index < _steps.Count;
|
||||
public bool Reading => Active && Step.Action == TutorialAction.Read;
|
||||
public CardInstance Card { get; private set; }
|
||||
public EnemyInstance Enemy { get; private set; }
|
||||
public bool CanEndTurn => !Active || Step.Action == TutorialAction.EndTurn;
|
||||
private ResolutionTrack ExpectedTrack => _lesson == 1 ? ResolutionTrack.Native
|
||||
: Step?.Id.Contains("haskell") == true ? ResolutionTrack.LazyStack : ResolutionTrack.InterpreterQueue;
|
||||
|
||||
public TutorialGuide(int lesson) { _lesson = lesson; _steps = Build(lesson); }
|
||||
|
||||
public bool AllowsCard(CardInstance card) => !Active || !Reading && ReferenceEquals(card, Card)
|
||||
&& Step.Action is TutorialAction.SelectCard or TutorialAction.TargetEnemy or TutorialAction.PlayShield;
|
||||
public bool AllowsEnemy(EnemyInstance enemy) => !Active || Step.Action == TutorialAction.TargetEnemy && ReferenceEquals(enemy, Enemy);
|
||||
|
||||
public void Acknowledge(CombatManager combat)
|
||||
{
|
||||
if (!Reading || !combat.TutorialInputReady) return;
|
||||
Advance(combat);
|
||||
}
|
||||
|
||||
public void CardPlayed(ResolutionTrack track)
|
||||
{ if (Active && !Reading && track == ExpectedTrack) _played = true; }
|
||||
public void CardResolved(ResolutionTrack track)
|
||||
{ if (Active && !Reading && track == ExpectedTrack) _resolved = true; }
|
||||
public void PhaseChanged(TurnPhase phase) { if (Active && Step.Action == TutorialAction.EndTurn && phase == TurnPhase.Interpret) _ended = true; }
|
||||
|
||||
public void Update(CombatManager combat)
|
||||
{
|
||||
if (!Active || combat.PlayerState == null) return;
|
||||
PickReferences(combat);
|
||||
switch (Step.Action)
|
||||
{
|
||||
case TutorialAction.SelectCard:
|
||||
if (Card != null && combat.PendingTargetCard == Card) Advance(combat);
|
||||
else if (_played && (Queued(combat) || _resolved))
|
||||
{ Advance(combat); if (Step?.Action == TutorialAction.TargetEnemy) Advance(combat); }
|
||||
break;
|
||||
case TutorialAction.TargetEnemy:
|
||||
if (_lesson == 1)
|
||||
{
|
||||
if (Step.Id == "target-zombie" && Enemy?.PendingRevive == true) Advance(combat);
|
||||
else if (Step.Id == "finish-zombie" && Enemy?.HasRevived == true && Enemy.State.IsDefeated) Advance(combat);
|
||||
}
|
||||
else if (_played && (Queued(combat) || _resolved)) Advance(combat);
|
||||
break;
|
||||
case TutorialAction.PlayShield:
|
||||
if (_resolved && Card != null && !combat.HandController.Cards.Contains(Card)) Advance(combat);
|
||||
break;
|
||||
case TutorialAction.EndTurn:
|
||||
if (_ended && combat.TutorialInputReady
|
||||
&& (_lesson != 1 || Enemy?.HasRevived == true)) Advance(combat);
|
||||
break;
|
||||
}
|
||||
combat.TutorialReading = Reading;
|
||||
}
|
||||
|
||||
private bool Queued(CombatManager combat) => Card != null && (combat.InterpreterQueue.Cards.Contains(Card)
|
||||
|| combat.LazyStack.Entries.Any(entry => entry.Card == Card));
|
||||
|
||||
private void Advance(CombatManager combat)
|
||||
{
|
||||
Index++;
|
||||
if (Active && Step.Action is TutorialAction.SelectCard or TutorialAction.PlayShield)
|
||||
{
|
||||
Card = null; _played = _resolved = false;
|
||||
combat.ClearTutorialSelection();
|
||||
}
|
||||
if (Active && Step.Action == TutorialAction.EndTurn) _ended = false;
|
||||
PickReferences(combat);
|
||||
combat.TutorialReading = Reading;
|
||||
}
|
||||
|
||||
private void PickReferences(CombatManager combat)
|
||||
{
|
||||
if (!Active) return;
|
||||
if (Enemy == null)
|
||||
Enemy = combat.Enemies.FirstOrDefault(enemy => _lesson != 1 || enemy.ArchetypeId == "zombie_process");
|
||||
if (Card != null || combat.HandController == null) return;
|
||||
string id = _lesson == 1 ? Step.Id is "shield-card" or "shield-result" ? "lang_rs_borrow"
|
||||
: Index >= 13 ? "lang_rs_fn_main" : "lang_rs_unwrap" : null;
|
||||
Card = combat.HandController.Cards.FirstOrDefault(card => !card.IsBroken && !card.IsLocked
|
||||
&& (id != null ? card.Definition.Id == id : card.Definition.ResolutionTrack == ExpectedTrack)
|
||||
&& combat.GetDisplayedPlayCost(card) <= combat.PlayerState.Cycles);
|
||||
}
|
||||
|
||||
public static IReadOnlyList<TutorialStep> Build(int lesson)
|
||||
{
|
||||
if (lesson == 1) return new[] {
|
||||
new TutorialStep("uptime", "This is your Uptime", "Uptime is your health. At 0, a normal run ends. This practice uses loan cards, full health and no distro passive procs; your collection is safe.", "TutorialUptime"),
|
||||
new TutorialStep("shield", "Shield protects Uptime", "Shield absorbs ordinary incoming damage first. This number shows how much protection you currently have.", "TutorialShield"),
|
||||
new TutorialStep("cycles", "Cycles pay for cards", "This is your remaining card budget. The cost in a card's upper-right corner is paid when you play it. Cycles refresh each round.", "TutorialCycles"),
|
||||
new TutorialStep("ram", "RAM is hand capacity", "This shows used RAM / capacity. Most cards use 1 RAM; Java uses 2. More Cycles do not let extra cards fit in a full hand.", "TutorialRam"),
|
||||
new TutorialStep("attack-card", "Read your attack card", "unwrap() costs Cycles and deals damage immediately: it is Native. Its rules and current estimate are printed here. Rust overkill can also grant Shield.", "card"),
|
||||
new TutorialStep("intent", "Read the enemy's intent", "This is what Zombie Process plans to do when enemies act. Check the attack range before ending your turn.", "zombie-intent"),
|
||||
new TutorialStep("select-attack", "1 / Select the attack", "Click the highlighted unwrap() card first. Selecting a targeted card asks for an enemy; it does not spend Cycles yet.", "card", TutorialAction.SelectCard),
|
||||
new TutorialStep("target-zombie", "2 / Choose the zombie", "Now click Zombie Process to dispatch your selected card. Other targets and End turn are locked for this demonstration.", "zombie", TutorialAction.TargetEnemy),
|
||||
new TutorialStep("pending-revival", "Zero Uptime, but not gone", "Your attack reduced the zombie to 0. RESTART PENDING means it will revive next round. A fresh zombie can do this once; finishing it from 30% Uptime or less reaps it instead.", "zombie"),
|
||||
new TutorialStep("end-turn", "3 / End your turn", "Click End turn (or press E). The remaining enemy acts, then the next round begins and the zombie revives. Watch its Uptime.", "TutorialEndTurn", TutorialAction.EndTurn),
|
||||
new TutorialStep("revived", "The zombie has respawned", "It has returned at half Uptime. RESTART USED means it cannot revive again. Your Cycles also refreshed for this round.", "zombie"),
|
||||
new TutorialStep("shield-card", "4 / Add protection", "Click borrow() to gain Shield now. It needs no enemy target. Any Shield you already have from Rust overkill is kept.", "card", TutorialAction.PlayShield),
|
||||
new TutorialStep("shield-result", "Your Shield increased", "That card added protection to this number. Shield is not healing: it absorbs damage before your Uptime is reduced.", "TutorialShield"),
|
||||
new TutorialStep("select-finisher", "5 / Select a finisher", "Select the highlighted fn main() card. Then you will choose the revived zombie as its target.", "card", TutorialAction.SelectCard),
|
||||
new TutorialStep("finish-zombie", "6 / Finish the revived zombie", "Click the zombie again. Its revival is already spent, so this attack can terminate it permanently.", "zombie", TutorialAction.TargetEnemy),
|
||||
new TutorialStep("piles", "Track your cards", "Played cards go to discard; an empty draw pile reshuffles discard. Exhausted cards stay out for this wave. These counters open pile inspectors.", "TutorialPiles"),
|
||||
new TutorialStep("practice", "Finish the encounter", "You have practiced targeting, revival and Shield. Clear the remaining orphan processes on your own. Use card → enemy, and End turn when needed. A zombie can leave an orphan when permanently defeated.", "enemies")
|
||||
};
|
||||
return new[] {
|
||||
new TutorialStep("leak", "A new threat: Memory Leak", "This enemy grows stronger each round and applies damage-over-time stacks. Your health and purchased upgrade carried over from wave one.", "enemy:memory_leak"),
|
||||
new TutorialStep("firewall", "A protector: firewalld", "firewalld shields itself and adjacent processes. Read its intent before choosing which enemy to remove first.", "enemy:firewalld"),
|
||||
new TutorialStep("queue-intro", "Python uses the queue", "Python waits until End turn. Its cards resolve oldest first (FIFO). Let's put a real card into this queue.", "TutorialQueue"),
|
||||
new TutorialStep("select-python", "Select the Python card", "Click the highlighted Python card. print() chooses its target when it resolves, so it does not ask you to click an enemy.", "card", TutorialAction.SelectCard),
|
||||
new TutorialStep("target-python", "Select a target", "Click the highlighted enemy to complete this play.", "enemy", TutorialAction.TargetEnemy),
|
||||
new TutorialStep("queued-python", "Python is waiting here", "Your card is now queued, not resolved. With multiple entries, the oldest would execute first.", "TutorialQueue"),
|
||||
new TutorialStep("stack-intro", "Haskell uses the stack", "Haskell waits until after Python and resolves newest first (LIFO). Each entry captures a multiplier for damage and explicit Shield.", "TutorialStack"),
|
||||
new TutorialStep("select-haskell", "Select the Haskell card", "Click the highlighted thunk() card, then select the highlighted enemy.", "card", TutorialAction.SelectCard),
|
||||
new TutorialStep("target-haskell", "Choose its target", "Click this enemy. The attack will wait on the stack rather than dealing damage immediately.", "enemy", TutorialAction.TargetEnemy),
|
||||
new TutorialStep("queued-haskell", "Both tracks are ready", "Python will resolve first, then Haskell, then surviving enemies. A defeated target can cause deferred damage to retarget.", "TutorialStack"),
|
||||
new TutorialStep("end-round", "Run the queued actions", "Click End turn (or press E). Watch the queue resolve before the stack. We will continue when the exchange finishes.", "TutorialEndTurn", TutorialAction.EndTurn),
|
||||
new TutorialStep("resolved", "The waiting cards resolved", "The scheduler has executed the deferred cards. Check enemy Uptime, Shield and intents before choosing your next move.", "enemies"),
|
||||
new TutorialStep("practice", "Clear wave two", "Finish every remaining enemy on your own. Clearing this wave completes training and unlocks 1,000 Bandwidth plus 1,000 Entropy: enough for a standard 10-pull.", "enemies")
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 42f2d4b1f5fdc5246b1f5300f014f8a5
|
||||
Reference in New Issue
Block a user