Rebalance most languages and revamp main game loop

This commit is contained in:
2026-10-25 23:50:04 +01:00
parent 53f831d91e
commit a4109f5be0
76 changed files with 4198 additions and 573 deletions
+2 -2
View File
@@ -14,7 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: fedora_dnf_update
displayName: dnf update
description: deal 9. overkill spills. costs 1 less per java card played this combat (min 0).
description: 'deal 9. overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave.'
flavorText: today everything gets newer.
language: 8
rarity: 0
@@ -22,6 +22,6 @@ MonoBehaviour:
resolutionTrack: 0
distroExclusive: 1
isToken: 0
designNotes: Java ramp card; cost reduction counts prior Java cards played this combat and clamps at 0.
designNotes: Uses shared capped Java warmup; two plays per discount and two warmup lost per wave. Final cost clamps at zero.
upgradeTarget: {fileID: 0}
effects: []
+1 -1
View File
@@ -14,7 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: lang_c_printf
displayName: printf()
description: deal 7. 50% of overkill spills per jump (rounded down). 25% segfault: uptime -3 and corrupt a random card in hand. then repair up to 1 corrupted card in your active deck.
description: deal 4. 50% of overkill spills per jump (rounded down). 25% segfault: uptime -3 and corrupt a random card in hand. then repair up to 1 corrupted card in your active deck.
flavorText: debugging by yelling into the void.
language: 0
rarity: 0
@@ -14,16 +14,16 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: lang_java_new_object
displayName: new Object()
description: uses 2 RAM. deal 3. overkill spills. JIT applies.
description: 'uses 2 RAM. deal 3. overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave.'
flavorText: allocation as a love language.
language: 8
rarity: 0
cycleCost: 1
cycleCost: 0
resolutionTrack: 0
distroExclusive: 0
isToken: 0
isRunOnly: 0
designNotes: Java starter cheap damage; benefits from combat-wide JIT warmup.
designNotes: Free cold-start warmup entry; retains 3 damage and 2 RAM.
requiresSystem: []
upgradeTarget: {fileID: 0}
effects: []
@@ -14,16 +14,16 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: lang_java_public_static_main
displayName: public static void main
description: uses 2 RAM. deal 7. overkill spills. JIT applies.
description: 'uses 2 RAM. deal 7. overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave.'
flavorText: verbose, but warmed up.
language: 8
rarity: 0
cycleCost: 3
cycleCost: 2
resolutionTrack: 0
distroExclusive: 0
isToken: 0
isRunOnly: 0
designNotes: Java starter heavy hit; JIT cost reduction is handled by combat-wide Java warmup and cools by 1 between waves.
designNotes: Lower cold-start cost; JIT gains one discount per two plays, stores at most six plays and loses two between waves.
requiresSystem: []
upgradeTarget: {fileID: 0}
effects: []
@@ -14,16 +14,16 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: lang_java_system_out_println
displayName: System.out.println
description: uses 2 RAM. deal 5. overkill spills. JIT applies.
description: 'uses 2 RAM. deal 5. overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave.'
flavorText: standard output, standard damage.
language: 8
rarity: 0
cycleCost: 2
cycleCost: 1
resolutionTrack: 0
distroExclusive: 0
isToken: 0
isRunOnly: 0
designNotes: Java starter mid-cost damage; benefits from combat-wide JIT warmup.
designNotes: Accessible cold-start hit; same damage and 2 RAM with slower capped JIT warmup.
requiresSystem: []
upgradeTarget: {fileID: 0}
effects: []
@@ -14,7 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: lang_js_typeof
displayName: typeof
description: deal 8; 25% chance to deal NaN (0) instead.
description: deal 14; 25% chance to deal NaN (0) instead.
flavorText: the answer is probably object.
language: 4
rarity: 0
@@ -22,7 +22,7 @@ MonoBehaviour:
resolutionTrack: 0
distroExclusive: 0
isToken: 0
designNotes: coercion gag - 25% roll converts hit to 0.
designNotes: 10.5 expected base damage for 1 Cycle versus fetch's 9; 25% failure pays for the higher successful hit.
requiresSystem:
- damage-range-roll
upgradeTarget: {fileID: 0}
@@ -14,7 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: lang_py_for_loop
displayName: for loop
description: 'queue: deal 2 to all enemies.'
description: "modifier: gain 2 Shield. repeat the next payload once. unused repeat expires after next round."
flavorText: 'for enemy in enemies: enemy.suffer()'
language: 3
rarity: 0
@@ -22,7 +22,7 @@ MonoBehaviour:
resolutionTrack: 1
distroExclusive: 0
isToken: 0
designNotes: queued AoE 2.
designNotes: "Python pipelines and automation; see runtime catalog for authoritative rules."
requiresSystem: []
upgradeTarget: {fileID: 0}
effects: []
@@ -14,15 +14,15 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: lang_py_import_antigravity
displayName: import antigravity
description: 'queue: draw 2 cards.'
description: "preparation: immediately draw 2 (fixed)."
flavorText: opened a browser tab. don't ask.
language: 3
rarity: 0
cycleCost: 1
resolutionTrack: 1
resolutionTrack: 0
distroExclusive: 0
isToken: 0
designNotes: queued draw 2.
designNotes: "Python pipelines and automation; see runtime catalog for authoritative rules."
requiresSystem: []
upgradeTarget: {fileID: 0}
effects: []
@@ -14,7 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: lang_py_print
displayName: print()
description: 'queue: deal 3.'
description: "payload: deal 4 to a chosen enemy."
flavorText: breakpoints are for people with time.
language: 3
rarity: 0
@@ -22,7 +22,7 @@ MonoBehaviour:
resolutionTrack: 1
distroExclusive: 0
isToken: 0
designNotes: end-of-turn queued 3 dmg.
designNotes: "Python pipelines and automation; see runtime catalog for authoritative rules."
requiresSystem: []
upgradeTarget: {fileID: 0}
effects: []
@@ -14,7 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: lang_rs_unwrap
displayName: unwrap()
description: deal 9. cannot miss. draw 1.
description: deal 5. overkill becomes Shield. draw 1 (fixed).
flavorText: confidence, weaponized.
language: 2
rarity: 0
+2 -2
View File
@@ -14,7 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: mint_cinnamon
displayName: cinnamon
description: "queue: gain 3 shield. draw 1."
description: "payload: gain 3 Shield; 5 if an earlier Python payload dealt damage this phase."
flavorText: a familiar desktop, a calmer turn.
language: 3
rarity: 0
@@ -22,6 +22,6 @@ MonoBehaviour:
resolutionTrack: 1
distroExclusive: 1
isToken: 0
designNotes: simple deterministic queue value; shield plus card replacement on resolve.
designNotes: "Python pipelines and automation; see runtime catalog for authoritative rules."
upgradeTarget: {fileID: 0}
effects: []
@@ -14,7 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: mint_timeshift
displayName: timeshift snapshot
description: "queue: record uptime now. at end of your next turn, restore to it if lower."
description: "automation: save your Uptime when this resolves. after enemies act in each of the next 2 rounds, heal up to 6 Uptime, without exceeding the saved value. no healing this round or if defeated. healing does not scale with upgrades. uses 1 of 2 script slots until both rounds finish; ends when the wave ends."
flavorText: save point created before touching anything scary.
language: 3
rarity: 1
@@ -22,6 +22,6 @@ MonoBehaviour:
resolutionTrack: 1
distroExclusive: 1
isToken: 0
designNotes: deterministic safety queue; record current uptime and restore at delayed checkpoint only if current uptime is lower.
designNotes: "Python pipelines and automation; see runtime catalog for authoritative rules."
upgradeTarget: {fileID: 0}
effects: []
+2 -2
View File
@@ -14,7 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: mint_update_manager
displayName: update manager
description: "queue: deal exactly 5 to all enemies. repeats at the end of your next turn."
description: "payload: deal 3 to all enemies; 5 if an automation ran earlier this phase."
flavorText: green checks all the way down.
language: 3
rarity: 1
@@ -22,6 +22,6 @@ MonoBehaviour:
resolutionTrack: 1
distroExclusive: 1
isToken: 0
designNotes: Rare deterministic queue aoe; schedules one identical delayed repeat at next-turn end.
designNotes: "Python pipelines and automation; see runtime catalog for authoritative rules."
upgradeTarget: {fileID: 0}
effects: []
+4 -4
View File
@@ -14,17 +14,17 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: shop_py_async_def
displayName: async def
description: 'queue: draw 2. gain 1 Cycle next turn.'
description: "automation: draw 1 immediately on play (fixed). capture the next payload without modifiers; replay it before the queue on each of the next 2 rounds. uses 1 of 2 script slots."
flavorText: returns eventually. emotionally, at least.
language: 3
rarity: 1
cycleCost: 1
cycleCost: 2
resolutionTrack: 1
distroExclusive: 0
isToken: 0
isRunOnly: 1
designNotes: Run-only Repository card. Draw 2 and grants +1 Cycle on the next turn.
designNotes: "Python pipelines and automation; see runtime catalog for authoritative rules."
requiresSystem:
- deferred-cycle-grant
- python-automation
upgradeTarget: {fileID: 0}
effects: []
+2 -2
View File
@@ -14,7 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: shop_py_list_append
displayName: list.append()
description: 'queue: deal 4. gains +1 damage each time it is re-queued.'
description: "payload: deal 6. +2 per subsequent hand play this wave; replays do not grow it."
flavorText: mutable state, but make it cute.
language: 3
rarity: 1
@@ -23,7 +23,7 @@ MonoBehaviour:
distroExclusive: 0
isToken: 0
isRunOnly: 1
designNotes: Run-only Repository card. Base deal 4 with per-combat requeue growth.
designNotes: "Python pipelines and automation; see runtime catalog for authoritative rules."
requiresSystem:
- requeue-tracking
upgradeTarget: {fileID: 0}
+3 -3
View File
@@ -14,7 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: shop_py_zip
displayName: zip()
description: 'next 2 queued cards resolve twice.'
description: "modifier: deal 2. the next single-target damage payload hits all enemies. unused conversion expires after next round."
flavorText: pairs nicely until lengths disagree.
language: 3
rarity: 1
@@ -23,8 +23,8 @@ MonoBehaviour:
distroExclusive: 0
isToken: 0
isRunOnly: 1
designNotes: Run-only Repository card. Adds two charges that make queued cards resolve twice.
designNotes: "Python pipelines and automation; see runtime catalog for authoritative rules."
requiresSystem:
- queue-effect-multiply
- python-pipeline-modifiers
upgradeTarget: {fileID: 0}
effects: []
+3 -3
View File
@@ -14,14 +14,14 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: ubuntu_ask_ubuntu
displayName: ask ubuntu
description: "queue: draw 2 cards."
description: "preparation: inspect the top 3 cards. take one; others keep their order."
flavorText: somebody solved this in 2014.
language: 3
rarity: 0
cycleCost: 0
resolutionTrack: 1
resolutionTrack: 0
distroExclusive: 1
isToken: 0
designNotes: pure draw on resolve.
designNotes: "Python pipelines and automation; see runtime catalog for authoritative rules."
upgradeTarget: {fileID: 0}
effects: []
@@ -14,14 +14,14 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: ubuntu_apt_install
displayName: sudo apt install
description: "queue: add a random common python card to your hand. it costs 0 this combat."
description: "preparation: choose one of 3 Python cards. temporary copy costs 0 this turn and exhausts after play."
flavorText: pull it from the repo and pretend it was always there.
language: 3
rarity: 0
cycleCost: 1
resolutionTrack: 1
resolutionTrack: 0
distroExclusive: 1
isToken: 0
designNotes: on-resolve card generation from the common Python pool.
designNotes: "Python pipelines and automation; see runtime catalog for authoritative rules."
upgradeTarget: {fileID: 0}
effects: []
@@ -14,7 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
id: ubuntu_unattended_upgrades
displayName: unattended-upgrades
description: gain 4 shield now and at the end of your next 2 turns.
description: "automation: gain 3 Shield now and before the queue on each of the next 2 rounds. uses 1 of 2 script slots."
flavorText: the machine fixes itself while you sleep.
language: 3
rarity: 0
@@ -22,6 +22,6 @@ MonoBehaviour:
resolutionTrack: 1
distroExclusive: 1
isToken: 0
designNotes: immediate shield + 2-turn delayed shield ticks.
designNotes: "Python pipelines and automation; see runtime catalog for authoritative rules."
upgradeTarget: {fileID: 0}
effects: []
+8 -1
View File
@@ -332,7 +332,7 @@ namespace KernelPanic.Editor
{
var text = new StringBuilder("# Seeded combat comparison\n\n");
text.AppendLine(report.policy).AppendLine().AppendLine(report.limitations).AppendLine();
text.AppendLine($"Encounter revision: seeded campaign variants, then endless. Route: {report.options.route}. Repair restores up to {RunJourney.RepairUptime} Uptime on departure; challenge adds a modified Daemon and awards Bits plus a draw rider on clear. Build rewards take Bits. Prefetch enabled: {report.options.prefetch}; used only when the bot cannot play another card. Total prefetches: {report.runs.Sum(run => run.prefetches)}. Milestone automatically continues into endless when the wave cap exceeds five. These results are not directly comparable to the old structural encounter benchmark.").AppendLine();
text.AppendLine($"Encounter revision: seeded campaign variants, then endless. Preferred route: {report.options.route}, when reachable on the seeded map; otherwise the default reachable path. Interactive stops are passed without changing the deck. Repair restores up to {RunJourney.RepairUptime} Uptime on departure; challenge adds a modified Daemon and awards Bits plus a draw rider on clear. Build rewards take Bits. Prefetch enabled: {report.options.prefetch}; used only when the bot cannot play another card. Total prefetches: {report.runs.Sum(run => run.prefetches)}. Milestone automatically continues into endless when the wave cap exceeds five. These results are not directly comparable to benchmarks without the route map.").AppendLine();
text.AppendLine($"Seeds: {string.Join(", ", report.options.seeds)}. Limits: {report.options.maxWaves} waves / {report.options.maxRounds} total rounds. Unity {report.unityVersion}.").AppendLine();
text.AppendLine($"Package levels: {string.Join(", ", report.options.packageLevels)}. Shop policies: {string.Join(", ", report.options.shoppingPolicies.Select(shop => shop ? "upgrade-shop" : "no-shop"))}.").AppendLine();
text.AppendLine("| Loadout | Runs | Uptime damage / round | Mean rounds | Mean waves cleared | Wave cap reached | Round cap alive | Died | Repeat checked |");
@@ -411,11 +411,18 @@ namespace KernelPanic.Editor
GameEvents.RaiseCombatantDeathVisualCompleted(new CombatantDeathVisualCompletedEvent(enemy.State));
}
if (_combat.RunLost) { Complete("defeat"); return false; }
if (_combat.Python.HasChoice)
{
for (int i = 0; i < _combat.Python.Choices.Count; i++)
if (_combat.Python.Choose(i)) { _trace.Append("python-choice:").Append(i).Append(';'); Progress(); break; }
return false;
}
if (_combat.AwaitingWaveContinue)
{
if (_run.WavesCleared >= _report.options.maxWaves) { Complete("wave-cap"); return false; }
if (_current.rounds >= _report.options.maxRounds) { Complete("round-cap"); return false; }
VisitRepository();
if (_run.RouteEventPending) _run.ResolveRouteEvent(skip: true);
if (_run.CampaignChoicePending) _combat.ContinueEndless();
else _combat.ContinueToNextWave();
Progress();
+81
View File
@@ -549,6 +549,86 @@
.kernel-ui .log-line { font-size: var(--type-meta); color: var(--kp-muted); margin: 6px 0; white-space: normal; }
/* Repository and run summary use the same manifest and numerical hierarchy. */
.kernel-ui .route-map-screen .route-map-footer { flex-direction: row; flex-wrap: nowrap; align-items: stretch; }
.kernel-ui .route-map-footer > .primary-action { flex-basis: 0; flex-grow: 1; flex-shrink: 1; width: auto; min-width: 0; min-height: 44px; height: auto; margin: 0 4px; padding: 10px; white-space: normal; -unity-text-align: middle-center; }
.kernel-ui .route-map-footer > .route-map-back { color: var(--kp-muted); border-color: var(--kp-border); background-color: var(--kp-panel); }
.kernel-ui .route-map-footer > .route-map-continue { color: var(--kp-bg); background-color: var(--kp-amber); }
.kernel-ui .route-map-footer > .route-map-continue:disabled { color: var(--kp-muted); background-color: var(--kp-panel); border-color: var(--kp-border); }
.kernel-ui .route-map-layout { width: 100%; align-self: stretch; flex-direction: row; flex-wrap: wrap; align-items: flex-start; }
.kernel-ui .route-map-body .run-route-section { padding: 0; margin: 0; border-top-width: 0; }
.kernel-ui .route-map-graph { flex-basis: 440px; flex-grow: 1; flex-shrink: 1; min-width: 0; padding: 8px; background-color: var(--kp-bg); }
.kernel-ui .route-map-scroll { height: 460px; min-height: 260px; }
.kernel-ui .route-map-detail { flex-basis: 280px; flex-grow: 0; flex-shrink: 1; min-width: 0; padding: 16px; margin: 8px 0 8px 16px; border-left-width: 1px; border-left-color: var(--kp-border); background-color: var(--kp-panel); }
.kernel-ui .route-preview-state { color: var(--kp-amber); font-size: var(--type-meta); white-space: normal; margin-bottom: 12px; }
.kernel-ui .route-map-eyebrow { color: var(--kp-cyan); font-size: var(--type-meta); white-space: normal; flex-shrink: 0; margin-bottom: 8px; }
.kernel-ui .route-map-legend { color: var(--kp-muted); font-size: var(--type-meta); white-space: normal; flex-shrink: 0; margin-bottom: 12px; }
.kernel-ui .route-map-canvas { position: relative; min-width: 0; flex-shrink: 0; }
.kernel-ui .route-map-wave { position: absolute; left: 0; font-size: 11px; color: var(--kp-primary-dim); margin: 0; padding: 0; }
.kernel-ui .route-map-node { width: 60px; height: 60px; min-width: 60px; min-height: 60px; padding: 5px 0 3px; margin: 0; border-radius: 30px; border-width: 1px; border-color: var(--kp-border); background-color: var(--kp-bg); align-items: center; justify-content: center; flex-shrink: 0; }
.kernel-ui .route-map-node:hover, .kernel-ui .route-map-node:focus { border-color: var(--kp-cyan); background-color: var(--kp-hover); }
.kernel-ui .route-map-node.map-choice { border-width: 2px; border-color: var(--kp-cyan); }
.kernel-ui .route-map-node.map-selected { border-width: 3px; border-color: var(--kp-amber); background-color: var(--kp-action-hover); }
.kernel-ui .route-map-node.map-taken { border-width: 2px; border-color: var(--kp-success); background-color: var(--kp-panel); }
.kernel-ui .route-map-node.map-muted { opacity: 0.45; }
.kernel-ui .route-map-node.map-future { border-color: var(--kp-primary-dim); }
.kernel-ui .route-map-node.map-boss { border-radius: 8px; border-width: 2px; border-color: var(--kp-amber); }
.kernel-ui .route-map-glyph { width: 24px; height: 24px; flex-shrink: 0; color: var(--kp-cyan); }
.kernel-ui .route-map-symbol { height: 24px; margin: 0; font-size: 22px; color: var(--kp-success); flex-shrink: 0; -unity-text-align: middle-center; }
.kernel-ui .map-selected .route-map-glyph { color: var(--kp-amber); }
.kernel-ui .map-taken .route-map-glyph { color: var(--kp-success); }
.kernel-ui .map-future .route-map-glyph { color: var(--kp-muted); }
.kernel-ui .route-map-name { color: var(--kp-text); font-size: 12px; white-space: nowrap; -unity-text-align: middle-center; flex-shrink: 0; margin: 1px 0 0; padding: 0; }
.kernel-ui .route-map-here { position: absolute; top: 65px; left: -12px; width: 84px; color: var(--kp-success); font-size: 11px; white-space: nowrap; -unity-text-align: middle-center; margin: 0; padding: 2px 0; background-color: var(--kp-bg); }
.kernel-ui .route-detail-title { color: var(--kp-text); font-size: var(--type-title); white-space: normal; flex-shrink: 0; margin-bottom: 12px; }
.kernel-ui .route-detail-copy, .kernel-ui .route-event-result { color: var(--kp-muted); font-size: var(--type-body); white-space: normal; flex-shrink: 0; margin-bottom: 12px; }
.kernel-ui .route-detail-battle { color: var(--kp-cyan); font-size: var(--type-body); white-space: normal; flex-shrink: 0; border-top-width: 1px; border-top-color: var(--kp-border); padding-top: 12px; margin-bottom: 8px; }
.kernel-ui .route-map-history { color: var(--kp-success); font-size: var(--type-meta); white-space: normal; flex-shrink: 0; margin: 8px 0; }
.kernel-ui .route-map-journal { margin-top: 16px; flex-shrink: 0; }
.kernel-ui .route-event { margin-top: 16px; padding-top: 12px; border-top-width: 1px; border-top-color: var(--kp-border); }
.kernel-ui .route-event .unity-base-field { flex-direction: column; align-items: stretch; flex-shrink: 0; margin: 0 0 12px; }
.kernel-ui .route-event .unity-base-field__label { color: var(--kp-cyan); white-space: normal; margin: 0 0 6px; min-width: 0; }
.kernel-ui .route-event .unity-base-field__input { min-height: 34px; margin: 0; min-width: 0; background-color: var(--kp-bg); color: var(--kp-text); }
.kernel-ui .route-event-card { min-width: 0; margin-bottom: 12px; }
.kernel-ui .route-event-card .software-card { width: 100%; min-width: 0; margin: 0; }
.kernel-ui .route-event .primary-action, .kernel-ui .route-event .secondary-action { white-space: normal; flex-shrink: 0; }
.kernel-ui.narrow .route-map-graph { padding: 4px 0; }
.kernel-ui.narrow .route-map-detail { flex-grow: 1; margin: 16px 0 0; padding: 16px; }
/* Departure is a sequence: reward, map, then one full-width event. */
.kernel-ui .departure-content { width: 100%; max-width: 1000px; align-self: center; padding: 8px 16px 16px; min-width: 0; }
.kernel-ui .departure-content > .primary-action { min-height: 44px; white-space: normal; flex-shrink: 0; margin-top: 12px; }
.kernel-ui .departure-content .unity-base-field { flex-direction: column; align-items: stretch; flex-shrink: 0; margin: 12px 0; }
.kernel-ui .departure-content .unity-base-field__label { color: var(--kp-cyan); white-space: normal; margin: 0 0 8px; min-width: 0; }
.kernel-ui .departure-content .unity-base-field__input { min-height: 36px; min-width: 0; background-color: var(--kp-bg); color: var(--kp-text); }
.kernel-ui .departure-actions { flex-direction: row; flex-wrap: wrap; margin: 4px 0 8px; }
.kernel-ui .departure-selectors { flex-direction: row; flex-wrap: wrap; }
.kernel-ui .departure-selectors > .unity-base-field { flex-basis: 280px; flex-grow: 1; flex-shrink: 1; min-width: 0; margin: 4px 8px 12px; }
.kernel-ui .departure-actions > .primary-action { flex-grow: 1; flex-shrink: 1; flex-basis: 220px; min-width: 0; white-space: normal; margin: 4px; }
.kernel-ui .departure-actions > .departure-selected { border-color: var(--kp-cyan); color: var(--kp-cyan); background-color: var(--kp-panel-hover); }
.kernel-ui .departure-previews { flex-direction: row; flex-wrap: wrap; align-items: stretch; }
.kernel-ui .departure-card { flex-basis: 280px; flex-grow: 1; flex-shrink: 1; min-width: 0; margin: 8px; }
.kernel-ui .departure-card .software-card { width: 100%; min-width: 0; margin: 8px 0 0; }
.kernel-ui .departure-content .route-event { margin-top: 4px; border-top-width: 0; padding-top: 0; }
.kernel-ui.narrow .departure-content { padding: 4px 0 12px; }
.kernel-ui.narrow .departure-card { margin: 8px 0; }
.kernel-ui.narrow .departure-selectors > .unity-base-field { margin: 4px 0 12px; }
.kernel-ui .overlay.python-choice-overlay { align-items: center; justify-content: center; background-color: rgba(4, 10, 8, 0.94); }
.kernel-ui .python-choice-dialog { width: 100%; max-width: 980px; max-height: 100%; min-height: 0; padding: 20px; background-color: var(--kp-panel); border-width: 2px 1px 1px; border-color: var(--kp-border); border-top-color: var(--kp-cyan); }
.kernel-ui .python-choice-eyebrow { flex-shrink: 0; color: var(--kp-cyan); font-size: var(--type-meta); margin-bottom: 8px; }
.kernel-ui .python-choice-title { flex-shrink: 0; color: var(--kp-text); font-size: var(--type-title); -unity-font-style: bold; white-space: normal; margin-bottom: 8px; }
.kernel-ui .python-choice-description { flex-shrink: 0; color: var(--kp-muted); font-size: var(--type-body); white-space: normal; margin-bottom: 12px; }
.kernel-ui .python-choice-scroll { min-height: 0; flex-shrink: 1; }
.kernel-ui .python-choice-grid { flex-direction: row; flex-wrap: wrap; align-items: stretch; }
.kernel-ui .python-choice-option { width: 260px; min-width: 220px; min-height: 80px; height: auto; flex-grow: 1; flex-shrink: 1; margin: 4px; padding: 0; border-radius: 0; border-width: 1px; border-color: var(--kp-border); background-color: var(--kp-bg); color: var(--kp-text); white-space: normal; -unity-text-align: upper-left; }
.kernel-ui .python-choice-option:hover, .kernel-ui .python-choice-option:focus { border-color: var(--kp-cyan); background-color: var(--kp-hover); }
.kernel-ui .python-choice-option:disabled { opacity: 0.45; }
.kernel-ui .python-choice-option > .python-choice-description { padding: 12px; }
.kernel-ui .python-choice-action { flex-shrink: 0; color: var(--kp-amber); font-size: var(--type-body); padding: 10px 12px; white-space: normal; border-top-width: 1px; border-top-color: var(--kp-border-subtle); }
.kernel-ui .python-choice-hint { flex-shrink: 0; color: var(--kp-muted); font-size: var(--type-meta); white-space: normal; margin-top: 12px; }
.kernel-ui.narrow .python-choice-dialog { padding: 12px; }
.kernel-ui.narrow .python-choice-option { width: 100%; min-width: 0; }
.kernel-ui .overlay { padding: 16px; }
.kernel-ui .repository { padding: 8px; border-width: 0; background-color: var(--kp-bg); }
.kernel-ui .repository-title { font-size: 27px; color: var(--kp-text); }
@@ -787,6 +867,7 @@
.kernel-ui.narrow .scheduler .track-zone-stack { flex-direction: column; align-items: stretch; }
.kernel-ui.narrow .scheduler .track-zone-stack .track-header { width: 100%; }
.kernel-ui.narrow .scheduler .track-zone-stack .track-scroll { width: 100%; }
.kernel-ui.short-screen .scheduler .track-zone-token .track-scroll { max-height: 48px; }
.kernel-ui .scheduler .stack-contents .card-chip-name { flex-shrink: 1; min-width: 0; }
.kernel-ui .process-restarting { border-bottom-color: var(--kp-lang-haskell); }
.kernel-ui .process-restarting .process-state { color: var(--kp-lang-haskell); }
+34 -22
View File
@@ -16,7 +16,7 @@ namespace KernelPanic.Combat
Cleanse, ShuffleToken, UpgradeHandCards, GenerateCard, NoOp, UpdateManager,
ShieldRepeatDamage, Timeshift, DnfAutoremove, FirstToPackage, Rawhide,
IncomingAttackHalve, ConsultWiki, RandomCommonLanguageCard, MinimalInstall, SizeofDamage,
RepairCorruptedCards, AskUbuntu
RepairCorruptedCards, AskUbuntu, FixedDraw, Python
}
/// <summary>
@@ -58,6 +58,8 @@ namespace KernelPanic.Combat
CardEffectKind.Damage => new DealDamageEffect(Amount, MaxAmount, Language, TrueDamage, CanCrit, AllEnemies),
CardEffectKind.Shield => new ShieldEffect(Amount),
CardEffectKind.Draw => new DrawEffect(Amount),
CardEffectKind.FixedDraw => new FixedDrawEffect(Amount),
CardEffectKind.Python => new PythonEffect((PythonOperation)SecondaryAmount, Amount),
CardEffectKind.AskUbuntu => new AskUbuntuEffect(),
CardEffectKind.ChanceDamage => new ChanceDamageEffect(Amount, SecondaryAmount, Language),
CardEffectKind.PreviousLanguageDamage => new PreviousLanguageDamageEffect(Amount, SecondaryAmount, Language),
@@ -126,6 +128,9 @@ namespace KernelPanic.Combat
/// Queue growth is resolved from the card without changing any combat state.
/// </summary>
public string GetRulesText(CardInstance card)
=> GetRulesText(card, null, 1);
public string GetRulesText(CardInstance card, string distroId, int distroVersion)
{
if (_rules == null)
{
@@ -133,7 +138,10 @@ namespace KernelPanic.Combat
? "effect not authored."
: card.Definition.Description + (card.UpgradeLevel > 0 ? " [upgraded]" : string.Empty);
}
string text = _rules;
int inspectCount = PythonPipeline.InspectCount(distroId, distroVersion);
int btwMultiplier = string.Equals(distroId, "arch", StringComparison.OrdinalIgnoreCase) && distroVersion >= 3 ? 4 : 3;
string text = _rules.Replace("{inspectCount}", inspectCount.ToString(CultureInfo.InvariantCulture))
.Replace("{btwMultiplier}", btwMultiplier.ToString(CultureInfo.InvariantCulture));
for (int i = 0; i < Effects.Count; i++)
{
CardEffectSpec effect = Effects[i];
@@ -148,6 +156,9 @@ namespace KernelPanic.Combat
text = Replace(text, "rawSecondary", i, effect.SecondaryAmount);
text = Replace(text, "failure", i, 100 - effect.SecondaryAmount);
text = Replace(text, "growth", i, UpgradeMath.ScaleAmount(effect.Amount + UnityEngine.Mathf.Max(0, (card?.QueuePlayCount ?? 0) - 1), card));
text = Replace(text, "listGrowth", i, CardScaling.Add(UpgradeMath.ScaleAmount(effect.Amount, card),
(int)Math.Min(int.MaxValue, 2L * Math.Max(0, (card?.QueuePlayCount ?? 0) - 1))));
text = Replace(text, "pythonBonus", i, UpgradeMath.ScaleAmount(5, card));
}
return text + (card?.UpgradeLevel > 0 ? " [upgraded]" : string.Empty);
}
@@ -168,7 +179,7 @@ namespace KernelPanic.Combat
private const CardTargeting Single = CardTargeting.SingleEnemy;
private const CardTargeting All = CardTargeting.AllEnemies;
private const string CRecoil = " 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card.";
private const string Jit = " overkill spills. JIT applies; discount decays by 1 after each wave.";
private const string Jit = " overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave.";
private static readonly IReadOnlyDictionary<string, CardCatalogEntry> ById;
public static IReadOnlyList<CardCatalogEntry> Entries { get; }
@@ -200,30 +211,29 @@ namespace KernelPanic.Combat
Add("shop_hs_foldmap", All, false, "stack: deal {amount:0} to all living enemies.", Damage(4, Language.Haskell, all: true));
Add("shop_hs_deepseq", Single, false, "stack: deal {amount:0}.", Damage(9, Language.Haskell));
Add("shop_hs_dollar_bang", Single, false, "stack: deal {amount:0}. gain {shield:1} Shield.", Damage(5, Language.Haskell), Shield(2));
Add("lang_py_print", None, false, "queue: deal {amount:0}.", Damage(3, Language.Python));
Add("lang_py_import_antigravity", None, false, "queue: draw {amount:0}.", Draw(2));
Add("lang_py_for_loop", All, false, "queue: deal {amount:0} to all enemies.", Damage(2, Language.Python, all: true));
Add("lang_py_print", Single, false, "payload: deal {amount:0} to a chosen enemy.", Py(PythonOperation.Print, 4));
Add("lang_py_import_antigravity", None, false, "preparation: immediately draw 2 (fixed).", Py(PythonOperation.Draw, 2));
Add("lang_py_for_loop", None, false, "modifier: gain {shield:0} Shield. repeat the next payload once. unused repeat expires after next round.", Py(PythonOperation.Loop, 2));
Add("lang_js_console_log", Single, true, "deal {amount:0}-{max:0}.", Damage(3, Language.JavaScript, 9));
Add("lang_js_fetch", Single, true, "deal {amount:0}-{max:0}.", Damage(5, Language.JavaScript, 13));
Add("lang_rs_fn_main", Single, true, "deal {amount:0}. overkill becomes shield.", Damage(6, Language.Rust));
Add("lang_rs_unwrap", Single, true, "deal {amount:0}. overkill becomes shield. draw {amount:1}.", Damage(9, Language.Rust), Draw(1));
Add("lang_rs_unwrap", Single, true, "deal {amount:0}. overkill becomes shield. draw {raw:1} (fixed).", Damage(5, Language.Rust), Fx(CardEffectKind.FixedDraw, 1));
Add("lang_rs_borrow", None, false, "gain {shield:0} shield.", Shield(5));
Add("lang_c_malloc", Single, true, "deal {amount:0}." + CRecoil, Damage(12, Language.C));
Add("lang_c_printf", Single, true, "deal {amount:0}." + CRecoil + " then repair up to {amount:1} corrupted card{plural:1} in your active deck.",
Damage(7, Language.C), Fx(CardEffectKind.RepairCorruptedCards, 1));
Damage(4, Language.C), Fx(CardEffectKind.RepairCorruptedCards, 1));
Add("lang_c_pointer", Single, true, "deal {amount:0}; {secondary:0} if the previous card was C." + CRecoil,
Fx(CardEffectKind.PreviousLanguageDamage, 9, secondary: 15, language: Language.C));
Add("lang_java_public_static_main", Single, true, "uses 2 RAM. deal {amount:0}. overkill spills. JIT: Java cards cost 1 less this combat each time you play a Java card; discount decays by 1 after each wave.", Damage(7, Language.Java));
Add("lang_java_public_static_main", Single, true, "uses 2 RAM. deal {amount:0}." + Jit, Damage(7, Language.Java));
Add("lang_java_system_out_println", Single, true, "uses 2 RAM. deal {amount:0}." + Jit, Damage(5, Language.Java));
Add("lang_java_new_object", Single, true, "uses 2 RAM. deal {amount:0}." + Jit, Damage(3, Language.Java));
Add("ubuntu_ask_ubuntu", None, false, "queue: draw {amount:0}.", Fx(CardEffectKind.AskUbuntu, AskUbuntuEffect.BaseDrawCount));
Add("ubuntu_unattended_upgrades", None, false, "queue: gain {shield:0} shield now and next {rawSecondary:1} turns.",
Shield(4), Fx(CardEffectKind.UnattendedUpgrades, 4, secondary: 2));
Add("ubuntu_ask_ubuntu", None, false, "preparation: inspect the top {inspectCount} cards. take one; others keep their order.", Py(PythonOperation.Inspect));
Add("ubuntu_unattended_upgrades", None, false, "automation: gain {shield:0} Shield now and before the queue on each of the next 2 rounds. uses 1 of 2 script slots.", Py(PythonOperation.Unattended, 3));
Add("mint_fix_broken", Single, true, "deal {amount:0}. cleanse harmful statuses.", Damage(8, Language.JavaScript), Fx(CardEffectKind.Cleanse));
Add("lang_js_typeof", Single, true, "{rawSecondary:0}%: deal {amount:0}. {failure:0}%: deal 0.", Fx(CardEffectKind.ChanceDamage, 8, secondary: 75, language: Language.JavaScript));
Add("shop_py_list_append", Single, false, "queue: deal {growth:0}; +1 each time re-queued.", Fx(CardEffectKind.QueuedGrowthDamage, 4, language: Language.Python));
Add("shop_py_async_def", None, false, "queue: draw {amount:0}. gain {amount:1} cycle next turn.", Draw(2), Fx(CardEffectKind.NextTurnCycle, 1));
Add("shop_py_zip", None, false, "next {amount:0} queued cards resolve twice.", Fx(CardEffectKind.QueueRepeat, 2));
Add("lang_js_typeof", Single, true, "{rawSecondary:0}%: deal {amount:0}. {failure:0}%: deal 0.", Fx(CardEffectKind.ChanceDamage, 14, secondary: 75, language: Language.JavaScript));
Add("shop_py_list_append", Single, false, "payload: deal {listGrowth:0}. +2 per subsequent hand play this wave; replays do not grow it.", Py(PythonOperation.List, 6));
Add("shop_py_async_def", None, false, "automation: draw 1 immediately on play (fixed). capture the next payload without modifiers; replay it before the queue on each of the next 2 rounds. uses 1 of 2 script slots.", Py(PythonOperation.Async));
Add("shop_py_zip", Single, false, "modifier: deal {amount:0}. the next single-target damage payload hits all enemies. unused conversion expires after next round.", Py(PythonOperation.Zip, 2));
Add("shop_js_math_random", Single, true, "deal {amount:0}-{max:0}.", Damage(2, Language.JavaScript, 20));
CardEffectSpec promiseHit = Damage(4, Language.JavaScript, 10);
Add("shop_js_promise_all", Single, true, "deal {amount:0}-{max:0} three times.", promiseHit, promiseHit, promiseHit);
@@ -231,22 +241,22 @@ namespace KernelPanic.Combat
Add("ubuntu_snap_install", Single, true, "deal {amount:0}-{max:0}. shuffle an ubuntu pro trial into your draw pile.", Damage(6, Language.JavaScript, 14),
new CardEffectSpec(CardEffectKind.ShuffleToken, referenceId: "ubuntu_pro_trial"));
Add("ubuntu_do_release_upgrade", None, false, "upgrade {amount:0}-{max:0} random hand cards.", Fx(CardEffectKind.UpgradeHandCards, 1, 3));
Add("ubuntu_apt_install", None, false, "queue: generate a random common Python card at 0c.", Fx(CardEffectKind.GenerateCard, language: Language.Python));
Add("ubuntu_apt_install", None, false, "preparation: choose one of 3 Python cards. temporary copy costs 0 this turn and exhausts after play.", Py(PythonOperation.Install));
Add("ubuntu_pro_trial", None, false, null, new CardEffectSpec(CardEffectKind.NoOp, referenceId: "ubuntu pro trial is unplayable"));
// UpdateManager expands its own targets at execution, and historically asks for no target.
Add("mint_update_manager", None, false, "queue: deal {amount:0} to all enemies. repeats at the end of your next turn.", Fx(CardEffectKind.UpdateManager, 5, language: Language.Python, all: true));
Add("mint_cinnamon", None, false, "queue: gain {shield:0} shield. draw {amount:1}.", Shield(3), Draw(1));
Add("mint_update_manager", All, false, "payload: deal {amount:0} to all enemies; {pythonBonus:0} if an automation ran earlier this phase.", Py(PythonOperation.Update, 3, true));
Add("mint_cinnamon", None, false, "payload: gain {shield:0} Shield; {pythonBonus:0} if an earlier Python payload dealt damage this phase.", Py(PythonOperation.Cinnamon, 3));
Add("mint_nemo", Single, true, "deal {amount:0}. if you have shield, deal it again.", Fx(CardEffectKind.ShieldRepeatDamage, 6, language: Language.JavaScript));
Add("mint_timeshift", None, false, "queue: record uptime now. at end of your next turn, restore to it if lower.", Fx(CardEffectKind.Timeshift));
Add("mint_timeshift", None, false, "automation: save your Uptime when this resolves. after enemies act in each of the next 2 rounds, heal up to 6 Uptime, without exceeding the saved value. no healing this round or if defeated. healing does not scale with upgrades. uses 1 of 2 script slots until both rounds finish; ends when the wave ends.", Py(PythonOperation.Timeshift));
Add("fedora_dnf_autoremove", Single, true, "deal {amount:0}. exhaust a junk/NOP/broken card from hand; if you do, gain {secondary:0} cycle. if not, do nothing.", Fx(CardEffectKind.DnfAutoremove, 7, secondary: 1, language: Language.Rust));
Add("fedora_first_to_package", Single, true, "deal {amount:0}. Java cards cost 1 less this turn.", Fx(CardEffectKind.FirstToPackage, 7, language: Language.Java));
Add("fedora_dnf_update", Single, true, "deal {amount:0}. overkill spills. costs 1 less per Java card played this combat.", Damage(9, Language.Java));
Add("fedora_dnf_update", Single, true, "deal {amount:0}." + Jit, Damage(9, Language.Java));
Add("fedora_rawhide", None, false, "draw {amount:0}. next card this turn gains bleeding edge.", Fx(CardEffectKind.Rawhide, RawhideEffect.DrawCount));
Add("fedora_selinux", None, false, "next {amount:0} enemy attacks deal half damage.", Fx(CardEffectKind.IncomingAttackHalve, 2));
Add("arch_pacman_syu", Single, true, "deal {amount:0}." + CRecoil, Damage(14, Language.C));
Add("arch_consult_wiki", Single, true, "fix a broken card and draw {secondary:0}; if none, deal {amount:0}.",
Fx(CardEffectKind.ConsultWiki, ConsultWikiEffect.FallbackDamage, secondary: ConsultWikiEffect.DrawCount, language: Language.Rust));
Add("arch_makepkg", Single, true, "deal {amount:0} + btw x{rawSecondary:0}; x4 at Arch v3+." + CRecoil, Fx(CardEffectKind.BtwScaledDamage, 7, secondary: 3, language: Language.C));
Add("arch_makepkg", Single, true, "deal {amount:0} + btw x{btwMultiplier}." + CRecoil, Fx(CardEffectKind.BtwScaledDamage, 7, secondary: 3, language: Language.C));
Add("arch_aur_helper", None, false, "add a random C/Rust common card to hand; it costs 0 this turn.", Fx(CardEffectKind.RandomCommonLanguageCard));
Add("arch_minimal_install", None, false, "exhaust up to {raw:0} hand cards. per card: gain {rawSecondary:0} Shield and {rawMax:0} Cycle.",
Fx(CardEffectKind.MinimalInstall, MinimalInstallEffect.MaxExhaust, MinimalInstallEffect.CyclesPerCard, MinimalInstallEffect.ShieldPerCard));
@@ -275,6 +285,8 @@ namespace KernelPanic.Combat
=> new(CardEffectKind.Damage, amount, max, language: language, allEnemies: all, trueDamage: trueDamage);
private static CardEffectSpec Shield(int amount) => new(CardEffectKind.Shield, amount);
private static CardEffectSpec Draw(int amount) => new(CardEffectKind.Draw, amount);
private static CardEffectSpec Py(PythonOperation operation, int amount = 0, bool all = false) =>
new(CardEffectKind.Python, amount, secondaryAmount: (int)operation, language: Language.Python, allEnemies: all);
private static CardEffectSpec Fx(CardEffectKind kind, int amount = 0, int max = -1, int secondary = 0, Language language = default, bool all = false)
=> new(kind, amount, max, secondary, language, all);
}
+30 -1
View File
@@ -375,6 +375,28 @@ namespace KernelPanic.Combat
}
}
/// <summary>A fixed replacement draw; magnitude and source effect bonuses do not increase it.</summary>
public sealed class FixedDrawEffect : ICardEffect
{
private readonly int _count;
public FixedDrawEffect(int count)
{
_count = count;
}
public void Execute(CombatContext context)
{
int added = 0;
// Use the same ordered, RAM-aware draw operation as ordinary draw effects.
while (added < _count && context.DeckController.TryDrawToHand(context.HandController, out _))
added++;
string capped = added < _count && context.DeckController.AvailableToDrawCount > 0
? " (not enough RAM)" : string.Empty;
context.CombatManager.ReportEffectResult($"drew {added}{capped}");
}
}
public sealed class AskUbuntuEffect : ICardEffect
{
internal const int BaseDrawCount = 2;
@@ -892,6 +914,12 @@ namespace KernelPanic.Combat
}
public static string GetRulesText(CardInstance card)
=> GetRulesText(card, null, 1);
public static string GetRulesText(CardInstance card, KernelPanic.Run.RunConfig config)
=> GetRulesText(card, config?.Distro?.Id, config?.DistroVersion ?? 1);
public static string GetRulesText(CardInstance card, string distroId, int distroVersion)
{
if (card?.Definition == null)
{
@@ -910,7 +938,8 @@ namespace KernelPanic.Combat
if (CardCatalog.TryGet(card.Definition.Id, out CardCatalogEntry entry))
{
return entry.GetRulesText(card);
return entry.GetRulesText(card, distroId, distroVersion)
+ (card.ExhaustOnPlay ? " Temporary copy: exhaust after play." : string.Empty);
}
return string.IsNullOrWhiteSpace(card.Definition.Description)
+2
View File
@@ -25,6 +25,7 @@ namespace KernelPanic.Combat
public int PermanentCostDelta { get; private set; }
public int MagnitudeBonus { get; private set; }
public int DrawRider { get; private set; }
public bool ExhaustOnPlay { get; set; }
public int UpgradeLevel { get; private set; }
public int QueuePlayCount { get; private set; }
public bool WasFirstCardThisTurn { get; private set; }
@@ -157,6 +158,7 @@ namespace KernelPanic.Combat
IsBroken = IsBroken,
IsLocked = IsLocked
};
copy.ExhaustOnPlay = ExhaustOnPlay;
copy.PermanentCostDelta = PermanentCostDelta;
copy.MagnitudeBonus = MagnitudeBonus;
+30 -2
View File
@@ -68,6 +68,8 @@ namespace KernelPanic.Combat
int cardDamageFlat = CardScaling.Add(source.FlatCardDamageBonus,
prospective && deferred ? combat.PreviewNextDnfDamageStack() : 0);
bool allEnemies = entry.TargetsAllEnemies || entry.Effects.Any(effect => effect.AllEnemies);
var python = combat.Python.PreviewState(card);
if (PythonPipeline.IsPayload(card.Definition) && python.area) allEnemies = true;
var targets = PreviewTargets(combat, card, target, queued, allEnemies);
bool hasSelectedTarget = target != null || queued && card.TargetSnapshot.Any(t => t != null && !t.IsDefeated)
|| combat.SelectedEnemyIndex >= 0 && combat.SelectedEnemyIndex < combat.Enemies.Count;
@@ -79,7 +81,7 @@ namespace KernelPanic.Combat
result.IsConditional = true;
}
if (lazy != 100 || card.Definition.Language == Language.Haskell)
notes.Add($"Haskell {(lazyEntry == null ? "next stack" : "captured")}: x{lazy / 100m:0.0} damage and explicit Shield.");
notes.Add($"Haskell {(lazyEntry == null ? "next stack" : "captured")}: x{(lazy / 100m).ToString("0.0#", System.Globalization.CultureInfo.InvariantCulture)} damage and explicit Shield.");
if (combat.Compilation.Active)
notes.Add($"Compilation {combat.Compilation.Level}/{combat.Compilation.Maximum}: {combat.Compilation.DamagePercent}% damage, {combat.Compilation.ShieldPercent}% explicit Shield.");
if (magnitude > 0) notes.Add($"Card magnitude: +{magnitude}" + (growth > 0 ? $" (includes +{growth} non-crash growth)" : string.Empty) + ".");
@@ -116,6 +118,29 @@ namespace KernelPanic.Combat
int repeats = 1;
switch (effect.Kind)
{
case CardEffectKind.Python:
var operation = (PythonOperation)effect.SecondaryAmount;
AddNote(notes, CardEffectFactory.GetRulesText(card, combat.RunConfig));
if (operation is PythonOperation.Print or PythonOperation.List or PythonOperation.Update or PythonOperation.Zip)
{
damage = true;
low = high = effect.Amount;
if (operation == PythonOperation.List)
low = high = CardScaling.Add(effect.Amount, (int)Math.Min(int.MaxValue, 2L * Math.Max(0, card.QueuePlayCount + (prospective ? 1 : 0) - 1)));
if (operation == PythonOperation.Update && python.automation) low = high = 5;
if (operation != PythonOperation.Zip) repeats = python.repeats;
}
if (operation is PythonOperation.Loop or PythonOperation.Cinnamon or PythonOperation.Unattended)
{
int shieldBase = operation == PythonOperation.Cinnamon && python.damageBefore ? 5 : effect.Amount;
int shieldRepeats = operation == PythonOperation.Cinnamon ? python.repeats : 1;
hasShield = true;
int shieldValue = ScaledShield(shieldBase, sourceFlat, magnitude, lazy, combat);
for (int i = 0; i < shieldRepeats; i++) targetShield = CardScaling.Add(targetShield, shieldValue);
}
if (PythonPipeline.IsPayload(card.Definition))
AddNote(notes, $"Pipeline: {python.repeats} execution(s){(python.area ? ", all enemies" : "")}. Earlier payloads may change conditions; replays never repeat draw or installation.");
break;
case CardEffectKind.Damage:
damage = true;
break;
@@ -185,6 +210,9 @@ namespace KernelPanic.Combat
hasShield = true;
targetShield = CardScaling.Add(targetShield, ScaledShield(effect.Amount, sourceFlat, magnitude, lazy, combat));
break;
case CardEffectKind.FixedDraw:
AddNote(notes, $"Draw {effect.Amount} (fixed): magnitude and effect bonuses do not increase this draw; available RAM still limits it.");
break;
case CardEffectKind.HaskellMaybe:
if (source.CurrentUptime >= source.MaxUptime)
{
@@ -324,7 +352,7 @@ namespace KernelPanic.Combat
if (captured != null) return captured.MultiplierPercent;
if (card.Definition.ResolutionTrack != ResolutionTrack.LazyStack || card.Definition.Language != Language.Haskell) return 100;
int haskell = combat.LazyStack?.Entries.Count(item => item.Card.Definition?.Language == Language.Haskell) ?? 0;
return 100 + 50 * Math.Min(3, haskell);
return CombatTuning.HaskellStackMultiplierPercent(haskell);
}
private static IReadOnlyList<CombatantState> PreviewTargets(CombatManager combat, CardInstance card,
+42 -16
View File
@@ -87,6 +87,9 @@ namespace KernelPanic.Combat
private bool _evaluatingLazyStack;
private LazyStackEntry _activeLazyEntry;
public CompilationState Compilation { get; } = new();
public PythonPipeline Python { get; } = new();
public IReadOnlyList<CardDefinition> GeneratedCardPool => _generatedCardPool.AsReadOnly();
public void NotifyPythonChanged() => StateChanged?.Invoke();
public TurnPhase CurrentPhase => currentPhase;
public RunConfig RunConfig => _runConfig;
@@ -118,8 +121,10 @@ namespace KernelPanic.Combat
_selectedEnemyIndex = -1; _pendingTargetCard = null;
}
public int CurrentWaveNumber => _runManager == null ? 1 : _runManager.CurrentWaveNumber;
public int RoundNumber => _turnNumberThisWave;
public int ActiveKernelRamPenalty => _activeKernelRamPenalty;
public bool CanSurrenderRun => currentPhase == TurnPhase.Execute
&& !Python.HasChoice
&& !TutorialReading
&& !_waveTransitionActive
&& !_awaitingWaveContinue
@@ -135,6 +140,7 @@ namespace KernelPanic.Combat
private void Awake()
{
Python.Bind(this);
_runManager = GetComponent<RunManager>();
_damagePipeline.ResistanceResolver = ResolveDamageResistance;
_damagePipeline.PreviewResistanceResolver = ResolveDamageResistance;
@@ -208,6 +214,7 @@ namespace KernelPanic.Combat
public void RestoreBoundaryState(RunConfig config, CheckpointCombat snapshot)
{
Python.Clear();
RunCompleted = false;
_waveTransitionActive = false;
RunEndedBySurrender = false;
@@ -230,7 +237,7 @@ namespace KernelPanic.Combat
_fedoraCrashChance = snapshot.fedoraCrashChance;
_packageInterpreterQueueShieldTriggeredThisWave = snapshot.interpreterShieldUsed;
_packageNativeDamageTriggeredThisWave = snapshot.nativeDamageUsed;
_javaCardsPlayedThisCombat = snapshot.javaCardsPlayed;
_javaCardsPlayedThisCombat = Mathf.Clamp(snapshot.javaCardsPlayed, 0, CombatTuning.JavaMaximumWarmup);
_rawhideBonusCharges = snapshot.rawhideCharges;
_queuedRepeatCharges = snapshot.repeatCharges;
_nextTurnCycleBonus = snapshot.nextTurnCycles;
@@ -297,13 +304,15 @@ namespace KernelPanic.Combat
{
if (_runConfig?.IsTutorial == true) return;
if (!_awaitingWaveContinue || RunFinished || _waveTransitionActive
|| _runManager?.IsSuspended == true || _runManager?.CampaignChoicePending == true || _runManager?.BuildRewardPending == true)
|| _runManager?.IsSuspended == true || _runManager?.CampaignChoicePending == true || _runManager?.BuildRewardPending == true
|| _runManager?.RouteEventPending == true)
{
return;
}
_waveTransitionActive = true;
_runManager?.PrepareNextEncounter(_playerState);
if (_runManager?.RepositoryVisitActive == true) { _waveTransitionActive = false; return; }
_awaitingWaveContinue = false;
DecayJavaWarmupForNextWave();
StartCoroutine(ContinueToNextWaveSequenced());
@@ -452,7 +461,7 @@ namespace KernelPanic.Combat
_playerState.HasLastPlayedCardLanguage = true;
if (card.Definition.Language == Language.Java)
{
_javaCardsPlayedThisCombat++;
_javaCardsPlayedThisCombat = Mathf.Min(CombatTuning.JavaMaximumWarmup, _javaCardsPlayedThisCombat + 1);
}
GameEvents.RaiseCardPlayed(new CardPlayedEvent(card, track));
@@ -507,6 +516,7 @@ namespace KernelPanic.Combat
case ResolutionTrack.InterpreterQueue:
card.MarkQueued();
_interpreterQueue.Enqueue(card);
if (PythonPipeline.IsAsync(card.Definition)) new FixedDrawEffect(1).Execute(BuildContext(card, Array.Empty<CombatantState>()));
break;
case ResolutionTrack.LazyStack:
_lazyStack.Enqueue(card);
@@ -514,9 +524,12 @@ namespace KernelPanic.Combat
default:
GameEvents.RaiseCardResolving(new CardResolvedEvent(card, ResolutionTrack.Native));
ExecuteCardEffects(card, ResolveTargets(card));
ResolveCardRiders(card);
_deckController.Discard(card);
GameEvents.RaiseCardResolved(new CardResolvedEvent(card, ResolutionTrack.Native));
Python.AfterChoice(() =>
{
ResolveCardRiders(card);
_deckController.Discard(card);
GameEvents.RaiseCardResolved(new CardResolvedEvent(card, ResolutionTrack.Native));
});
_selectedEnemyIndex = -1;
break;
}
@@ -528,10 +541,12 @@ namespace KernelPanic.Combat
_cCardsPlayedThisTurn++;
}
ApplyPackageCardPlayedEffects(card);
_pendingTargetCard = null;
TryApplyUbuntuEmptyHandRefill();
Python.AfterChoice(() =>
{
ApplyPackageCardPlayedEffects(card);
TryApplyUbuntuEmptyHandRefill();
});
StateChanged?.Invoke();
return true;
}
@@ -551,7 +566,7 @@ namespace KernelPanic.Combat
int cost = GetCardCost(card);
if (card?.Definition != null && card.Definition.Language == Language.Java)
{
cost -= _javaCardsPlayedThisCombat + _javaCardsDiscountThisTurn;
cost -= CombatTuning.JavaWarmupDiscount(_javaCardsPlayedThisCombat) + _javaCardsDiscountThisTurn;
}
cost = ApplyPackageCostRules(card, cost);
@@ -604,7 +619,7 @@ namespace KernelPanic.Combat
int cost = GetCardCost(card);
if (card.Definition.Language == Language.Java)
{
int reduction = _javaCardsPlayedThisCombat + _javaCardsDiscountThisTurn;
int reduction = CombatTuning.JavaWarmupDiscount(_javaCardsPlayedThisCombat) + _javaCardsDiscountThisTurn;
if (reduction > 0) lines.Add($"Java warmup: -{reduction}");
cost -= reduction;
}
@@ -1290,13 +1305,18 @@ namespace KernelPanic.Combat
private IEnumerator InterpretQueueSequenced()
{
Python.BeginPhase(_turnNumberThisWave);
while (VisualResolutionPending && !_runLost && !_awaitingWaveContinue) yield return null;
if (CheckWinOrLoss()) yield break;
while (_interpreterQueue.TryDequeue(out CardInstance card))
{
LogPlayIntent(card);
int resolutionCount = ConsumeQueuedResolutionCount(card);
// Legacy repeat charges must never duplicate Python installation/preparation effects.
int resolutionCount = PythonPipeline.IsPythonCard(card.Definition) ? 1 : ConsumeQueuedResolutionCount(card);
for (int repeatIndex = 0; repeatIndex < resolutionCount; repeatIndex++)
{
ExecuteCardEffects(card, ResolveQueuedTargets(card));
while (Python.HasChoice && !_runLost && !_awaitingWaveContinue) yield return null;
if (CheckWinOrLoss())
{
yield break;
@@ -1373,6 +1393,7 @@ namespace KernelPanic.Combat
private void ClearDeferredCards()
{
Python.Clear();
foreach (var card in _lazyStack.Cards.Concat(_interpreterQueue.Cards).Distinct())
{
card.ClearTargetSnapshot();
@@ -1444,6 +1465,7 @@ namespace KernelPanic.Combat
return;
}
Python.EndRound();
ResolveDelayedEndOfTurnEffects();
if (CheckWinOrLoss())
{
@@ -1487,6 +1509,7 @@ namespace KernelPanic.Combat
private IEnumerator DrawCardsToHandSequenced(int requestedCount, string label)
{
while (Python.HasChoice) yield return null;
if (_handController == null || _playerState == null || requestedCount <= 0)
{
yield break;
@@ -1506,6 +1529,7 @@ namespace KernelPanic.Combat
int added = 0;
for (int i = 0; i < drawn.Count; i++)
{
while (Python.HasChoice) yield return null;
if (!_handController.Add(drawn[i]))
{
blockedByRam = true;
@@ -1632,8 +1656,9 @@ namespace KernelPanic.Combat
return;
}
_javaCardsPlayedThisCombat = Mathf.Max(0, _javaCardsPlayedThisCombat - 1);
Log($"Java JIT cooled: discount now -{_javaCardsPlayedThisCombat}");
_javaCardsPlayedThisCombat = Mathf.Max(0,
Mathf.Min(CombatTuning.JavaMaximumWarmup, _javaCardsPlayedThisCombat) - CombatTuning.JavaPlaysPerDiscount);
Log($"Java JIT cooled: discount now -{CombatTuning.JavaWarmupDiscount(_javaCardsPlayedThisCombat)}");
}
private bool CanApplyFedoraPassiveBonus()
@@ -2848,7 +2873,8 @@ namespace KernelPanic.Combat
{
EnemyArchetypeDescriptor archetype = EnemyArchetypeCatalog.Get(archetypeId);
int baseUptime = RandomRoll.RollRange(archetype.BaseUptimeMin, archetype.BaseUptimeMax, RollContext.None);
if (_runConfig?.IsTutorial == true && CurrentWaveNumber == 1 && archetypeId == "zombie_process") baseUptime = 6;
// The guided first hit must kill even when the starter unwrap() does not crit.
if (_runConfig?.IsTutorial == true && CurrentWaveNumber == 1 && archetypeId == "zombie_process") baseUptime = 5;
EnemyInstance enemy = new(archetype, baseUptime + Mathf.Max(0, uptimeBonus));
_enemies.Add(enemy);
return enemy;
@@ -3286,7 +3312,7 @@ namespace KernelPanic.Combat
|| _enemyExitAwaitingVisual != null
|| _deathSpawnSequencesActive > 0;
private bool IsCombatPaused => _awaitingWaveContinue || _waveTransitionActive || RunFinished || VisualResolutionPending;
private bool IsCombatPaused => Python.HasChoice || _awaitingWaveContinue || _waveTransitionActive || RunFinished || VisualResolutionPending;
private enum DelayedCombatEffectKind
{
+9
View File
@@ -13,6 +13,15 @@ namespace KernelPanic.Combat
public const int CCriticalChancePercent = 35;
public const int COverkillSpillPercent = 50;
public const int OrphanSpawnChancePercent = 25;
public const int JavaPlaysPerDiscount = 2;
public const int JavaMaximumWarmup = 6;
public static int JavaWarmupDiscount(int plays) =>
System.Math.Clamp(plays, 0, JavaMaximumWarmup) / JavaPlaysPerDiscount;
// Lift small stacks while preserving the third position and the x2.5 ceiling.
public static int HaskellStackMultiplierPercent(int pendingHaskellCards) =>
pendingHaskellCards <= 0 ? 150 : pendingHaskellCards == 1 ? 175 : pendingHaskellCards == 2 ? 200 : 250;
public const int BaseEnemyUptimeMin = 5;
public const int BaseEnemyUptimeMax = 10;
+14
View File
@@ -186,10 +186,24 @@ namespace KernelPanic.Combat
{
if (card != null)
{
if (card.ExhaustOnPlay) { Exhaust(card); return; }
_discardPile.Add(card);
}
}
public IReadOnlyList<CardInstance> PeekTop(int count)
{
if (_drawPile.Count == 0) ReshuffleDiscardIntoDraw();
return _drawPile.AsEnumerable().Reverse().Take(System.Math.Max(0, count)).ToArray();
}
public bool TakeToHand(CardInstance card, HandController hand)
{
if (!_drawPile.Contains(card) || hand == null || !hand.Add(card)) return false;
_drawPile.Remove(card);
return true;
}
public void AddToDrawPile(CardInstance card, bool shuffle)
{
if (card == null)
+46 -2
View File
@@ -22,6 +22,7 @@ namespace KernelPanic.Combat
// A stable integer mixer, independent of both gameplay random streams and runtime hash codes.
public static EncounterPlan Plan(int wave, WaveRoute route, int seed, int revision)
{
if (revision >= 2) return CampaignPlan(wave, route, seed);
if (revision == 0) return Plan(wave, route);
uint hash = unchecked((uint)seed ^ ((uint)wave * 0x9E3779B9u));
hash ^= hash >> 16; hash = unchecked(hash * 0x7FEB352Du); hash ^= hash >> 15;
@@ -56,7 +57,7 @@ namespace KernelPanic.Combat
enemies = new[] { "race_condition", "race_condition", variant == 1 ? "firewalld" : "memory_leak" };
advice = "Race partners act in uncertain order; defeating one enrages the survivor. Choose between support and paired threats.";
break;
case RunJourney.BossWave:
case RunJourney.LegacyBossWave:
title = variant == 1 ? "Kernel Overseer / scheduled interrupt" : "Kernel Overseer / memory pressure";
enemies = new[] { "kernel_overseer", variant == 1 ? "cron_job" : "memory_leak" };
advice = baseline.Advice;
@@ -99,7 +100,7 @@ namespace KernelPanic.Combat
title = "Concurrency fault";
advice = "Race partners attack in uncertain order; killing one enrages the survivor. Segfault has a death payload.";
enemies = new[] { "race_condition", "race_condition", "segfault" }; break;
case RunJourney.BossWave:
case RunJourney.LegacyBossWave:
title = "Kernel Overseer";
advice = "Boss cycle: shield, probe, heavy interrupt. At half uptime its NEXT announced attacks become stronger.";
enemies = new[] { "kernel_overseer", "firewalld" }; break;
@@ -123,5 +124,48 @@ namespace KernelPanic.Combat
}
return new EncounterPlan(title, advice, Math.Max(0, wave - 1) * CombatTuning.EnemyUptimeGrowthPerWave, enemies);
}
private static EncounterPlan CampaignPlan(int wave, WaveRoute route, int seed)
{
// Keep introductory encounters familiar; introduce the heavier systems before the final boss.
int legacyStage = wave <= 4 ? wave : wave == RunJourney.BossWave ? RunJourney.LegacyBossWave
: wave > RunJourney.BossWave ? wave - 5 : 3;
var baseline = Plan(legacyStage, route, seed, 1);
string title = baseline.Title, advice = baseline.Advice;
var enemies = new List<string>(baseline.Enemies);
string support = unchecked((uint)seed + (uint)wave) % 2 == 0 ? "firewalld" : "cron_job";
switch (wave)
{
case 5:
title = "Privilege escalation";
advice = "Rootkit resists damage while allies remain. Remove its support first.";
enemies = new() { "rootkit", "zombie_process", support }; break;
case 6:
title = "Telemetry breach";
advice = "Telemetry Collector interferes with your resources. Contain the growing Memory Leak.";
enemies = new() { "telemetry_collector", "memory_leak", support }; break;
case 7:
title = "Protected subsystem";
advice = "DRM Guardian protects the subsystem. Plan your damage around its defenses.";
enemies = new() { "drm_guardian", "segfault", support }; break;
case 8:
title = "Critical concurrency";
advice = "Race partners act in uncertain order; defeating one enrages the survivor. Remove their support deliberately.";
enemies = new() { "race_condition", "race_condition", support }; break;
case 9:
title = "Kernel perimeter";
advice = "Kernel Panic pressures your RAM. Clear this last perimeter before the Overseer.";
enemies = new() { "kernel_panic", "daemon", support }; break;
}
if (wave >= 5 && wave < RunJourney.BossWave && route == WaveRoute.Challenge)
{
enemies.Add("daemon"); title += " / challenge";
advice += baseline.EscortShield > 0 ? " Extra Daemon: 6 starting Shield, hidden intent."
: baseline.EscortUptime > 0 ? " Extra Daemon: +4 Uptime, hidden intent." : " Extra Daemon: hidden intent.";
}
if (wave > RunJourney.BossWave) title = "Survival / " + wave;
return new EncounterPlan(title, advice, Math.Max(0, wave - 1) * CombatTuning.EnemyUptimeGrowthPerWave, enemies.ToArray())
{ EscortShield = baseline.EscortShield, EscortUptime = baseline.EscortUptime };
}
}
}
+4 -2
View File
@@ -10,13 +10,15 @@ namespace KernelPanic.Combat
{
var lines = new List<string>();
if (combat?.PlayerState == null) return lines;
lines.Add("Native cards already executed. End turn resolves Python FIFO, then Haskell LIFO, then surviving enemies, then cleanup.");
lines.Add("Native cards and Python preparation already executed. End turn runs ready Python automation, then Python FIFO, Haskell LIFO, surviving enemies, and cleanup.");
if (combat.Python.AutomationCount > 0 || combat.Python.RepeatCount > 0 || combat.Python.AreaCount > 0)
foreach (string script in combat.Python.Readout) lines.Add(script);
int order = 0;
foreach (var card in combat.InterpreterQueue.Cards)
lines.Add(CardLine(combat, card, ++order, "FIFO", card.TargetSnapshot));
foreach (var entry in combat.LazyStack.Entries)
lines.Add(CardLine(combat, entry.Card, ++order, "LIFO " + entry.MultiplierLabel, entry.Targets));
if (order == 0) lines.Add("No deferred cards: surviving enemies act next.");
if (order == 0) lines.Add("No deferred cards: ready automation runs before surviving enemies act.");
lines.Add("ENEMIES / current announced intents (after deferred cards; each enemy's start-of-turn status ticks before its action)");
foreach (var enemy in combat.Enemies)
{
+2 -2
View File
@@ -11,7 +11,7 @@ namespace KernelPanic.Combat
public CardInstance Card { get; }
public int MultiplierPercent { get; }
public IReadOnlyList<CombatantState> Targets { get; }
public string MultiplierLabel => $"x{MultiplierPercent / 100}.{MultiplierPercent % 100 / 10}";
public string MultiplierLabel => "x" + (MultiplierPercent / 100m).ToString("0.0#", System.Globalization.CultureInfo.InvariantCulture);
internal LazyStackEntry(CardInstance card, int multiplierPercent)
{
Card = card;
@@ -34,7 +34,7 @@ namespace KernelPanic.Combat
if (card == null || _cards.Contains(card)) return;
int multiplier = 100;
if (card.Definition != null && card.Definition.Language == Language.Haskell)
multiplier = 100 + 50 * Math.Min(3, _entries.Count(e => e.Card.Definition != null && e.Card.Definition.Language == Language.Haskell));
multiplier = CombatTuning.HaskellStackMultiplierPercent(_entries.Count(e => e.Card.Definition != null && e.Card.Definition.Language == Language.Haskell));
_entries.Insert(0, new LazyStackEntry(card, multiplier));
_cards.Insert(0, card);
}
+275
View File
@@ -0,0 +1,275 @@
using System;
using System.Collections.Generic;
using System.Linq;
using KernelPanic.Core;
using KernelPanic.Data;
namespace KernelPanic.Combat
{
public enum PythonOperation { Print, Loop, Draw, List, Zip, Async, Inspect, Install, Unattended, Cinnamon, Update, Timeshift }
public sealed class PythonEffect : ICardEffect
{
private readonly PythonOperation _operation;
private readonly int _amount;
public PythonEffect(PythonOperation operation, int amount) { _operation = operation; _amount = amount; }
public void Execute(CombatContext context) => context.CombatManager.Python.Execute(context, _operation, _amount);
}
public sealed class PythonChoiceOption
{
public string Label { get; }
public bool Enabled { get; }
public PythonChoiceOption(string label, bool enabled = true) { Label = label; Enabled = enabled; }
public CardInstance Card { get; }
public int Cost { get; }
public string ActionLabel { get; }
public PythonChoiceOption(CardInstance card, int cost, string actionLabel, bool enabled = true)
{
Card = card; Cost = cost; ActionLabel = actionLabel;
Label = card.Definition.DisplayName; Enabled = enabled;
}
}
/// <summary>Wave-local FIFO transformations, immutable payload snapshots and bounded background tasks.</summary>
public sealed class PythonPipeline
{
private sealed class Payload
{
public CardInstance Card;
public int Damage, Shield;
public bool All;
public CombatantState Target;
}
private sealed class Script
{
public string Name;
public CardInstance Owner;
public Payload Payload;
public bool Waiting, Restore;
public int FirstRound, Remaining = 2, Uptime, LastRunRound = -1;
}
private readonly List<int> _loops = new(), _areas = new();
private readonly List<Script> _scripts = new();
private readonly Dictionary<CardInstance, int> _temporaryDiscounts = new();
private Action<int> _choose;
private Action _afterChoice;
private CombatManager _combat;
private int _round;
public bool DamageThisPhase { get; private set; }
public bool AutomationRan { get; private set; }
public string ChoiceTitle { get; private set; }
public IReadOnlyList<PythonChoiceOption> Choices { get; private set; } = Array.Empty<PythonChoiceOption>();
public bool HasChoice => _choose != null;
public int AutomationCount => _scripts.Count;
public int RepeatCount => _loops.Count;
public int AreaCount => _areas.Count;
public (int repeats, bool area, bool damageBefore, bool automation) PreviewState(CardInstance card)
{
int round = _combat.RoundNumber;
int loops = _loops.Count(r => round <= r + 1), areas = _areas.Count(r => round <= r + 1);
var ready = _scripts.Where(s => !s.Waiting && !s.Restore && round >= s.FirstRound && round > s.LastRunRound).ToArray();
bool damage = (_round == round && DamageThisPhase) || ready.Any(s => s.Payload.Damage > 0);
bool automated = (_round == round && AutomationRan) || ready.Length > 0;
foreach (var previous in _combat.InterpreterQueue.Cards)
{
if (previous == card) break;
if (!IsPythonCard(previous.Definition)) continue;
string id = previous.Definition.Id;
if (id == "lang_py_for_loop") loops++;
else if (id == "shop_py_zip") areas++;
else if (IsPayload(previous.Definition))
{
if (loops > 0) loops--;
if (id is "lang_py_print" or "shop_py_list_append") { if (areas > 0) areas--; }
if (id != "mint_cinnamon") damage = true;
}
}
return (loops > 0 ? 2 : 1, areas > 0 && card.Definition.Id is "lang_py_print" or "shop_py_list_append", damage, automated);
}
public IEnumerable<string> Readout => new[] { $"Python: repeat {_loops.Count} | area {_areas.Count} | scripts {_scripts.Count}/2" }
.Concat(_scripts.Select(s => s.Waiting ? $"{s.Name}: waiting for payload"
: $"{s.Name}{(s.Name == "async def" ? " / " + s.Payload.Card.Definition.DisplayName : "")}: {s.Remaining} runs remaining"));
public void Bind(CombatManager combat) => _combat = combat;
public void Clear()
{
ExpireDiscounts();
_loops.Clear(); _areas.Clear(); _scripts.Clear(); _choose = null; _afterChoice = null;
Choices = Array.Empty<PythonChoiceOption>(); ChoiceTitle = null;
DamageThisPhase = AutomationRan = false; _round = 0;
}
private void ExpireDiscounts()
{
foreach (var entry in _temporaryDiscounts) entry.Key.TemporaryCostDelta = entry.Value;
_temporaryDiscounts.Clear();
}
public bool Choose(int index)
{
if (!HasChoice || index < 0 || index >= Choices.Count || !Choices[index].Enabled) return false;
var action = _choose;
var afterChoice = _afterChoice;
_afterChoice = null;
_choose = null; Choices = Array.Empty<PythonChoiceOption>(); ChoiceTitle = null;
action(index);
afterChoice?.Invoke();
_combat.NotifyPythonChanged();
return true;
}
public void AfterChoice(Action action)
{
if (HasChoice) _afterChoice += action;
else action();
}
private void Offer(string title, IEnumerable<PythonChoiceOption> options, Action<int> choose)
{
if (HasChoice) throw new InvalidOperationException("Resolve the current Python choice first.");
ChoiceTitle = title; Choices = Array.AsReadOnly(options.ToArray()); _choose = choose;
_combat.NotifyPythonChanged();
}
public static bool IsPythonCard(CardDefinition card) => card != null && card.Language == Language.Python
&& !card.Effects.Any(e => e != null) && CardCatalog.TryGet(card.Id, out var entry)
&& entry.Effects.Any(e => e.Kind == CardEffectKind.Python);
public static bool IsPayload(CardDefinition card) => IsPythonCard(card)
&& card.Id is "lang_py_print" or "shop_py_list_append" or "mint_cinnamon" or "mint_update_manager";
public static bool IsAsync(CardDefinition card) => IsPythonCard(card) && card.Id == "shop_py_async_def";
public static int InspectCount(string distroId, int version) =>
string.Equals(distroId, "ubuntu", StringComparison.OrdinalIgnoreCase) && version >= 3 ? 5 : 3;
public void BeginPhase(int round)
{
_round = round;
ExpireDiscounts();
_loops.RemoveAll(r => round > r + 1); _areas.RemoveAll(r => round > r + 1);
DamageThisPhase = AutomationRan = false;
foreach (var script in _scripts.ToArray())
{
if (script.Waiting || script.Restore || round < script.FirstRound || round <= script.LastRunRound) continue;
script.LastRunRound = round;
AutomationRan = true;
Run(script.Payload, script.Payload.All);
if (--script.Remaining == 0) _scripts.Remove(script);
if (_combat.RunFinished || _combat.AwaitingWaveContinue || _combat.PlayerState.IsDefeated) break;
}
}
public void EndRound()
{
if (_combat.PlayerState.IsDefeated || _combat.RunFinished || _combat.AwaitingWaveContinue) return;
foreach (var script in _scripts.ToArray())
{
if (!script.Restore || _round < script.FirstRound || _round <= script.LastRunRound) continue;
script.LastRunRound = _round;
if (_combat.CanPlayerReceiveCardHeal(script.Owner))
{
int heal = Math.Min(6, Math.Max(0, Math.Min(script.Uptime, _combat.PlayerState.MaxUptime) - _combat.PlayerState.CurrentUptime));
_combat.PlayerState.CurrentUptime += heal;
_combat.ReportEffectResult($"timeshift restored {heal} Uptime");
}
if (--script.Remaining == 0) _scripts.Remove(script);
}
}
private CombatContext Context(CardInstance card, CombatantState target = null) => new(card, _combat.PlayerState,
target == null ? Array.Empty<CombatantState>() : new[] { target }, _combat, _combat.DamagePipeline,
new StatusEffectController(), _combat.DeckController, _combat.HandController, _combat.Enemies);
public void Execute(CombatContext context, PythonOperation operation, int amount)
{
Bind(context.CombatManager);
if (operation is PythonOperation.Print or PythonOperation.List or PythonOperation.Cinnamon or PythonOperation.Update)
{
int value = amount;
if (operation == PythonOperation.List) value = CardScaling.Add(value, (int)Math.Min(int.MaxValue, 2L * Math.Max(0, context.Card.QueuePlayCount - 1)));
if (operation == PythonOperation.Cinnamon && DamageThisPhase) value = 5;
if (operation == PythonOperation.Update && AutomationRan) value = 5;
var payload = new Payload { Card = context.Card.CopyForCombat(), Target = context.Targets.FirstOrDefault(), All = operation == PythonOperation.Update };
if (operation == PythonOperation.Cinnamon) payload.Shield = CardShieldExecutor.ScaleAmount(value, context);
else payload.Damage = CardDamageExecutor.ScaleAmount(value, context);
// Capture the operation once, before applying any temporary repeat/area transformations.
foreach (var script in _scripts.Where(s => s.Waiting))
{ script.Payload = payload; script.Waiting = false; script.FirstRound = _round + 1; }
bool all = payload.All;
if (!all && payload.Damage > 0 && _areas.Count > 0) { all = true; _areas.RemoveAt(0); }
int repeats = 1;
if (_loops.Count > 0) { repeats = 2; _loops.RemoveAt(0); }
for (int i = 0; i < repeats; i++)
{
Run(payload, all);
if (_combat.RunFinished || _combat.AwaitingWaveContinue || context.Source.IsDefeated) break;
}
return;
}
switch (operation)
{
case PythonOperation.Loop:
CardShieldExecutor.Execute(context, CardShieldExecutor.ScaleAmount(amount, context), "for loop");
_loops.Add(_round); break;
case PythonOperation.Zip:
CardDamageExecutor.Execute(context, () => CardDamageExecutor.ScaleAmount(amount, context), Language.Python);
_areas.Add(_round); break;
case PythonOperation.Draw: new FixedDrawEffect(amount).Execute(context); break;
case PythonOperation.Inspect: Inspect(context); break;
case PythonOperation.Install: Install(context); break;
case PythonOperation.Async:
AddScript(new Script { Name = "async def", Owner = context.Card.CopyForCombat(), Waiting = true }); break;
case PythonOperation.Unattended:
int shield = CardShieldExecutor.ScaleAmount(amount, context);
CardShieldExecutor.Execute(context, shield, "unattended-upgrades");
AddScript(new Script { Name = "unattended-upgrades", Owner = context.Card.CopyForCombat(), FirstRound = _round + 1,
Payload = new Payload { Card = context.Card.CopyForCombat(), Shield = shield } }); break;
case PythonOperation.Timeshift:
AddScript(new Script { Name = "timeshift snapshot", Owner = context.Card.CopyForCombat(), Restore = true,
Uptime = context.Source.CurrentUptime, FirstRound = _round + 1 }); break;
}
}
private void Run(Payload payload, bool all)
{
var target = payload.Target;
if (target == null || target.IsDefeated)
target = _combat.Enemies.Where(e => !e.State.IsDefeated).OrderBy(e => e.State.CurrentUptime).Select(e => e.State).FirstOrDefault();
var context = Context(payload.Card, target);
var before = _combat.Enemies.Select(e => (state: e.State, health: (long)e.State.CurrentUptime + e.State.Shield)).ToArray();
if (payload.Damage > 0) CardDamageExecutor.Execute(context, () => payload.Damage, Language.Python, allEnemies: all);
if (before.Any(e => (long)e.state.CurrentUptime + e.state.Shield < e.health)) DamageThisPhase = true;
if (payload.Shield > 0 && !_combat.PlayerState.IsDefeated) CardShieldExecutor.Execute(context, payload.Shield, "Python payload");
}
private void AddScript(Script script)
{
if (_scripts.Count < 2) { _scripts.Add(script); return; }
var existing = _scripts.ToArray();
Offer($"Install {script.Name}: replace a script (2/2 slots)", existing.Select((s, slot) => new PythonChoiceOption($"Slot {slot + 1}: {s.Name}"
+ (s.Name == "async def" && !s.Waiting ? " / " + s.Payload.Card.Definition.DisplayName : "")
+ (s.Waiting ? " — waiting for payload" : $" — {s.Remaining} runs left"))), index =>
{ _scripts.Remove(existing[index]); _scripts.Add(script); });
}
private void Inspect(CombatContext context)
{
var cards = context.DeckController.PeekTop(InspectCount(_combat.RunConfig?.Distro?.Id, _combat.RunConfig?.DistroVersion ?? 1)).ToArray();
if (cards.Length == 0) { _combat.ReportEffectResult("ask ubuntu: draw pile empty"); return; }
if (!cards.Any(context.HandController.CanAdd)) { _combat.ReportEffectResult("ask ubuntu: not enough RAM"); return; }
Offer("ask ubuntu: choose one card; the others keep their order", cards.Select(c =>
new PythonChoiceOption(c, _combat.GetDisplayedPlayCost(c),
context.HandController.CanAdd(c) ? $"> take card / {HandController.GetRamCost(c)} RAM" : $"needs {HandController.GetRamCost(c)} free RAM",
context.HandController.CanAdd(c))),
index => context.DeckController.TakeToHand(cards[index], context.HandController));
}
private void Install(CombatContext context)
{
if (context.HandController.RemainingRam < 1) { _combat.ReportEffectResult("apt install: not enough RAM"); return; }
var pool = _combat.GeneratedCardPool.Where(c => IsPythonCard(c) && !c.DistroExclusive && !c.IsToken && !c.IsJunk)
.GroupBy(c => c.Id).Select(g => g.First()).OrderBy(c => c.Id, StringComparer.Ordinal).ToList();
var offers = new List<CardDefinition>();
while (offers.Count < 3 && pool.Count > 0)
{ int index = RandomRoll.RollRange(0, pool.Count - 1, RollContext.None); offers.Add(pool[index]); pool.RemoveAt(index); }
if (offers.Count == 0) { _combat.ReportEffectResult("apt install: no Python packages available"); return; }
Offer("apt install: choose a temporary card (0 Cycles this turn; exhausts after play)", offers.Select(c =>
new PythonChoiceOption(new CardInstance(c) { ExhaustOnPlay = true }, 0, "> install / 1 RAM")), index =>
{
var card = new CardInstance(offers[index]) { ExhaustOnPlay = true };
if (!context.HandController.Add(card)) return;
_temporaryDiscounts[card] = card.TemporaryCostDelta;
card.TemporaryCostDelta = -card.Definition.CycleCost;
});
}
}
}
+3 -3
View File
@@ -15,12 +15,12 @@ namespace KernelPanic.Data
new(Language.C, "C", "bare metal", ResolutionTrack.Native, $"C is immediate, high-risk burst damage. C damage rolls a {CombatTuning.CCriticalChancePercent}% crit chance instead of the normal 25%, spills {CombatTuning.COverkillSpillPercent}% of remaining overkill into other enemies per jump (rounded down), and C cards can segfault: hurting you and corrupting a hand card. Segfault corruption recovers automatically after 3 rounds. C repair cards restore corrupted cards sooner.", null, Distro("arch", "Arch"), Distro("gentoo", "Gentoo"), Distro("templeos", "TempleOS")),
new(Language.CPlusPlus, "C++", "template arsenal", ResolutionTrack.Native, "C++ is planned as a Native setup/payoff language built from upgraded C cards. It should keep C's direct-hit pressure while adding heavier combo requirements.", "unlock: upgrade a C card during a run"),
new(Language.Rust, "Rust", "safe systems", ResolutionTrack.Native, "Rust is immediate, reliable damage with defensive payoff. Rust overkill becomes Shield, and Rust damage has a tiny 0.001% chance to overflow into the unsigned 64-bit limit.", null, Distro("arch", "Arch"), Distro("fedora", "Fedora")),
new(Language.Python, "Python", "queued scripts", ResolutionTrack.InterpreterQueue, "Python cards enter the interpreter queue instead of resolving immediately. They are slower, but let you stage delayed damage, draw, and repeat effects around the exchange structure.", null, Distro("ubuntu", "Ubuntu"), Distro("kali", "Kali"), Distro("mint", "Mint")),
new(Language.Python, "Python", "pipelines and automation", ResolutionTrack.InterpreterQueue, "Preparation acts immediately. Payloads and modifiers resolve FIFO before enemies: for loop repeats the next payload, zip spreads a single-target payload to all enemies. Unused modifiers expire after the following round. Two automation slots run captured operations for two future rounds. Replays copy damage and Shield only, never draw, growth or installation. Scripts and modifiers clear each wave.", null, Distro("ubuntu", "Ubuntu"), Distro("kali", "Kali"), Distro("mint", "Mint")),
new(Language.JavaScript, "JavaScript", "runtime chaos", ResolutionTrack.Native, "JavaScript resolves immediately and is intentionally swingy: wide damage ranges, chance-based outcomes, and conditional repeat effects. It rewards embracing variance.", null, Distro("ubuntu", "Ubuntu"), Distro("endeavouros", "EndeavourOS"), Distro("mint", "Mint")),
new(Language.TypeScript, "TypeScript", "typed runtime", ResolutionTrack.Native, "TypeScript is planned as the steadier JavaScript branch: Native timing with less chaos and more controlled setup/payoff patterns.", "unlock: upgrade a JavaScript card during a run"),
new(Language.Haskell, "Haskell", "lazy proofs", ResolutionTrack.LazyStack, "Lazy proofs. Build a stack of delayed operations. Later cards gain stronger effects when evaluated. Snapshot x1.0 / x1.5 / x2.0 / x2.5 at play; LIFO after Python. Only damage and explicit Shield multiply.", null, Distro("gentoo", "Gentoo"), Distro("nixos", "NixOS")),
new(Language.Haskell, "Haskell", "lazy proofs", ResolutionTrack.LazyStack, "Lazy proofs. Build a stack of delayed operations. Later cards gain stronger effects when evaluated. Snapshot x1.5 / x1.75 / x2.0 / x2.5 at play; LIFO after Python. Only damage and explicit Shield multiply.", null, Distro("gentoo", "Gentoo"), Distro("nixos", "NixOS")),
new(Language.Assembly, "Assembly", "raw opcodes", ResolutionTrack.Native, "Assembly is planned as the most direct Native language: low-level, high-commitment effects that should trade flexibility for extreme precision or shield-bypass pressure.", null, Distro("templeos", "TempleOS")),
new(Language.Java, "Java", "warming vm", ResolutionTrack.Native, "Java cards are heavy but scale over the run: each Java card uses 2 RAM, Java damage spills overkill into other enemies, and JIT makes Java cards cheaper as you keep playing them. The discount cools after each wave.", null, Distro("debian", "Debian"), Distro("fedora", "Fedora")),
new(Language.Java, "Java", "warming vm", ResolutionTrack.Native, "Each Java card uses 2 RAM and spills overkill into other enemies. JIT gives -1 Cycle per 2 Java plays, capped at -3. Store at most 6 warmup plays; lose 2 after each wave, cooling the discount by 1.", null, Distro("debian", "Debian"), Distro("fedora", "Fedora")),
new(Language.Go, "Go", "small services", ResolutionTrack.Native, "Go is planned as a straightforward Native language for small, dependable actions. Its identity should be simple scaling, services, and concurrency-style utility without much randomness.", null, Distro("cachyos", "CachyOS"), Distro("nixos", "NixOS")),
new(Language.Ruby, "Ruby", "sharp scripts", ResolutionTrack.InterpreterQueue, "Ruby is planned as an interpreter-queue combo language: delayed scripting with expressive effects that should get better when sequenced with other queued cards.", null, Distro("kali", "Kali"), Distro("endeavouros", "EndeavourOS")),
new(Language.Php, "PHP", "legacy glue", ResolutionTrack.InterpreterQueue, "PHP is planned as a queued utility language that benefits from messy boards and legacy leftovers: practical, delayed effects that turn clutter into value.", null, Distro("debian", "Debian"), Distro("cachyos", "CachyOS")),
+100
View File
@@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.IO;
using KernelPanic.Combat;
using KernelPanic.Core;
namespace KernelPanic.Meta
{
/// <summary>Records real gameplay immediately, independently of run rewards and checkpoints.</summary>
public sealed class DailyQuestTracker : IDisposable
{
private readonly SaveService _save;
private readonly Func<bool> _eligible;
private readonly Func<CombatantState> _player;
private readonly Func<DateTime> _utcNow;
private readonly List<(DailyQuestKind kind, int amount, DateTime time)> _pending = new();
public string SaveError { get; private set; }
public DailyQuestTracker(SaveService save, Func<bool> eligible, Func<CombatantState> player,
Func<DateTime> utcNow = null)
{
_save = save;
_eligible = eligible;
_player = player;
_utcNow = utcNow ?? (() => DateTime.UtcNow);
GameEvents.WaveCleared += OnWaveCleared;
GameEvents.CardPlayed += OnCardPlayed;
GameEvents.DamageDealt += OnDamageDealt;
GameEvents.PhaseChanged += OnPhaseChanged;
}
private void OnWaveCleared(WaveClearedEvent evt)
{
Record(DailyQuestKind.Waves, 1);
if (evt.WaveNumber == 5) Record(DailyQuestKind.WaveFive, 1);
}
private void OnCardPlayed(CardPlayedEvent evt)
{
Record(DailyQuestKind.Cards, 1);
if (evt.Track == ResolutionTrack.Native) Record(DailyQuestKind.NativeCards, 1);
}
private void OnPhaseChanged(PhaseChangedEvent evt)
{
if (evt.PreviousPhase == TurnPhase.EnemyProcess && evt.NextPhase == TurnPhase.GarbageCollection
&& _player()?.CurrentUptime > 0) Record(DailyQuestKind.SurviveRounds, 1);
}
private void OnDamageDealt(DamageDealtEvent evt)
{
var player = _player();
if (player != null && ReferenceEquals(evt.Source, player) && !ReferenceEquals(evt.Target, player))
{
Record(DailyQuestKind.Damage, evt.UptimeDamage);
Record(DailyQuestKind.ShieldDamage, evt.ShieldDamage);
}
else if (player != null && ReferenceEquals(evt.Target, player) && !ReferenceEquals(evt.Source, player))
Record(DailyQuestKind.BlockDamage, evt.ShieldDamage);
}
private void Record(DailyQuestKind kind, int amount)
{
if (!_eligible() || amount <= 0) return;
_pending.Add((kind, amount, _utcNow()));
Flush();
}
public bool Flush()
{
if (_pending.Count == 0) return true;
try
{
// Reload before every transaction so checkpoint and run settlement writes are preserved.
var data = _save.Load();
bool changed = false;
foreach (var entry in _pending)
changed |= DailyQuests.Record(data.dailyQuests, entry.kind, entry.amount, entry.time);
changed |= DailyQuests.Refresh(data.dailyQuests, _utcNow());
if (changed) _save.Save(data);
_pending.Clear();
SaveError = null;
return true;
}
catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
{
SaveError = ex.Message;
return false;
}
}
public void Dispose()
{
GameEvents.WaveCleared -= OnWaveCleared;
GameEvents.CardPlayed -= OnCardPlayed;
GameEvents.DamageDealt -= OnDamageDealt;
GameEvents.PhaseChanged -= OnPhaseChanged;
Flush();
}
}
}
+198
View File
@@ -0,0 +1,198 @@
using System;
using System.Collections.Generic;
namespace KernelPanic.Meta
{
// Keep values stable: selections and claim bits are persisted in player saves.
public enum DailyQuestKind { Waves, Cards, Damage, BlockDamage, NativeCards, ShieldDamage, SurviveRounds, WaveFive }
[Serializable]
public sealed class DailyQuestState
{
public long refreshAtUtcTicks;
public int waves;
public int cards;
public int damage;
public int claimedMask;
public DailyQuestKind[] selectedQuests;
public int selectionSeed;
public int blockedDamage;
public int nativeCards;
public int shieldDamage;
public int survivedRounds;
public int waveFive;
}
/// <summary>One persistent, rolling 24-hour window. All time comes from the caller for deterministic tests.</summary>
public static class DailyQuests
{
public const int Count = 3;
public const long PeriodTicks = TimeSpan.TicksPerDay;
public static readonly IReadOnlyList<DailyQuestKind> Pool = Array.AsReadOnly((DailyQuestKind[])Enum.GetValues(typeof(DailyQuestKind)));
private static readonly DailyQuestKind[] LegacySelection = { DailyQuestKind.Waves, DailyQuestKind.Cards, DailyQuestKind.Damage };
public static IReadOnlyList<DailyQuestKind> Active(DailyQuestState state) =>
ValidSelection(state.selectedQuests) ? state.selectedQuests : LegacySelection;
public static bool IsActive(DailyQuestState state, DailyQuestKind kind)
{
foreach (var selected in Active(state)) if (selected == kind) return true;
return false;
}
private static bool ValidSelection(DailyQuestKind[] selection)
{
if (selection == null || selection.Length != Count) return false;
for (int i = 0; i < selection.Length; i++)
{
if (!Enum.IsDefined(typeof(DailyQuestKind), selection[i])) return false;
for (int j = 0; j < i; j++) if (selection[i] == selection[j]) return false;
}
return true;
}
private static void PickQuests(DailyQuestState state)
{
if (state.selectionSeed == 0)
{
state.selectionSeed = Guid.NewGuid().GetHashCode();
if (state.selectionSeed == 0) state.selectionSeed = 1;
}
// Local randomness never consumes the combat, shop, or Unity RNG streams.
var random = new Random(unchecked(state.selectionSeed ^ (int)state.refreshAtUtcTicks ^ (int)(state.refreshAtUtcTicks >> 32)));
var candidates = (DailyQuestKind[])Enum.GetValues(typeof(DailyQuestKind));
for (int i = candidates.Length - 1; i > 0; i--)
{
int swap = random.Next(i + 1);
(candidates[i], candidates[swap]) = (candidates[swap], candidates[i]);
}
bool sameSet = ValidSelection(state.selectedQuests);
for (int i = 0; i < Count; i++) sameSet &= IsActive(state, candidates[i]);
if (sameSet) (candidates[Count - 1], candidates[Count]) = (candidates[Count], candidates[Count - 1]);
state.selectedQuests = new DailyQuestKind[Count];
Array.Copy(candidates, state.selectedQuests, Count);
}
public static int Target(DailyQuestKind kind) => kind switch
{
DailyQuestKind.Waves => 3,
DailyQuestKind.Cards => 25,
DailyQuestKind.Damage => 200,
DailyQuestKind.BlockDamage => 40,
DailyQuestKind.NativeCards => 15,
DailyQuestKind.ShieldDamage => 60,
DailyQuestKind.SurviveRounds => 8,
DailyQuestKind.WaveFive => 1,
_ => throw new ArgumentOutOfRangeException(nameof(kind))
};
// Routine actions < focused combat objectives < sustained/encounter-dependent play < wave-5 milestone.
// Display and settlement share this table; rewards are not persisted separately from claim flags.
public static (int Bandwidth, int Entropy) Reward(DailyQuestKind kind) => kind switch
{
DailyQuestKind.Cards => (75, 25),
DailyQuestKind.NativeCards => (75, 25),
DailyQuestKind.Damage => (100, 50),
DailyQuestKind.BlockDamage => (100, 50),
DailyQuestKind.Waves => (150, 75),
DailyQuestKind.ShieldDamage => (150, 75),
DailyQuestKind.SurviveRounds => (150, 75),
DailyQuestKind.WaveFive => (250, 125),
_ => throw new ArgumentOutOfRangeException(nameof(kind))
};
public static string Description(DailyQuestKind kind) => kind switch
{
DailyQuestKind.Waves => "Clear 3 waves",
DailyQuestKind.Cards => "Play 25 cards",
DailyQuestKind.Damage => "Deal 200 Uptime damage",
DailyQuestKind.BlockDamage => "Block 40 damage with Shield",
DailyQuestKind.NativeCards => "Play 15 Native cards",
DailyQuestKind.ShieldDamage => "Deal 60 damage to enemy Shields",
DailyQuestKind.SurviveRounds => "Survive 8 enemy rounds",
DailyQuestKind.WaveFive => "Clear wave 5",
_ => throw new ArgumentOutOfRangeException(nameof(kind))
};
public static int Progress(DailyQuestState state, DailyQuestKind kind) => Math.Clamp(kind switch
{
DailyQuestKind.Waves => state.waves,
DailyQuestKind.Cards => state.cards,
DailyQuestKind.Damage => state.damage,
DailyQuestKind.BlockDamage => state.blockedDamage,
DailyQuestKind.NativeCards => state.nativeCards,
DailyQuestKind.ShieldDamage => state.shieldDamage,
DailyQuestKind.SurviveRounds => state.survivedRounds,
DailyQuestKind.WaveFive => state.waveFive,
_ => throw new ArgumentOutOfRangeException(nameof(kind))
}, 0, Target(kind));
public static bool Claimed(DailyQuestState state, DailyQuestKind kind) =>
(state.claimedMask & (1 << (int)kind)) != 0;
public static bool Refresh(DailyQuestState state, DateTime utcNow)
{
long now = utcNow.ToUniversalTime().Ticks;
if (state.refreshAtUtcTicks > now && state.refreshAtUtcTicks <= DateTime.MaxValue.Ticks)
{
if (ValidSelection(state.selectedQuests)) return false;
// Schema 7 had three fixed quests. Preserve that day's progress and rewards.
state.selectedQuests = (DailyQuestKind[])LegacySelection.Clone();
return true;
}
// Advance by whole periods, retaining the original reset time even after days away.
if (state.refreshAtUtcTicks > 0 && !ValidSelection(state.selectedQuests))
state.selectedQuests = (DailyQuestKind[])LegacySelection.Clone();
state.refreshAtUtcTicks = state.refreshAtUtcTicks > 0 && state.refreshAtUtcTicks <= now
? state.refreshAtUtcTicks + ((now - state.refreshAtUtcTicks) / PeriodTicks + 1) * PeriodTicks
: now + PeriodTicks;
state.waves = state.cards = state.damage = state.claimedMask = 0;
state.blockedDamage = state.nativeCards = state.shieldDamage = state.survivedRounds = state.waveFive = 0;
PickQuests(state);
return true;
}
public static bool Record(DailyQuestState state, DailyQuestKind kind, int amount, DateTime utcNow)
{
if (amount <= 0 || !Enum.IsDefined(typeof(DailyQuestKind), kind)) return false;
bool changed = Refresh(state, utcNow);
// Delayed retries from an expired period must not count toward today's quests.
if (utcNow.ToUniversalTime().Ticks < state.refreshAtUtcTicks - PeriodTicks || !IsActive(state, kind)) return changed;
int previous = Progress(state, kind);
int next = (int)Math.Min(Target(kind), (long)previous + amount);
switch (kind)
{
case DailyQuestKind.Waves: state.waves = next; break;
case DailyQuestKind.Cards: state.cards = next; break;
case DailyQuestKind.Damage: state.damage = next; break;
case DailyQuestKind.BlockDamage: state.blockedDamage = next; break;
case DailyQuestKind.NativeCards: state.nativeCards = next; break;
case DailyQuestKind.ShieldDamage: state.shieldDamage = next; break;
case DailyQuestKind.SurviveRounds: state.survivedRounds = next; break;
case DailyQuestKind.WaveFive: state.waveFive = next; break;
}
return changed || next != previous;
}
public static bool Claim(SaveData data, DailyQuestKind kind, long expectedRefresh, DateTime utcNow)
{
data.dailyQuests ??= new DailyQuestState();
Refresh(data.dailyQuests, utcNow);
if (!Enum.IsDefined(typeof(DailyQuestKind), kind) || !IsActive(data.dailyQuests, kind) || data.dailyQuests.refreshAtUtcTicks != expectedRefresh
|| Claimed(data.dailyQuests, kind) || Progress(data.dailyQuests, kind) < Target(kind)) return false;
var reward = Reward(kind);
if (data.bandwidthBalance > int.MaxValue - reward.Bandwidth
|| data.entropyBalance > int.MaxValue - reward.Entropy) return false;
data.dailyQuests.claimedMask |= 1 << (int)kind;
data.bandwidthBalance += reward.Bandwidth;
data.entropyBalance += reward.Entropy;
return true;
}
public static string Countdown(DailyQuestState state, DateTime utcNow)
{
var remaining = TimeSpan.FromTicks(Math.Max(0, state.refreshAtUtcTicks - utcNow.ToUniversalTime().Ticks));
return $"refresh in {(int)remaining.TotalHours:00}:{remaining.Minutes:00}:{remaining.Seconds:00}";
}
}
}
+1 -1
View File
@@ -43,7 +43,7 @@ namespace KernelPanic.Meta
{
1 => "start of turn: apt update chooses the cheaper of top 2 draw cards",
2 => "apt update looks at top 3 instead of top 2",
3 => "ask ubuntu draws 3 instead of 2",
3 => "ask ubuntu inspects 5 cards instead of 3; take one",
4 => "apt update card costs 1 less this turn",
5 => "once per combat, empty hand refills up to RAM",
_ => "--"
+229 -5
View File
@@ -38,6 +38,13 @@ namespace KernelPanic.Run
}
// Install before the menu's OnEnable can schedule the animated boot sequence.
UIPreferences.ReducedMotion = true; // Session only; never writes preferences.
if (args.Contains("--kernel-panic-python-ui-smoke") || args.Contains("--kernel-panic-route-ui-smoke"))
{
var fixture = SaveData.CreateDefault();
fixture.starterChosen = true;
fixture.ownedUnits.Add(new OwnedUnitSaveEntry { id = "ubuntu", version = 3 });
new SaveService().Save(fixture);
}
if (args.Contains("--kernel-panic-quest-ui-smoke"))
{
// The unused, isolated save-path guard above also applies to this UI fixture.
@@ -77,6 +84,18 @@ namespace KernelPanic.Run
try
{
if (_failure != null) throw new InvalidOperationException(_failure);
var choosingCombat = FindFirstObjectByType<CombatManager>();
if (choosingCombat?.Python.HasChoice == true && !Environment.GetCommandLineArgs().Contains("--kernel-panic-python-ui-smoke"))
{
var document = FindFirstObjectByType<CombatSceneController>()?.GetComponent<UIDocument>();
for (int i = 0; i < choosingCombat.Python.Choices.Count; i++)
{
var button = document?.rootVisualElement.Q<Button>($"PythonChoice{i}");
if (button?.enabledInHierarchy != true) continue;
Submit(button);
break;
}
}
if (Time.realtimeSinceStartup > _deadline) throw new TimeoutException("Smoke check timed out at " + _stage);
next = scenario.MoveNext();
if (next) yielded = scenario.Current;
@@ -107,6 +126,18 @@ namespace KernelPanic.Run
yield return new WaitForSecondsRealtime(2);
var menu = FindFirstObjectByType<MainMenuController>();
Require(menu != null, "Main menu scene did not initialize.");
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-route-ui-smoke"))
{
var routeScenario = RouteUiScenario(menu);
while (routeScenario.MoveNext()) yield return routeScenario.Current;
yield break;
}
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-python-ui-smoke"))
{
var pythonScenario = PythonUiScenario(menu);
while (pythonScenario.MoveNext()) yield return pythonScenario.Current;
yield break;
}
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-quest-ui-smoke"))
{
var questScenario = QuestUiScenario(menu);
@@ -576,6 +607,186 @@ namespace KernelPanic.Run
commandInput.SendEvent(enter);
}
private IEnumerator RouteUiScenario(MainMenuController menu)
{
_stage = "route map UI fixture";
Call(menu, "CompleteBootIntro"); ConfigureMenu(menu); Call(menu, "BootSelectedPackage");
CombatManager combat = null;
while (combat == null || !combat.CanSurrenderRun)
{ yield return null; combat = FindFirstObjectByType<CombatManager>(); }
var view = FindFirstObjectByType<CombatSceneController>();
var run = combat.GetComponent<RunManager>();
var document = view.GetComponent<UIDocument>();
// UI fixture only: remove enemies to exercise real repository transitions without a combat bot.
Field<System.Collections.Generic.List<EnemyInstance>>(combat, "_enemies").Clear();
Call(combat, "CheckWin");
yield return null;
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
var capture = CapturePanel(document, "route-map");
while (capture.MoveNext()) yield return capture.Current;
var back = document.rootVisualElement.Q<Button>("BackToRepositoryButton");
var next = document.rootVisualElement.Q<Button>("ConfirmRouteButton");
Require(Mathf.Abs(back.worldBound.width - next.worldBound.width) < 2, "Route footer buttons must have equal widths.");
Require(Mathf.Abs(back.worldBound.height - next.worldBound.height) < 2, "Route footer buttons must have equal heights.");
Require(next.worldBound.xMax <= document.rootVisualElement.worldBound.xMax, "Continue button exceeds the screen.");
var position = document.rootVisualElement.Q("CurrentMapPosition");
Require(position != null, "Map is missing the player's current position.");
if (Screen.height >= 720)
{
var viewport = document.rootVisualElement.Q<ScrollView>(className: "repository-body").contentViewport;
Require(position.Q<Label>(className: "route-map-here").worldBound.yMax <= viewport.worldBound.yMax + 1,
"Current-position marker should be visible together with the upcoming route.");
}
Submit(document.rootVisualElement.Q<Button>("RouteSacrifice"));
Require(document.rootVisualElement.Q("RouteEvent") == null, "Map must not contain event controls.");
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
Require(document.rootVisualElement.Q("RunMap") == null && document.rootVisualElement.Q("RouteEventScreen") != null,
"Entering a stop must open its own screen.");
string untouched = DeckSignature(run);
Submit(document.rootVisualElement.Q<Button>("BackToRouteButton"));
Require(document.rootVisualElement.Q("RunMap") != null && DeckSignature(run) == untouched, "Backing out of an event changed the deck.");
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
capture = CapturePanel(document, "route-sacrifice");
while (capture.MoveNext()) yield return capture.Current;
int count = run.RunDeck.Count, magnitude = run.RunDeck.Sum(c => c.MagnitudeBonus);
Require(document.rootVisualElement.Q<Button>("ConfirmRouteButton") == null, "Unresolved events must not offer departure.");
var commit = document.rootVisualElement.Q<Button>("ResolveRouteEventButton");
capture = CapturePanel(document, "route-sacrifice-confirm");
while (capture.MoveNext()) yield return capture.Current;
Submit(commit);
Require(run.RunDeck.Count == count - 1 && run.RunDeck.Sum(c => c.MagnitudeBonus) == magnitude + 4, "Sacrifice did not remove one card and grant +4 effect.");
string deck = DeckSignature(run);
Require(!document.rootVisualElement.Q<Button>("BackToRouteButton").enabledInHierarchy, "Committed stop must not allow undoing the path.");
Submit(document.rootVisualElement.Q<Button>("SaveAndExitRunButton"));
menu = null;
while (menu == null) { yield return null; menu = FindFirstObjectByType<MainMenuController>(); }
Call(menu, "ResumeSavedRun"); combat = null;
while (combat == null || !combat.AwaitingWaveContinue)
{ yield return null; combat = FindFirstObjectByType<CombatManager>(); }
view = FindFirstObjectByType<CombatSceneController>(); run = combat.GetComponent<RunManager>(); document = view.GetComponent<UIDocument>();
Require(DeckSignature(run) == deck && !run.RouteEventPending && !run.ResolveRouteEvent(skip: true), "Resume replayed or lost the route event.");
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
capture = CapturePanel(document, "route-resumed");
while (capture.MoveNext()) yield return capture.Current;
for (int wave = 2; wave <= 3; wave++)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
while (!combat.CanSurrenderRun) yield return null;
Require(run.CurrentWaveNumber == wave, "Map departure skipped a wave.");
Field<System.Collections.Generic.List<EnemyInstance>>(combat, "_enemies").Clear(); Call(combat, "CheckWin");
yield return null;
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
if (run.BuildRewardPending)
{
Require(document.rootVisualElement.Q("RunMap") == null && document.rootVisualElement.Q("BuildRewardScreen") != null,
"Build reward must have its own screen.");
capture = CapturePanel(document, "build-reward");
while (capture.MoveNext()) yield return capture.Current;
Submit(document.rootVisualElement.Q<Button>("RewardBits"));
Require(document.rootVisualElement.Q("BuildRewardScreen") == null && document.rootVisualElement.Q("RunMap") != null,
"Claiming a reward must open the map.");
}
if (run.RouteEventPending)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
Submit(document.rootVisualElement.Q<Button>("SkipRouteEventButton"));
}
capture = CapturePanel(document, "route-history-" + wave);
while (capture.MoveNext()) yield return capture.Current;
}
Require(run.AvailableRouteNodes.Count >= 2 && run.Journey.visits.Count == 2, "Expected branching routes and two past choices.");
var journal = document.rootVisualElement.Q<Foldout>("RouteHistory"); journal.value = true;
document.rootVisualElement.Q<ScrollView>(className: "repository-body").ScrollTo(journal);
capture = CapturePanel(document, "route-journal");
while (capture.MoveNext()) yield return capture.Current;
journal.value = false;
for (int wave = 4; wave <= RunJourney.BossWave; wave++)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
while (!combat.CanSurrenderRun) yield return null;
Require(run.CurrentWaveNumber == wave && !run.CampaignChoicePending, "Extended route ended before its final boss.");
if (wave == RunJourney.BossWave)
Require(combat.Enemies.Count(e => e.ArchetypeId == "kernel_overseer") == 1, "Final tier did not lead to the boss.");
Field<System.Collections.Generic.List<EnemyInstance>>(combat, "_enemies").Clear(); Call(combat, "CheckWin");
yield return null;
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
if (run.BuildRewardPending) Submit(document.rootVisualElement.Q<Button>("RewardBits"));
capture = CapturePanel(document, "route-stage-" + run.CurrentWaveNumber);
while (capture.MoveNext()) yield return capture.Current;
if (run.CampaignChoicePending) break;
if (run.RouteEventPending)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
Submit(document.rootVisualElement.Q<Button>("SkipRouteEventButton"));
}
}
Require(run.CampaignChoicePending && run.Journey.visits.Count == 9, "Normal route must finish after nine route departures and ten battles.");
string completedDeck = DeckSignature(run), completedRun = run.RunId;
Submit(document.rootVisualElement.Q<Button>("ContinueEndlessButton"));
Require(run.Journey.endless && run.RunId == completedRun && DeckSignature(run) == completedDeck, "Survival transition lost the completed build.");
if (run.RouteEventPending)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
Submit(document.rootVisualElement.Q<Button>("SkipRouteEventButton"));
}
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
while (!combat.CanSurrenderRun) yield return null;
Require(run.CurrentWaveNumber == 11, "Survival must start at wave eleven.");
capture = CapturePanel(document, "route-survival");
while (capture.MoveNext()) yield return capture.Current;
_campaignSuccess = "PASS: ten-wave route UI, separate rewards/events, sacrifice, exact save/resume, full travelled history, boss convergence and wave-eleven survival with the same build.";
}
private IEnumerator PythonUiScenario(MainMenuController menu)
{
_stage = "Python selection UI";
Call(menu, "CompleteBootIntro");
ConfigureMenu(menu);
Call(menu, "BootSelectedPackage");
CombatManager combat = null;
while (combat == null || !combat.CanSurrenderRun)
{
yield return null;
combat = FindFirstObjectByType<CombatManager>();
}
var view = FindFirstObjectByType<CombatSceneController>();
var document = view.GetComponent<UIDocument>();
var database = Field<CardDatabase>(view, "cardDatabase");
combat.HandController.Clear();
combat.HandController.SetRamCapacity(10);
foreach (string id in new[] { "ubuntu_apt_install", "ubuntu_ask_ubuntu", "ubuntu_unattended_upgrades" })
{
if (id == "ubuntu_ask_ubuntu")
foreach (string offer in new[] { "mint_timeshift", "ubuntu_ask_ubuntu", "lang_py_print", "shop_py_async_def", "shop_py_zip" })
combat.DeckController.AddToDrawPile(new CardInstance(database.FindById(offer)), false);
var card = new CardInstance(database.FindById(id));
var context = new CombatContext(card, combat.PlayerState, Array.Empty<CombatantState>(), combat,
combat.DamagePipeline, new StatusEffectController(), combat.DeckController, combat.HandController, combat.Enemies);
int repeats = id == "ubuntu_unattended_upgrades" ? 3 : 1;
for (int i = 0; i < repeats; i++)
foreach (var effect in CardEffectFactory.CreateEffects(card.Definition)) effect.Execute(context);
Call(view, "RefreshOverlay");
yield return null;
Require(combat.Python.HasChoice, "Expected a Python choice for " + id);
var capture = CapturePanel(document, id);
while (capture.MoveNext()) yield return capture.Current;
var dialog = document.rootVisualElement.Q("PythonChoiceDialog");
Require(dialog != null && dialog.worldBound.yMin >= -1
&& dialog.worldBound.yMax <= document.rootVisualElement.worldBound.yMax + 1, "Choice dialog exceeds viewport.");
if (id == "ubuntu_ask_ubuntu")
{
Require(combat.Python.Choices.Count == 5, "Ubuntu V3 must offer five cards.");
var last = dialog.Q<Button>("PythonChoice4");
last.Focus();
capture = CapturePanel(document, "inspect-last-card");
while (capture.MoveNext()) yield return capture.Current;
}
Submit(dialog.Query<Button>().ToList().First(button => button.enabledInHierarchy));
Require(!combat.Python.HasChoice, "Submitting a card must resolve the choice.");
}
_campaignSuccess = "PASS: install, Ubuntu V3 five-card inspection, Timeshift description, script replacement, keyboard selection and runtime panel captures.";
}
private IEnumerator QuestUiScenario(MainMenuController menu)
{
_stage = "daily quest widget";
@@ -659,7 +870,8 @@ namespace KernelPanic.Run
{
Require(document.rootVisualElement.Q("RunRouteChoices") == null, "Shop must not contain route choices.");
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
Require(combat.AwaitingWaveContinue && document.rootVisualElement.Q("RouteSelectionScreen") != null,
Require(combat.AwaitingWaveContinue && (document.rootVisualElement.Q("RouteSelectionScreen") != null
|| document.rootVisualElement.Q("BuildRewardScreen") != null),
"Boot must open route selection before starting combat.");
if (run.BuildRewardPending)
{
@@ -679,7 +891,13 @@ namespace KernelPanic.Run
: offer.Kind == RepositoryOfferKind.CardUpgrade ? 80 : 10).ToArray())
if (offer.Price <= run.Bits) run.BuyOffer(offer, combat.PlayerState);
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
Submit(document.rootVisualElement.Q<Button>("RouteRepair"));
var repair = document.rootVisualElement.Q<Button>("RouteRepair");
if (repair?.enabledInHierarchy == true) Submit(repair);
if (run.RouteEventPending)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
Submit(document.rootVisualElement.Q<Button>("SkipRouteEventButton"));
}
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
}
else if (combat.CanSurrenderRun)
@@ -716,7 +934,7 @@ namespace KernelPanic.Run
}
yield return null;
}
Require(!combat.RunLost && run.WavesCleared == 5 && capturedBoss, "Seeded campaign bot did not clear the boss.");
Require(!combat.RunLost && run.WavesCleared == RunJourney.BossWave && capturedBoss, "Seeded campaign bot did not clear the boss.");
_stage = "campaign milestone";
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
var milestone = CapturePanel(document, "campaign-milestone");
@@ -728,8 +946,14 @@ namespace KernelPanic.Run
if (endless)
{
Submit(document.rootVisualElement.Q<Button>("ContinueEndlessButton"));
if (run.RouteEventPending)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
Submit(document.rootVisualElement.Q<Button>("SkipRouteEventButton"));
}
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
while (!combat.CanSurrenderRun) yield return null;
Require(run.Journey.endless && run.CurrentWaveNumber == 6 && run.RunId == runId && !run.RewardsSettled,
Require(run.Journey.endless && run.CurrentWaveNumber == RunJourney.BossWave + 1 && 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;
@@ -747,7 +971,7 @@ namespace KernelPanic.Run
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, "
_campaignSuccess = "PASS: real ten-wave campaign, repair route, purchases, boss, "
+ (endless ? "endless continuation, surrender" : "victory") + ", saved rewards/history exactly once, menu return.";
}
+2 -1
View File
@@ -43,9 +43,10 @@ namespace KernelPanic.Run
public ResolvedRunCheckpoint Resolve(DistroDatabase distros, CardDatabase cards,
LanguageDeckDatabase languages, PackageDatabase packageDatabase)
{
Require(version >= 1 && version <= 3, "This checkpoint needs a different game version.");
Require(version >= 1 && version <= 4, "This checkpoint needs a different game version.");
Require(version < 2 || journey != null, "Missing saved route decisions.");
journey?.Validate(wave);
journey?.ValidateMap(seed, 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.");
+57 -11
View File
@@ -1,14 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace KernelPanic.Run
{
public enum WaveRoute { Repair, Challenge }
public enum WaveRoute { Repair, Challenge, Encounter, Cache, Forge, Sacrifice, Recycle }
/// <summary>Serializable route decisions, independent of combat and repository presentation.</summary>
[Serializable]
public sealed class RunJourney
{
public const int BossWave = 5;
public const int BossWave = 10;
public const int LegacyBossWave = 5;
public const int RepairUptime = 6;
public const int ChallengeBits = 4;
public bool campaign;
@@ -19,23 +22,66 @@ namespace KernelPanic.Run
public int encounterRevision;
public int pendingRewardWave;
public int claimedRewardWave;
public int mapRevision;
public int mapStartWave = 2;
public int selectedNodeId;
public int resolvedEventWave;
public string eventOutcome;
public List<RouteVisit> visits = new();
public bool AtMilestone(int wavesCleared) => campaign && !endless && wavesCleared >= BossWave;
public static RunJourney NewCampaign() => new() { campaign = true, encounterRevision = 1 };
public RunJourney Copy() => (RunJourney)MemberwiseClone();
// Revisions are persisted: an existing route must never change underneath its saved decisions.
public int FinalWave => encounterRevision >= 2 ? BossWave : LegacyBossWave;
public bool IsRewardWave(int wave) => encounterRevision > 0 && wave >= 2 && wave < FinalWave && wave % 2 == 0;
public bool AtMilestone(int wavesCleared) => campaign && !endless && wavesCleared >= FinalWave;
public static RunJourney NewCampaign() => new() { campaign = true, encounterRevision = 2, mapRevision = 2 };
public RunJourney Copy()
{
var copy = (RunJourney)MemberwiseClone();
copy.visits = (visits ?? new List<RouteVisit>()).Select(v => v.Copy()).ToList();
return copy;
}
public void Validate(int wave)
{
RunCheckpoint.Require(encounterRevision >= 0 && encounterRevision <= 1, "Unsupported encounter revision.");
RunCheckpoint.Require((pendingRewardWave == 0 || pendingRewardWave == 2 || pendingRewardWave == 4)
&& (claimedRewardWave == 0 || claimedRewardWave == 2 || claimedRewardWave == 4)
RunCheckpoint.Require(encounterRevision >= 0 && encounterRevision <= 2, "Unsupported encounter revision.");
RunCheckpoint.Require((pendingRewardWave == 0 || IsRewardWave(pendingRewardWave))
&& (claimedRewardWave == 0 || IsRewardWave(claimedRewardWave))
&& claimedRewardWave < wave
&& (pendingRewardWave == 0 || (campaign && encounterRevision == 1
&& (pendingRewardWave == 0 || (campaign && encounterRevision > 0
&& pendingRewardWave == wave - 1 && pendingRewardWave > claimedRewardWave)), "Invalid saved reward choice.");
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.");
RunCheckpoint.Require(!endless || (campaign && wave > FinalWave), "Invalid endless-mode checkpoint.");
RunCheckpoint.Require(!campaign || endless || wave <= FinalWave + 1, "Missing campaign completion choice.");
RunCheckpoint.Require(mapRevision >= 0 && mapRevision <= 2, "Unsupported route map.");
if (mapRevision == 0) return;
RunCheckpoint.Require(campaign && mapStartWave >= 2 && mapStartWave <= wave,
"Invalid route map start.");
RunCheckpoint.Require(visits != null && visits.Count <= wave && visits.All(v => v != null
&& v.wave >= mapStartWave && v.wave < wave && v.nodeId / 10 == v.wave
&& Enum.IsDefined(typeof(WaveRoute), v.route) && v.cleared), "Invalid route history.");
RunCheckpoint.Require(visits.Select(v => v.wave).Distinct().Count() == visits.Count,
"Duplicate route history.");
RunCheckpoint.Require(resolvedEventWave == 0 || resolvedEventWave == wave,
"Invalid route event claim.");
}
public void ValidateMap(int seed, int wave)
{
if (mapRevision == 0) return;
RouteNode previous = null;
foreach (var visit in visits)
{
var node = RunRouteMap.Row(seed, visit.wave, mapStartWave, mapRevision).FirstOrDefault(n => n.Id == visit.nodeId);
RunCheckpoint.Require(node != null && node.Route == visit.route
&& (previous == null ? visit.wave == mapStartWave : RunRouteMap.Connected(seed, previous, node, mapStartWave, mapRevision)),
"Disconnected route history.");
previous = node;
}
RunCheckpoint.Require(visits.Count == Math.Max(0, wave - mapStartWave), "Incomplete route history.");
var selected = RunRouteMap.Available(seed, wave, this).FirstOrDefault(n => n.Id == selectedNodeId);
RunCheckpoint.Require(selected != null && selected.Route == selectedRoute, "Unavailable saved route.");
RunCheckpoint.Require(resolvedEventWave == 0 || RunRouteMap.IsEvent(selectedRoute), "Unexpected event claim.");
}
}
}
+114 -3
View File
@@ -59,6 +59,80 @@ namespace KernelPanic.Run
public bool CampaignChoicePending => Journey.AtMilestone(_wavesCleared);
public bool BuildRewardPending => Journey.pendingRewardWave > 0;
public const int BuildRewardBits = 8;
public bool RouteEventPending => Journey.mapRevision > 0 && RunRouteMap.IsEvent(Journey.selectedRoute)
&& Journey.resolvedEventWave != currentWaveNumber;
public IReadOnlyList<RouteNode> AvailableRouteNodes => CurrentConfig == null ? Array.Empty<RouteNode>()
: RunRouteMap.Available(CurrentConfig.RunSeed, currentWaveNumber, Journey);
private void EnsureRouteSelection()
{
if (Journey.mapRevision == 0) return;
var available = AvailableRouteNodes;
if (available.Any(n => n.Id == Journey.selectedNodeId)) return;
var node = available.FirstOrDefault(n => n.Route == WaveRoute.Repair)
?? available.FirstOrDefault(n => !RunRouteMap.IsEvent(n.Route)) ?? available.FirstOrDefault();
if (node == null) return;
Journey.selectedNodeId = node.Id;
Journey.selectedRoute = node.Route;
}
public bool SelectRouteNode(int nodeId)
{
if (!isRunActive || IsSuspended || !_repositoryVisitActive || CampaignChoicePending
|| Journey.mapRevision == 0 || Journey.resolvedEventWave == currentWaveNumber) return false;
var node = AvailableRouteNodes.FirstOrDefault(n => n.Id == nodeId);
if (node == null) return false;
Journey.selectedNodeId = node.Id;
Journey.selectedRoute = node.Route;
RepositoryChanged?.Invoke();
return true;
}
public bool CanImproveRouteCard(CardInstance card)
{
if (card?.Definition == null || !_runDeck.Contains(card) || card.Definition.IsToken || card.Definition.IsJunk
|| card.MagnitudeBonus > int.MaxValue - 4 || card.UpgradeLevel == int.MaxValue) return false;
var preview = card.CopyForCombat();
preview.ApplyMagnitudeUpgrade(2);
return CardEffectFactory.GetRulesText(preview, CurrentConfig).Replace(" [upgraded]", "")
!= CardEffectFactory.GetRulesText(card, CurrentConfig).Replace(" [upgraded]", "");
}
public bool ResolveRouteEvent(CardInstance donor = null, CardInstance target = null, bool skip = false)
{
if (!isRunActive || IsSuspended || !_repositoryVisitActive || CampaignChoicePending || BuildRewardPending
|| !RouteEventPending || !AvailableRouteNodes.Any(n => n.Id == Journey.selectedNodeId)) return false;
string outcome;
if (skip) outcome = "Passed without changing the deck.";
else
{
bool remove = Journey.selectedRoute is WaveRoute.Sacrifice or WaveRoute.Recycle;
bool upgrade = Journey.selectedRoute is WaveRoute.Sacrifice or WaveRoute.Forge;
if (remove && (donor?.Definition == null || !_runDeck.Contains(donor) || donor.Definition.IsToken
|| _runDeck.Count <= 1 || (Journey.selectedRoute == WaveRoute.Sacrifice && donor.Definition.IsJunk))) return false;
if (upgrade && (ReferenceEquals(donor, target) || !CanImproveRouteCard(target))) return false;
if (Journey.selectedRoute == WaveRoute.Recycle && _bits > int.MaxValue - 4) return false;
int bonus = Journey.selectedRoute == WaveRoute.Sacrifice ? 4 : 2;
if (upgrade) target.ApplyMagnitudeUpgrade(bonus);
if (remove)
{
_runDeck.Remove(donor);
_repositoryOffers.RemoveAll(o => !o.Sold && o.Kind == RepositoryOfferKind.CardUpgrade && o.TargetCard == donor);
}
if (Journey.selectedRoute == WaveRoute.Recycle) _bits += 4;
outcome = Journey.selectedRoute switch
{
WaveRoute.Sacrifice => $"Sacrificed {donor.Definition.DisplayName}; {target.Definition.DisplayName} gained +4 effect.",
WaveRoute.Forge => $"Patched {target.Definition.DisplayName}: +2 effect.",
_ => $"Recycled {donor.Definition.DisplayName}: +4 Bits."
};
}
Journey.resolvedEventWave = currentWaveNumber;
Journey.eventOutcome = outcome;
Journey.lastReward = outcome;
RepositoryChanged?.Invoke();
return true;
}
public bool ClaimBuildReward(CardInstance card, CardUpgradeKind kind, bool takeBits = false)
{
@@ -82,6 +156,11 @@ namespace KernelPanic.Run
{
if (!isRunActive || IsSuspended || !_repositoryVisitActive || CampaignChoicePending
|| !Enum.IsDefined(typeof(WaveRoute), route)) return false;
if (Journey.mapRevision > 0)
{
var node = AvailableRouteNodes.FirstOrDefault(n => n.Route == route);
return node != null && SelectRouteNode(node.Id);
}
Journey.selectedRoute = route;
RepositoryChanged?.Invoke();
return true;
@@ -98,10 +177,25 @@ namespace KernelPanic.Run
// Called exactly once by the guarded combat transition, never by UI callbacks.
public void PrepareNextEncounter(CombatantState player)
{
if (!_repositoryVisitActive || !isRunActive || IsSuspended || CampaignChoicePending || BuildRewardPending) return;
if (!_repositoryVisitActive || !isRunActive || IsSuspended || CampaignChoicePending || BuildRewardPending || RouteEventPending) return;
if (Journey.mapRevision > 0 && !AvailableRouteNodes.Any(n => n.Id == Journey.selectedNodeId)) return;
Journey.activeRoute = Journey.selectedRoute;
string outcome = Journey.eventOutcome;
if (Journey.campaign && Journey.activeRoute == WaveRoute.Repair && player != null)
{
int before = player.CurrentUptime;
player.CurrentUptime = Mathf.Min(player.MaxUptime, player.CurrentUptime + RunJourney.RepairUptime);
outcome = $"Restored {player.CurrentUptime - before} Uptime.";
}
if (Journey.activeRoute == WaveRoute.Cache)
{
int reward = Math.Min(6, int.MaxValue - _bits);
_bits += reward;
outcome = $"Recovered {reward} Bits.";
}
if (Journey.mapRevision > 0)
Journey.visits.Add(new RouteVisit { wave = currentWaveNumber, nodeId = Journey.selectedNodeId,
route = Journey.activeRoute, outcome = outcome ?? RunRouteMap.Title(Journey.activeRoute) });
_repositoryVisitActive = false;
}
@@ -170,7 +264,7 @@ namespace KernelPanic.Run
bandwidth = _accruedBandwidth, entropy = _accruedEntropy,
maxUptimeBonus = _maxUptimeBonus, maxCyclesBonus = _maxCyclesBonus, ramBonus = _ramBonus,
rerolls = _rerollsThisVisit, shopRandomDraws = _repositoryRandom.Draws,
version = 3, journey = Journey.Copy(),
version = 4, journey = Journey.Copy(),
combat = combat.CaptureBoundaryState()
};
foreach (PackageInstance package in CurrentConfig.EquippedPackages)
@@ -217,6 +311,15 @@ namespace KernelPanic.Run
_soldOfferKeys.Clear();
foreach (string key in snapshot.soldKeys) _soldOfferKeys.Add(key);
_repositoryVisitActive = true;
// Old saves begin a map here; do not invent decisions for earlier waves.
if (Journey.campaign && Journey.mapRevision == 0)
{
Journey.mapRevision = 1;
Journey.mapStartWave = currentWaveNumber;
Journey.selectedNodeId = RunRouteMap.Row(CurrentConfig.RunSeed, currentWaveNumber, currentWaveNumber, 1)
.FirstOrDefault(n => n.Route == Journey.selectedRoute)?.Id ?? 0;
}
EnsureRouteSelection();
}
public void AddBits(int amount)
@@ -237,6 +340,7 @@ namespace KernelPanic.Run
_soldOfferKeys.Clear();
FillRepositoryOffers(cardDatabase, languageDeckDatabase);
_repositoryVisitActive = true;
EnsureRouteSelection();
RepositoryChanged?.Invoke();
}
@@ -389,6 +493,8 @@ namespace KernelPanic.Run
{
int clearedWave = Mathf.Max(1, payload.WaveNumber);
if (!isRunActive || clearedWave <= _wavesCleared) return;
var visit = Journey.visits?.LastOrDefault(v => v.wave == clearedWave);
if (visit != null) visit.cleared = true;
Journey.lastReward = null;
if (Journey.campaign && clearedWave > 1 && Journey.activeRoute == WaveRoute.Challenge)
{
@@ -405,9 +511,13 @@ namespace KernelPanic.Run
_bits += RunJourney.ChallengeBits;
Journey.lastReward = $"Challenge cleared: +{RunJourney.ChallengeBits * 2} Bits (all cards already have draw riders).";
}
if (visit != null) visit.outcome = Journey.lastReward;
}
Journey.selectedRoute = WaveRoute.Repair;
if (Journey.campaign && Journey.encounterRevision > 0 && (clearedWave == 2 || clearedWave == 4))
Journey.selectedNodeId = 0;
Journey.resolvedEventWave = 0;
Journey.eventOutcome = null;
if (Journey.campaign && Journey.IsRewardWave(clearedWave))
Journey.pendingRewardWave = clearedWave;
_wavesCleared = Mathf.Max(_wavesCleared, clearedWave);
if (CurrentConfig?.IsTutorial != true)
@@ -416,6 +526,7 @@ namespace KernelPanic.Run
_accruedEntropy += CalculateEntropyReward(clearedWave);
}
currentWaveNumber = Mathf.Max(currentWaveNumber + 1, payload.WaveNumber + 1);
EnsureRouteSelection();
_repositoryOffers.Clear();
_rerollsThisVisit = 0;
_soldOfferKeys.Clear();
+137
View File
@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace KernelPanic.Run
{
public sealed class RouteNode
{
public int Wave { get; }
public int Lane { get; }
public int Id => Wave * 10 + Lane;
public WaveRoute Route { get; }
public RouteNode(int wave, int lane, WaveRoute route) { Wave = wave; Lane = lane; Route = route; }
}
[Serializable]
public sealed class RouteVisit
{
public int wave, nodeId;
public WaveRoute route;
public string outcome;
public bool cleared;
public RouteVisit Copy() => (RouteVisit)MemberwiseClone();
}
/// <summary>Stable topology and public event previews. Never consumes combat or shop randomness.</summary>
public static class RunRouteMap
{
private static uint Hash(int seed, int wave)
{
uint value = unchecked((uint)seed ^ (uint)wave * 0x9E3779B9u ^ 0xA37151E7u);
value ^= value >> 16; value = unchecked(value * 0x7FEB352Du);
value ^= value >> 15; return value;
}
public static IReadOnlyList<RouteNode> Row(int seed, int wave, int startWave = 2)
=> Row(seed, wave, startWave, 2);
public static IReadOnlyList<RouteNode> Row(int seed, int wave, int startWave, int revision)
{
if (wave < startWave) return Array.Empty<RouteNode>();
if (revision >= 2)
{
if (wave == RunJourney.BossWave)
return new[] { new RouteNode(wave, 1, WaveRoute.Encounter) };
if (wave == startWave)
return new[] { new RouteNode(wave, 0, WaveRoute.Repair), new RouteNode(wave, 1, WaveRoute.Challenge), new RouteNode(wave, 2, WaveRoute.Sacrifice) };
uint roll = Hash(seed, wave);
// Three lanes keep two alternatives reachable even at the outer edge.
// Occasional four-lane tiers widen the route, then merge back on even waves.
int width = wave % 2 == 1 && (roll & 1) != 0 ? 4 : 3;
// Every tier has recovery and a useful alternative; at most one optional elite.
var utility = new[] { WaveRoute.Forge, WaveRoute.Cache, WaveRoute.Recycle, WaveRoute.Sacrifice };
var routes = new List<WaveRoute> { WaveRoute.Repair, utility[(roll >> 4) % 4] };
bool elite = wave >= 7 || (wave >= 4 && (roll & 8) != 0);
if (width > 2) routes.Add(elite ? WaveRoute.Challenge : utility[((roll >> 4) + 1) % 4]);
if (width > 3) routes.Add(utility[((roll >> 4) + 2) % 4]);
// Keep recovery near the middle, instead of isolating it on an edge path.
(routes[0], routes[1]) = (routes[1], routes[0]);
return routes.Select((route, lane) => new RouteNode(wave, lane, route)).ToArray();
}
if (wave == startWave)
return new[] { new RouteNode(wave, 0, WaveRoute.Repair), new RouteNode(wave, 1, WaveRoute.Challenge), new RouteNode(wave, 2, WaveRoute.Sacrifice) };
if (wave == RunJourney.LegacyBossWave || (wave - startWave) % 3 == 2)
return new[] { new RouteNode(wave, 1, WaveRoute.Encounter) };
uint hash = Hash(seed, wave);
var pool = new[] { WaveRoute.Cache, WaveRoute.Forge, WaveRoute.Recycle, WaveRoute.Repair, WaveRoute.Challenge, WaveRoute.Sacrifice };
int count = (hash & 1) == 0 ? 2 : 3;
int offset = (int)((hash >> 4) % (uint)pool.Length);
return Enumerable.Range(0, count).Select(i => new RouteNode(wave, count == 2 ? i * 2 : i,
pool[(offset + i) % pool.Length])).ToArray();
}
public static bool Connected(int seed, RouteNode from, RouteNode to, int startWave = 2)
=> Connected(seed, from, to, startWave, 2);
public static bool Connected(int seed, RouteNode from, RouteNode to, int startWave, int revision)
{
if (from == null || to == null || to.Wave != from.Wave + 1) return false;
var before = Row(seed, from.Wave, startWave, revision).ToList();
var after = Row(seed, to.Wave, startWave, revision).ToList();
int a = before.FindIndex(n => n.Id == from.Id), b = after.FindIndex(n => n.Id == to.Id);
if (a < 0 || b < 0) return false;
if (before.Count == 1 || after.Count == 1) return true;
if (revision >= 2)
{
// Neighbouring lanes branch and merge, never jump across the whole map.
// Normalized positions keep every lane connected when tier widths change.
float x = (float)a / (before.Count - 1), y = (float)b / (after.Count - 1);
if (before.Count == 3 && after.Count == 4 && a == 1)
return b != ((Hash(seed, from.Wave) & 1) == 0 ? 3 : 0);
return Math.Abs(x - y) <= .51f;
}
uint hash = Hash(seed, from.Wave);
int target = (hash & 2) == 0 ? a % after.Count : after.Count - 1 - a % after.Count;
// A spanning set gives every node an entrance and exit; optional side paths add forks.
if (b == target) return true;
bool hasEntrance = Enumerable.Range(0, before.Count).Any(i =>
((hash & 2) == 0 ? i % after.Count : after.Count - 1 - i % after.Count) == b);
if (!hasEntrance && a == 0) return true;
return ((hash >> (a + 3)) & 1) != 0 && b == (target + 1) % after.Count;
}
public static IReadOnlyList<RouteNode> Available(int seed, int wave, RunJourney journey)
{
var row = Row(seed, wave, journey.mapStartWave, journey.mapRevision);
var previous = journey.visits?.LastOrDefault(v => v.wave == wave - 1);
if (previous == null) return row;
var from = Row(seed, wave - 1, journey.mapStartWave, journey.mapRevision).FirstOrDefault(n => n.Id == previous.nodeId);
return row.Where(to => Connected(seed, from, to, journey.mapStartWave, journey.mapRevision)).ToArray();
}
public static bool IsEvent(WaveRoute route) => route is WaveRoute.Forge or WaveRoute.Sacrifice or WaveRoute.Recycle;
public static string Title(WaveRoute route) => route switch
{
WaveRoute.Repair => "Repair stop", WaveRoute.Challenge => "Elite detour",
WaveRoute.Cache => "Lost cache", WaveRoute.Forge => "Patch workshop",
WaveRoute.Sacrifice => "Sacrifice altar", WaveRoute.Recycle => "Recycler",
_ => "Direct route"
};
public static string Symbol(WaveRoute route) => route switch
{
WaveRoute.Repair => "+", WaveRoute.Challenge => "!", WaveRoute.Cache => "$",
WaveRoute.Forge => "^", WaveRoute.Sacrifice => "X", WaveRoute.Recycle => "-", _ => ">"
};
public static string Detail(WaveRoute route) => route switch
{
WaveRoute.Repair => "Restore up to 6 Uptime on departure.",
WaveRoute.Challenge => "Fight an extra Daemon. On clear: +4 Bits and a draw rider on the first eligible card; +4 more Bits if none is eligible.",
WaveRoute.Cache => "Recover 6 Bits on departure. No extra enemy.",
WaveRoute.Forge => "Choose a card to gain +2 effect magnitude for this run. You may pass.",
WaveRoute.Sacrifice => "Remove one card from this run's deck. Give a different card +4 effect magnitude for this run. You may pass.",
WaveRoute.Recycle => "Remove one card from this run's deck and recover 4 Bits. You may pass.",
_ => "A direct continuation to the next battle. No extra reward or enemy."
};
}
}
+2 -2
View File
@@ -152,8 +152,8 @@ namespace KernelPanic.Run
return new[] {
new TutorialStep("leak", "A new threat: Memory Leak", "Memory Leak grows stronger each round and applies damage over time. Your purchased patch carried over.", "enemy:memory_leak"),
new TutorialStep("firewall", "A protector: firewalld", "firewalld shields itself and its neighbors. Check its intent before choosing a target.", "enemy:firewalld"),
new TutorialStep("queue-intro", "Python uses the queue", "Python waits until End turn. Oldest queued card resolves first (FIFO).", "TutorialQueue"),
new TutorialStep("select-python", "Select the Python card", "Click print(). It chooses a target when it resolves, so no enemy click is needed.", "card", TutorialAction.SelectCard),
new TutorialStep("queue-intro", "Python builds a pipeline", "Preparation acts immediately. Payloads and modifiers wait until End turn, oldest first (FIFO). Scripts run before the queue.", "TutorialQueue"),
new TutorialStep("select-python", "Select the Python card", "Click print(), then choose the highlighted enemy. This payload can later be repeated by for loop or spread by zip.", "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", "The card is queued, not resolved. With multiple entries, the oldest executes first.", "TutorialQueue"),
new TutorialStep("stack-intro", "Haskell uses the stack", "Haskell resolves after Python, newest first (LIFO). Its entry multiplier scales damage and Shield.", "TutorialStack"),
+6 -1
View File
@@ -53,6 +53,11 @@ namespace KernelPanic.UI
public static VisualElement BuildBrowser(string initialPile,
IReadOnlyDictionary<string, IReadOnlyList<CardInstance>> inventories, Action close,
Func<CardInstance, string> costDetails = null)
=> BuildBrowser(initialPile, inventories, close, costDetails, CardEffectFactory.GetRulesText);
public static VisualElement BuildBrowser(string initialPile,
IReadOnlyDictionary<string, IReadOnlyList<CardInstance>> inventories, Action close,
Func<CardInstance, string> costDetails, Func<CardInstance, string> rulesText)
{
var piles = inventories.ToDictionary(pair => pair.Key,
pair => (pair.Value ?? Array.Empty<CardInstance>()).Where(card => card?.Definition != null).ToArray());
@@ -180,7 +185,7 @@ namespace KernelPanic.UI
var card = copies[0];
var face = new VisualElement { name = "PileCard", userData = copies.Length };
face.AddToClassList("pile-card");
SoftwareCardView.Populate(face, card, CombatManager.GetCardCost(card));
SoftwareCardView.Populate(face, card, CombatManager.GetCardCost(card), rulesText(card));
face.Q<Label>(className: "software-cost").text = $"{CombatManager.GetCardCost(card)}c stored";
// The full rules remain inline; no hover is required for keyboard or touch readers.
face.tooltip = string.Empty;
@@ -1795,7 +1795,7 @@ namespace KernelPanic.UI
summary.Add(meta);
row.Add(summary);
Label description = new(GetCardCollectionDescription(entry.Card));
Label description = new(GetOwnedCardRules(entry.Card));
description.AddToClassList("package-description");
row.Add(description);
return row;
@@ -1810,7 +1810,7 @@ namespace KernelPanic.UI
if (card == null) return;
var manifest = new VisualElement();
manifest.AddToClassList("collection-manifest");
SoftwareCardView.Populate(manifest, new CardInstance(card), card.CycleCost);
SoftwareCardView.Populate(manifest, new CardInstance(card), card.CycleCost, GetOwnedCardRules(card));
_detail.Add(manifest);
if (!string.IsNullOrWhiteSpace(card.FlavorText))
{
@@ -1820,6 +1820,13 @@ namespace KernelPanic.UI
}
}
private string GetOwnedCardRules(CardDefinition card)
{
var distro = _units.FirstOrDefault(unit => unit.ExclusiveCards.Contains(card));
return distro == null ? GetCardCollectionDescription(card)
: CardEffectFactory.GetRulesText(new CardInstance(card), distro.Id, GetUnitVersion(distro));
}
private static string GetCardCollectionDescription(CardDefinition card)
{
if (card == null)
@@ -1827,11 +1834,6 @@ namespace KernelPanic.UI
return "--";
}
if (!string.IsNullOrWhiteSpace(card.Description))
{
return card.Description;
}
string rulesText = CardEffectFactory.GetRulesText(new CardInstance(card));
return string.IsNullOrWhiteSpace(rulesText) || rulesText == "effect not authored." ? "--" : rulesText;
}
+189 -25
View File
@@ -117,6 +117,7 @@ namespace KernelPanic.UI
private string _saveError;
private string _checkpointError;
private bool _routeSelectionOpen;
private bool _routeEventOpen;
private DailyQuestTracker _dailyQuestTracker;
private IVisualElementScheduledItem _dailyQuestSaveSchedule;
private CombatRunTelemetry _runTelemetry;
@@ -500,7 +501,11 @@ namespace KernelPanic.UI
_lazyStackPile.name = "TutorialStack";
_queueView = new ExecutionTrackView(_interpreterStrip, false);
_stackView = new ExecutionTrackView(_lazyStackPile, true);
_tokenArea = AddTrackZone(scheduler, "|| goroutines", "no active runtime", "track-zone-token");
_tokenArea = AddTrackZone(scheduler, "py automation", "2 script slots / expires at wave end", "track-zone-token");
_tokenArea.name = "PythonAutomationReadout";
_tokenArea.style.flexDirection = FlexDirection.Column;
_tokenArea.style.alignItems = Align.Stretch;
_tokenArea.style.width = Length.Percent(100);
_root.Add(scheduler);
VisualElement bottom = new();
@@ -648,7 +653,7 @@ namespace KernelPanic.UI
header.Add(subtitleLabel);
zone.Add(header);
var scroll = new ScrollView(className == "track-zone-stack" ? ScrollViewMode.Vertical : ScrollViewMode.Horizontal);
var scroll = new ScrollView(className == "track-zone-queue" ? ScrollViewMode.Horizontal : ScrollViewMode.Vertical);
scroll.AddToClassList("track-scroll");
VisualElement contents = new();
contents.AddToClassList("track-contents");
@@ -747,10 +752,10 @@ namespace KernelPanic.UI
}
RunConfig config = _runManager.CurrentConfig;
_waveLabel.text = _runManager.Journey.campaign && !_runManager.Journey.endless
? $"{Math.Min(RunJourney.BossWave, _runManager.CurrentWaveNumber)}/{RunJourney.BossWave}"
? $"{Math.Min(_runManager.Journey.FinalWave, _runManager.CurrentWaveNumber)}/{_runManager.Journey.FinalWave}"
: _runManager.CurrentWaveNumber.ToString();
_waveLabel.tooltip = _runManager.Journey.campaign && !_runManager.Journey.endless
? "Clear five waves, defeat the Kernel Overseer, then finish or continue into endless mode."
? $"Clear {_runManager.Journey.FinalWave} waves, defeat the Kernel Overseer, then finish or continue into endless mode."
: "Endless mode";
if (config?.IsTutorial == true)
{
@@ -866,10 +871,19 @@ namespace KernelPanic.UI
_stackView.EndExecution();
}
_tokenArea.Clear();
_tokenArea.Add(EmptyState("inactive"));
((VisualElement)_tokenArea.userData).EnableInClassList("track-idle", true);
bool pythonIdle = _combatManager.Python.AutomationCount == 0
&& _combatManager.Python.RepeatCount == 0 && _combatManager.Python.AreaCount == 0;
IEnumerable<string> pythonReadout = pythonIdle ? new[] { "0 / 2 slots" } : _combatManager.Python.Readout;
foreach (string line in pythonReadout)
{
var label = new Label(line);
label.style.whiteSpace = WhiteSpace.Normal;
_tokenArea.Add(label);
}
((VisualElement)_tokenArea.userData).EnableInClassList("track-idle", _combatManager.Python.AutomationCount == 0);
_root.Q(className: "scheduler").EnableInClassList("scheduler-idle",
_combatManager.InterpreterQueue.Count == 0 && _combatManager.LazyStack.Count == 0);
_combatManager.InterpreterQueue.Count == 0 && _combatManager.LazyStack.Count == 0
&& _combatManager.Python.AutomationCount == 0 && _combatManager.Python.RepeatCount == 0 && _combatManager.Python.AreaCount == 0);
((VisualElement)_interpreterStrip.userData).EnableInClassList("track-resolving", _combatManager.CurrentPhase == TurnPhase.Interpret);
}
@@ -1163,7 +1177,8 @@ namespace KernelPanic.UI
["exhaust"] = new List<CardInstance>(_combatManager.DeckController.ExhaustPile)
};
inventories[pile] = new List<CardInstance>(cards);
_overlay.Add(CardPileView.BuildBrowser(pile, inventories, ClosePileInspector, _combatManager.GetPileCostDetails));
_overlay.Add(CardPileView.BuildBrowser(pile, inventories, ClosePileInspector, _combatManager.GetPileCostDetails,
card => CardEffectFactory.GetRulesText(card, _combatManager.RunConfig)));
_overlay.style.display = DisplayStyle.Flex;
_overlay.Q<TextField>("PileSearch")?.Focus();
}
@@ -1204,7 +1219,7 @@ namespace KernelPanic.UI
victory = _combatManager.RunCompleted
};
_runTelemetry?.FillReport(entry);
if (entry.victory) entry.cause = "Kernel Overseer defeated. Five-wave campaign complete.";
if (entry.victory) entry.cause = $"Kernel Overseer defeated. {_runManager.Journey.FinalWave}-wave campaign complete.";
entry.cause ??= entry.surrendered ? "Shutdown signal accepted." : "Uptime reached 0; no damaging action recorded.";
_runHistoryEntry = entry;
return entry;
@@ -1287,6 +1302,75 @@ namespace KernelPanic.UI
return;
}
if (_combatManager.Python.HasChoice && !_combatManager.RunFinished)
{
_pileInspectorOpen = false;
_overlay.RemoveFromClassList("pile-overlay");
TerminalTheme.PreserveFocus(_overlay);
_overlay.Clear();
_overlay.style.display = DisplayStyle.Flex;
_overlay.AddToClassList("python-choice-overlay");
var dialog = new VisualElement { name = "PythonChoiceDialog" };
dialog.AddToClassList("python-choice-dialog");
dialog.Add(SoftwareCardView.Text("[ python / select one ]", "python-choice-eyebrow"));
string heading = _combatManager.Python.ChoiceTitle;
int separator = heading.IndexOf(':');
dialog.Add(SoftwareCardView.Text(separator < 0 ? heading : heading.Substring(0, separator), "python-choice-title"));
if (separator >= 0)
dialog.Add(SoftwareCardView.Text(heading.Substring(separator + 1).Trim(), "python-choice-description"));
var choices = new ScrollView(ScrollViewMode.Vertical) { name = "PythonChoiceScroll" };
choices.AddToClassList("python-choice-scroll");
choices.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
choices.contentContainer.AddToClassList("python-choice-grid");
for (int i = 0; i < _combatManager.Python.Choices.Count; i++)
{
int index = i;
var option = _combatManager.Python.Choices[i];
var button = new Button(() => _combatManager.Python.Choose(index)) { name = $"PythonChoice{index}" };
if (option.Card != null)
SoftwareCardView.Populate(button, option.Card, option.Cost,
CardEffectFactory.GetRulesText(option.Card, _combatManager.RunConfig));
else
button.Add(SoftwareCardView.Text(option.Label, "python-choice-description"));
button.AddToClassList("python-choice-option");
// These choices already show the complete rules; a repeated tooltip
// would cover the dialog header on small screens.
button.tooltip = null;
button.Add(SoftwareCardView.Text(option.ActionLabel ?? "> replace script", "python-choice-action"));
button.SetEnabled(option.Enabled);
choices.Add(button);
}
dialog.Add(choices);
dialog.Add(SoftwareCardView.Text("Tab / Shift+Tab to browse · Enter to select", "python-choice-hint"));
// Intercept focus before ScrollView tracks it: its automatic scrolling
// aligns oversized cards to their bottom, hiding the card's name.
dialog.RegisterCallback<FocusInEvent>(evt =>
{
if (evt.target is not Button focused || !focused.ClassListContains("python-choice-option")) return;
evt.StopPropagation();
void RevealChoice()
{
if (focused.worldBound.height > choices.contentViewport.worldBound.height)
choices.scrollOffset = new Vector2(0, Mathf.Max(0,
focused.worldBound.yMin - choices.contentContainer.worldBound.yMin));
else choices.ScrollTo(focused);
}
RevealChoice();
// Repeat after layout for newly attached cards, but never scroll back
// to a stale selection after the player has moved focus again.
choices.schedule.Execute(() =>
{
if (dialog.focusController?.focusedElement == focused) RevealChoice();
});
}, TrickleDown.TrickleDown);
TerminalTheme.ConstrainModalFocus(dialog);
_overlay.Add(dialog);
choices.Query<Button>().ToList().Find(b => b.enabledSelf)?.Focus();
return;
}
_overlay.RemoveFromClassList("python-choice-overlay");
if (_pileInspectorOpen && !_combatManager.RunFinished && !_combatManager.AwaitingWaveContinue
&& _combatManager.CurrentPhase == TurnPhase.Execute) return;
_pileInspectorOpen = false;
@@ -1298,6 +1382,7 @@ namespace KernelPanic.UI
if (_combatManager.RunFinished)
{
_routeSelectionOpen = false;
_routeEventOpen = false;
SettleRunRewardsIfNeeded();
_overlay.style.display = DisplayStyle.Flex;
_overlay.Add(BuildRunEndOverlay());
@@ -1322,6 +1407,7 @@ namespace KernelPanic.UI
}
_routeSelectionOpen = false;
_routeEventOpen = false;
_overlay.style.display = DisplayStyle.None;
}
@@ -1528,25 +1614,33 @@ namespace KernelPanic.UI
private void SetRouteSelectionOpen(bool open)
{
_routeSelectionOpen = open;
_routeEventOpen = false;
RefreshOverlay();
_overlay.Q<Button>(open ? "BackToRepositoryButton" : "BootNextWaveButton")?.Focus();
}
private VisualElement BuildRouteSelectionView()
{
var screen = new VisualElement { name = "RouteSelectionScreen" };
bool reward = _runManager.BuildRewardPending;
bool eventScreen = !reward && _routeEventOpen && !_runManager.CampaignChoicePending;
bool committed = eventScreen && !_runManager.RouteEventPending;
var screen = new VisualElement { name = reward ? "BuildRewardScreen" : eventScreen ? "RouteEventScreen" : "RouteSelectionScreen" };
screen.AddToClassList("repository");
screen.AddToClassList("screen-frame");
screen.AddToClassList("route-map-screen");
var header = new VisualElement();
header.AddToClassList("repository-header");
header.AddToClassList("screen-frame-header");
var copy = new VisualElement();
copy.AddToClassList("repository-header-copy");
var title = new Label(_runManager.CampaignChoicePending ? "campaign complete" : "choose your route");
var title = new Label(_runManager.CampaignChoicePending ? "campaign complete" : reward ? "claim your build reward"
: eventScreen ? RunRouteMap.Title(_runManager.Journey.selectedRoute) : "choose your route");
title.AddToClassList("screen-frame-title");
copy.Add(title);
var subtitle = new Label(_runManager.CampaignChoicePending
? "bank your rewards or continue into endless"
: reward ? "1 / claim reward > 2 / choose route > 3 / enter stop"
: eventScreen ? committed ? "stop complete / ready for battle" : "choose your cards / nothing changes until you confirm"
: $"preparing wave {_runManager.CurrentWaveNumber} / {_runManager.Bits} bits remaining");
subtitle.AddToClassList("repository-subtitle");
copy.Add(subtitle);
@@ -1556,29 +1650,99 @@ namespace KernelPanic.UI
var body = new ScrollView(ScrollViewMode.Vertical);
body.AddToClassList("repository-body");
body.AddToClassList("screen-frame-content");
body.Add(RunRouteView.Build(_runManager, _combatManager));
body.Add(reward ? RunRouteView.BuildReward(_runManager)
: eventScreen ? RunMapView.BuildEvent(_runManager) : RunRouteView.Build(_runManager, _combatManager));
if (!reward && !eventScreen && !_runManager.CampaignChoicePending)
{
body.AddToClassList("route-map-body");
body.contentViewport.RegisterCallback<GeometryChangedEvent>(evt =>
{
var mapScroll = body.Q<ScrollView>("RouteMapScroll");
if (mapScroll != null)
mapScroll.style.height = Mathf.Max(260, evt.newRect.height - 20);
});
}
if (committed)
{
var save = new Button(SaveAndExitRun) { name = "SaveAndExitRunButton", text = "save and exit / keep this result" };
save.AddToClassList("secondary-action"); body.Add(save);
}
screen.Add(body);
var footer = new VisualElement();
footer.AddToClassList("screen-frame-footer");
footer.style.flexDirection = FlexDirection.Column;
footer.style.alignItems = Align.Stretch;
var back = new Button(() => SetRouteSelectionOpen(false))
{ name = "BackToRepositoryButton", text = "< back to repository" };
back.AddToClassList("primary-action");
footer.Add(back);
if (!_runManager.CampaignChoicePending)
footer.AddToClassList("route-map-footer");
var back = new Button(() =>
{
var confirm = new Button(() => _combatManager.ContinueToNextWave())
if (!eventScreen) SetRouteSelectionOpen(false);
else if (_runManager.RouteEventPending)
{
_routeEventOpen = false; RefreshOverlay();
_overlay.Q<Button>("ConfirmRouteButton")?.Focus();
}
})
{ name = eventScreen ? "BackToRouteButton" : "BackToRepositoryButton",
text = committed ? "stop committed" : eventScreen ? "< back to map" : "< back to repository" };
back.SetEnabled(!committed);
back.AddToClassList("primary-action");
back.AddToClassList("route-map-back");
footer.Add(back);
screen.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.keyCode != KeyCode.Escape || !back.enabledSelf) return;
using var submit = NavigationSubmitEvent.GetPooled();
submit.target = back; back.SendEvent(submit); evt.StopPropagation();
});
void MoveAction(string name, string caption = null)
{
var button = body.Q<Button>(name);
if (button == null) return;
button.RemoveFromHierarchy();
if (caption != null) button.text = caption;
if (name == "ResolveRouteEventButton")
{
string fullCaption = button.text;
button.RegisterCallback<GeometryChangedEvent>(evt => button.text = evt.newRect.width < 160 ? "apply" : fullCaption);
}
button.AddToClassList("primary-action");
button.AddToClassList(name is "ClaimBuildRewardButton" or "ResolveRouteEventButton" ? "route-map-continue" : "route-map-back");
footer.Add(button);
}
if (reward)
{
back.text = "< back"; back.tooltip = "Back to repository";
MoveAction("RewardBits", $"{RunManager.BuildRewardBits} Bits");
MoveAction("ClaimBuildRewardButton", "claim");
}
else if (eventScreen && !committed)
{
back.text = "< map";
MoveAction("SkipRouteEventButton", "pass");
MoveAction("ResolveRouteEventButton");
}
else if (!_runManager.CampaignChoicePending)
{
var confirm = new Button(() =>
{
if (_runManager.RouteEventPending && !eventScreen)
{
_routeEventOpen = true; RefreshOverlay();
_overlay.Q<Button>("BackToRouteButton")?.Focus();
}
else _combatManager.ContinueToNextWave();
})
{
name = "ConfirmRouteButton",
text = _runManager.BuildRewardPending ? "choose a build reward to continue" : "> depart / boot next-wave"
text = eventScreen ? committed ? "> continue to battle" : "confirm or pass above"
: _runManager.RouteEventPending ? "> enter stop" : "> continue to battle"
};
confirm.AddToClassList("primary-action");
confirm.SetEnabled(!_runManager.BuildRewardPending && !_runManager.IsSuspended);
confirm.AddToClassList("route-map-continue");
confirm.SetEnabled((!eventScreen || committed) && !_runManager.IsSuspended);
footer.Add(confirm);
}
screen.Add(footer);
if (committed) screen.schedule.Execute(() => screen.Q<Button>("ConfirmRouteButton")?.Focus());
return screen;
}
@@ -1810,13 +1974,13 @@ namespace KernelPanic.UI
{
VisualElement face = new();
face.AddToClassList("hand-card");
SoftwareCardView.Populate(face, card, GetDisplayCardCost(card));
SoftwareCardView.Populate(face, card, GetDisplayCardCost(card), CardEffectFactory.GetRulesText(card, _combatManager.RunConfig));
return face;
}
private void PopulateCardFace(VisualElement target, CardInstance card)
{
SoftwareCardView.Populate(target, card, GetDisplayCardCost(card));
SoftwareCardView.Populate(target, card, GetDisplayCardCost(card), CardEffectFactory.GetRulesText(card, _combatManager.RunConfig));
var preview = CardPreviewService.Build(_combatManager, card);
if (!string.IsNullOrEmpty(preview.Summary) && !preview.Summary.StartsWith("Utility", StringComparison.Ordinal))
{
@@ -2158,7 +2322,7 @@ namespace KernelPanic.UI
{
VisualElement chip = CardChip(cards[i]);
chip.Insert(0, SoftwareCardView.Text($"{i + 1:00} >", "execution-order"));
chip.tooltip = CardEffectFactory.GetRulesText(cards[i]);
chip.tooltip = CardEffectFactory.GetRulesText(cards[i], _combatManager.RunConfig);
if (target == _interpreterStrip)
{
_queueChipElements[cards[i]] = chip;
+174
View File
@@ -0,0 +1,174 @@
using System;
using KernelPanic.Meta;
using UnityEngine;
using UnityEngine.UIElements;
namespace KernelPanic.UI
{
public static class DailyQuestView
{
public static Button BuildWidget(DailyQuestState state, DateTime utcNow, Action open)
{
var widget = new Button(open) { name = "DailyQuestWidget", tooltip = "Open daily quests (Enter)" };
widget.AddToClassList("daily-quest-widget");
var counts = Counts(state);
var heading = new VisualElement();
heading.AddToClassList("daily-service-summary");
heading.Add(TerminalLayout.Heading("[ cron.daily ]", className: "daily-service-title"));
var reward = TerminalLayout.BodyText(counts.Ready == 1 ? "1 reward ready" : $"{counts.Ready} rewards ready",
"DailyQuestRewardReady", "daily-reward-ready");
reward.style.display = counts.Ready > 0 ? DisplayStyle.Flex : DisplayStyle.None;
heading.Add(reward);
widget.Add(heading);
widget.Add(TerminalLayout.BodyText(DailyQuests.Countdown(state, utcNow), "DailyQuestCountdown", "daily-service-meta"));
var summary = new VisualElement();
summary.AddToClassList("daily-service-summary");
summary.Add(TerminalLayout.BodyText($"{counts.Completed}/{DailyQuests.Count} completed", "DailyQuestCompleted", "daily-service-meta"));
summary.Add(TerminalLayout.BodyText($"{counts.Claimed} claimed", "DailyQuestClaimed", "daily-service-meta"));
widget.Add(summary);
foreach (var kind in DailyQuests.Active(state))
{
var row = new VisualElement();
row.AddToClassList("daily-service-entry");
row.EnableInClassList("daily-service-ready", !DailyQuests.Claimed(state, kind)
&& DailyQuests.Progress(state, kind) >= DailyQuests.Target(kind));
row.EnableInClassList("daily-service-claimed", DailyQuests.Claimed(state, kind));
row.Add(TerminalLayout.BodyText(ShortName(kind), className: "daily-service-name"));
row.Add(TerminalLayout.BodyText($"{DailyQuests.Progress(state, kind)}/{DailyQuests.Target(kind)}", className: "daily-service-progress"));
widget.Add(row);
}
widget.Add(TerminalLayout.BodyText(counts.Ready > 0 ? "> claim available rewards" : "> inspect tasks",
"DailyQuestInspect", "daily-service-command"));
widget.EnableInClassList("daily-has-rewards", counts.Ready > 0);
// Child copy is part of one button, not additional focus targets.
widget.Query<VisualElement>().ForEach(child => { if (child != widget) child.pickingMode = PickingMode.Ignore; });
widget.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.keyCode == KeyCode.Escape)
{
widget.Blur();
widget.panel?.focusController.IgnoreEvent(evt);
evt.StopImmediatePropagation();
return;
}
if (evt.keyCode != KeyCode.Return && evt.keyCode != KeyCode.KeypadEnter) return;
open();
widget.panel?.focusController.IgnoreEvent(evt);
evt.StopImmediatePropagation();
});
return widget;
}
private static (int Completed, int Claimed, int Ready) Counts(DailyQuestState state)
{
int completed = 0, claimed = 0, ready = 0;
foreach (var kind in DailyQuests.Active(state))
{
bool complete = DailyQuests.Progress(state, kind) >= DailyQuests.Target(kind);
if (complete) completed++;
if (DailyQuests.Claimed(state, kind)) claimed++;
else if (complete) ready++;
}
return (completed, claimed, ready);
}
public static void RefreshHeader(VisualElement overlay, DailyQuestState state, DateTime utcNow)
{
overlay.Q<Label>("DailyQuestDetailCountdown").text = DailyQuests.Countdown(state, utcNow).Replace("refresh in ", "reset ");
overlay.Q<Label>("DailyQuestDetailSummary").text = $"{DailyQuests.Count} tasks / {Counts(state).Completed} completed";
}
private static string ShortName(DailyQuestKind kind) => kind switch
{
DailyQuestKind.Waves => "Waves cleared",
DailyQuestKind.Cards => "Cards played",
DailyQuestKind.Damage => "Uptime damage",
DailyQuestKind.BlockDamage => "Damage blocked",
DailyQuestKind.NativeCards => "Native cards",
DailyQuestKind.ShieldDamage => "Enemy Shield damage",
DailyQuestKind.SurviveRounds => "Rounds survived",
DailyQuestKind.WaveFive => "Wave 5 cleared",
_ => DailyQuests.Description(kind)
};
public static VisualElement BuildOverlay(DailyQuestState state, DateTime utcNow,
Action<DailyQuestKind, long> claim, Action close)
{
var overlay = new VisualElement { name = "DailyQuestOverlay" };
overlay.AddToClassList("modal-overlay");
overlay.AddToClassList("modal-open");
overlay.AddToClassList("daily-quest-overlay");
var dialog = new VisualElement { name = "DailyQuestDialog" };
dialog.AddToClassList("daily-quest-dialog");
var header = new VisualElement { name = "DailyQuestHeader" };
header.AddToClassList("daily-detail-header");
header.Add(TerminalLayout.BodyText("$ cat /etc/cron.daily/quests", className: "daily-detail-command"));
var titleRow = new VisualElement();
titleRow.AddToClassList("daily-service-summary");
titleRow.Add(TerminalLayout.Heading("DAILY TASKS", className: "daily-service-title"));
titleRow.Add(TerminalLayout.BodyText("", "DailyQuestDetailCountdown", "daily-service-meta"));
header.Add(titleRow);
header.Add(TerminalLayout.BodyText("", "DailyQuestDetailSummary", "daily-service-meta"));
dialog.Add(header);
var scroll = new ScrollView(ScrollViewMode.Vertical) { name = "DailyQuestDetailScroll" };
scroll.AddToClassList("daily-quest-detail-scroll");
scroll.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
scroll.Add(Build(state, utcNow, claim));
dialog.Add(scroll);
var feedback = TerminalLayout.BodyText("", "DailyQuestFeedback", "daily-quest-feedback");
feedback.style.display = DisplayStyle.None;
dialog.Add(feedback);
var dismiss = new Button(close) { name = "CloseDailyQuests", text = "[ Esc ] close" };
dismiss.AddToClassList("terminal-button");
dialog.Add(dismiss);
overlay.Add(dialog);
RefreshHeader(overlay, state, utcNow);
overlay.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.keyCode == KeyCode.Escape) { close(); evt.StopImmediatePropagation(); }
});
TerminalTheme.ConstrainModalFocus(overlay);
return overlay;
}
public static VisualElement Build(DailyQuestState state, DateTime utcNow, Action<DailyQuestKind, long> claim)
{
var panel = new VisualElement { name = "DailyQuestsPanel" };
panel.AddToClassList("daily-quests");
var quests = new VisualElement();
quests.AddToClassList("daily-quest-list");
panel.Add(quests);
long period = state.refreshAtUtcTicks;
foreach (var kind in DailyQuests.Active(state))
{
var row = new VisualElement { name = "DailyQuest" + kind };
row.AddToClassList("daily-quest");
int progress = DailyQuests.Progress(state, kind);
bool claimed = DailyQuests.Claimed(state, kind);
bool complete = progress >= DailyQuests.Target(kind);
row.EnableInClassList("daily-quest-complete", complete);
row.EnableInClassList("daily-quest-claimed", claimed);
row.Add(TerminalLayout.BodyText(DailyQuests.Description(kind), className: "daily-quest-name"));
int filled = progress * 10 / DailyQuests.Target(kind);
var progressRow = new VisualElement();
progressRow.AddToClassList("daily-detail-progress-row");
progressRow.Add(TerminalLayout.BodyText($"[{new string('#', filled)}{new string('.', 10 - filled)}]",
className: "daily-detail-progress"));
progressRow.Add(TerminalLayout.BodyText($"{progress}/{DailyQuests.Target(kind)}", className: "daily-detail-values"));
row.Add(progressRow);
var reward = DailyQuests.Reward(kind);
row.Add(TerminalLayout.BodyText($"+{reward.Bandwidth} Bandwidth / +{reward.Entropy} Entropy"));
var button = new Button(() => claim(kind, period))
{ name = "ClaimDailyQuest" + kind, text = claimed ? "[ CLAIMED ]" : complete ? "> CLAIM REWARD" : "[ in progress ]" };
button.AddToClassList("terminal-button");
button.AddToClassList("daily-claim-action");
button.EnableInClassList("daily-claim-ready", !claimed && complete);
button.EnableInClassList("daily-claim-done", claimed);
button.SetEnabled(!claimed && complete);
row.Add(button);
quests.Add(row);
}
return panel;
}
}
}
+1 -1
View File
@@ -81,7 +81,7 @@ namespace KernelPanic.UI
{
if (_disposed) return;
foreach (var card in pending)
Chip(card).tooltip = CardEffectFactory.GetRulesText(card) + "\n\n" + CardPreviewService.Build(combat, card).Details;
Chip(card).tooltip = CardEffectFactory.GetRulesText(card, combat.RunConfig) + "\n\n" + CardPreviewService.Build(combat, card).Details;
}
public void Resolving(CardInstance card)
+1 -1
View File
@@ -71,7 +71,7 @@ namespace KernelPanic.UI
_tracks.Add(_resources);
AddTrack("NOW / Native", "Executes when played.");
if (config?.PrimaryLanguage == Language.Python || config?.SecondaryLanguage == Language.Python)
AddTrack("1 / Python queue", "End turn: oldest first.");
AddTrack("1 / Python pipeline", "Preparation acts immediately. End turn: scripts run, then FIFO modifiers and payloads. Loops repeat; zip spreads damage. Two script slots, cleared each wave.");
if (config?.PrimaryLanguage == Language.Haskell || config?.SecondaryLanguage == Language.Haskell)
AddTrack("2 / Haskell stack", "After the queue: newest first. Entry multiplier scales damage and Shield.");
AddTrack("LAST / Enemies", "Surviving enemies carry out their intents.");
+4 -5
View File
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using KernelPanic.Combat;
using KernelPanic.Core;
using KernelPanic.Data;
using KernelPanic.Meta;
@@ -2123,11 +2124,9 @@ namespace KernelPanic.UI
summary.ElementAt(2).AddToClassList("package-meta");
row.Add(summary);
if (!string.IsNullOrWhiteSpace(card.Description))
{
row.Add(new Label(card.Description) { name = "RunSetupCardDescription" });
row.ElementAt(1).AddToClassList("package-description");
}
row.Add(new Label(CardEffectFactory.GetRulesText(new CardInstance(card), unit.Id,
_playerCollection?.GetVersion(unit.Id) ?? 1)) { name = "RunSetupCardDescription" });
row.ElementAt(1).AddToClassList("package-description");
if (!string.IsNullOrWhiteSpace(card.FlavorText))
{
+362
View File
@@ -0,0 +1,362 @@
using System;
using System.Collections.Generic;
using System.Linq;
using KernelPanic.Combat;
using KernelPanic.Run;
using UnityEngine;
using UnityEngine.UIElements;
namespace KernelPanic.UI
{
internal static class RunMapView
{
public static VisualElement Build(RunManager run)
{
var layout = new VisualElement { name = "RunMap" };
layout.AddToClassList("route-map-layout");
var map = new VisualElement { name = "RouteGraph" };
map.AddToClassList("route-map-graph");
if (run.Journey.mapStartWave > 2)
map.Add(Text("Earlier decisions are unavailable for this older save. Your map starts here.", "route-map-legend"));
int current = run.CurrentWaveNumber, seed = run.CurrentConfig.RunSeed;
int revision = run.Journey.mapRevision, startWave = run.Journey.mapStartWave;
int first = run.Journey.endless ? Math.Max(startWave, current - 3) : startWave;
int last = run.Journey.endless ? current + 5 : run.Journey.FinalWave;
IReadOnlyList<RouteNode> Row(int wave) => RunRouteMap.Row(seed, wave, startWave, revision);
bool Connected(RouteNode a, RouteNode b) => RunRouteMap.Connected(seed, a, b, startWave, revision);
var detail = new VisualElement { name = "RouteDetails" };
detail.AddToClassList("route-map-detail");
var preview = new VisualElement { name = "RoutePreview" };
detail.Add(preview);
void Preview(RouteNode node)
{
if (node == null) return;
preview.Clear();
bool boss = node.Wave == run.Journey.FinalWave && !run.Journey.endless;
string phase = run.Journey.endless ? "SURVIVAL" : node.Wave <= 3 ? "BOOT SECTOR"
: node.Wave <= 6 ? "ESCALATION" : boss ? "FINAL ENCOUNTER" : "KERNEL PERIMETER";
preview.Add(Text($"{node.Wave:00} / {(run.Journey.endless ? "ENDLESS" : run.Journey.FinalWave.ToString("00"))} {phase}", "route-map-eyebrow"));
string state = node.Wave < current ? run.Journey.visits.Any(v => v.nodeId == node.Id) ? "CLEARED" : "NOT TAKEN"
: node.Wave > current ? "FUTURE STOP" : node.Id == run.Journey.selectedNodeId ? "SELECTED DESTINATION"
: run.AvailableRouteNodes.Any(n => n.Id == node.Id) ? "AVAILABLE / select to take this path" : "UNREACHABLE FROM HERE";
preview.Add(Text(state, "route-preview-state"));
preview.Add(Text(boss ? "Kernel Overseer" : RunRouteMap.Title(node.Route), "route-detail-title"));
preview.Add(Text(boss ? "Defeat the Overseer to complete the route. Bank your rewards, or continue this build in endless survival."
: RunRouteMap.Detail(node.Route), "route-detail-copy"));
var encounter = EncounterDirector.Plan(node.Wave, node.Route, seed, run.Journey.encounterRevision);
preview.Add(Text("BATTLE / " + encounter.Title, "route-map-eyebrow"));
preview.Add(Text(encounter.Advice, "route-detail-copy"));
if (node.Wave == current && run.Journey.resolvedEventWave == current && node.Id == run.Journey.selectedNodeId)
preview.Add(Text("[ resolved ]\n" + run.Journey.eventOutcome, "route-map-history"));
}
void SelectedPreview() => Preview(Row(current).FirstOrDefault(n => n.Id == run.Journey.selectedNodeId));
var available = run.AvailableRouteNodes.Select(n => n.Id).ToHashSet();
var chosen = run.Journey.visits.ToDictionary(v => v.wave, v => v.nodeId);
chosen[current] = run.Journey.selectedNodeId;
var potential = new HashSet<int> { run.Journey.selectedNodeId };
var lit = new HashSet<int>(potential);
for (int wave = current + 1; wave <= last; wave++)
{
var before = Row(wave - 1);
var after = Row(wave);
potential = after.Where(to => before.Any(from => potential.Contains(from.Id)
&& Connected(from, to))).Select(n => n.Id).ToHashSet();
lit.UnionWith(potential);
}
// One coordinate space for both nodes and trails. Future is up; travelled ground is below.
bool origin = first == startWave;
int bottom = origin ? first - 1 : first;
const float pitch = 96, radius = 30, top = 48;
var scroll = new ScrollView(ScrollViewMode.Vertical) { name = "RouteMapScroll" };
scroll.AddToClassList("route-map-scroll");
scroll.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
var canvas = new VisualElement { name = "RouteCanvas" };
canvas.AddToClassList("route-map-canvas");
canvas.style.height = top + (last - bottom) * pitch + 62;
var nodesById = new Dictionary<int, VisualElement>();
var points = new Dictionary<int, Vector2>();
var rows = new Dictionary<int, IReadOnlyList<RouteNode>>();
void AddMarker(int id, int wave, float position, VisualElement marker)
{
marker.style.position = Position.Absolute;
marker.style.top = top + (last - wave) * pitch - radius;
marker.style.left = new Length(12 + position * 76, LengthUnit.Percent);
marker.style.marginLeft = -radius;
marker.userData = id;
nodesById.Add(id, marker); canvas.Add(marker);
}
for (int wave = first; wave <= last; wave++)
{
var nodes = Row(wave);
rows.Add(wave, nodes);
var waveLabel = Text(wave.ToString("00"), "route-map-wave");
waveLabel.style.top = top + (last - wave) * pitch - 42;
canvas.Add(waveLabel);
foreach (var node in nodes)
{
bool selected = chosen.TryGetValue(wave, out int id) && id == node.Id;
bool reachable = wave == current ? available.Contains(node.Id) : wave > current && lit.Contains(node.Id);
VisualElement tile;
if (wave == current)
{
var button = new Button(() => run.SelectRouteNode(node.Id)) { name = "Route" + node.Route };
button.SetEnabled(reachable && run.Journey.resolvedEventWave != current);
tile = button;
}
else tile = new VisualElement { name = "MapNode" + node.Id };
tile.AddToClassList("route-map-node");
tile.EnableInClassList("map-choice", wave == current && reachable);
tile.EnableInClassList("map-selected", wave == current && selected);
tile.EnableInClassList("map-taken", wave < current && selected);
tile.EnableInClassList("map-muted", !selected && !reachable);
tile.EnableInClassList("map-future", wave > current);
tile.EnableInClassList("map-boss", wave == run.Journey.FinalWave && !run.Journey.endless);
tile.Add(Glyph(node.Route));
tile.Add(Text(wave == run.Journey.FinalWave && !run.Journey.endless ? "BOSS" : CompactTitle(node.Route), "route-map-name"));
tile.tooltip = $"Wave {wave} / {RunRouteMap.Title(node.Route)}\n{RunRouteMap.Detail(node.Route)}";
tile.RegisterCallback<MouseEnterEvent>(_ => Preview(node));
tile.RegisterCallback<MouseLeaveEvent>(_ => SelectedPreview());
tile.RegisterCallback<FocusInEvent>(_ => Preview(node));
tile.RegisterCallback<FocusOutEvent>(_ => SelectedPreview());
AddMarker(node.Id, wave, nodes.Count == 1 ? .5f : (float)nodes.ToList().IndexOf(node) / (nodes.Count - 1), tile);
if (selected && wave == current - 1)
{
tile.name = "CurrentMapPosition";
var here = Text("YOU ARE HERE", "route-map-here"); tile.Add(here);
}
}
}
if (origin)
{
var start = new VisualElement { name = current == startWave ? "CurrentMapPosition" : "RouteStart" };
start.AddToClassList("route-map-node"); start.AddToClassList("map-taken");
start.Add(Text("OK", "route-map-symbol")); start.Add(Text("Cleared", "route-map-name"));
if (current == startWave) start.Add(Text("YOU ARE HERE", "route-map-here"));
start.tooltip = $"Wave {startWave - 1} cleared. The route begins here.";
AddMarker(-1, bottom, .5f, start);
}
var edges = new List<(int from, int to, bool taken, bool active, bool future)>();
foreach (var row in rows)
{
if (!rows.TryGetValue(row.Key + 1, out var next)) continue;
foreach (var a in row.Value)
foreach (var b in next)
{
if (!Connected(a, b)) continue;
bool taken = b.Wave < current && chosen.TryGetValue(a.Wave, out int aId) && aId == a.Id
&& chosen.TryGetValue(b.Wave, out int bId) && bId == b.Id;
bool active = a.Wave == current - 1 ? chosen.GetValueOrDefault(a.Wave) == a.Id && b.Id == run.Journey.selectedNodeId
: a.Wave >= current && lit.Contains(a.Id);
edges.Add((a.Id, b.Id, taken, active, a.Wave >= current));
}
}
if (origin) foreach (var node in rows[first])
edges.Add((-1, node.Id, first < current && chosen.GetValueOrDefault(first) == node.Id,
first == current && node.Id == run.Journey.selectedNodeId, false));
canvas.generateVisualContent += context =>
{
points.Clear();
foreach (var entry in nodesById)
points[entry.Key] = entry.Value.layout.center;
var painter = context.painter2D;
// Muted trails first, then the player's path. At crossings the active trail stays legible.
foreach (var edge in edges.OrderBy(e => e.taken || e.active))
{
Vector2 a = points[edge.from], b = points[edge.to];
var direction = (b - a).normalized;
a += direction * radius; b -= direction * radius;
Color color = edge.taken ? new Color(.48f, .76f, .59f) : edge.active ? new Color(.91f, .72f, .43f) : new Color(.24f, .33f, .28f);
// A dark under-stroke separates real crossings without inventing junctions.
Trail(painter, a, b, new Color(.055f, .085f, .067f), 7, false);
Trail(painter, a, b, color, edge.active || edge.taken ? 2.5f : 1.5f, edge.future);
}
};
canvas.RegisterCallback<GeometryChangedEvent>(_ => canvas.MarkDirtyRepaint());
scroll.Add(canvas); map.Add(scroll);
bool positioned = false;
scroll.RegisterCallback<GeometryChangedEvent>(_ =>
{
if (positioned || scroll.contentViewport.layout.height < 20) return;
positioned = true;
scroll.schedule.Execute(() =>
{
var here = canvas.Q("CurrentMapPosition");
if (here != null)
scroll.scrollOffset = new Vector2(0, Mathf.Max(0, here.layout.yMax + 36 - scroll.contentViewport.layout.height));
});
});
var choices = nodesById.Values.OfType<Button>().Where(b => b.enabledSelf).OrderBy(b => (int)b.userData).ToList();
void MoveFocus(int direction)
{
if (choices.Count == 0) return;
int index = choices.FindIndex(b => b == layout.focusController?.focusedElement);
var next = choices[(index + direction + choices.Count) % choices.Count];
next.Focus(); scroll.ScrollTo(next);
}
canvas.RegisterCallback<NavigationMoveEvent>(evt =>
{
if (evt.direction is not (NavigationMoveEvent.Direction.Left or NavigationMoveEvent.Direction.Right
or NavigationMoveEvent.Direction.Up or NavigationMoveEvent.Direction.Down)) return;
MoveFocus(evt.direction is NavigationMoveEvent.Direction.Left or NavigationMoveEvent.Direction.Up ? -1 : 1);
evt.StopPropagation(); evt.PreventDefault();
});
canvas.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.keyCode is not (KeyCode.W or KeyCode.A or KeyCode.S or KeyCode.D)) return;
MoveFocus(evt.keyCode is KeyCode.W or KeyCode.A ? -1 : 1);
evt.StopPropagation();
});
if (run.Journey.visits.Count > 0)
{
var history = new Foldout { text = "Travel journal / " + run.Journey.visits.Count + " decisions", value = false, name = "RouteHistory" };
history.AddToClassList("route-map-journal");
foreach (var visit in run.Journey.visits)
history.Add(Text($"Wave {visit.wave} / {RunRouteMap.Title(visit.route)}\n{visit.outcome}", "route-map-history"));
detail.Add(history);
}
layout.Add(map);
SelectedPreview();
layout.Add(detail);
return layout;
}
private static void Trail(Painter2D painter, Vector2 a, Vector2 b, Color color, float width, bool dotted)
{
painter.strokeColor = color; painter.lineWidth = width;
if (!dotted)
{
painter.BeginPath(); painter.MoveTo(a); painter.LineTo(b); painter.Stroke();
return;
}
float length = Vector2.Distance(a, b);
for (float offset = 0; offset < length; offset += 10)
{
painter.BeginPath(); painter.MoveTo(Vector2.Lerp(a, b, offset / length));
painter.LineTo(Vector2.Lerp(a, b, Mathf.Min(offset + 4, length) / length)); painter.Stroke();
}
}
private static VisualElement Glyph(WaveRoute route)
{
var glyph = new VisualElement { pickingMode = PickingMode.Ignore };
glyph.AddToClassList("route-map-glyph");
glyph.generateVisualContent += context =>
{
var p = context.painter2D; p.strokeColor = glyph.resolvedStyle.color; p.lineWidth = 1.8f;
void Line(params Vector2[] points)
{
p.BeginPath(); p.MoveTo(points[0]); foreach (var point in points.Skip(1)) p.LineTo(point); p.Stroke();
}
switch (route)
{
case WaveRoute.Repair:
Line(new(12, 3), new(12, 21)); Line(new(3, 12), new(21, 12)); break;
case WaveRoute.Challenge:
Line(new(4, 3), new(20, 3), new(20, 13), new(12, 22), new(4, 13), new(4, 3));
Line(new(12, 7), new(12, 13)); Line(new(12, 16), new(12, 17)); break;
case WaveRoute.Cache:
Line(new(3, 8), new(12, 3), new(21, 8), new(21, 20), new(3, 20), new(3, 8), new(21, 8));
Line(new(12, 9), new(12, 14)); break;
case WaveRoute.Forge:
Line(new(5, 19), new(16, 8)); Line(new(10, 4), new(14, 2), new(22, 10), new(19, 14), new(10, 4)); break;
case WaveRoute.Sacrifice:
Line(new(12, 2), new(18, 9), new(12, 16), new(6, 9), new(12, 2));
Line(new(3, 21), new(5, 17), new(19, 17), new(21, 21), new(3, 21)); break;
case WaveRoute.Recycle:
Line(new(4, 8), new(9, 3), new(19, 3), new(21, 8)); Line(new(16, 8), new(21, 8), new(21, 2));
Line(new(20, 16), new(15, 21), new(5, 21), new(3, 16)); Line(new(8, 16), new(3, 16), new(3, 22)); break;
default:
Line(new(6, 14), new(12, 8), new(18, 14)); Line(new(6, 21), new(12, 15), new(18, 21)); break;
}
};
return glyph;
}
public static VisualElement BuildEvent(RunManager run)
{
var content = new VisualElement { name = "RouteEventContent" };
content.AddToClassList("departure-content");
content.Add(Text(RunRouteMap.Detail(run.Journey.selectedRoute), "route-detail-copy"));
if (run.RouteEventPending) content.Add(Event(run));
else content.Add(Text("STOP COMPLETE\n" + run.Journey.eventOutcome, "route-event-result"));
return content;
}
private static VisualElement Event(RunManager run)
{
var panel = new VisualElement { name = "RouteEvent" }; panel.AddToClassList("route-event");
var selectors = new VisualElement(); selectors.AddToClassList("departure-selectors"); panel.Add(selectors);
bool remove = run.Journey.selectedRoute is WaveRoute.Sacrifice or WaveRoute.Recycle;
bool upgrade = run.Journey.selectedRoute is WaveRoute.Sacrifice or WaveRoute.Forge;
int amount = run.Journey.selectedRoute == WaveRoute.Sacrifice ? 4 : 2;
var donors = run.RunDeck.Where(c => c.Definition != null && !c.Definition.IsToken
&& (run.Journey.selectedRoute != WaveRoute.Sacrifice || !c.Definition.IsJunk)).ToList();
var targets = run.RunDeck.Where(run.CanImproveRouteCard).ToList();
int donorIndex = 0, targetIndex = Math.Max(0, targets.FindIndex(c => !remove || donors.Count == 0 || c != donors[0]));
var previews = new VisualElement(); previews.AddToClassList("departure-previews");
var result = Text("", "route-event-result");
var commit = new Button { name = "ResolveRouteEventButton", text = run.Journey.selectedRoute switch
{ WaveRoute.Sacrifice => "sacrifice & empower", WaveRoute.Forge => "apply patch", _ => "recycle card" } };
commit.AddToClassList("primary-action");
CardInstance Donor() => remove && donors.Count > 0 ? donors[donorIndex] : null;
CardInstance Target() => upgrade && targets.Count > 0 ? targets[targetIndex] : null;
void Refresh()
{
previews.Clear();
var donor = Donor(); var target = Target();
if (donor != null) previews.Add(Preview(donor, run, "REMOVE FROM THIS RUN"));
if (target != null)
{
previews.Add(Preview(target, run, "BEFORE UPGRADE"));
var after = target.CopyForCombat(); after.ApplyMagnitudeUpgrade(amount);
previews.Add(Preview(after, run, $"AFTER / +{amount} EFFECT"));
}
bool valid = (!remove || (donor != null && run.RunDeck.Count > 1)) && (!upgrade || target != null)
&& (!remove || !upgrade || donor != target);
result.text = !valid ? run.Journey.selectedRoute == WaveRoute.Sacrifice
? "Choose two different cards, or pass if there are no eligible cards. Your deck must keep at least one card."
: "No eligible card is selected. You may pass; your deck must keep at least one card."
: remove ? $"{donor.Definition.DisplayName} will leave this run's deck. " + (upgrade ? $"{target.Definition.DisplayName}: +{target.MagnitudeBonus} -> +{target.MagnitudeBonus + amount} effect." : "Receive 4 Bits.")
: $"{target.Definition.DisplayName}: +{target.MagnitudeBonus} -> +{target.MagnitudeBonus + amount} effect.";
if (run.BuildRewardPending) result.text = "Choose your build reward first, then resolve this stop.";
commit.SetEnabled(valid && !run.BuildRewardPending);
}
if (remove && donors.Count > 0)
{
var picker = new DropdownField("Card to remove", donors.Select((c, i) => $"{i + 1}. {c.Definition.DisplayName}").ToList(), donorIndex) { name = "RouteDonor" };
picker.RegisterValueChangedCallback(_ => { donorIndex = picker.index; Refresh(); }); selectors.Add(picker);
}
if (upgrade && targets.Count > 0)
{
var picker = new DropdownField("Card to empower", targets.Select((c, i) => $"{i + 1}. {c.Definition.DisplayName}").ToList(), targetIndex) { name = "RouteTarget" };
picker.RegisterValueChangedCallback(_ => { targetIndex = picker.index; Refresh(); }); selectors.Add(picker);
}
panel.Add(Text("Run only; your collection is unaffected. Confirm or pass to commit this path.", "route-detail-copy"));
panel.Add(previews); panel.Add(result);
commit.clicked += () => run.ResolveRouteEvent(Donor(), Target());
panel.Add(commit);
var skip = new Button(() => run.ResolveRouteEvent(skip: true)) { text = "pass / keep my deck", name = "SkipRouteEventButton" };
skip.AddToClassList("secondary-action"); skip.SetEnabled(!run.BuildRewardPending); panel.Add(skip);
Refresh();
return panel;
}
private static VisualElement Preview(CardInstance card, RunManager run, string heading)
{
var holder = new VisualElement(); holder.AddToClassList("route-event-card"); holder.AddToClassList("departure-card");
holder.Add(Text(heading, "route-map-eyebrow"));
var face = new VisualElement();
SoftwareCardView.Populate(face, card, CombatManager.GetCardCost(card), CardEffectFactory.GetRulesText(card, run.CurrentConfig));
holder.Add(face); return holder;
}
private static Label Text(string text, string style) => SoftwareCardView.Text(text, style);
private static string CompactTitle(WaveRoute route) => route switch
{
WaveRoute.Repair => "Repair", WaveRoute.Challenge => "Elite", WaveRoute.Cache => "Cache",
WaveRoute.Forge => "Patch", WaveRoute.Sacrifice => "Altar", WaveRoute.Recycle => "Scrap", _ => "Path"
};
}
}
+76 -35
View File
@@ -11,45 +11,21 @@ namespace KernelPanic.UI
{
public static VisualElement Build(RunManager run, CombatManager combat)
{
var section = TerminalLayout.Section(run.CampaignChoicePending ? "KERNEL SECURED" : "Route", "RunRouteChoices");
var section = run.Journey.mapRevision > 0 && !run.CampaignChoicePending
? new VisualElement { name = "RunRouteChoices" }
: TerminalLayout.Section(run.CampaignChoicePending ? "KERNEL SECURED" : "Route", "RunRouteChoices");
section.AddToClassList("run-route-section");
if (!string.IsNullOrEmpty(run.Journey.lastReward)) section.Add(TerminalLayout.BodyText(run.Journey.lastReward));
if (run.BuildRewardPending)
{
section.Add(TerminalLayout.BodyText("Build reward / choose one before departure. Upgrade a card for this run, or take Bits to spend freely."));
var cards = run.RunDeck.Where(card => card.Definition != null && !card.Definition.IsToken && !card.Definition.IsJunk).ToList();
if (cards.Count > 0)
{
int selected = 0;
var target = TerminalLayout.BodyText("", "BuildRewardTarget");
section.Add(target);
var navigation = new VisualElement();
navigation.AddToClassList("reward-target-navigation");
section.Add(navigation);
section.Add(Action($"Upgrade effect +{CombatTuning.UpgradeMagnitudeBonus}", "RewardMagnitude",
() => run.ClaimBuildReward(cards[selected], CardUpgradeKind.MagnitudeUp)));
var draw = Action("Add draw 1 on resolution", "RewardDraw",
() => run.ClaimBuildReward(cards[selected], CardUpgradeKind.DrawRider));
void Select(int offset)
{
selected = (selected + offset + cards.Count) % cards.Count;
var card = cards[selected];
target.text = $"Target {selected + 1}/{cards.Count}: {card.Definition.DisplayName}\n+{card.MagnitudeBonus} effect / +{card.DrawRider} draw";
draw.SetEnabled(card.DrawRider == 0);
}
navigation.Add(Action("Previous card", "RewardPrevious", () => Select(-1)));
navigation.Add(Action("Next card", "RewardNext", () => Select(1)));
Select(0);
section.Add(draw);
}
section.Add(Action($"Take {RunManager.BuildRewardBits} Bits", "RewardBits",
() => run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true)));
}
if (run.BuildRewardPending) return BuildReward(run);
if (run.CampaignChoicePending)
{
section.Add(TerminalLayout.BodyText("Five waves cleared. Finish this campaign and bank your rewards, or keep this build running in endless mode. Rewards are saved when the run ends."));
section.Add(TerminalLayout.BodyText($"All {run.Journey.FinalWave} waves cleared. Kernel Overseer defeated. Finish and bank your rewards, or carry this deck and remaining Uptime into endless survival. Rewards are saved when the run ends."));
section.Add(Action("Finish campaign", "FinishCampaignButton", () => combat.CompleteCampaign()));
section.Add(Action("Continue into endless", "ContinueEndlessButton", () => combat.ContinueEndless()));
section.Add(Action("Continue into endless", "ContinueEndlessButton", () => run.EnterEndless()));
return section;
}
if (run.Journey.mapRevision > 0)
{
section.Add(RunMapView.Build(run));
return section;
}
var plan = EncounterDirector.Plan(run.CurrentWaveNumber, run.Journey.selectedRoute,
@@ -66,6 +42,71 @@ namespace KernelPanic.UI
return section;
}
public static VisualElement BuildReward(RunManager run)
{
var content = new VisualElement { name = "BuildRewardChoices" };
content.AddToClassList("departure-content");
content.Add(TerminalLayout.BodyText($"Upgrade one card, or take {RunManager.BuildRewardBits} Bits."));
var cards = run.RunDeck.Where(c => c.Definition != null && !c.Definition.IsToken && !c.Definition.IsJunk).ToList();
if (cards.Count > 0)
{
int index = 0;
CardUpgradeKind kind = run.CanImproveRouteCard(cards[0]) ? CardUpgradeKind.MagnitudeUp : CardUpgradeKind.DrawRider;
var picker = new DropdownField("Card to upgrade", cards.Select((c, i) => $"{i + 1}. {c.Definition.DisplayName}").ToList(), 0)
{ name = "BuildRewardCard" };
content.Add(picker);
var target = TerminalLayout.BodyText("", "BuildRewardTarget");
var modes = new VisualElement(); modes.AddToClassList("departure-actions"); content.Add(modes);
var beforeAfter = new VisualElement { name = "BuildRewardPreviews" };
beforeAfter.AddToClassList("departure-previews"); content.Add(beforeAfter);
var effect = new Button { name = "RewardMagnitude", text = $"Effect +{CombatTuning.UpgradeMagnitudeBonus}" };
var draw = new Button { name = "RewardDraw", text = "Draw +1 on resolution" };
effect.AddToClassList("primary-action"); draw.AddToClassList("primary-action");
modes.Add(effect); modes.Add(draw);
var claim = Action("claim upgrade / open map", "ClaimBuildRewardButton", () => run.ClaimBuildReward(cards[index], kind));
content.Add(claim);
void Refresh()
{
var card = cards[index];
bool canEffect = run.CanImproveRouteCard(card);
bool canDraw = card.DrawRider == 0 && card.UpgradeLevel < int.MaxValue;
effect.SetEnabled(canEffect); draw.SetEnabled(canDraw);
if (kind == CardUpgradeKind.MagnitudeUp && !canEffect && canDraw) kind = CardUpgradeKind.DrawRider;
if (kind == CardUpgradeKind.DrawRider && !canDraw && canEffect) kind = CardUpgradeKind.MagnitudeUp;
bool valid = kind == CardUpgradeKind.MagnitudeUp ? canEffect : canDraw;
target.text = valid ? "" : "No eligible upgrade. Choose another card or take Bits.";
effect.EnableInClassList("departure-selected", kind == CardUpgradeKind.MagnitudeUp);
draw.EnableInClassList("departure-selected", kind == CardUpgradeKind.DrawRider);
beforeAfter.Clear(); beforeAfter.Add(CardPreview(card, run, "BEFORE"));
var after = card.CopyForCombat();
if (valid)
{
if (kind == CardUpgradeKind.MagnitudeUp) after.ApplyMagnitudeUpgrade(CombatTuning.UpgradeMagnitudeBonus);
else after.ApplyDrawRider(1);
}
beforeAfter.Add(CardPreview(after, run, valid ? "AFTER UPGRADE" : "UNCHANGED"));
claim.SetEnabled(valid);
}
picker.RegisterValueChangedCallback(_ => { index = picker.index; Refresh(); });
effect.clicked += () => { kind = CardUpgradeKind.MagnitudeUp; Refresh(); };
draw.clicked += () => { kind = CardUpgradeKind.DrawRider; Refresh(); };
Refresh();
content.Add(target);
}
content.Add(Action($"take {RunManager.BuildRewardBits} Bits instead / open map", "RewardBits",
() => run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true)));
return content;
}
private static VisualElement CardPreview(CardInstance card, RunManager run, string title)
{
var panel = new VisualElement(); panel.AddToClassList("departure-card");
panel.Add(SoftwareCardView.Text(title, "route-map-eyebrow"));
var face = new VisualElement();
SoftwareCardView.Populate(face, card, CombatManager.GetCardCost(card), CardEffectFactory.GetRulesText(card, run.CurrentConfig));
panel.Add(face); return panel;
}
private static void AddChoice(VisualElement parent, RunManager run, WaveRoute route, string title, string detail)
{
var card = new VisualElement();
+3 -1
View File
@@ -15,6 +15,9 @@ namespace KernelPanic.UI
};
public static void Populate(VisualElement target, CardInstance card, int cost)
=> Populate(target, card, cost, CardEffectFactory.GetRulesText(card));
public static void Populate(VisualElement target, CardInstance card, int cost, string rules)
{
if (card?.Definition == null) return;
var definition = card.Definition;
@@ -33,7 +36,6 @@ namespace KernelPanic.UI
target.Add(Text(string.IsNullOrWhiteSpace(definition.DisplayName) ? definition.name : definition.DisplayName, "software-name"));
target.Add(Text(TrackName(definition.ResolutionTrack), "software-track"));
string rules = CardEffectFactory.GetRulesText(card);
if (card.DrawRider > 0) rules += $" Draw {card.DrawRider}.";
target.tooltip = rules;
if (card.IsBroken) target.tooltip += "\n\n" + CardPreviewService.CorruptionDetails(card);
+29 -5
View File
@@ -71,7 +71,7 @@ public class CampaignTests
Assert.That(pair[0].PairId, Is.GreaterThanOrEqualTo(0));
Assert.That(pair[1].PairId, Is.EqualTo(pair[0].PairId));
((List<EnemyInstance>)_combat.Enemies).Clear();
Set(_run, "currentWaveNumber", 5);
Set(_run, "currentWaveNumber", RunJourney.BossWave);
Call(_combat, "SpawnEncounter");
Assert.That(_combat.Enemies.Count(enemy => enemy.Archetype.Tier == EnemyTier.Boss), Is.EqualTo(1));
}
@@ -107,6 +107,30 @@ public class CampaignTests
Assert.That(RandomRoll.DrawCount, Is.EqualTo(draws));
}
[Test]
public void ExtendedEncountersEscalateWithoutAnEarlyBossAndContinueIntoSurvival()
{
int draws = RandomRoll.DrawCount;
for (int seed = 0; seed < 50; seed++)
for (int wave = 1; wave <= 12; wave++)
{
var plan = EncounterDirector.Plan(wave, WaveRoute.Repair, seed, 2);
Assert.That(plan.Enemies.All(id => EnemyArchetypeCatalog.Get(id).Id == id), Is.True);
Assert.That(plan.Enemies.Count(id => id == "race_condition") % 2, Is.Zero);
if (wave < 10) Assert.That(plan.Enemies, Does.Not.Contain("kernel_overseer"));
if (wave == 10) Assert.That(plan.Enemies.Count(id => id == "kernel_overseer"), Is.EqualTo(1));
if (wave > 10) Assert.That(plan.Title, Does.StartWith("Survival"));
Assert.That(plan.UptimeBonus, Is.EqualTo((wave - 1) * CombatTuning.EnemyUptimeGrowthPerWave));
if (wave > 1)
{
var elite = EncounterDirector.Plan(wave, WaveRoute.Challenge, seed, 2);
Assert.That(elite.Enemies.Count, Is.EqualTo(plan.Enemies.Count + 1));
Assert.That(elite.Enemies.Last(), Is.EqualTo("daemon"));
}
}
Assert.That(RandomRoll.DrawCount, Is.EqualTo(draws));
}
[Test]
public void BuildRewardBlocksDepartureAndOnlyUpgradesTheChosenCardOnce()
{
@@ -309,7 +333,7 @@ public class CampaignTests
[Test]
public void CompletedCampaignIsAVictoryAndCannotContinueOrCompleteTwice()
{
RepositoryAfter(5);
RepositoryAfter(RunJourney.BossWave);
Assert.That(_run.CampaignChoicePending, Is.True);
_combat.ContinueToNextWave();
Assert.That(_combat.AwaitingWaveContinue, Is.True);
@@ -326,13 +350,13 @@ public class CampaignTests
public void EndlessIsExplicitAndKeepsTheSameRunAndRewards()
{
Assert.That(_run.EnterEndless(), Is.False);
RepositoryAfter(5);
RepositoryAfter(RunJourney.BossWave);
string id = _run.RunId;
int bandwidth = _run.AccruedBandwidth;
Assert.That(_run.EnterEndless(), Is.True);
Assert.That(_run.EnterEndless(), Is.False);
Assert.That(_run.CampaignChoicePending, Is.False);
Assert.That(_run.CurrentWaveNumber, Is.EqualTo(6));
Assert.That(_run.CurrentWaveNumber, Is.EqualTo(RunJourney.BossWave + 1));
Assert.That(_run.AccruedBandwidth, Is.EqualTo(bandwidth));
Assert.That(_run.RunId, Is.EqualTo(id));
Assert.That(_run.RewardsSettled, Is.False);
@@ -353,7 +377,7 @@ public class CampaignTests
int draws = RandomRoll.DrawCount;
var lines = ExecutionPreview.Build(_combat);
Assert.That(lines[1], Does.Contain(python.Definition.DisplayName).And.Contain("FIFO").And.Contain("Memory Leak"));
Assert.That(lines[2], Does.Contain(thunk.Definition.DisplayName).And.Contain("LIFO x1.5"));
Assert.That(lines[2], Does.Contain(thunk.Definition.DisplayName).And.Contain("LIFO x1.75"));
Assert.That(lines[3], Does.Contain(map.Definition.DisplayName));
Assert.That(ExecutionPreview.Build(_combat), Is.EqualTo(lines));
Assert.That(RandomRoll.DrawCount, Is.EqualTo(draws));
+68 -55
View File
@@ -74,15 +74,15 @@ public class CardCatalogTests
yield return new TestCaseData("shop_hs_dollar_bang", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Haskell|_maxAmount=5|_minAmount=5|_trueDamage=False;ShieldEffect|_amount=2", true, false, false,
"stack: deal 5. gain 2 Shield.",
"stack: deal 7. gain 4 Shield. [upgraded]").SetName("Catalog_preserves_shop_hs_dollar_bang");
yield return new TestCaseData("lang_py_print", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Python|_maxAmount=3|_minAmount=3|_trueDamage=False", false, false, false,
"queue: deal 3.",
"queue: deal 5. [upgraded]").SetName("Catalog_preserves_lang_py_print");
yield return new TestCaseData("lang_py_import_antigravity", "DrawEffect|_count=2", false, false, false,
"queue: draw 2.",
"queue: draw 4. [upgraded]").SetName("Catalog_preserves_lang_py_import_antigravity");
yield return new TestCaseData("lang_py_for_loop", "DealDamageEffect|_allEnemies=True|_canCrit=True|_language=Python|_maxAmount=2|_minAmount=2|_trueDamage=False", false, true, false,
"queue: deal 2 to all enemies.",
"queue: deal 4 to all enemies. [upgraded]").SetName("Catalog_preserves_lang_py_for_loop");
yield return new TestCaseData("lang_py_print", "PythonEffect|_amount=4|_operation=Print", true, false, false,
"payload: deal 4 to a chosen enemy.",
"payload: deal 6 to a chosen enemy. [upgraded]").SetName("Catalog_preserves_lang_py_print");
yield return new TestCaseData("lang_py_import_antigravity", "PythonEffect|_amount=2|_operation=Draw", false, false, false,
"preparation: immediately draw 2 (fixed).",
"preparation: immediately draw 2 (fixed). [upgraded]").SetName("Catalog_preserves_lang_py_import_antigravity");
yield return new TestCaseData("lang_py_for_loop", "PythonEffect|_amount=2|_operation=Loop", false, false, false,
"modifier: gain 2 Shield. repeat the next payload once. unused repeat expires after next round.",
"modifier: gain 4 Shield. repeat the next payload once. unused repeat expires after next round. [upgraded]").SetName("Catalog_preserves_lang_py_for_loop");
yield return new TestCaseData("lang_js_console_log", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=JavaScript|_maxAmount=9|_minAmount=3|_trueDamage=False", true, false, true,
"deal 3-9.",
"deal 5-11. [upgraded]").SetName("Catalog_preserves_lang_js_console_log");
@@ -92,51 +92,51 @@ public class CardCatalogTests
yield return new TestCaseData("lang_rs_fn_main", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Rust|_maxAmount=6|_minAmount=6|_trueDamage=False", true, false, true,
"deal 6. overkill becomes shield.",
"deal 8. overkill becomes shield. [upgraded]").SetName("Catalog_preserves_lang_rs_fn_main");
yield return new TestCaseData("lang_rs_unwrap", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Rust|_maxAmount=9|_minAmount=9|_trueDamage=False;DrawEffect|_count=1", true, false, true,
"deal 9. overkill becomes shield. draw 1.",
"deal 11. overkill becomes shield. draw 3. [upgraded]").SetName("Catalog_preserves_lang_rs_unwrap");
yield return new TestCaseData("lang_rs_unwrap", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Rust|_maxAmount=5|_minAmount=5|_trueDamage=False;FixedDrawEffect|_count=1", true, false, true,
"deal 5. overkill becomes shield. draw 1 (fixed).",
"deal 7. overkill becomes shield. draw 1 (fixed). [upgraded]").SetName("Catalog_preserves_lang_rs_unwrap");
yield return new TestCaseData("lang_rs_borrow", "ShieldEffect|_amount=5", false, false, false,
"gain 5 shield.",
"gain 7 shield. [upgraded]").SetName("Catalog_preserves_lang_rs_borrow");
yield return new TestCaseData("lang_c_malloc", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=C|_maxAmount=12|_minAmount=12|_trueDamage=False", true, false, true,
"deal 12. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card.",
"deal 14. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. [upgraded]").SetName("Catalog_preserves_lang_c_malloc");
yield return new TestCaseData("lang_c_printf", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=C|_maxAmount=7|_minAmount=7|_trueDamage=False;RepairCorruptedCardsEffect|_count=1", true, false, true,
"deal 7. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. then repair up to 1 corrupted card in your active deck.",
"deal 9. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. then repair up to 3 corrupted cards in your active deck. [upgraded]").SetName("Catalog_preserves_lang_c_printf");
yield return new TestCaseData("lang_c_printf", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=C|_maxAmount=4|_minAmount=4|_trueDamage=False;RepairCorruptedCardsEffect|_count=1", true, false, true,
"deal 4. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. then repair up to 1 corrupted card in your active deck.",
"deal 6. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. then repair up to 3 corrupted cards in your active deck. [upgraded]").SetName("Catalog_preserves_lang_c_printf");
yield return new TestCaseData("lang_c_pointer", "PreviousLanguageDamageEffect|_baseAmount=9|_language=C|_matchingAmount=15", true, false, true,
"deal 9; 15 if the previous card was C. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card.",
"deal 11; 17 if the previous card was C. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. [upgraded]").SetName("Catalog_preserves_lang_c_pointer");
yield return new TestCaseData("lang_java_public_static_main", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Java|_maxAmount=7|_minAmount=7|_trueDamage=False", true, false, true,
"uses 2 RAM. deal 7. overkill spills. JIT: Java cards cost 1 less this combat each time you play a Java card; discount decays by 1 after each wave.",
"uses 2 RAM. deal 9. overkill spills. JIT: Java cards cost 1 less this combat each time you play a Java card; discount decays by 1 after each wave. [upgraded]").SetName("Catalog_preserves_lang_java_public_static_main");
"uses 2 RAM. deal 7. overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave.",
"uses 2 RAM. deal 9. overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave. [upgraded]").SetName("Catalog_preserves_lang_java_public_static_main");
yield return new TestCaseData("lang_java_system_out_println", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Java|_maxAmount=5|_minAmount=5|_trueDamage=False", true, false, true,
"uses 2 RAM. deal 5. overkill spills. JIT applies; discount decays by 1 after each wave.",
"uses 2 RAM. deal 7. overkill spills. JIT applies; discount decays by 1 after each wave. [upgraded]").SetName("Catalog_preserves_lang_java_system_out_println");
"uses 2 RAM. deal 5. overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave.",
"uses 2 RAM. deal 7. overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave. [upgraded]").SetName("Catalog_preserves_lang_java_system_out_println");
yield return new TestCaseData("lang_java_new_object", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Java|_maxAmount=3|_minAmount=3|_trueDamage=False", true, false, true,
"uses 2 RAM. deal 3. overkill spills. JIT applies; discount decays by 1 after each wave.",
"uses 2 RAM. deal 5. overkill spills. JIT applies; discount decays by 1 after each wave. [upgraded]").SetName("Catalog_preserves_lang_java_new_object");
yield return new TestCaseData("ubuntu_ask_ubuntu", "AskUbuntuEffect", false, false, false,
"queue: draw 2.",
"queue: draw 4. [upgraded]").SetName("Catalog_preserves_ubuntu_ask_ubuntu");
yield return new TestCaseData("ubuntu_unattended_upgrades", "ShieldEffect|_amount=4;ApplyStatusEffect|_duration=2|_skipNextTick=True|_stacks=4|_statusType=UnattendedUpgrades|_targetSelf=True", false, false, false,
"queue: gain 4 shield now and next 2 turns.",
"queue: gain 6 shield now and next 2 turns. [upgraded]").SetName("Catalog_preserves_ubuntu_unattended_upgrades");
"uses 2 RAM. deal 3. overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave.",
"uses 2 RAM. deal 5. overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave. [upgraded]").SetName("Catalog_preserves_lang_java_new_object");
yield return new TestCaseData("ubuntu_ask_ubuntu", "PythonEffect|_amount=0|_operation=Inspect", false, false, false,
"preparation: inspect the top 3 cards. take one; others keep their order.",
"preparation: inspect the top 3 cards. take one; others keep their order. [upgraded]").SetName("Catalog_preserves_ubuntu_ask_ubuntu");
yield return new TestCaseData("ubuntu_unattended_upgrades", "PythonEffect|_amount=3|_operation=Unattended", false, false, false,
"automation: gain 3 Shield now and before the queue on each of the next 2 rounds. uses 1 of 2 script slots.",
"automation: gain 5 Shield now and before the queue on each of the next 2 rounds. uses 1 of 2 script slots. [upgraded]").SetName("Catalog_preserves_ubuntu_unattended_upgrades");
yield return new TestCaseData("mint_fix_broken", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=JavaScript|_maxAmount=8|_minAmount=8|_trueDamage=False;CleanseEffect|_harmfulOnly=True", true, false, true,
"deal 8. cleanse harmful statuses.",
"deal 10. cleanse harmful statuses. [upgraded]").SetName("Catalog_preserves_mint_fix_broken");
yield return new TestCaseData("lang_js_typeof", "ChanceDamageEffect|_damageAmount=8|_language=JavaScript|_successPercent=75", true, false, true,
"75%: deal 8. 25%: deal 0.",
"75%: deal 10. 25%: deal 0. [upgraded]").SetName("Catalog_preserves_lang_js_typeof");
yield return new TestCaseData("shop_py_list_append", "QueuedGrowthDamageEffect|_baseAmount=4|_language=Python", true, false, false,
"queue: deal 4; +1 each time re-queued.",
"queue: deal 8; +1 each time re-queued. [upgraded]").SetName("Catalog_preserves_shop_py_list_append");
yield return new TestCaseData("shop_py_async_def", "DrawEffect|_count=2;NextTurnCycleEffect|_amount=1", false, false, false,
"queue: draw 2. gain 1 cycle next turn.",
"queue: draw 4. gain 3 cycle next turn. [upgraded]").SetName("Catalog_preserves_shop_py_async_def");
yield return new TestCaseData("shop_py_zip", "QueueRepeatEffect|_count=2", false, false, false,
"next 2 queued cards resolve twice.",
"next 4 queued cards resolve twice. [upgraded]").SetName("Catalog_preserves_shop_py_zip");
yield return new TestCaseData("lang_js_typeof", "ChanceDamageEffect|_damageAmount=14|_language=JavaScript|_successPercent=75", true, false, true,
"75%: deal 14. 25%: deal 0.",
"75%: deal 16. 25%: deal 0. [upgraded]").SetName("Catalog_preserves_lang_js_typeof");
yield return new TestCaseData("shop_py_list_append", "PythonEffect|_amount=6|_operation=List", true, false, false,
"payload: deal 6. +2 per subsequent hand play this wave; replays do not grow it.",
"payload: deal 12. +2 per subsequent hand play this wave; replays do not grow it. [upgraded]").SetName("Catalog_preserves_shop_py_list_append");
yield return new TestCaseData("shop_py_async_def", "PythonEffect|_amount=0|_operation=Async", false, false, false,
"automation: draw 1 immediately on play (fixed). capture the next payload without modifiers; replay it before the queue on each of the next 2 rounds. uses 1 of 2 script slots.",
"automation: draw 1 immediately on play (fixed). capture the next payload without modifiers; replay it before the queue on each of the next 2 rounds. uses 1 of 2 script slots. [upgraded]").SetName("Catalog_preserves_shop_py_async_def");
yield return new TestCaseData("shop_py_zip", "PythonEffect|_amount=2|_operation=Zip", true, false, false,
"modifier: deal 2. the next single-target damage payload hits all enemies. unused conversion expires after next round.",
"modifier: deal 4. the next single-target damage payload hits all enemies. unused conversion expires after next round. [upgraded]").SetName("Catalog_preserves_shop_py_zip");
yield return new TestCaseData("shop_js_math_random", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=JavaScript|_maxAmount=20|_minAmount=2|_trueDamage=False", true, false, true,
"deal 2-20.",
"deal 4-22. [upgraded]").SetName("Catalog_preserves_shop_js_math_random");
@@ -152,24 +152,24 @@ public class CardCatalogTests
yield return new TestCaseData("ubuntu_do_release_upgrade", "UpgradeHandCardsEffect|_maxCount=3|_minCount=1", false, false, false,
"upgrade 1-3 random hand cards.",
"upgrade 3-5 random hand cards. [upgraded]").SetName("Catalog_preserves_ubuntu_do_release_upgrade");
yield return new TestCaseData("ubuntu_apt_install", "GenerateCardEffect|_language=Python|_rarity=Common", false, false, false,
"queue: generate a random common Python card at 0c.",
"queue: generate a random common Python card at 0c. [upgraded]").SetName("Catalog_preserves_ubuntu_apt_install");
yield return new TestCaseData("ubuntu_apt_install", "PythonEffect|_amount=0|_operation=Install", false, false, false,
"preparation: choose one of 3 Python cards. temporary copy costs 0 this turn and exhausts after play.",
"preparation: choose one of 3 Python cards. temporary copy costs 0 this turn and exhausts after play. [upgraded]").SetName("Catalog_preserves_ubuntu_apt_install");
yield return new TestCaseData("ubuntu_pro_trial", "NoOpCardEffect|_message=ubuntu pro trial is unplayable", false, false, false,
"unplayable. exhausts at end of combat.",
"unplayable. exhausts at end of combat. [upgraded]").SetName("Catalog_preserves_ubuntu_pro_trial");
yield return new TestCaseData("mint_update_manager", "UpdateManagerEffect|_amount=5", false, false, false,
"queue: deal 5 to all enemies. repeats at the end of your next turn.",
"queue: deal 7 to all enemies. repeats at the end of your next turn. [upgraded]").SetName("Catalog_preserves_mint_update_manager");
yield return new TestCaseData("mint_cinnamon", "ShieldEffect|_amount=3;DrawEffect|_count=1", false, false, false,
"queue: gain 3 shield. draw 1.",
"queue: gain 5 shield. draw 3. [upgraded]").SetName("Catalog_preserves_mint_cinnamon");
yield return new TestCaseData("mint_update_manager", "PythonEffect|_amount=3|_operation=Update", false, true, false,
"payload: deal 3 to all enemies; 5 if an automation ran earlier this phase.",
"payload: deal 5 to all enemies; 7 if an automation ran earlier this phase. [upgraded]").SetName("Catalog_preserves_mint_update_manager");
yield return new TestCaseData("mint_cinnamon", "PythonEffect|_amount=3|_operation=Cinnamon", false, false, false,
"payload: gain 3 Shield; 5 if an earlier Python payload dealt damage this phase.",
"payload: gain 5 Shield; 7 if an earlier Python payload dealt damage this phase. [upgraded]").SetName("Catalog_preserves_mint_cinnamon");
yield return new TestCaseData("mint_nemo", "ConditionalShieldRepeatDamageEffect|_amount=6|_language=JavaScript", true, false, true,
"deal 6. if you have shield, deal it again.",
"deal 8. if you have shield, deal it again. [upgraded]").SetName("Catalog_preserves_mint_nemo");
yield return new TestCaseData("mint_timeshift", "TimeshiftSnapshotEffect", false, false, false,
"queue: record uptime now. at end of your next turn, restore to it if lower.",
"queue: record uptime now. at end of your next turn, restore to it if lower. [upgraded]").SetName("Catalog_preserves_mint_timeshift");
yield return new TestCaseData("mint_timeshift", "PythonEffect|_amount=0|_operation=Timeshift", false, false, false,
"automation: save your Uptime when this resolves. after enemies act in each of the next 2 rounds, heal up to 6 Uptime, without exceeding the saved value. no healing this round or if defeated. healing does not scale with upgrades. uses 1 of 2 script slots until both rounds finish; ends when the wave ends.",
"automation: save your Uptime when this resolves. after enemies act in each of the next 2 rounds, heal up to 6 Uptime, without exceeding the saved value. no healing this round or if defeated. healing does not scale with upgrades. uses 1 of 2 script slots until both rounds finish; ends when the wave ends. [upgraded]").SetName("Catalog_preserves_mint_timeshift");
yield return new TestCaseData("fedora_dnf_autoremove", "DnfAutoremoveEffect|_cycleGain=1|_damageAmount=7", true, false, true,
"deal 7. exhaust a junk/NOP/broken card from hand; if you do, gain 1 cycle. if not, do nothing.",
"deal 9. exhaust a junk/NOP/broken card from hand; if you do, gain 3 cycle. if not, do nothing. [upgraded]").SetName("Catalog_preserves_fedora_dnf_autoremove");
@@ -177,8 +177,8 @@ public class CardCatalogTests
"deal 7. Java cards cost 1 less this turn.",
"deal 9. Java cards cost 1 less this turn. [upgraded]").SetName("Catalog_preserves_fedora_first_to_package");
yield return new TestCaseData("fedora_dnf_update", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Java|_maxAmount=9|_minAmount=9|_trueDamage=False", true, false, true,
"deal 9. overkill spills. costs 1 less per Java card played this combat.",
"deal 11. overkill spills. costs 1 less per Java card played this combat. [upgraded]").SetName("Catalog_preserves_fedora_dnf_update");
"deal 9. overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave.",
"deal 11. overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave. [upgraded]").SetName("Catalog_preserves_fedora_dnf_update");
yield return new TestCaseData("fedora_rawhide", "RawhideEffect", false, false, false,
"draw 2. next card this turn gains bleeding edge.",
"draw 4. next card this turn gains bleeding edge. [upgraded]").SetName("Catalog_preserves_fedora_rawhide");
@@ -192,8 +192,8 @@ public class CardCatalogTests
"fix a broken card and draw 1; if none, deal 6.",
"fix a broken card and draw 3; if none, deal 8. [upgraded]").SetName("Catalog_preserves_arch_consult_wiki");
yield return new TestCaseData("arch_makepkg", "BtwScaledDamageEffect|_baseAmount=7|_language=C|_perBtw=3", true, false, true,
"deal 7 + btw x3; x4 at Arch v3+. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card.",
"deal 9 + btw x3; x4 at Arch v3+. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. [upgraded]").SetName("Catalog_preserves_arch_makepkg");
"deal 7 + btw x3. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card.",
"deal 9 + btw x3. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. [upgraded]").SetName("Catalog_preserves_arch_makepkg");
yield return new TestCaseData("arch_aur_helper", "RandomCommonLanguageCardEffect", false, false, false,
"add a random C/Rust common card to hand; it costs 0 this turn.",
"add a random C/Rust common card to hand; it costs 0 this turn. [upgraded]").SetName("Catalog_preserves_arch_aur_helper");
@@ -345,6 +345,19 @@ public class CardCatalogTests
}
}
[TestCase("arch", 2, 3)]
[TestCase("arch", 3, 4)]
[TestCase("arch", 5, 4)]
[TestCase("ubuntu", 5, 3)]
public void MakepkgShowsOnlyTheActiveVersionMultiplier(string distro, int version, int multiplier)
{
var card = new CardInstance(Database.FindById("arch_makepkg"));
card.ApplyMagnitudeUpgrade(2);
string rules = CardEffectFactory.GetRulesText(card, distro, version);
Assert.That(rules, Does.StartWith($"deal 9 + btw x{multiplier}."));
Assert.That(rules, Does.Not.Contain("v3"));
}
[Test]
public void SerializedOverrideStillWinsAndUsesItsOwnDescription()
{
+41 -7
View File
@@ -138,7 +138,7 @@ public class CardPreviewTests
{
var queuedPreview = CardPreviewService.Build(combat, card, Target);
Assert.That(queuedPreview.MinimumDamage, Is.EqualTo(preview.MinimumDamage), "Queued preview must not add the play hook twice.");
ResolveEffects(card);
ResolveEffects(card, combat.LazyStack.Entries.First(entry => entry.Card == card).MultiplierPercent);
}
Assert.That(before - Target.CurrentUptime, Is.EqualTo(preview.MinimumDamage));
Assert.That(preview.MaximumDamage, Is.EqualTo(preview.MinimumDamage));
@@ -240,7 +240,7 @@ public class CardPreviewTests
Player.ForceMaxRolls = false;
Player.JavaScriptFlatDamageBonus = 2;
var preview = CardPreviewService.Build(combat, Card("lang_js_typeof"), Target);
Assert.That((preview.MinimumDamage, preview.MaximumDamage), Is.EqualTo((2, 15)));
Assert.That((preview.MinimumDamage, preview.MaximumDamage), Is.EqualTo((2, 24)));
}
[Test]
@@ -252,14 +252,47 @@ public class CardPreviewTests
Play(first);
Play(second);
var third = Card("lang_hs_thunk");
Assert.That(CardPreviewService.Build(combat, first, Target).MaximumDamage, Is.EqualTo(4));
Assert.That(CardPreviewService.Build(combat, second, Target).MaximumDamage, Is.EqualTo(6));
Assert.That(CardPreviewService.Build(combat, first, Target).MaximumDamage, Is.EqualTo(6));
Assert.That(CardPreviewService.Build(combat, second, Target).MaximumDamage, Is.EqualTo(7));
Assert.That(CardPreviewService.Build(combat, third, Target).MaximumDamage, Is.EqualTo(8));
Assert.That(CardPreviewService.Build(combat, second).Details, Does.Contain("captured: x1.5"));
Assert.That(CardPreviewService.Build(combat, second).Details, Does.Contain("captured: x1.75"));
Assert.That(CardPreviewService.Build(combat, third).Details, Does.Contain("next stack: x2.0"));
int before = Target.CurrentUptime;
ResolveEffects(second, combat.LazyStack.Entries.First(entry => entry.Card == second).MultiplierPercent);
Assert.That(before - Target.CurrentUptime, Is.EqualTo(6));
Assert.That(before - Target.CurrentUptime, Is.EqualTo(7));
}
[Test]
public void JavaAcceptedPlaysWarmGraduallyCapAndCoolWithoutChangingDamage()
{
Configure("Ubuntu", 1);
var main = Card("lang_java_public_static_main");
var println = Card("lang_java_system_out_println");
var allocation = Card("lang_java_new_object");
Assert.That((main.Definition.CycleCost, println.Definition.CycleCost, allocation.Definition.CycleCost),
Is.EqualTo((2, 1, 0)));
int[] costs = { 2, 2, 1, 1, 0, 0, 0, 0, 0 };
int before = Target.CurrentUptime;
for (int plays = 0; plays < costs.Length; plays++)
{
var preview = CardPreviewService.Build(combat, main, Target);
Assert.That(preview.Cost, Is.EqualTo(costs[plays]), $"After {plays} Java plays");
Assert.That(preview.MaximumDamage, Is.EqualTo(7));
if (plays < costs.Length - 1) Play(Card("lang_java_new_object"));
}
Assert.That(before - Target.CurrentUptime, Is.EqualTo(24), "Eight unchanged 3-damage hits.");
Assert.That(Player.Cycles, Is.EqualTo(100), "The entry card is free but still uses hand space.");
Assert.That(CardPreviewService.Build(combat, println, Target).MaximumDamage, Is.EqualTo(5));
Call(combat, "DecayJavaWarmupForNextWave");
Assert.That(combat.GetEffectiveCardCost(main), Is.Zero);
Call(combat, "DecayJavaWarmupForNextWave");
Assert.That(combat.GetEffectiveCardCost(main), Is.EqualTo(1), "Excess plays cannot bank extra cooling immunity.");
Call(combat, "DecayJavaWarmupForNextWave");
Assert.That(combat.GetEffectiveCardCost(main), Is.EqualTo(2));
Call(combat, "DecayJavaWarmupForNextWave");
Assert.That(combat.GetEffectiveCardCost(main), Is.EqualTo(2));
combat.AddJavaCostDiscountThisTurn(1);
Assert.That(combat.GetEffectiveCardCost(main), Is.EqualTo(1), "Turn discounts still stack independently.");
}
[Test]
@@ -397,7 +430,8 @@ public class CardPreviewTests
{
var card = Card("lang_c_malloc");
card.CorruptForRounds(3, 1);
var populate = typeof(CombatManager).Assembly.GetType("KernelPanic.UI.SoftwareCardView").GetMethod("Populate");
var populate = typeof(CombatManager).Assembly.GetType("KernelPanic.UI.SoftwareCardView")
.GetMethod("Populate", new[] { typeof(VisualElement), typeof(CardInstance), typeof(int) });
var face = new VisualElement();
populate.Invoke(null, new object[] { face, card, 3 });
var preview = CardPreviewService.Build(combat, card);
+51 -10
View File
@@ -44,12 +44,12 @@ public class CardUtilityEffectTests
_temporary.Clear();
}
[TestCase("ubuntu", 2, 2)]
[TestCase("ubuntu", 3, 3)]
[TestCase("ubuntu", 5, 3)]
[TestCase("UBUNTU", 3, 3)]
[TestCase("mint", 5, 2)]
[TestCase(null, 3, 2)]
[TestCase("ubuntu", 2, 3)]
[TestCase("ubuntu", 3, 5)]
[TestCase("ubuntu", 5, 5)]
[TestCase("UBUNTU", 3, 5)]
[TestCase("mint", 5, 3)]
[TestCase(null, 3, 3)]
public void CatalogAskUbuntuUsesBonusOnlyForUbuntuVersionThreeAndLater(string distro, int version, int expected)
{
if (distro != null) Configure(distro, version);
@@ -58,8 +58,10 @@ public class CardUtilityEffectTests
ExecuteCatalog(card);
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(expected));
Assert.That(_combat.DeckController.DrawPile.Count, Is.EqualTo(10 - expected));
Assert.That(_combat.Python.Choices.Count, Is.EqualTo(expected));
Assert.That(_combat.Python.Choose(0), Is.True);
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(1));
Assert.That(_combat.DeckController.DrawPile.Count, Is.EqualTo(9));
}
[Test]
@@ -73,8 +75,10 @@ public class CardUtilityEffectTests
ExecuteCatalog(card);
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(8), "Three base draws plus two flat and three magnitude.");
Assert.That(_combat.DeckController.DrawPile.Count, Is.EqualTo(4));
Assert.That(_combat.Python.Choices.Count, Is.EqualTo(5), "Inspection count is fixed, regardless of effect bonuses.");
Assert.That(_combat.Python.Choose(0), Is.True);
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(1));
Assert.That(_combat.DeckController.DrawPile.Count, Is.EqualTo(11));
}
[TestCase(2)]
@@ -193,6 +197,43 @@ public class CardUtilityEffectTests
Assert.That(_combat.DeckController.DrawPile, Is.Empty);
}
[TestCase(0, 0)]
[TestCase(2, 3)]
[TestCase(6, 10)]
public void UnwrapReplacementDrawDoesNotScaleWithMagnitudeOrSourceBonuses(int magnitude, int flatBonus)
{
FillDeck(12);
var card = Card("lang_rs_unwrap", Language.Rust);
card.ApplyMagnitudeUpgrade(magnitude);
Player.FlatEffectBonus = flatBonus;
ExecuteCatalog(card);
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(1));
Assert.That(_combat.DeckController.DrawPile.Count, Is.EqualTo(11));
Assert.That(CardEffectFactory.GetRulesText(card), Does.Contain("draw 1 (fixed)"));
}
[TestCase(0)]
[TestCase(1)]
public void UnwrapFixedDrawPreservesBlockedJavaCardAndDrawOrder(int ram)
{
_combat.HandController.SetRamCapacity(ram);
var java = Card("java_top", Language.Java);
var next = Card("python_next");
SetDrawOrder(java, next);
var card = Card("lang_rs_unwrap", Language.Rust);
ExecuteCatalog(card);
Assert.That(_combat.HandController.Cards, Is.Empty);
Assert.That(_combat.DeckController.DrawPile, Is.EqualTo(new[] { next, java }));
_combat.HandController.SetRamCapacity(2);
ExecuteCatalog(card);
Assert.That(_combat.HandController.Cards, Is.EqualTo(new[] { java }));
Assert.That(_combat.DeckController.DrawPile, Is.EqualTo(new[] { next }));
}
private void Configure(string distroId, int version)
{
var distro = ScriptableObject.CreateInstance<DistroDefinition>();
+287 -29
View File
@@ -112,6 +112,67 @@ public class CombatLayoutTests
enemies.Add(new EnemyInstance(EnemyArchetypeCatalog.Get("memory_leak"), 4));
}
[UnityTest]
public IEnumerator PythonChoicesFitViewportsAndResolveThroughAKeyboardSubmit()
{
var database = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
_combat.SetGeneratedCardPool(database.AllCards);
foreach (var size in new[] { new Vector2(1280, 720), new Vector2(390, 844), new Vector2(960, 400) })
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
{
UIPreferences.TextSize = textSize;
Resize(size);
_combat.Python.Clear();
_combat.HandController.Clear();
var card = new CardInstance(database.FindById("ubuntu_apt_install"));
var context = new CombatContext(card, _combat.PlayerState, Array.Empty<CombatantState>(), _combat,
_combat.DamagePipeline, new StatusEffectController(), _combat.DeckController, _combat.HandController, _combat.Enemies);
foreach (var effect in CardEffectFactory.CreateEffects(card.Definition)) effect.Execute(context);
Call(_view, "RefreshOverlay");
for (int frame = 0; frame < 5; frame++) yield return null;
var buttons = _root.Query<Button>().ToList().Where(b => b.name?.StartsWith("PythonChoice") == true).ToList();
Assert.That(buttons.Count, Is.EqualTo(3));
var dialog = _root.Q("PythonChoiceDialog");
Assert.That(dialog, Is.Not.Null);
AssertContainedHorizontally(dialog, _root, size.ToString());
Assert.That(dialog.worldBound.yMin, Is.GreaterThanOrEqualTo(_root.worldBound.yMin - 1));
Assert.That(dialog.worldBound.yMax, Is.LessThanOrEqualTo(_root.worldBound.yMax + 1));
foreach (var button in buttons)
{
AssertContainedHorizontally(button, _root, size.ToString());
Assert.That(button.worldBound.height, Is.GreaterThanOrEqualTo(47.99f));
Assert.That(button.Q<Label>(className: "software-name"), Is.Not.Null);
Assert.That(button.Q<Label>(className: "software-cost").text, Is.EqualTo("0c"));
Assert.That(button.Q<Label>(className: "python-choice-action").text, Does.StartWith("> install"));
foreach (var label in button.Query<Label>().ToList()) AssertContainedHorizontally(label, button, size.ToString());
}
buttons[2].Focus();
for (int frame = 0; frame < 3; frame++) yield return null;
var viewport = _root.Q<ScrollView>("PythonChoiceScroll").contentViewport;
if (buttons[2].worldBound.height > viewport.worldBound.height)
Assert.That(buttons[2].worldBound.yMin, Is.EqualTo(viewport.worldBound.yMin).Within(1));
else Assert.That(buttons[2].worldBound.yMax, Is.LessThanOrEqualTo(viewport.worldBound.yMax + 1));
buttons[0].Focus();
using (var submit = NavigationSubmitEvent.GetPooled()) buttons[0].SendEvent(submit);
Assert.That(_combat.Python.HasChoice, Is.False);
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(1));
Call(_view, "RefreshOverlay");
card = new CardInstance(database.FindById("ubuntu_unattended_upgrades"));
context = new CombatContext(card, _combat.PlayerState, Array.Empty<CombatantState>(), _combat,
_combat.DamagePipeline, new StatusEffectController(), _combat.DeckController, _combat.HandController, _combat.Enemies);
foreach (var effect in CardEffectFactory.CreateEffects(card.Definition)) effect.Execute(context);
foreach (var effect in CardEffectFactory.CreateEffects(card.Definition)) effect.Execute(context);
Call(_view, "RefreshTracks");
for (int frame = 0; frame < 5; frame++) yield return null;
var readout = _root.Q("PythonAutomationReadout");
Assert.That(readout.Query<Label>().ToList().Count, Is.EqualTo(3));
foreach (var label in readout.Query<Label>().ToList()) AssertContainedHorizontally(label, _root, size.ToString());
Assert.That(_root.Q(className: "scheduler").ClassListContains("scheduler-idle"), Is.False);
Assert.That(_root.Q<Button>(className: "primary-action").worldBound.yMax,
Is.LessThanOrEqualTo(_root.worldBound.yMax + 1), size.ToString());
}
}
[UnityTest]
public IEnumerator FirstBattleGuideAndReplayControlFitAcrossViewports()
{
@@ -240,6 +301,49 @@ public class CombatLayoutTests
Assert.That(overlay.Query<Label>().ToList().Any(label => label.text.Contains("FINAL ROUND 0")), Is.False);
}
[UnityTest]
public IEnumerator FullMapUsesTheViewportAndPreviewsWithoutCommittingKeyboardOrMouseChoices()
{
_run.RepositoryChanged += () => Call(_view, "RefreshOverlay");
foreach (var size in new[] { new Vector2(1280, 720), new Vector2(1920, 1080) })
{
Resize(size);
Set(_run, "currentWaveNumber", 2); Set(_run, "_wavesCleared", 1);
_run.GenerateRepositoryOffers(null, null);
Set(_combat, "_awaitingWaveContinue", true); Set(_view, "_routeSelectionOpen", true);
Call(_view, "RefreshOverlay");
for (int i = 0; i < 8; i++) yield return null;
var scroll = _root.Q<ScrollView>("RouteMapScroll");
var canvas = _root.Q("RouteCanvas");
Assert.That(scroll.worldBound.width, Is.GreaterThan(size.x * .55f));
Assert.That(scroll.worldBound.height, Is.GreaterThan(size.y * .5f));
Assert.That(canvas.Query(className: "route-map-wave").ToList().Count, Is.EqualTo(9));
Assert.That(canvas.Query(className: "route-map-node").ToList().Count, Is.GreaterThanOrEqualTo(21));
var here = canvas.Q("CurrentMapPosition");
Assert.That(here.worldBound.yMax + 24, Is.LessThanOrEqualTo(scroll.contentViewport.worldBound.yMax + 1));
var repair = canvas.Q<Button>("RouteRepair");
var elite = canvas.Q<Button>("RouteChallenge");
int selected = _run.Journey.selectedNodeId;
repair.Focus();
using (var key = KeyDownEvent.GetPooled('d', KeyCode.D, EventModifiers.None))
{ key.target = repair; repair.SendEvent(key); }
Assert.That(_root.focusController.focusedElement, Is.SameAs(elite));
Assert.That(_run.Journey.selectedNodeId, Is.EqualTo(selected));
Assert.That(_root.Q("RoutePreview").Query<Label>().ToList().Any(l => l.text == "Elite detour"), Is.True);
var boss = canvas.Q(className: "map-boss");
using (var hover = MouseEnterEvent.GetPooled()) { hover.target = boss; boss.SendEvent(hover); }
Assert.That(_root.Q("RoutePreview").Query<Label>().ToList().Any(l => l.text == "Kernel Overseer"), Is.True);
Assert.That(_run.Journey.selectedNodeId, Is.EqualTo(selected));
using (var submit = NavigationSubmitEvent.GetPooled()) { submit.target = elite; elite.SendEvent(submit); }
Assert.That(_run.Journey.selectedRoute, Is.EqualTo(WaveRoute.Challenge));
for (int i = 0; i < 4; i++) yield return null;
var screen = _root.Q("RouteSelectionScreen");
using (var escape = KeyDownEvent.GetPooled('\0', KeyCode.Escape, EventModifiers.None))
{ escape.target = screen; screen.SendEvent(escape); }
Assert.That(_root.Q("RouteSelectionScreen"), Is.Null);
}
}
[UnityTest]
public IEnumerator RouteChoicesAndMilestoneRemainReadableAndReachable()
{
@@ -247,9 +351,9 @@ public class CombatLayoutTests
_run.RepositoryChanged += () => Call(_view, "RefreshOverlay");
foreach (var size in Viewports)
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
foreach (int nextWave in new[] { 2, 3, 6 })
foreach (int nextWave in new[] { 2, 3, RunJourney.BossWave + 1 })
{
bool milestone = nextWave == 6;
bool milestone = nextWave == RunJourney.BossWave + 1;
UIPreferences.TextSize = textSize;
Resize(size);
Set(_run, "currentWaveNumber", nextWave);
@@ -270,6 +374,20 @@ public class CombatLayoutTests
boot.SendEvent(submit);
}
for (int frame = 0; frame < 6; frame++) yield return null;
if (nextWave == 3)
{
Assert.That(overlay.Q("BuildRewardScreen"), Is.Not.Null);
Assert.That(overlay.Q("RunMap"), Is.Null, "Rewards and route selection must be separate screens.");
Assert.That(overlay.Q("RouteEvent"), Is.Null);
Assert.That(overlay.Q<DropdownField>("BuildRewardCard").value, Does.Contain(_run.RunDeck[0].Definition.DisplayName));
Assert.That(overlay.Q("BuildRewardPreviews").childCount, Is.EqualTo(2));
int before = _run.Bits;
using (var submit = NavigationSubmitEvent.GetPooled())
{ var button = overlay.Q<Button>("RewardBits"); submit.target = button; button.SendEvent(submit); }
Assert.That(_run.Bits, Is.EqualTo(before + RunManager.BuildRewardBits));
for (int frame = 0; frame < 6; frame++) yield return null;
Assert.That(overlay.Q("BuildRewardScreen"), Is.Null);
}
var section = overlay.Q("RunRouteChoices");
var scroll = overlay.Q<ScrollView>(className: "repository-body");
string context = $"{size}, {textSize}, milestone={milestone}";
@@ -278,15 +396,9 @@ public class CombatLayoutTests
Assert.That(_combat.AwaitingWaveContinue, Is.True, "Opening departure must not start the wave.");
var confirm = overlay.Q<Button>("ConfirmRouteButton");
if (milestone) Assert.That(confirm, Is.Null, context);
else Assert.That(confirm.enabledInHierarchy, Is.EqualTo(nextWave != 3), context);
if (nextWave == 3)
{
var target = section.Q<Label>("BuildRewardTarget");
Assert.That(target, Is.Not.Null, context);
Assert.That(target.text, Does.Contain(_run.RunDeck[0].Definition.DisplayName), context);
AssertContainedHorizontally(target, scroll.contentViewport, context);
Assert.That(section.Q<Button>("RewardBits"), Is.Not.Null, context);
}
else Assert.That(confirm.enabledInHierarchy, Is.True, context);
Assert.That(section.Q("RouteEvent"), Is.Null, "Map browsing must not contain event controls.");
Assert.That(section.Query<Label>().ToList().Any(label => label.text.Contains("THEN / WAVE")), Is.False);
Assert.That(scroll.contentViewport.worldBound.height, Is.GreaterThan(35), context);
foreach (var label in section.Query<Label>().ToList())
{
@@ -297,7 +409,9 @@ public class CombatLayoutTests
}
foreach (var button in section.Query<Button>().ToList())
{
scroll.ScrollTo(button);
var routeScroll = section.Q<ScrollView>("RouteMapScroll");
if (routeScroll != null && routeScroll.Contains(button)) routeScroll.ScrollTo(button);
else scroll.ScrollTo(button);
for (int frame = 0; frame < 2; frame++) yield return null;
AssertContainedHorizontally(button, scroll.contentViewport, context);
Assert.That(button.worldBound.yMin, Is.GreaterThanOrEqualTo(scroll.contentViewport.worldBound.yMin - 1), context);
@@ -310,26 +424,34 @@ public class CombatLayoutTests
{
AssertContainedHorizontally(confirm, overlay, context);
Assert.That(confirm.worldBound.yMax, Is.LessThanOrEqualTo(overlay.worldBound.yMax + 1), context);
var challenge = overlay.Q<Button>("RouteChallenge");
Assert.That(Mathf.Abs(back.worldBound.width - confirm.worldBound.width), Is.LessThanOrEqualTo(2), context);
Assert.That(Mathf.Abs(back.worldBound.height - confirm.worldBound.height), Is.LessThanOrEqualTo(2), context);
Assert.That(overlay.Q("RunMap"), Is.Not.Null, context);
var canvas = overlay.Q("RouteCanvas");
Assert.That(canvas, Is.Not.Null, "Trails and markers must share one continuous canvas.");
foreach (var marker in canvas.Query(className: "route-map-node").ToList())
{
Assert.That(marker.parent, Is.SameAs(canvas), context);
Assert.That(marker.layout.width, Is.EqualTo(60).Within(1), context);
Assert.That(marker.layout.height, Is.EqualTo(60).Within(1), context);
}
if (nextWave == 2)
{
var here = canvas.Q("CurrentMapPosition");
var selected = canvas.Q(className: "map-selected");
Assert.That(here, Is.Not.Null, context);
Assert.That(here.layout.center.y, Is.GreaterThan(selected.layout.center.y), "Travel proceeds upward from the player's position.");
Assert.That(canvas.Query(className: "map-future").ToList().All(n => n.layout.center.y < selected.layout.center.y), Is.True, context);
}
var choice = _run.AvailableRouteNodes.FirstOrDefault(n => !RunRouteMap.IsEvent(n.Route)) ?? _run.AvailableRouteNodes[0];
var challenge = overlay.Q<Button>("Route" + choice.Route);
using (var submit = NavigationSubmitEvent.GetPooled())
{
submit.target = challenge;
challenge.SendEvent(submit);
}
Assert.That(_run.Journey.selectedRoute, Is.EqualTo(WaveRoute.Challenge), context);
Assert.That(_run.Journey.selectedRoute, Is.EqualTo(choice.Route), context);
Assert.That(overlay.Q("RouteSelectionScreen"), Is.Not.Null, "Route selection must survive refresh.");
if (nextWave == 3)
{
int bitsBefore = _run.Bits;
var reward = overlay.Q<Button>("RewardBits");
using (var submit = NavigationSubmitEvent.GetPooled())
{
submit.target = reward;
reward.SendEvent(submit);
}
Assert.That(_run.Bits, Is.EqualTo(bitsBefore + RunManager.BuildRewardBits), context);
Assert.That(overlay.Q<Button>("ConfirmRouteButton").enabledInHierarchy, Is.True, context);
}
}
back = overlay.Q<Button>("BackToRepositoryButton");
using (var submit = NavigationSubmitEvent.GetPooled())
@@ -340,11 +462,147 @@ public class CombatLayoutTests
Assert.That(overlay.Q("RunRouteChoices"), Is.Null, context);
Assert.That(overlay.Q(className: "repository-offers"), Is.Not.Null, context);
Assert.That(overlay.Q<Button>("SaveAndExitRunButton").enabledInHierarchy, Is.True, context);
if (!milestone) Assert.That(_run.Journey.selectedRoute, Is.EqualTo(WaveRoute.Challenge));
if (!milestone) Assert.That(_run.AvailableRouteNodes.Any(n => n.Id == _run.Journey.selectedNodeId), Is.True);
LogAssert.NoUnexpectedReceived();
}
}
[UnityTest]
public IEnumerator RewardScreenPreviewsWithoutMutatingAndOpensOnlyTheMapAfterClaim()
{
_run.RepositoryChanged += () => Call(_view, "RefreshOverlay");
foreach (var size in Viewports)
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
{
UIPreferences.TextSize = textSize; Resize(size);
Set(_run, "currentWaveNumber", 3); Set(_run, "_wavesCleared", 2);
_run.Journey.pendingRewardWave = 2;
_run.GenerateRepositoryOffers(null, null);
Set(_combat, "_awaitingWaveContinue", true);
Set(_view, "_routeSelectionOpen", true); Set(_view, "_routeEventOpen", false);
Call(_view, "RefreshOverlay");
for (int frame = 0; frame < 6; frame++) yield return null;
var screen = _root.Q("BuildRewardScreen");
string context = $"reward {size} {textSize}";
Assert.That(screen, Is.Not.Null, context);
Assert.That(screen.Q("RunMap"), Is.Null, context);
Assert.That(screen.Q("RouteEvent"), Is.Null, context);
var scroll = screen.Q<ScrollView>(className: "repository-body");
foreach (var label in screen.Q("BuildRewardChoices").Query<Label>().ToList())
{
AssertContainedHorizontally(label, scroll.contentViewport, context);
float height = label.MeasureTextSize(label.text, label.contentRect.width,
VisualElement.MeasureMode.AtMost, 0, VisualElement.MeasureMode.Undefined).y;
Assert.That(height, Is.LessThanOrEqualTo(label.contentRect.height + 2), context + ": " + label.text);
}
foreach (string name in new[] { "BuildRewardCard", "RewardMagnitude", "RewardDraw" })
{
var control = screen.Q(name); scroll.ScrollTo(control);
for (int frame = 0; frame < 2; frame++) yield return null;
AssertContainedHorizontally(control, scroll.contentViewport, context);
Assert.That(control.worldBound.yMin, Is.GreaterThanOrEqualTo(scroll.contentViewport.worldBound.yMin - 1), context);
Assert.That(control.worldBound.yMax, Is.LessThanOrEqualTo(scroll.contentViewport.worldBound.yMax + 1), context);
}
foreach (string name in new[] { "ClaimBuildRewardButton", "RewardBits", "BackToRepositoryButton" })
{
var control = screen.Q(name);
AssertContainedHorizontally(control, screen, context);
Assert.That(control.worldBound.yMax, Is.LessThanOrEqualTo(screen.worldBound.yMax + 1), context);
Assert.That(scroll.Contains(control), Is.False, "Reward actions must remain fixed outside the scrolling previews.");
}
var before = _run.RunDeck.Select(c => (c.MagnitudeBonus, c.DrawRider)).ToArray();
var picker = screen.Q<DropdownField>("BuildRewardCard"); picker.index = Math.Min(1, _run.RunDeck.Count - 1);
using (var submit = NavigationSubmitEvent.GetPooled())
{ var button = screen.Q<Button>("RewardDraw"); submit.target = button; button.SendEvent(submit); }
Assert.That(_run.RunDeck.Select(c => (c.MagnitudeBonus, c.DrawRider)), Is.EqualTo(before), context);
using (var submit = NavigationSubmitEvent.GetPooled())
{ var button = screen.Q<Button>("BackToRepositoryButton"); submit.target = button; button.SendEvent(submit); }
Assert.That(_run.BuildRewardPending, Is.True, context);
Assert.That(_root.Q("BuildRewardScreen"), Is.Null, context);
using (var submit = NavigationSubmitEvent.GetPooled())
{ var button = _root.Q<Button>("BootNextWaveButton"); submit.target = button; button.SendEvent(submit); }
Assert.That(_root.Q("BuildRewardScreen"), Is.Not.Null, context);
using (var submit = NavigationSubmitEvent.GetPooled())
{ var button = _root.Q<Button>("RewardBits"); submit.target = button; button.SendEvent(submit); }
Assert.That(_root.Q("BuildRewardScreen"), Is.Null, context);
Assert.That(_root.Q("RouteSelectionScreen"), Is.Not.Null, context);
Assert.That(_root.Q("RouteEventScreen"), Is.Null, context);
Assert.That(_run.BuildRewardPending, Is.False, context);
}
}
[UnityTest]
public IEnumerator RewardUpgradeCommitsOnlyThePreviewedCardAndReturnsToMap()
{
_run.RepositoryChanged += () => Call(_view, "RefreshOverlay");
Set(_run, "currentWaveNumber", 3); Set(_run, "_wavesCleared", 2);
_run.Journey.pendingRewardWave = 2; _run.GenerateRepositoryOffers(null, null);
Set(_combat, "_awaitingWaveContinue", true); Set(_view, "_routeSelectionOpen", true);
Resize(new Vector2(1280, 720)); Call(_view, "RefreshOverlay");
for (int frame = 0; frame < 5; frame++) yield return null;
_root.Q<DropdownField>("BuildRewardCard").index = 1;
using (var submit = NavigationSubmitEvent.GetPooled())
{ var button = _root.Q<Button>("RewardDraw"); submit.target = button; button.SendEvent(submit); }
Assert.That(_run.RunDeck[1].DrawRider, Is.Zero, "Previewing must not grant the upgrade.");
using (var submit = NavigationSubmitEvent.GetPooled())
{ var button = _root.Q<Button>("ClaimBuildRewardButton"); submit.target = button; button.SendEvent(submit); }
Assert.That(_run.RunDeck[1].DrawRider, Is.EqualTo(1));
Assert.That(_run.RunDeck[0].DrawRider, Is.Zero);
Assert.That(_run.BuildRewardPending, Is.False);
Assert.That(_root.Q("BuildRewardScreen"), Is.Null);
Assert.That(_root.Q("RunMap"), Is.Not.Null);
Assert.That(_root.Q("RouteEvent"), Is.Null);
Assert.That(_run.ClaimBuildReward(_run.RunDeck[1], CardUpgradeKind.DrawRider), Is.False);
}
[UnityTest]
public IEnumerator SacrificeControlsAndCardPreviewsFitSmallScreens()
{
foreach (var size in new[] { new Vector2(1280, 720), new Vector2(390, 844), new Vector2(960, 400) })
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
{
UIPreferences.TextSize = textSize; Resize(size);
Set(_run, "currentWaveNumber", 2); Set(_run, "_wavesCleared", 1);
_run.GenerateRepositoryOffers(null, null); _run.SelectRoute(WaveRoute.Sacrifice);
Set(_combat, "_awaitingWaveContinue", true);
Set(_view, "_routeSelectionOpen", true); Set(_view, "_routeEventOpen", true);
var overlay = _root.Q(className: "overlay"); overlay.Clear(); overlay.style.display = DisplayStyle.Flex;
overlay.Add((VisualElement)Call(_view, "BuildRouteSelectionView"));
for (int frame = 0; frame < 6; frame++) yield return null;
string context = $"Sacrifice {size} {textSize}";
var scroll = overlay.Q<ScrollView>(className: "repository-body");
var panel = overlay.Q("RouteEvent");
Assert.That(panel, Is.Not.Null, context);
Assert.That(overlay.Q("RouteEventScreen"), Is.Not.Null, context);
Assert.That(overlay.Q("RunMap"), Is.Null, context);
Assert.That(overlay.Q("BuildRewardChoices"), Is.Null, context);
foreach (var label in panel.Query<Label>().ToList())
{
AssertContainedHorizontally(label, scroll.contentViewport, context);
float height = label.MeasureTextSize(label.text, label.contentRect.width,
VisualElement.MeasureMode.AtMost, 0, VisualElement.MeasureMode.Undefined).y;
Assert.That(height, Is.LessThanOrEqualTo(label.contentRect.height + 2), context + ": " + label.text);
}
foreach (string name in new[] { "RouteDonor", "RouteTarget" })
{
var control = panel.Q(name); Assert.That(control, Is.Not.Null, context + " " + name);
scroll.ScrollTo(control);
for (int frame = 0; frame < 3; frame++) yield return null;
AssertContainedHorizontally(control, scroll.contentViewport, context);
Assert.That(control.worldBound.yMin, Is.GreaterThanOrEqualTo(scroll.contentViewport.worldBound.yMin - 1), context);
Assert.That(control.worldBound.yMax, Is.LessThanOrEqualTo(scroll.contentViewport.worldBound.yMax + 1), context);
}
foreach (string name in new[] { "ResolveRouteEventButton", "SkipRouteEventButton", "BackToRouteButton" })
{
var control = overlay.Q(name);
AssertContainedHorizontally(control, overlay, context);
Assert.That(control.worldBound.yMax, Is.LessThanOrEqualTo(overlay.worldBound.yMax + 1), context);
Assert.That(scroll.Contains(control), Is.False, "Event actions must remain fixed outside the scrolling previews.");
}
Assert.That(overlay.Q<Button>("ConfirmRouteButton"), Is.Null, context);
}
}
[UnityTest]
public IEnumerator ExecutionPreviewWrapsAndDoesNotDisplaceDispatchControls()
{
@@ -604,7 +862,7 @@ public class CombatLayoutTests
for (int frame = 0; frame < 4; frame++) yield return null;
var chip = _root.Query(className: "card-chip").ToList().Single(item => item.userData == second);
Assert.That(chip.focusable, Is.True);
Assert.That(chip.tooltip, Does.Contain("Haskell captured: x1.5"));
Assert.That(chip.tooltip, Does.Contain("Haskell captured: x1.75"));
Assert.That(chip.tooltip, Does.Contain("Already played"));
Assert.That(chip.tooltip, Does.Not.Contain("Successful play package Shield"));
Assert.That(chip.tooltip, Does.Contain("Compilation 0/4"));
@@ -613,7 +871,7 @@ public class CombatLayoutTests
Call(_view, "RefreshTracks");
Assert.That(_root.focusController.focusedElement, Is.SameAs(chip));
Assert.That(chip.tooltip, Does.Contain("Compilation 1/4"));
Assert.That(chip.tooltip, Does.Contain("Haskell captured: x1.5"));
Assert.That(chip.tooltip, Does.Contain("Haskell captured: x1.75"));
}
[UnityTest]
@@ -0,0 +1,196 @@
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using KernelPanic.Meta;
using KernelPanic.Data;
using KernelPanic.UI;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UIElements;
public class DailyQuestLayoutTests
{
[Test]
public void WidgetAndDetailsDistinguishAllThreeStatesWithoutAdditionalFocusTargets()
{
var state = new DailyQuestState
{
selectedQuests = new[] { DailyQuestKind.Cards, DailyQuestKind.Damage, DailyQuestKind.Waves },
cards = 15, damage = 200, waves = 3, claimedMask = 1 << (int)DailyQuestKind.Waves,
refreshAtUtcTicks = DateTime.UtcNow.AddHours(12).Ticks
};
var widget = DailyQuestView.BuildWidget(state, DateTime.UtcNow, () => { });
Assert.That(widget.Q<Label>("DailyQuestRewardReady").text, Is.EqualTo("1 reward ready"));
Assert.That(widget.Q<Label>("DailyQuestCompleted").text, Is.EqualTo("2/3 completed"));
Assert.That(widget.Q<Label>("DailyQuestClaimed").text, Is.EqualTo("1 claimed"));
foreach (var child in widget.Query<VisualElement>().ToList().Where(child => child != widget))
Assert.That(child.pickingMode, Is.EqualTo(PickingMode.Ignore), "Every part of the widget belongs to its button.");
var overlay = DailyQuestView.BuildOverlay(state, DateTime.UtcNow, (_, _) => { }, () => { });
Assert.That(overlay.Q<Button>("ClaimDailyQuestCards").text, Is.EqualTo("[ in progress ]"));
Assert.That(overlay.Q<Button>("ClaimDailyQuestDamage").text, Is.EqualTo("> CLAIM REWARD"));
Assert.That(overlay.Q<Button>("ClaimDailyQuestWaves").text, Is.EqualTo("[ CLAIMED ]"));
Assert.That(overlay.Q<Button>("ClaimDailyQuestCards").enabledSelf, Is.False);
Assert.That(overlay.Q<Button>("ClaimDailyQuestDamage").enabledSelf, Is.True);
Assert.That(overlay.Q<Button>("ClaimDailyQuestWaves").enabledSelf, Is.False);
Assert.That(overlay.Q("DailyQuestCards").Q<Label>(className: "daily-detail-progress").text, Is.EqualTo("[######....]"));
foreach (var label in overlay.Query<Label>(className: "daily-detail-progress").ToList())
Assert.That(label.text.Length, Is.EqualTo(12));
state.claimedMask |= 1 << (int)DailyQuestKind.Damage;
widget = DailyQuestView.BuildWidget(state, DateTime.UtcNow, () => { });
Assert.That(widget.Q("DailyQuestRewardReady").style.display.value, Is.EqualTo(DisplayStyle.None));
Assert.That(widget.Q<Label>("DailyQuestInspect").text, Is.EqualTo("> inspect tasks"));
}
[UnityTest]
public IEnumerator MenuQuestsWrapAndClaimsRemainReachableAcrossViewports()
{
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null)
Assert.Ignore("Requires a rendered editor panel.");
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
var previousSize = UIPreferences.TextSize;
try
{
window.minSize = new Vector2(100, 100);
window.maxSize = new Vector2(4000, 3000);
window.Show();
var root = window.rootVisualElement;
// Match UIDocument stylesheet scope and order, including the later readability sheet.
AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/MainMenu.uxml").CloneTree(root);
var font = typeof(MainMenuController).Assembly.GetType("KernelPanic.UI.TerminalFontResolver")
.GetMethod("Resolve").Invoke(null, new object[] { null }) as UnityEngine.TextCore.Text.FontAsset;
root.style.unityFontDefinition = new StyleFontDefinition(font);
typeof(MainMenuController).Assembly.GetType("KernelPanic.UI.TerminalTheme")
.GetMethod("Attach", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { root });
root.Q("BootIntroPanel").style.display = DisplayStyle.None;
root.Q("ShellRoot").style.opacity = 1;
var featured = new FeaturedUnitPanel();
featured.Bind(root, null);
featured.Refresh(new[] { AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Ubuntu.asset") });
var scroll = root.Q<ScrollView>(className: "home-scroll");
// 1024x576 also covers 1280x720 with the player's 1.25 panel scale.
foreach (var size in new[] { new Vector2(1920, 1080), new Vector2(1366, 768), new Vector2(1280, 720), new Vector2(1024, 576), new Vector2(390, 844), new Vector2(960, 400) })
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
foreach (int group in new[] { 0, 3, 6 })
{
UIPreferences.TextSize = textSize;
window.position = new Rect(20, 20, size.x, size.y);
root.style.width = size.x;
root.style.height = size.y;
var data = SaveData.CreateDefault();
var now = DateTime.UtcNow;
DailyQuests.Refresh(data.dailyQuests, now);
data.dailyQuests.selectedQuests = new[] { DailyQuests.Pool[group],
DailyQuests.Pool[(group + 1) % DailyQuests.Pool.Count], DailyQuests.Pool[(group + 2) % DailyQuests.Pool.Count] };
foreach (var kind in DailyQuests.Active(data.dailyQuests))
DailyQuests.Record(data.dailyQuests, kind, int.MaxValue, now);
var host = root.Q("DailyQuestsHost");
host.Clear();
VisualElement overlay = null;
void RefreshWidget()
{
host.Clear();
host.Add(DailyQuestView.BuildWidget(data.dailyQuests, now, () =>
{
overlay = DailyQuestView.BuildOverlay(data.dailyQuests, now, (kind, period) =>
{
Assert.That(DailyQuests.Claim(data, kind, period, now), Is.True);
RefreshWidget();
}, () => overlay.RemoveFromHierarchy());
root.Add(overlay);
}));
}
RefreshWidget();
scroll.scrollOffset = Vector2.zero;
for (int frame = 0; frame < 6; frame++) yield return null;
string context = $"{size}, {textSize}";
Assert.That(host.Query(className: "daily-service-entry").ToList().Count, Is.EqualTo(3), context);
Assert.That(host.Q<ProgressBar>(), Is.Null);
Assert.That(host.parent, Is.SameAs(root.Q("FeaturedUnitPanel").parent));
Assert.That(host.worldBound.yMin, Is.GreaterThanOrEqualTo(root.Q("FeaturedUnitPanel").worldBound.yMax - 1), context);
if (size.x >= 1280)
{
Assert.That(host.worldBound.yMax, Is.LessThanOrEqualTo(scroll.contentViewport.worldBound.yMax + 1), context + ": fits below neofetch");
Assert.That(host.worldBound.xMin, Is.GreaterThan(root.Q(className: "command-column").worldBound.xMin + 300), context);
}
foreach (var label in host.Query<Label>().ToList())
{
Assert.That(label.worldBound.xMin, Is.GreaterThanOrEqualTo(scroll.contentViewport.worldBound.xMin - 1), context);
Assert.That(label.worldBound.xMax, Is.LessThanOrEqualTo(scroll.contentViewport.worldBound.xMax + 1), context);
float needed = label.MeasureTextSize(label.text, label.contentRect.width,
VisualElement.MeasureMode.AtMost, 0, VisualElement.MeasureMode.Undefined).y;
Assert.That(label.contentRect.height + 2, Is.GreaterThanOrEqualTo(needed), context + ": " + label.text);
}
var before = root.Q(className: "content-row").worldBound;
using (var submit = NavigationSubmitEvent.GetPooled())
{
var widget = host.Q<Button>("DailyQuestWidget");
submit.target = widget;
widget.SendEvent(submit);
}
for (int frame = 0; frame < 6; frame++) yield return null;
Assert.That(root.Q(className: "content-row").worldBound.yMin, Is.EqualTo(before.yMin).Within(1), "Opening details cannot push the menu downward.");
Assert.That(root.Q(className: "content-row").worldBound.height, Is.EqualTo(before.height).Within(1), "Details must not add menu height.");
var dialog = overlay.Q("DailyQuestDialog");
Assert.That(dialog.worldBound.xMin, Is.GreaterThanOrEqualTo(0), context);
Assert.That(dialog.worldBound.xMax, Is.LessThanOrEqualTo(size.x + 1), context);
Assert.That(dialog.worldBound.yMin, Is.GreaterThanOrEqualTo(0), context);
Assert.That(dialog.worldBound.yMax, Is.LessThanOrEqualTo(size.y + 1), context);
var details = overlay.Q<ScrollView>("DailyQuestDetailScroll");
// Include the two-line confirmation in the desktop fit requirement.
var feedback = overlay.Q<Label>("DailyQuestFeedback");
feedback.text = "[ OK ] Daily task completed.\n[ OK ] +250 Bandwidth, +125 Entropy deposited.";
feedback.style.display = DisplayStyle.Flex;
for (int frame = 0; frame < 3; frame++) yield return null;
if (size.x >= 1024 && size.y >= 576)
Assert.That(details.contentContainer.worldBound.height, Is.LessThanOrEqualTo(details.contentViewport.worldBound.height + 1),
context + ": all three tasks fit without scrolling, including feedback");
if (size.y <= 400)
Assert.That(details.contentContainer.worldBound.height, Is.GreaterThan(details.contentViewport.worldBound.height), context + ": short viewports scroll");
var headerBounds = overlay.Q("DailyQuestHeader").worldBound;
foreach (var kind in DailyQuests.Active(data.dailyQuests))
{
var reward = DailyQuests.Reward(kind);
Assert.That(details.Q("DailyQuest" + kind).Query<Label>().ToList().Select(label => label.text),
Does.Contain($"+{reward.Bandwidth} Bandwidth / +{reward.Entropy} Entropy"));
}
foreach (var label in details.Query<Label>().ToList())
{
Assert.That(label.worldBound.xMax, Is.LessThanOrEqualTo(details.contentViewport.worldBound.xMax + 1), context + label.text);
float needed = label.MeasureTextSize(label.text, label.contentRect.width,
VisualElement.MeasureMode.AtMost, 0, VisualElement.MeasureMode.Undefined).y;
Assert.That(label.contentRect.height + 2, Is.GreaterThanOrEqualTo(needed), context + label.text);
}
foreach (var button in details.Query<Button>().ToList())
{
details.ScrollTo(button);
for (int frame = 0; frame < 3; frame++) yield return null;
Assert.That(overlay.Q("DailyQuestHeader").worldBound, Is.EqualTo(headerBounds), "The header stays fixed while scrolling.");
Assert.That(button.worldBound.yMin, Is.GreaterThanOrEqualTo(details.contentViewport.worldBound.yMin - 1), context);
Assert.That(button.worldBound.yMax, Is.LessThanOrEqualTo(details.contentViewport.worldBound.yMax + 1), context);
using var submit = NavigationSubmitEvent.GetPooled();
submit.target = button;
button.SendEvent(submit);
}
Assert.That(data.bandwidthBalance, Is.EqualTo(DailyQuests.Active(data.dailyQuests).Sum(kind => DailyQuests.Reward(kind).Bandwidth)));
Assert.That(data.entropyBalance, Is.EqualTo(DailyQuests.Active(data.dailyQuests).Sum(kind => DailyQuests.Reward(kind).Entropy)));
Assert.That(host.Q<Label>("DailyQuestCompleted").text, Is.EqualTo("3/3 completed"));
Assert.That(host.Q("DailyQuestRewardReady").style.display.value, Is.EqualTo(DisplayStyle.None));
using (var escape = KeyDownEvent.GetPooled(new Event { type = EventType.KeyDown, keyCode = KeyCode.Escape }))
{
escape.target = overlay.Q<Button>("CloseDailyQuests");
overlay.Q<Button>("CloseDailyQuests").SendEvent(escape);
}
Assert.That(root.Q("DailyQuestOverlay"), Is.Null);
LogAssert.NoUnexpectedReceived();
}
}
finally
{
UIPreferences.TextSize = previousSize;
window.Close();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a41d2608975f4d4c99e00d5f20eeac05
+344
View File
@@ -0,0 +1,344 @@
using System;
using System.IO;
using System.Linq;
using KernelPanic.Combat;
using KernelPanic.Core;
using KernelPanic.Meta;
using NUnit.Framework;
using UnityEngine;
public class DailyQuestTests
{
private static readonly DateTime Start = new(2026, 10, 24, 12, 30, 0, DateTimeKind.Utc);
private string _directory;
private SaveService _save;
private static SaveData FixedQuests()
{
var data = SaveData.CreateDefault();
data.dailyQuests.refreshAtUtcTicks = Start.AddDays(1).Ticks;
data.dailyQuests.selectionSeed = 17;
DailyQuests.Refresh(data.dailyQuests, Start);
return data;
}
[SetUp]
public void SetUp()
{
_directory = Path.Combine(Path.GetTempPath(), "KernelPanic-DailyTests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_directory);
_save = new SaveService(Path.Combine(_directory, "save.json"));
}
[TearDown]
public void TearDown() => Directory.Delete(_directory, true);
[Test]
public void LegacyDataStartsWithThreeEmptyQuestsWithoutChangingBalances()
{
var data = JsonUtility.FromJson<SaveData>("{\"entropyBalance\":73,\"bandwidthBalance\":129}");
data.EnsureLists();
Assert.That(DailyQuests.Refresh(data.dailyQuests, Start), Is.True);
Assert.That(data.dailyQuests.refreshAtUtcTicks, Is.EqualTo(Start.AddHours(24).Ticks));
for (int i = 0; i < DailyQuests.Count; i++)
{
Assert.That(DailyQuests.Progress(data.dailyQuests, (DailyQuestKind)i), Is.Zero);
Assert.That(DailyQuests.Claimed(data.dailyQuests, (DailyQuestKind)i), Is.False);
}
Assert.That(data.entropyBalance, Is.EqualTo(73));
Assert.That(data.bandwidthBalance, Is.EqualTo(129));
}
[Test]
public void ResetOccursAtExactlyTwentyFourHoursAndKeepsItsAnchorAfterDaysAway()
{
var data = FixedQuests();
DailyQuests.Record(data.dailyQuests, DailyQuestKind.Waves, 3, Start);
long firstPeriod = data.dailyQuests.refreshAtUtcTicks;
Assert.That(DailyQuests.Refresh(data.dailyQuests, Start.AddDays(1).AddTicks(-1)), Is.False);
Assert.That(DailyQuests.Refresh(data.dailyQuests, Start.AddDays(1)), Is.True);
Assert.That(data.dailyQuests.waves, Is.Zero);
Assert.That(DailyQuests.Claim(data, DailyQuestKind.Waves, firstPeriod, Start.AddDays(1)), Is.False);
DailyQuests.Record(data.dailyQuests, DailyQuestKind.Cards, 10, Start.AddDays(1));
Assert.That(DailyQuests.Refresh(data.dailyQuests, Start.AddDays(8).AddHours(7)), Is.True);
Assert.That(data.dailyQuests.refreshAtUtcTicks, Is.EqualTo(Start.AddDays(9).Ticks));
Assert.That(data.dailyQuests.cards, Is.Zero);
}
[Test]
public void ClockRollbackDoesNotResetClaimsOrMoveTheDeadline()
{
var data = FixedQuests();
DailyQuests.Record(data.dailyQuests, DailyQuestKind.Cards, 25, Start);
long period = data.dailyQuests.refreshAtUtcTicks;
Assert.That(DailyQuests.Claim(data, DailyQuestKind.Cards, period, Start), Is.True);
Assert.That(DailyQuests.Refresh(data.dailyQuests, Start.AddHours(-2)), Is.False);
Assert.That(data.dailyQuests.refreshAtUtcTicks, Is.EqualTo(period));
Assert.That(DailyQuests.Claim(data, DailyQuestKind.Cards, period, Start.AddHours(-2)), Is.False);
}
[Test]
public void EachQuestPaysBothCurrenciesExactlyOnceAndSurvivesReload()
{
var data = FixedQuests();
DailyQuests.Refresh(data.dailyQuests, Start);
long period = data.dailyQuests.refreshAtUtcTicks;
for (int i = 0; i < DailyQuests.Count; i++)
{
var kind = (DailyQuestKind)i;
Assert.That(DailyQuests.Claim(data, kind, period, Start), Is.False);
DailyQuests.Record(data.dailyQuests, kind, -1, Start);
Assert.That(DailyQuests.Progress(data.dailyQuests, kind), Is.Zero);
DailyQuests.Record(data.dailyQuests, kind, int.MaxValue, Start);
Assert.That(DailyQuests.Progress(data.dailyQuests, kind), Is.EqualTo(DailyQuests.Target(kind)));
Assert.That(DailyQuests.Claim(data, kind, period, Start), Is.True);
_save.Save(data);
data = _save.Load();
Assert.That(DailyQuests.Claim(data, kind, period, Start), Is.False);
}
Assert.That(data.bandwidthBalance, Is.EqualTo(325));
Assert.That(data.entropyBalance, Is.EqualTo(150));
DailyQuests.Refresh(data.dailyQuests, Start.AddDays(1));
var nextQuest = DailyQuests.Active(data.dailyQuests)[0];
DailyQuests.Record(data.dailyQuests, nextQuest, int.MaxValue, Start.AddDays(1));
Assert.That(DailyQuests.Claim(data, nextQuest, period, Start.AddDays(1)), Is.False,
"An old button cannot claim a newly completed quest.");
Assert.That(DailyQuests.Claim(data, nextQuest, data.dailyQuests.refreshAtUtcTicks, Start.AddDays(1)), Is.True);
}
[TestCase(DailyQuestKind.Cards, 75, 25)]
[TestCase(DailyQuestKind.NativeCards, 75, 25)]
[TestCase(DailyQuestKind.Damage, 100, 50)]
[TestCase(DailyQuestKind.BlockDamage, 100, 50)]
[TestCase(DailyQuestKind.Waves, 150, 75)]
[TestCase(DailyQuestKind.ShieldDamage, 150, 75)]
[TestCase(DailyQuestKind.SurviveRounds, 150, 75)]
[TestCase(DailyQuestKind.WaveFive, 250, 125)]
public void DifficultyRewardsPayExactAmountsOnceAcrossReload(DailyQuestKind kind, int bandwidth, int entropy)
{
var data = FixedQuests();
data.dailyQuests.selectedQuests = new[] { kind }.Concat(DailyQuests.Pool.Where(other => other != kind).Take(2)).ToArray();
data.bandwidthBalance = 37;
data.entropyBalance = 19;
long period = data.dailyQuests.refreshAtUtcTicks;
Assert.That(DailyQuests.Reward(kind), Is.EqualTo((bandwidth, entropy)));
Assert.That(DailyQuests.Claim(data, kind, period, Start), Is.False);
DailyQuests.Record(data.dailyQuests, kind, int.MaxValue, Start);
Assert.That(DailyQuests.Claim(data, kind, period, Start), Is.True);
_save.Save(data);
data = _save.Load();
Assert.That(DailyQuests.Claim(data, kind, period, Start), Is.False);
Assert.That(data.bandwidthBalance, Is.EqualTo(37 + bandwidth));
Assert.That(data.entropyBalance, Is.EqualTo(19 + entropy));
Assert.That(data.dailyQuests.refreshAtUtcTicks, Is.EqualTo(period));
Assert.That(DailyQuests.Progress(data.dailyQuests, kind), Is.EqualTo(DailyQuests.Target(kind)));
}
[Test]
public void EveryRewardChecksBothBalancesBeforeChangingEitherCurrencyOrClaimFlag()
{
foreach (var kind in DailyQuests.Pool)
{
var data = FixedQuests();
data.dailyQuests.selectedQuests = new[] { kind }.Concat(DailyQuests.Pool.Where(other => other != kind).Take(2)).ToArray();
DailyQuests.Record(data.dailyQuests, kind, int.MaxValue, Start);
long period = data.dailyQuests.refreshAtUtcTicks;
var reward = DailyQuests.Reward(kind);
foreach (bool overflowBandwidth in new[] { true, false })
{
int bandwidth = int.MaxValue - reward.Bandwidth + (overflowBandwidth ? 1 : 0);
int entropy = int.MaxValue - reward.Entropy + (overflowBandwidth ? 0 : 1);
data.bandwidthBalance = bandwidth;
data.entropyBalance = entropy;
Assert.That(DailyQuests.Claim(data, kind, period, Start), Is.False, kind.ToString());
Assert.That(data.bandwidthBalance, Is.EqualTo(bandwidth));
Assert.That(data.entropyBalance, Is.EqualTo(entropy));
Assert.That(DailyQuests.Claimed(data.dailyQuests, kind), Is.False);
}
data.bandwidthBalance = int.MaxValue - reward.Bandwidth;
data.entropyBalance = int.MaxValue - reward.Entropy;
Assert.That(DailyQuests.Claim(data, kind, period, Start), Is.True);
Assert.That(data.bandwidthBalance, Is.EqualTo(int.MaxValue));
Assert.That(data.entropyBalance, Is.EqualTo(int.MaxValue));
}
}
[Test]
public void PreviouslyPaidFlatRewardCannotBeClaimedAgainAfterRewardChange()
{
var data = FixedQuests();
data.dailyQuests.waves = 3;
data.dailyQuests.claimedMask = 1 << (int)DailyQuestKind.Waves;
data.bandwidthBalance = 100;
data.entropyBalance = 50;
_save.Save(data);
data = _save.Load();
Assert.That(DailyQuests.Claim(data, DailyQuestKind.Waves, data.dailyQuests.refreshAtUtcTicks, Start), Is.False);
Assert.That(data.bandwidthBalance, Is.EqualTo(100));
Assert.That(data.entropyBalance, Is.EqualTo(50));
}
[Test]
public void GameplayPersistsAcrossTrackerRecreationAndIgnoresIneligibleAndIncomingDamage()
{
bool eligible = false;
var player = new CombatantState(100, 6, 3);
var enemy = new CombatantState(100, 6, 3);
using (var tracker = new DailyQuestTracker(_save, () => eligible, () => player, () => Start))
{
GameEvents.RaiseWaveCleared(new WaveClearedEvent(1));
GameEvents.RaiseCardPlayed(default);
GameEvents.RaiseDamageDealt(new DamageDealtEvent(player, enemy, 20, Language.C));
Assert.That(File.Exists(_save.SavePath), Is.False, "Tutorial or suspended runs cannot progress quests.");
_save.Save(FixedQuests());
eligible = true;
GameEvents.RaiseWaveCleared(new WaveClearedEvent(1));
GameEvents.RaiseCardPlayed(default);
GameEvents.RaiseDamageDealt(new DamageDealtEvent(player, enemy, 20, Language.C));
GameEvents.RaiseDamageDealt(new DamageDealtEvent(enemy, player, 50, Language.C));
GameEvents.RaiseDamageDealt(new DamageDealtEvent(player, player, 50, Language.C));
GameEvents.RaiseDamageDealt(new DamageDealtEvent(player, enemy, 20, Language.C, 20, 20, false, 20, 0));
}
var saved = _save.Load();
Assert.That(saved.dailyQuests.waves, Is.EqualTo(1));
Assert.That(saved.dailyQuests.cards, Is.EqualTo(1));
Assert.That(saved.dailyQuests.damage, Is.EqualTo(20));
saved.bandwidthBalance = 451;
_save.Save(saved);
using (var tracker = new DailyQuestTracker(_save, () => true, () => player, () => Start))
GameEvents.RaiseWaveCleared(new WaveClearedEvent(2));
GameEvents.RaiseWaveCleared(new WaveClearedEvent(3)); // Disposed subscriptions must not keep counting.
Assert.That(_save.Load().dailyQuests.waves, Is.EqualTo(2));
Assert.That(_save.Load().bandwidthBalance, Is.EqualTo(451));
}
[Test]
public void FailedProgressSaveRetriesWithoutDroppingOrDuplicatingEvents()
{
_save.Save(FixedQuests());
using var tracker = new DailyQuestTracker(_save, () => true, () => null, () => Start);
using (var locked = new FileStream(_save.SavePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
GameEvents.RaiseCardPlayed(default);
GameEvents.RaiseCardPlayed(default);
Assert.That(tracker.SaveError, Is.Not.Null);
}
Assert.That(tracker.Flush(), Is.True);
Assert.That(tracker.SaveError, Is.Null);
Assert.That(_save.Load().dailyQuests.cards, Is.EqualTo(2));
tracker.Flush();
Assert.That(_save.Load().dailyQuests.cards, Is.EqualTo(2));
}
[Test]
public void ExpiredPendingProgressCannotLeakIntoTheNewDay()
{
var now = Start;
var data = FixedQuests();
DailyQuests.Refresh(data.dailyQuests, now);
_save.Save(data);
using var tracker = new DailyQuestTracker(_save, () => true, () => null, () => now);
using (var locked = new FileStream(_save.SavePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
GameEvents.RaiseCardPlayed(default);
now = Start.AddDays(1);
GameEvents.RaiseCardPlayed(default);
var state = _save.Load().dailyQuests;
Assert.That(state.cards, Is.EqualTo(DailyQuests.IsActive(state, DailyQuestKind.Cards) ? 1 : 0));
Assert.That(_save.Load().dailyQuests.refreshAtUtcTicks, Is.EqualTo(Start.AddDays(2).Ticks));
}
[Test]
public void RandomSelectionIsDistinctPersistentVariedAndDoesNotConsumeUnityRandom()
{
var data = SaveData.CreateDefault();
data.dailyQuests.selectionSeed = 731;
var randomBefore = UnityEngine.Random.state;
var seen = new System.Collections.Generic.HashSet<DailyQuestKind>();
DailyQuestKind[] previous = null;
for (int day = 0; day < 120; day++)
{
var now = Start.AddDays(day);
Assert.That(DailyQuests.Refresh(data.dailyQuests, now), Is.True);
var active = DailyQuests.Active(data.dailyQuests).ToArray();
Assert.That(active.Length, Is.EqualTo(3));
Assert.That(active.Distinct().Count(), Is.EqualTo(3));
Assert.That(active.All(kind => DailyQuests.Pool.Contains(kind)), Is.True);
if (previous != null) Assert.That(active, Is.Not.EquivalentTo(previous));
foreach (var kind in active) seen.Add(kind);
_save.Save(data);
data = _save.Load();
Assert.That(DailyQuests.Refresh(data.dailyQuests, now.AddHours(5)), Is.False);
Assert.That(DailyQuests.Active(data.dailyQuests), Is.EqualTo(active));
previous = active;
}
Assert.That(seen, Is.EquivalentTo(DailyQuests.Pool));
Assert.That(UnityEngine.Random.state, Is.EqualTo(randomBefore));
}
[Test]
public void UpgradingAnActiveFixedDayPreservesProgressAndClaimsUntilReset()
{
var data = SaveData.CreateDefault();
data.dailyQuests.refreshAtUtcTicks = Start.AddDays(1).Ticks;
data.dailyQuests.waves = 3;
data.dailyQuests.cards = 7;
data.dailyQuests.claimedMask = 1;
Assert.That(DailyQuests.Refresh(data.dailyQuests, Start), Is.True);
Assert.That(DailyQuests.Active(data.dailyQuests), Is.EqualTo(new[] { DailyQuestKind.Waves, DailyQuestKind.Cards, DailyQuestKind.Damage }));
Assert.That(data.dailyQuests.waves, Is.EqualTo(3));
Assert.That(data.dailyQuests.cards, Is.EqualTo(7));
Assert.That(DailyQuests.Claim(data, DailyQuestKind.Waves, data.dailyQuests.refreshAtUtcTicks, Start), Is.False);
DailyQuests.Refresh(data.dailyQuests, Start.AddDays(1));
Assert.That(data.dailyQuests.claimedMask, Is.Zero);
Assert.That(data.dailyQuests.cards, Is.Zero);
Assert.That(DailyQuests.Active(data.dailyQuests), Is.Not.EquivalentTo(new[] { DailyQuestKind.Waves, DailyQuestKind.Cards, DailyQuestKind.Damage }));
}
[Test]
public void InactiveQuestsCannotAccumulateProgressOrPayRewards()
{
var data = FixedQuests();
foreach (var kind in DailyQuests.Pool.Where(kind => !DailyQuests.IsActive(data.dailyQuests, kind)))
{
Assert.That(DailyQuests.Record(data.dailyQuests, kind, int.MaxValue, Start), Is.False);
Assert.That(DailyQuests.Progress(data.dailyQuests, kind), Is.Zero);
Assert.That(DailyQuests.Claim(data, kind, data.dailyQuests.refreshAtUtcTicks, Start), Is.False);
}
Assert.That(data.bandwidthBalance, Is.Zero);
Assert.That(data.entropyBalance, Is.Zero);
}
[Test]
public void AddedCombatObjectivesCountOnlyTheMatchingGameplay()
{
var data = FixedQuests();
data.dailyQuests.selectedQuests = new[] { DailyQuestKind.BlockDamage, DailyQuestKind.ShieldDamage, DailyQuestKind.NativeCards };
_save.Save(data);
var player = new CombatantState(100, 6, 3);
var enemy = new CombatantState(100, 6, 3);
using var tracker = new DailyQuestTracker(_save, () => true, () => player, () => Start);
GameEvents.RaiseCardPlayed(new CardPlayedEvent(null, ResolutionTrack.Native));
GameEvents.RaiseCardPlayed(new CardPlayedEvent(null, ResolutionTrack.InterpreterQueue));
GameEvents.RaiseCardPlayed(new CardPlayedEvent(null, ResolutionTrack.LazyStack));
GameEvents.RaiseDamageDealt(new DamageDealtEvent(enemy, player, 14, Language.C, 14, 0, false, 9, 5));
GameEvents.RaiseDamageDealt(new DamageDealtEvent(player, enemy, 20, Language.C, 20, 0, false, 7, 13));
GameEvents.RaiseDamageDealt(new DamageDealtEvent(player, player, 20, Language.C, 20, 0, false, 20, 0));
data = _save.Load();
Assert.That(data.dailyQuests.nativeCards, Is.EqualTo(1));
Assert.That(data.dailyQuests.blockedDamage, Is.EqualTo(9));
Assert.That(data.dailyQuests.shieldDamage, Is.EqualTo(7));
data.dailyQuests.selectedQuests = new[] { DailyQuestKind.SurviveRounds, DailyQuestKind.WaveFive, DailyQuestKind.Waves };
_save.Save(data);
GameEvents.RaisePhaseChanged(new PhaseChangedEvent(TurnPhase.Allocate, TurnPhase.Execute));
GameEvents.RaisePhaseChanged(new PhaseChangedEvent(TurnPhase.EnemyProcess, TurnPhase.GarbageCollection));
player.CurrentUptime = 0;
GameEvents.RaisePhaseChanged(new PhaseChangedEvent(TurnPhase.EnemyProcess, TurnPhase.GarbageCollection));
GameEvents.RaiseWaveCleared(new WaveClearedEvent(4));
Assert.That(_save.Load().dailyQuests.waveFive, Is.Zero);
GameEvents.RaiseWaveCleared(new WaveClearedEvent(5));
data = _save.Load();
Assert.That(data.dailyQuests.survivedRounds, Is.EqualTo(1));
Assert.That(data.dailyQuests.waveFive, Is.EqualTo(1));
Assert.That(data.dailyQuests.waves, Is.EqualTo(2));
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a41d2608975f4d4c99e00d5f20eeac04
@@ -63,9 +63,55 @@ public class DamageEffectExecutionTests
card, Player, targets, _combat, _combat.DamagePipeline, new StatusEffectController(),
_combat.DeckController, _combat.HandController, _combat.Enemies);
[TestCase("lang_rs_unwrap", Language.Rust, 5)]
[TestCase("lang_c_printf", Language.C, 4)]
public void RebalancedNativeCardsMatchPreviewAndRetainTheirUtility(string id, Language language, int damage)
{
var card = Card(id, language);
var target = Enemy();
var broken = Card("broken_dependency", Language.Python);
broken.IsBroken = true;
_combat.HandController.Add(broken);
var replacement = Card("replacement", Language.Python);
_combat.DeckController.AddToDrawPile(replacement, false);
var preview = CardPreviewService.Build(_combat, card, target);
foreach (var effect in CardEffectFactory.CreateEffects(card.Definition)) effect.Execute(Context(card, target));
Assert.That(100 - target.CurrentUptime, Is.EqualTo(damage));
Assert.That(preview.MinimumDamage, Is.EqualTo(damage));
Assert.That(preview.MaximumDamage, Is.EqualTo(damage));
if (language == Language.C) Assert.That(broken.IsBroken, Is.False);
else
{
Assert.That(_combat.HandController.Cards, Has.Member(replacement));
Assert.That(preview.Details, Does.Contain("Draw 1 (fixed)"));
}
}
[TestCase(0, 0, 6)]
[TestCase(1, 0, 8)]
[TestCase(3, 2, 14)]
public void ListAppendPreviewMatchesFirstPlayAndRequeueGrowth(int previousPlays, int magnitude, int expected)
{
var card = Card("shop_py_list_append", Language.Python);
card.ApplyMagnitudeUpgrade(magnitude);
for (int i = 0; i < previousPlays; i++) card.MarkQueued();
var target = Enemy();
var preview = CardPreviewService.Build(_combat, card, target);
card.MarkQueued();
foreach (var effect in CardEffectFactory.CreateEffects(card.Definition)) effect.Execute(Context(card, target));
Assert.That(100 - target.CurrentUptime, Is.EqualTo(expected));
Assert.That(preview.MinimumDamage, Is.EqualTo(expected));
Assert.That(preview.MaximumDamage, Is.EqualTo(expected));
Assert.That(CardEffectFactory.GetRulesText(card), Does.Contain($"deal {expected}."));
}
[TestCase("fedora_first_to_package", Language.Java, 18)]
[TestCase("fedora_dnf_autoremove", Language.Rust, 18)]
[TestCase("mint_update_manager", Language.Python, 15)]
[TestCase("mint_update_manager", Language.Python, 12)]
public void WrappersAndPreviewApplyFlatAndMagnitudeBonusesExactlyOnce(string id, Language language, int expected)
{
var card = Card(id, language);
@@ -128,7 +174,8 @@ public class DamageEffectExecutionTests
Call(_combat, "ResolveDelayedEndOfTurnEffects");
Assert.That(newcomer.CurrentUptime, Is.EqualTo(100 - repeatIncoming), "A scheduled repeat executes only once.");
Assert.That(CardPreviewService.Build(_combat, card, target).Details, Does.Contain("captures"));
Assert.That(CardPreviewService.Build(_combat, card, target).Details, Does.Contain("automation ran earlier"),
"Legacy delayed effects remain executable, but the live card now uses the Python payload rule.");
}
private static ICardEffect DamageEffect(string kind, Language language) => kind switch
+10 -10
View File
@@ -236,16 +236,16 @@ public class GentooHaskellTests
for (int i=0;i<cards.Length;i++)
{
stack.Enqueue(cards[i]);
Assert.That(stack.Entries[0].MultiplierPercent, Is.EqualTo(Math.Min(250,100+i*50)));
Assert.That(stack.Entries[0].MultiplierPercent, Is.EqualTo(new[] {150,175,200,250,250,250}[i]));
}
int[] expected = {250,250,250,200,150,100,100};
int[] expected = {250,250,250,200,175,150,100};
foreach (int percent in expected)
{
Assert.That(stack.TryPopEntry(out var entry), Is.True);
Assert.That(entry.MultiplierPercent, Is.EqualTo(percent));
}
stack.Enqueue(cards[3].CopyForCombat());
Assert.That(stack.Entries[0].MultiplierPercent, Is.EqualTo(100));
Assert.That(stack.Entries[0].MultiplierPercent, Is.EqualTo(150));
stack.Enqueue(stack.Cards[0]);
Assert.That(stack.Count, Is.EqualTo(1), "Same pending instance cannot be pushed twice");
}
@@ -275,8 +275,8 @@ public class GentooHaskellTests
CollectionAssert.AreEqual(cards, played);
CollectionAssert.AreEqual(cards.Reverse().ToArray(), resolving);
CollectionAssert.AreEqual(resolving, resolved);
Assert.That(Target.CurrentUptime, Is.EqualTo(9980)); // 10 + 8 + 2
Assert.That(Player.Shield, Is.EqualTo(4)); // 3 * 1.5, nearest-even
Assert.That(Target.CurrentUptime, Is.EqualTo(9979)); // 10 + 8 + 3
Assert.That(Player.Shield, Is.EqualTo(5)); // 3 * 1.75, nearest-even
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(2)); // draw + rider, not multiplied
foreach (var card in cards)
{
@@ -300,7 +300,7 @@ public class GentooHaskellTests
{
Drain("InterpretQueueSequenced"); Drain();
CollectionAssert.AreEqual(new[]{"shop_py_list_append","lang_hs_thunk"},order);
Assert.That(Target.CurrentUptime, Is.EqualTo(9990)); // round(4*1.3), twice; not wave-start 85%.
Assert.That(Target.CurrentUptime, Is.EqualTo(9984)); // round(6*1.3) + round(4*1.5*1.3); resolution-time Compilation.
}
finally { GameEvents.CardResolved -= observe; }
}
@@ -476,7 +476,7 @@ public class GentooHaskellTests
var dead=Target; dead.State.IsDefeated=true;
((List<EnemyInstance>)_combat.Enemies).Remove(dead);
Drain(); Drain();
Assert.That(other.CurrentUptime,Is.EqualTo(9996));
Assert.That(other.CurrentUptime,Is.EqualTo(9994)); // One 4 * 1.5 hit after retargeting.
Assert.That(_combat.DeckController.DiscardPile.Count(c=>c==card),Is.EqualTo(1));
}
@@ -540,7 +540,7 @@ public class GentooHaskellTests
Assert.That(Player.FlatCardDamageBonus,Is.EqualTo(7));
Assert.That(Player.FlatEffectBonus,Is.Zero,"DNF does not amplify non-damage effects");
Drain();
Assert.That(10000-Target.CurrentUptime,Is.EqualTo(95),"DNF is additive before stack/Compilation, not applied twice");
Assert.That(10000-Target.CurrentUptime,Is.EqualTo(105),"DNF is additive before stack/Compilation: 20 + 24 + 27 + 34, not applied twice");
}
[TestCase(0, 2)]
@@ -609,7 +609,7 @@ public class GentooHaskellTests
card.ClearTargetSnapshot();
Assert.That(_combat.LazyStack.Entries[0].Targets[0],Is.SameAs(captured));
Drain();
Assert.That(10000-Target.CurrentUptime,Is.EqualTo(3));
Assert.That(10000-Target.CurrentUptime,Is.EqualTo(5)); // round(4 * 1.5 * 0.85).
}
[UnityTest]
@@ -640,7 +640,7 @@ public class GentooHaskellTests
Assert.That(text,Does.Contain("6/6"));
Assert.That(text,Does.Contain("+50%"));
var multipliers=root.Query<Label>(className:"execution-multiplier").ToList();
CollectionAssert.AreEqual(new[]{"x2.5","x2.0","x1.5","x1.0"},multipliers.Select(l=>l.text));
CollectionAssert.AreEqual(new[]{"x2.5","x2.0","x1.75","x1.5"},multipliers.Select(l=>l.text));
foreach(var label in multipliers)
Assert.That(label.worldBound.xMax,Is.LessThanOrEqualTo(root.worldBound.xMax+1),size.ToString());
var end=root.Query<Button>().ToList().Single(b=>b.text=="[E] end turn");
@@ -249,7 +249,7 @@ public class PackageReadinessTests
var card = Card(5, ResolutionTrack.Native, "lang_java_public_static_main", Language.Java);
card.ApplyCostUpgrade(-1);
card.TemporaryCostDelta = -1;
Set(_combat, "_javaCardsPlayedThisCombat", 1);
Set(_combat, "_javaCardsPlayedThisCombat", 2);
string explanation = _combat.GetCardCostBreakdown(card);
Assert.That(explanation, Does.Contain("upgrades: -1").And.Contain("temporary: -1")
.And.Contain("Java warmup: -1").And.Contain("ccache: -1").And.Contain("Bleeding Edge: -1"));
@@ -99,7 +99,7 @@ public class PileCostDetailsTests
var card = Card(5, "lang_java_public_static_main", Language.Java);
card.ApplyCostUpgrade(-1);
card.TemporaryCostDelta = -1;
Set(_combat, "_javaCardsPlayedThisCombat", 1);
Set(_combat, "_javaCardsPlayedThisCombat", 2);
int seed = RandomRoll.CurrentSeed, draws = RandomRoll.DrawCount;
var random = UnityEngine.Random.state;
int cycles = _combat.PlayerState.Cycles, shield = _combat.PlayerState.Shield;
@@ -0,0 +1,308 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using KernelPanic.Combat;
using KernelPanic.Core;
using KernelPanic.Data;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
public class PythonPipelineTests
{
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
private GameObject owner;
private CombatManager combat;
private CardDatabase database;
private int seed, draws;
private CombatantState Player => combat.PlayerState;
private CombatantState Target => combat.Enemies[0].State;
private static void Set(object obj, string name, object value) => obj.GetType().GetField(name, Private).SetValue(obj, value);
private static object Call(object obj, string name, params object[] args) => obj.GetType().GetMethod(name, Private).Invoke(obj, args);
[SetUp]
public void Setup()
{
seed = RandomRoll.CurrentSeed; draws = RandomRoll.DrawCount; RandomRoll.Seed(17);
database = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
owner = new GameObject("Python pipeline tests");
combat = owner.AddComponent<CombatManager>();
Call(combat, "OnDisable"); Call(combat, "Awake");
Set(combat, "_playerState", new CombatantState(100, 32, 100) { ForceMaxRolls = true });
Set(combat, "_handController", new HandController(32));
Set(combat, "currentPhase", TurnPhase.Execute);
((List<EnemyInstance>)combat.Enemies).Add(new EnemyInstance("first", 10000, Array.Empty<EnemyIntent>()));
((List<EnemyInstance>)combat.Enemies).Add(new EnemyInstance("second", 10000, Array.Empty<EnemyIntent>()));
combat.SetGeneratedCardPool(database.AllCards);
Begin(1);
}
[TearDown]
public void Cleanup()
{
Call(combat, "OnDisable"); UnityEngine.Object.DestroyImmediate(owner);
RandomRoll.Restore(seed, draws);
}
private CardInstance Card(string id) => new(database.FindById(id));
private void Begin(int round) { Set(combat, "_turnNumberThisWave", round); combat.Python.BeginPhase(round); }
private void Effect(CardInstance card)
{
var context = new CombatContext(card, Player, new[] { Target }, combat, combat.DamagePipeline,
new StatusEffectController(), combat.DeckController, combat.HandController, combat.Enemies);
foreach (var effect in CardEffectFactory.CreateEffects(card.Definition)) effect.Execute(context);
}
private CardInstance Effect(string id) { var card = Card(id); Effect(card); return card; }
private void Play(CardInstance card)
{
combat.HandController.Add(card); combat.SelectEnemy(0);
Assert.That(combat.PlayCard(card), Is.True);
}
private void ResolveQueue()
{
var routine = (IEnumerator)Call(combat, "InterpretQueueSequenced");
int steps = 0;
while (routine.MoveNext()) Assert.That(++steps, Is.LessThan(100));
}
[Test]
public void LoopSkipsZipAndRepeatsOnlyTheAreaPayloadWithMatchingPreview()
{
Play(Card("lang_py_for_loop")); Play(Card("shop_py_zip"));
var payload = Card("lang_py_print"); Play(payload);
var preview = CardPreviewService.Build(combat, payload, Target);
Assert.That(preview.MinimumDamage, Is.EqualTo(8));
ResolveQueue();
Assert.That(Target.CurrentUptime, Is.EqualTo(9990)); // zip 2 + print 4 twice
Assert.That(combat.Enemies[1].State.CurrentUptime, Is.EqualTo(9992));
Assert.That(Player.Shield, Is.EqualTo(2));
Assert.That(combat.Python.RepeatCount, Is.Zero);
Assert.That(combat.Python.AreaCount, Is.Zero);
Assert.That(combat.DeckController.DiscardPile.Count, Is.EqualTo(3));
}
[Test]
public void ExtraModifiersWaitForOtherPayloadsAndNeverMultiplyEachOther()
{
Effect("lang_py_for_loop"); Effect("lang_py_for_loop");
Effect("shop_py_zip"); Effect("shop_py_zip");
Effect("lang_py_print");
Assert.That(combat.Python.RepeatCount, Is.EqualTo(1));
Assert.That(combat.Python.AreaCount, Is.EqualTo(1));
Assert.That(combat.Enemies[1].State.CurrentUptime, Is.EqualTo(9992));
Effect("lang_py_print");
Assert.That(combat.Enemies[1].State.CurrentUptime, Is.EqualTo(9984));
}
[Test]
public void ModifiersSurviveOneFollowingRoundThenExpireAndNativeCardsDoNotConsumeThem()
{
Effect("lang_py_for_loop"); Effect("shop_py_zip"); Effect("lang_js_console_log");
Assert.That(combat.Python.RepeatCount, Is.EqualTo(1));
Begin(2);
Assert.That(combat.Python.AreaCount, Is.EqualTo(1));
Begin(3);
Assert.That(combat.Python.RepeatCount, Is.Zero);
Assert.That(combat.Python.AreaCount, Is.Zero);
}
[Test]
public void PreparationDrawsImmediatelyWithFixedCountAndDoesNotUseModifiers()
{
Effect("lang_py_for_loop");
for (int i = 0; i < 8; i++) combat.DeckController.AddToDrawPile(Card("lang_py_print"), false);
var prepare = Card("lang_py_import_antigravity"); prepare.ApplyMagnitudeUpgrade(10);
Player.FlatEffectBonus = 10;
Play(prepare);
Assert.That(combat.HandController.Cards.Count, Is.EqualTo(2));
Assert.That(combat.InterpreterQueue.Count, Is.Zero);
Assert.That(combat.Python.RepeatCount, Is.EqualTo(1));
}
[Test]
public void AsyncSnapshotsUnmodifiedPayloadAndCannotReplayDrawRidersOrGrowth()
{
var script = Card("shop_py_async_def");
for (int i = 0; i < 4; i++) combat.DeckController.AddToDrawPile(Card("lang_py_print"), false);
Play(script);
Assert.That(combat.HandController.Cards.Count, Is.EqualTo(1), "Async draws on play, before interpretation.");
Play(Card("lang_py_for_loop")); Play(Card("shop_py_zip"));
var list = Card("shop_py_list_append"); list.ApplyMagnitudeUpgrade(2); list.ApplyDrawRider(1);
Play(list); ResolveQueue();
Assert.That(Target.CurrentUptime, Is.EqualTo(9982)); // zip 2 + 8 twice
Assert.That(combat.Enemies[1].State.CurrentUptime, Is.EqualTo(9984));
int hand = combat.HandController.Cards.Count;
list.ApplyMagnitudeUpgrade(20); Player.FlatEffectBonus = 20; Player.FlatCardDamageBonus = 30;
Begin(2);
Assert.That(Target.CurrentUptime, Is.EqualTo(9974), "Captured 8, not later upgrades or area/repeat modifiers.");
Assert.That(combat.Enemies[1].State.CurrentUptime, Is.EqualTo(9984));
Begin(3); Begin(4);
Assert.That(Target.CurrentUptime, Is.EqualTo(9966));
Assert.That(combat.HandController.Cards.Count, Is.EqualTo(hand));
Assert.That(list.QueuePlayCount, Is.EqualTo(1));
Assert.That(combat.Python.AutomationCount, Is.Zero);
}
[Test]
public void AutomationReplacementRequiresAChoiceAndBlocksCombatInput()
{
Effect("ubuntu_unattended_upgrades"); Effect("shop_py_async_def"); Effect("mint_timeshift");
Assert.That(combat.Python.HasChoice, Is.True);
Assert.That(combat.Python.AutomationCount, Is.EqualTo(2));
Assert.That(combat.CanSurrenderRun, Is.False);
var card = Card("lang_py_print"); combat.HandController.Add(card);
Assert.That(combat.PlayCard(card), Is.False);
combat.EndPlayerTurn(); Assert.That(combat.CurrentPhase, Is.EqualTo(TurnPhase.Execute));
Assert.That(combat.Python.Choose(-1), Is.False);
Assert.That(combat.Python.Choose(0), Is.True);
Assert.That(combat.Python.Choose(0), Is.False, "Cannot replay a resolved choice.");
Assert.That(combat.Python.Readout.Any(s => s.StartsWith("timeshift snapshot")), Is.True);
Assert.That(combat.Python.Readout.Any(s => s.StartsWith("unattended-upgrades")), Is.False);
}
[Test]
public void UnattendedRunsTwiceAndUpdateAndCinnamonUseActualPhaseConditions()
{
Effect("mint_cinnamon"); Assert.That(Player.Shield, Is.EqualTo(3));
Effect("mint_update_manager"); Assert.That(Target.CurrentUptime, Is.EqualTo(9997));
Effect("mint_cinnamon"); Assert.That(Player.Shield, Is.EqualTo(8));
Effect("ubuntu_unattended_upgrades"); Assert.That(Player.Shield, Is.EqualTo(11));
Begin(2); Assert.That(Player.Shield, Is.EqualTo(14));
Effect("mint_update_manager"); Assert.That(Target.CurrentUptime, Is.EqualTo(9992));
Begin(3); Assert.That(Player.Shield, Is.EqualTo(17));
Begin(4); Assert.That(Player.Shield, Is.EqualTo(17));
Assert.That(combat.Python.AutomationRan, Is.False);
Assert.That(combat.Python.DamageThisPhase, Is.False);
}
[Test]
public void TimeshiftWaitsForFutureRoundsCapsRecoveryAndCannotResurrect()
{
Player.CurrentUptime = 80;
var timeshift = Card("mint_timeshift"); timeshift.ApplyMagnitudeUpgrade(30);
Effect(timeshift); Player.CurrentUptime = 50;
combat.Python.EndRound(); Assert.That(Player.CurrentUptime, Is.EqualTo(50));
Begin(2); combat.Python.EndRound(); Assert.That(Player.CurrentUptime, Is.EqualTo(56));
Begin(3); combat.Python.EndRound(); Assert.That(Player.CurrentUptime, Is.EqualTo(62));
Begin(4); combat.Python.EndRound(); Assert.That(Player.CurrentUptime, Is.EqualTo(62));
Effect("mint_timeshift"); Begin(5); Player.CurrentUptime = 0; Player.IsDefeated = true;
combat.Python.EndRound(); Assert.That(Player.CurrentUptime, Is.Zero);
}
[Test]
public void InspectTakesChosenCardPreservesOthersAndRejectsRamBlockedOptions()
{
var bottom = Card("lang_py_print"); var chosen = Card("shop_py_list_append"); var top = Card("lang_java_new_object");
combat.DeckController.AddToDrawPile(bottom, false); combat.DeckController.AddToDrawPile(chosen, false); combat.DeckController.AddToDrawPile(top, false);
combat.HandController.SetRamCapacity(1);
Effect("ubuntu_ask_ubuntu");
Assert.That(combat.Python.Choices.Count, Is.EqualTo(3));
Assert.That(combat.Python.Choose(0), Is.False);
Assert.That(combat.Python.Choose(1), Is.True);
Assert.That(combat.HandController.Cards, Is.EqualTo(new[] { chosen }));
Assert.That(combat.DeckController.DrawPile, Is.EqualTo(new[] { bottom, top }));
}
[TestCase("Ubuntu", 1, 3)]
[TestCase("Ubuntu", 2, 3)]
[TestCase("Ubuntu", 3, 5)]
[TestCase("Ubuntu", 5, 5)]
[TestCase("Mint", 5, 3)]
public void InspectDescriptionMatchesActualChoicesAtTheActiveDistroVersion(string distroName, int version, int count)
{
var distro = AssetDatabase.LoadAssetAtPath<DistroDefinition>($"Assets/Data/Distros/{distroName}.asset");
var config = new KernelPanic.Run.RunConfig(distro, Language.Python, Language.C, distro.ExclusiveCards.Take(4).ToArray(), 17, version);
Set(combat, "_runConfig", config);
var card = Card("ubuntu_ask_ubuntu");
card.ApplyMagnitudeUpgrade(2);
for (int i = 0; i < 6; i++) combat.DeckController.AddToDrawPile(Card("lang_py_print"), false);
string rules = CardEffectFactory.GetRulesText(card, config);
Assert.That(rules, Does.Contain($"inspect the top {count} cards."));
Assert.That(rules, Does.Not.Contain(count == 3 ? "5" : "3"));
Assert.That(rules, Does.Not.Contain("V3"));
Effect(card);
Assert.That(combat.Python.Choices.Count, Is.EqualTo(count));
}
[Test]
public void InspectionChoiceResolvesBeforeDrawRidersAndDiscard()
{
var chosen = Card("lang_py_print");
combat.DeckController.AddToDrawPile(Card("shop_py_list_append"), false);
combat.DeckController.AddToDrawPile(chosen, false);
combat.HandController.SetRamCapacity(1);
var inspect = Card("ubuntu_ask_ubuntu"); inspect.ApplyDrawRider(1);
Play(inspect);
Assert.That(combat.Python.HasChoice, Is.True);
Assert.That(combat.HandController.Cards, Is.Empty);
Assert.That(combat.DeckController.DiscardPile, Has.No.Member(inspect));
Assert.That(combat.Python.Choose(0), Is.True);
Assert.That(combat.HandController.Cards, Is.EqualTo(new[] { chosen }));
Assert.That(combat.DeckController.DiscardPile, Does.Contain(inspect));
}
[Test]
public void InstallOffersDistinctNonExclusivePythonCardsAndFreeCopyExpiresThenExhausts()
{
Effect("ubuntu_apt_install");
Assert.That(combat.Python.Choices.Count, Is.EqualTo(3));
Assert.That(combat.Python.Choices.Select(c => c.Label).Distinct().Count(), Is.EqualTo(3));
combat.Python.Choose(0);
var card = combat.HandController.Cards.Single();
Assert.That(card.Definition.Language, Is.EqualTo(Language.Python));
Assert.That(card.Definition.DistroExclusive || card.Definition.IsToken, Is.False);
Assert.That(combat.GetEffectiveCardCost(card), Is.Zero);
Assert.That(CardEffectFactory.GetRulesText(card), Does.Contain("Temporary copy: exhaust after play."));
Begin(2); Assert.That(combat.GetEffectiveCardCost(card), Is.EqualTo(card.Definition.CycleCost));
combat.HandController.Remove(card); combat.DeckController.Discard(card);
Assert.That(combat.DeckController.ExhaustPile, Does.Contain(card));
Assert.That(combat.DeckController.DiscardPile, Has.No.Member(card));
}
[Test]
public void PreviewDoesNotCarryLastRoundsConditionsAndIncludesUpcomingDamageScripts()
{
Effect("mint_update_manager");
Set(combat, "_turnNumberThisWave", 2);
Assert.That(combat.Python.PreviewState(Card("mint_cinnamon")).damageBefore, Is.False);
Begin(2); Effect("shop_py_async_def"); Effect("lang_py_print");
Set(combat, "_turnNumberThisWave", 3);
Assert.That(combat.Python.PreviewState(Card("mint_cinnamon")).damageBefore, Is.True);
Assert.That(combat.Python.PreviewState(Card("mint_update_manager")).automation, Is.True);
Begin(3); Begin(4);
Set(combat, "_turnNumberThisWave", 5);
Assert.That(combat.Python.PreviewState(Card("mint_update_manager")).automation, Is.False);
}
[Test]
public void ScriptsActivateAtMostOncePerRoundAndRetargetDefeatedEnemies()
{
Effect("shop_py_async_def"); Effect("lang_py_print");
Effect("mint_timeshift"); Player.CurrentUptime = 50;
Target.IsDefeated = true; Target.CurrentUptime = 0;
Begin(2); combat.Python.EndRound();
Begin(2); combat.Python.EndRound();
Assert.That(combat.Enemies[1].State.CurrentUptime, Is.EqualTo(9996));
Assert.That(Player.CurrentUptime, Is.EqualTo(56));
Assert.That(combat.Python.AutomationCount, Is.EqualTo(2));
Begin(3); combat.Python.EndRound();
Assert.That(combat.Enemies[1].State.CurrentUptime, Is.EqualTo(9992));
Assert.That(Player.CurrentUptime, Is.EqualTo(62));
Assert.That(combat.Python.AutomationCount, Is.Zero);
}
[Test]
public void WaveCleanupClearsScriptsChoicesModifiersAndTemporaryDiscounts()
{
Effect("lang_py_for_loop"); Effect("shop_py_zip"); Effect("shop_py_async_def");
Effect("ubuntu_apt_install"); combat.Python.Choose(0);
var generated = combat.HandController.Cards.Single();
Effect("ubuntu_unattended_upgrades"); Effect("mint_timeshift");
Assert.That(ExecutionPreview.Build(combat).Any(s => s.Contains("scripts 2/2")), Is.True);
Call(combat, "ClearDeferredCards");
Assert.That(combat.Python.HasChoice, Is.False);
Assert.That(combat.Python.AutomationCount, Is.Zero);
Assert.That(combat.Python.RepeatCount + combat.Python.AreaCount, Is.Zero);
Assert.That(generated.TemporaryCostDelta, Is.Zero);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: fae416900ff44939bb6075c2ecfda4c5
@@ -132,8 +132,8 @@ public class RewardSettlementTests
_save.Save(SaveData.CreateDefault());
Set(_run, "_accruedBandwidth", 100);
Set(_run, "_accruedEntropy", 3);
Set(_run, "currentWaveNumber", 6);
Set(_run, "_wavesCleared", 5);
Set(_run, "currentWaveNumber", RunJourney.BossWave + 1);
Set(_run, "_wavesCleared", RunJourney.BossWave);
var combat = _owner.GetComponent<CombatManager>();
Set(combat, "_runManager", _run);
Set(combat, "_awaitingWaveContinue", true);
@@ -147,10 +147,10 @@ public class RewardSettlementTests
var saved = _save.Load();
Assert.That(saved.bandwidthBalance, Is.EqualTo(100));
Assert.That(saved.entropyBalance, Is.EqualTo(3));
Assert.That(saved.GetBestWave("gentoo"), Is.EqualTo(5));
Assert.That(saved.GetBestWave("gentoo"), Is.EqualTo(RunJourney.BossWave));
Assert.That(saved.recentRuns.Count, Is.EqualTo(1));
Assert.That(saved.recentRuns[0].victory, Is.True);
Assert.That(saved.recentRuns[0].waveReached, Is.EqualTo(5));
Assert.That(saved.recentRuns[0].waveReached, Is.EqualTo(RunJourney.BossWave));
Assert.That(saved.recentRuns[0].cause, Does.Contain("campaign complete"));
}
private void RefreshStatus() => typeof(CombatSceneController).GetMethod("RefreshStatus", Private).Invoke(_controller, null);
+228
View File
@@ -0,0 +1,228 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using KernelPanic.Combat;
using KernelPanic.Core;
using KernelPanic.Data;
using KernelPanic.Run;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
public class RouteMapTests
{
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
private GameObject _owner;
private RunManager _run;
private CombatManager _combat;
private CardDatabase _cards;
private int _seed, _draws;
[SetUp]
public void Setup()
{
_seed = RandomRoll.CurrentSeed; _draws = RandomRoll.DrawCount;
_owner = new GameObject("route map tests"); _owner.SetActive(false);
_run = _owner.AddComponent<RunManager>(); _combat = _owner.AddComponent<CombatManager>();
_cards = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
var distro = AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Ubuntu.asset");
var config = new RunConfig(distro, Language.Python, Language.JavaScript,
new[] { _cards.FindById("lang_py_print"), _cards.FindById("lang_py_print"), _cards.FindById("mint_timeshift") }, 12345);
_run.StartRun(config);
Set(_combat, "_runConfig", config); Set(_combat, "_runManager", _run);
Set(_combat, "_playerState", new CombatantState(50, 6, 3) { CurrentUptime = 20 });
ClearWave(1);
}
[TearDown]
public void Cleanup()
{
UnityEngine.Object.DestroyImmediate(_owner);
RandomRoll.Restore(_seed, _draws);
}
[Test]
public void SeededGraphHasEntrancesExitsCrossingsVarietyAndFinalConvergence()
{
int draws = RandomRoll.DrawCount;
var kinds = new System.Collections.Generic.HashSet<WaveRoute>();
bool crossing = false, fork = false;
for (int seed = 0; seed < 64; seed++)
for (int wave = 2; wave < 15; wave++)
{
var row = RunRouteMap.Row(seed, wave); var next = RunRouteMap.Row(seed, wave + 1);
Assert.That(row.Select(n => n.Route), Is.EqualTo(RunRouteMap.Row(seed, wave).Select(n => n.Route)));
foreach (var a in row)
{
kinds.Add(a.Route);
Assert.That(next.Any(b => RunRouteMap.Connected(seed, a, b)), Is.True);
fork |= next.Count(b => RunRouteMap.Connected(seed, a, b)) > 1;
foreach (var b in next.Where(b => RunRouteMap.Connected(seed, a, b)))
crossing |= row.Any(c => c.Lane > a.Lane && next.Any(d => d.Lane < b.Lane && RunRouteMap.Connected(seed, c, d)));
}
Assert.That(next.All(b => row.Any(a => RunRouteMap.Connected(seed, a, b))), Is.True);
}
Assert.That(kinds, Is.EquivalentTo(Enum.GetValues(typeof(WaveRoute))));
Assert.That(crossing && fork, Is.True);
Assert.That(RunRouteMap.Row(12345, 4).Count, Is.InRange(2, 4));
Assert.That(RunRouteMap.Row(12345, RunJourney.BossWave).Single().Route, Is.EqualTo(WaveRoute.Encounter));
Assert.That(RandomRoll.DrawCount, Is.EqualTo(draws));
}
[Test]
public void CampaignHasEightChoiceTiersWithRecoveryBoundedElitesAndNoDeadEnds()
{
for (int seed = -128; seed < 128; seed++)
{
var reachable = RunRouteMap.Row(seed, 2).Select(n => n.Id).ToHashSet();
for (int wave = 2; wave < RunJourney.BossWave; wave++)
{
var row = RunRouteMap.Row(seed, wave);
var next = RunRouteMap.Row(seed, wave + 1);
Assert.That(row.Count, Is.InRange(2, 4));
Assert.That(row.All(n => reachable.Contains(n.Id)), Is.True, $"Seed {seed}, wave {wave}");
Assert.That(row.Count(n => n.Route == WaveRoute.Repair), Is.EqualTo(1));
Assert.That(row.Count(n => n.Route == WaveRoute.Challenge), Is.LessThanOrEqualTo(1));
if (wave >= 7) Assert.That(row.Any(n => n.Route == WaveRoute.Challenge), Is.True);
Assert.That(row.All(a => next.Any(b => RunRouteMap.Connected(seed, a, b))), Is.True);
if (wave + 1 < RunJourney.BossWave)
foreach (var node in row)
Assert.That(next.Count(n => RunRouteMap.Connected(seed, node, n)), Is.InRange(2, 3));
reachable = next.Where(b => row.Any(a => RunRouteMap.Connected(seed, a, b))).Select(n => n.Id).ToHashSet();
}
Assert.That(reachable, Does.Contain(RunJourney.BossWave * 10 + 1));
}
}
[TestCase(1, 5)]
[TestCase(2, 10)]
public void CompleteRouteSurvivesEveryCheckpointAndEntersEndlessOnlyAfterItsBoss(int revision, int boss)
{
_run.Journey.mapRevision = revision;
_run.Journey.encounterRevision = revision;
int rewards = 0;
for (int wave = 2; wave <= boss; wave++)
{
Assert.That(_run.CampaignChoicePending, Is.False, "Must not finish an extended campaign at wave five.");
if (_run.BuildRewardPending) { _run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true); rewards++; }
Assert.That(_run.SelectRouteNode(_run.AvailableRouteNodes[0].Id), Is.True);
if (_run.RouteEventPending) _run.ResolveRouteEvent(skip: true);
var snapshot = JsonUtility.FromJson<RunCheckpoint>(JsonUtility.ToJson(_run.CaptureCheckpoint(_combat)));
var restored = snapshot.Resolve(
AssetDatabase.LoadAssetAtPath<DistroDatabase>("Assets/Data/Distros/DistroDatabase.asset"), _cards,
AssetDatabase.LoadAssetAtPath<LanguageDeckDatabase>("Assets/Data/Cards/Languages/LanguageDeckDatabase.asset"),
AssetDatabase.LoadAssetAtPath<PackageDatabase>("Assets/Data/Packages/PackageDatabase.asset"));
_run.RestoreCheckpoint(restored);
Assert.That(_run.Journey.FinalWave, Is.EqualTo(boss));
_run.PrepareNextEncounter(_combat.PlayerState); ClearWave(wave);
}
Assert.That(rewards, Is.EqualTo(revision == 2 ? 4 : 2));
Assert.That(_run.Journey.visits.Count, Is.EqualTo(boss - 1));
Assert.That(_run.CampaignChoicePending, Is.True);
_run.Journey.Validate(boss + 1); _run.Journey.ValidateMap(12345, boss + 1);
Assert.That(_run.SelectRouteNode(_run.AvailableRouteNodes[0].Id), Is.False);
Assert.That(_run.EnterEndless(), Is.True);
Assert.That(_run.CampaignChoicePending, Is.False);
_run.Journey.Validate(boss + 1); _run.Journey.ValidateMap(12345, boss + 1);
Assert.That(_run.SelectRouteNode(_run.AvailableRouteNodes[0].Id), Is.True);
if (_run.RouteEventPending) _run.ResolveRouteEvent(skip: true);
_run.PrepareNextEncounter(_combat.PlayerState); ClearWave(boss + 1);
Assert.That(_run.CurrentWaveNumber, Is.EqualTo(boss + 2));
}
[Test]
public void SacrificeRequiresDifferentEligibleCardsAndCommitsExactlyOnce()
{
var donor = _run.RunDeck[0]; var target = _run.RunDeck[1];
int count = _run.RunDeck.Count, bits = _run.Bits;
Assert.That(_run.SelectRoute(WaveRoute.Sacrifice), Is.True);
Assert.That(_run.RunDeck.Count, Is.EqualTo(count));
_run.PrepareNextEncounter(_combat.PlayerState);
Assert.That(_run.RepositoryVisitActive, Is.True);
Assert.That(_run.ResolveRouteEvent(donor, donor), Is.False);
Assert.That(_run.ResolveRouteEvent(donor, _run.RunDeck[2]), Is.False, "Timeshift is not magnitude-scaled.");
Assert.That(_run.ResolveRouteEvent(new CardInstance(donor.Definition), target), Is.False);
Assert.That(_run.ResolveRouteEvent(donor, target), Is.True);
Assert.That(_run.RunDeck.Count, Is.EqualTo(count - 1));
Assert.That(_run.RunDeck.Contains(donor), Is.False);
Assert.That(target.MagnitudeBonus, Is.EqualTo(4));
Assert.That(_run.Bits, Is.EqualTo(bits));
Assert.That(_run.ResolveRouteEvent(target, target), Is.False);
Assert.That(_run.ResolveRouteEvent(skip: true), Is.False);
Assert.That(_run.SelectRoute(WaveRoute.Repair), Is.False, "Claiming an event locks the path.");
}
[Test]
public void PassingLocksStopWithoutChangingDeckAndHistoryConstrainsNextChoice()
{
_run.SelectRoute(WaveRoute.Sacrifice);
var before = _run.RunDeck.ToArray();
Assert.That(_run.ResolveRouteEvent(skip: true), Is.True);
Assert.That(_run.RunDeck, Is.EqualTo(before));
_run.PrepareNextEncounter(_combat.PlayerState); ClearWave(2);
var previous = RunRouteMap.Row(12345, 2).Single(n => n.Route == WaveRoute.Sacrifice);
Assert.That(_run.AvailableRouteNodes.Select(n => n.Id), Is.EquivalentTo(
RunRouteMap.Row(12345, 3).Where(n => RunRouteMap.Connected(12345, previous, n)).Select(n => n.Id)));
Assert.That(_run.SelectRouteNode(999), Is.False);
Assert.That(_run.Journey.visits.Single().outcome, Does.Contain("Passed"));
Assert.That(_run.Journey.visits.Single().cleared, Is.True);
_run.Journey.Validate(3); _run.Journey.ValidateMap(12345, 3);
var copy = _run.Journey.Copy(); copy.visits[0].nodeId = 999;
Assert.That(_run.Journey.visits[0].nodeId, Is.EqualTo(previous.Id));
Assert.Throws<InvalidDataException>(() => copy.ValidateMap(12345, 3));
}
[Test]
public void ResolvedSacrificeRoundTripsWithoutDuplicatingUpgradeOrRemoval()
{
var donor = _run.RunDeck[0]; var target = _run.RunDeck[1]; string id = target.InstanceId;
_run.SelectRoute(WaveRoute.Sacrifice); _run.ResolveRouteEvent(donor, target);
var snapshot = JsonUtility.FromJson<RunCheckpoint>(JsonUtility.ToJson(_run.CaptureCheckpoint(_combat)));
var resolved = snapshot.Resolve(
AssetDatabase.LoadAssetAtPath<DistroDatabase>("Assets/Data/Distros/DistroDatabase.asset"), _cards,
AssetDatabase.LoadAssetAtPath<LanguageDeckDatabase>("Assets/Data/Cards/Languages/LanguageDeckDatabase.asset"),
AssetDatabase.LoadAssetAtPath<PackageDatabase>("Assets/Data/Packages/PackageDatabase.asset"));
_run.RestoreCheckpoint(resolved);
Assert.That(_run.RunDeck.Count, Is.EqualTo(2));
Assert.That(_run.RunDeck.Single(c => c.InstanceId == id).MagnitudeBonus, Is.EqualTo(4));
Assert.That(_run.RouteEventPending, Is.False);
Assert.That(_run.ResolveRouteEvent(skip: true), Is.False);
_run.PrepareNextEncounter(_combat.PlayerState); ClearWave(2);
Assert.That(_run.Journey.visits.Single().outcome, Does.Contain("Sacrificed"));
_run.Journey.Validate(3); _run.Journey.ValidateMap(12345, 3);
}
[TestCase(WaveRoute.Forge, 2, 0, 0)]
[TestCase(WaveRoute.Recycle, 0, 4, 1)]
[TestCase(WaveRoute.Cache, 0, 6, 0)]
public void OtherStopsApplyTheirAdvertisedEffectsOnlyOnce(WaveRoute route, int magnitude, int bits, int removed)
{
// A seeded third row containing the desired event, with its actual connected entrance.
int seed = Enumerable.Range(0, 100).First(s => RunRouteMap.Row(s, 3).Any(n => n.Route == route));
var config = new RunConfig(_run.CurrentConfig.Distro, Language.Python, Language.JavaScript, _run.CurrentConfig.StartingDeck, seed);
_run.StartRun(config); ClearWave(1);
var desired = RunRouteMap.Row(seed, 3).Single(n => n.Route == route);
var entrance = RunRouteMap.Row(seed, 2).First(n => RunRouteMap.Connected(seed, n, desired));
_run.SelectRouteNode(entrance.Id);
if (_run.RouteEventPending) _run.ResolveRouteEvent(skip: true);
_run.PrepareNextEncounter(_combat.PlayerState); ClearWave(2);
_run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true);
Assert.That(_run.SelectRouteNode(desired.Id), Is.True);
int before = _run.Bits, count = _run.RunDeck.Count;
var donor = _run.RunDeck[0]; var target = _run.RunDeck[1];
if (_run.RouteEventPending) Assert.That(_run.ResolveRouteEvent(donor, target), Is.True);
_run.PrepareNextEncounter(_combat.PlayerState); _run.PrepareNextEncounter(_combat.PlayerState);
Assert.That(target.MagnitudeBonus, Is.EqualTo(magnitude));
Assert.That(_run.RunDeck.Count, Is.EqualTo(count - removed));
Assert.That(_run.Bits, Is.EqualTo(before + bits));
}
private void ClearWave(int wave)
{
typeof(RunManager).GetMethod("HandleWaveCleared", Private).Invoke(_run, new object[] { new WaveClearedEvent(wave) });
Set(_combat, "_awaitingWaveContinue", true);
_run.GenerateRepositoryOffers(_cards, null);
}
private static void Set(object obj, string name, object value) => obj.GetType().GetField(name, Private).SetValue(obj, value);
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a703072a87444cc89b2c215bb3e8fa1a
+21 -4
View File
@@ -54,6 +54,7 @@ public class RunCheckpointTests
var config = new RunConfig(distro, Language.Python, Language.JavaScript, starting,
new[] { new PackageInstance(_packages.FindById("pkg_fedora_dnf"), 3) }, -7712, 2);
_run.StartRun(config); // No bound CombatManager: do not start Play-mode coroutines.
_run.Journey.mapRevision = 0; // This fixture jumps directly to an older repository boundary.
Set(_combat, "_runManager", _run);
Set(_combat, "_runConfig", config);
Set(_combat, "_playerState", new CombatantState(_run.EffectiveMaxUptime(), _run.EffectiveRam(), _run.EffectiveMaxCycles())
@@ -141,7 +142,7 @@ public class RunCheckpointTests
var resume = Prepare();
_run.RestoreCheckpoint(resume);
Assert.That(_run.BuildRewardPending, Is.True);
Assert.That(_run.Journey.encounterRevision, Is.EqualTo(1));
Assert.That(_run.Journey.encounterRevision, Is.EqualTo(2));
int bits = _run.Bits;
Assert.That(_run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true), Is.True);
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
@@ -200,6 +201,22 @@ public class RunCheckpointTests
Assert.That(_combat.RunConfig.RunSeed, Is.EqualTo(-7712));
}
[TestCase(0, 0, 0)]
[TestCase(1, 1, 0)]
[TestCase(3, 3, 1)]
[TestCase(5, 5, 3)]
[TestCase(6, 6, 4)]
[TestCase(int.MaxValue, 6, 4)]
public void JavaWarmupRestoresPartialProgressClampsLegacyExcessAndCools(int saved, int restored, int cooled)
{
var snapshot = _combat.CaptureBoundaryState();
snapshot.javaCardsPlayed = saved;
_combat.RestoreBoundaryState(_combat.RunConfig, snapshot);
Assert.That(_combat.CaptureBoundaryState().javaCardsPlayed, Is.EqualTo(restored));
typeof(CombatManager).GetMethod("DecayJavaWarmupForNextWave", Private).Invoke(_combat, null);
Assert.That(_combat.CaptureBoundaryState().javaCardsPlayed, Is.EqualTo(cooled));
}
[Test]
public void FailedCheckpointWriteKeepsRunActiveAndExistingSaveUnchanged()
{
@@ -306,7 +323,7 @@ public class RunCheckpointTests
Assert.That(_run.SelectRoute(WaveRoute.Challenge), Is.True);
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
var restored = Prepare();
Assert.That(restored.Snapshot.version, Is.EqualTo(3));
Assert.That(restored.Snapshot.version, Is.EqualTo(4));
_run.RestoreCheckpoint(restored);
_combat.RestoreBoundaryState(restored.Config, restored.Snapshot.combat);
Assert.That(_run.Journey.campaign, Is.True);
@@ -331,8 +348,8 @@ public class RunCheckpointTests
[Test]
public void BossMilestoneSurvivesSaveAndResumeWithoutStartingEndless()
{
Set(_run, "currentWaveNumber", 6);
Set(_run, "_wavesCleared", 5);
Set(_run, "currentWaveNumber", RunJourney.BossWave + 1);
Set(_run, "_wavesCleared", RunJourney.BossWave);
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
var restored = Prepare();
_run.RestoreCheckpoint(restored);
@@ -72,7 +72,7 @@ public class SerializedEffectTargetingTests
}
[TestCase("lang_c_malloc", true, false)]
[TestCase("lang_py_for_loop", false, true)]
[TestCase("lang_py_for_loop", false, false)]
[TestCase("lang_rs_borrow", false, false)]
[TestCase("external_card", false, false)]
public void EmptyAndNullOnlyOverridesUseCatalogTargeting(string id, bool single, bool all)
+2 -2
View File
@@ -438,7 +438,7 @@ public class TerminalUiTests
var instance = new CardInstance(card) { IsBroken = true };
instance.ApplyDrawRider(2);
var face = new VisualElement();
Runtime.GetType("KernelPanic.UI.SoftwareCardView").GetMethod("Populate").Invoke(null, new object[] { face, instance, 3 });
Runtime.GetType("KernelPanic.UI.SoftwareCardView").GetMethod("Populate", new[] { typeof(VisualElement), typeof(CardInstance), typeof(int) }).Invoke(null, new object[] { face, instance, 3 });
Assert.That(face.ClassListContains("software-c"), Is.True);
Assert.That(face.ClassListContains("software-corrupted"), Is.True);
Assert.That(face.Q<Label>(className: "software-cost").text, Is.EqualTo("3c"));
@@ -450,7 +450,7 @@ public class TerminalUiTests
[Test]
public void EveryCardRetainsItsCompleteRulesInTheManifest()
{
var populate = Runtime.GetType("KernelPanic.UI.SoftwareCardView").GetMethod("Populate");
var populate = Runtime.GetType("KernelPanic.UI.SoftwareCardView").GetMethod("Populate", new[] { typeof(VisualElement), typeof(CardInstance), typeof(int) });
var guids = AssetDatabase.FindAssets("t:CardDefinition", new[] { "Assets/Data/Cards" });
Assert.That(guids.Length, Is.GreaterThan(0));
foreach (string guid in guids)
+22
View File
@@ -180,6 +180,28 @@ public class TutorialTests
Assert.That(restored.Offers.Any(o => o.Sold), Is.True);
}
[Test]
public void RebalancedUnwrapStillCompletesTheGuidedFirstKillWithoutACrit()
{
Call(_combat, "SpawnEncounter");
var zombie = _combat.Enemies.Single(enemy => enemy.ArchetypeId == "zombie_process");
_combat.PlayerState.ForceMaxRolls = true; // Disables critical hits and Rust's rare overflow.
var card = _run.RunDeck.Single(item => item.Definition.Id == "lang_rs_unwrap");
var context = new CombatContext(card, _combat.PlayerState, new[] { zombie.State },
_combat, _combat.DamagePipeline, new StatusEffectController(), _combat.DeckController,
_combat.HandController, _combat.Enemies);
Call(_combat, "OnEnable");
try
{
foreach (var effect in CardEffectFactory.CreateEffects(card.Definition)) effect.Execute(context);
Assert.That(zombie.State.IsDefeated, Is.True);
Assert.That(zombie.PendingRevive, Is.True, "The guide requires an actual first kill and pending revival.");
}
finally { Call(_combat, "OnDisable"); }
}
[Test]
public void TargetingRequiresSelectingTheExpectedCardAndActualZombieRevival()
{