890 lines
37 KiB
C#
890 lines
37 KiB
C#
using KernelPanic.Combat;
|
|
using KernelPanic.Core;
|
|
using KernelPanic.Data;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using UnityEngine;
|
|
|
|
namespace KernelPanic.Run
|
|
{
|
|
/// <summary>
|
|
/// Coordinates run lifecycle, wave progression, and run-level event handling.
|
|
/// </summary>
|
|
public sealed class RunManager : MonoBehaviour
|
|
{
|
|
[SerializeField] private CombatManager combatManager;
|
|
[SerializeField] private int currentWaveNumber;
|
|
[SerializeField] private bool isRunActive;
|
|
[SerializeField] private bool isPlayerDead;
|
|
|
|
private readonly List<CardInstance> _runDeck = new();
|
|
private readonly List<RepositoryOffer> _repositoryOffers = new();
|
|
private readonly HashSet<string> _soldOfferKeys = new(StringComparer.OrdinalIgnoreCase);
|
|
// A separate stream keeps combat rolls, presentation and shop browsing independent.
|
|
private ReplayableRandom _repositoryRandom = new(0);
|
|
private int _bits;
|
|
private int _rerollsThisVisit;
|
|
private int _maxUptimeBonus;
|
|
private int _maxCyclesBonus;
|
|
private int _ramBonus;
|
|
private int _packageMaxUptimeBonus;
|
|
private int _packageMaxCyclesBonus;
|
|
private int _packageRamBonus;
|
|
private int _wavesCleared;
|
|
private int _accruedBandwidth;
|
|
private int _accruedEntropy;
|
|
private bool _repositoryVisitActive;
|
|
private bool _rewardsSettled;
|
|
|
|
public int CurrentWaveNumber => currentWaveNumber;
|
|
public bool IsRunActive => isRunActive;
|
|
public bool IsPlayerDead => isPlayerDead;
|
|
public RunConfig CurrentConfig { get; private set; }
|
|
public IReadOnlyList<CardInstance> RunDeck => _runDeck;
|
|
public IReadOnlyList<RepositoryOffer> RepositoryOffers => _repositoryOffers;
|
|
public bool RepositoryVisitActive => _repositoryVisitActive;
|
|
public int Bits => _bits;
|
|
public int RerollCost => CombatTuning.RerollBaseCost + (_rerollsThisVisit * CombatTuning.RerollCostStep);
|
|
public int MaxUptimeBonus => _maxUptimeBonus;
|
|
public int MaxCyclesBonus => _maxCyclesBonus;
|
|
public int RamBonus => _ramBonus;
|
|
public int WavesCleared => _wavesCleared;
|
|
public int AccruedBandwidth => _accruedBandwidth;
|
|
public int AccruedEntropy => _accruedEntropy;
|
|
public bool RewardsSettled => _rewardsSettled;
|
|
public string RunId { get; private set; }
|
|
public bool IsSuspended { get; private set; }
|
|
public RunJourney Journey { get; private set; } = new();
|
|
public Meta.RunPerformanceSnapshot Performance { get; private set; } = new();
|
|
public List<CheckpointCard> FinalDeck { get; private set; }
|
|
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)
|
|
{
|
|
if (!isRunActive || IsSuspended || !_repositoryVisitActive || !BuildRewardPending) return false;
|
|
if (!takeBits && (card?.Definition == null || !_runDeck.Contains(card)
|
|
|| card.Definition.IsToken || card.Definition.IsJunk
|
|
|| (kind != CardUpgradeKind.MagnitudeUp && kind != CardUpgradeKind.DrawRider)
|
|
|| (kind == CardUpgradeKind.DrawRider && card.DrawRider > 0))) return false;
|
|
if (!takeBits && !ApplyCardUpgrade(card, kind)) return false;
|
|
if (takeBits) _bits += BuildRewardBits;
|
|
Journey.claimedRewardWave = Journey.pendingRewardWave;
|
|
Journey.pendingRewardWave = 0;
|
|
Journey.lastReward = takeBits ? $"Build reward: +{BuildRewardBits} Bits."
|
|
: $"Build reward: {card.Definition.DisplayName} gained " +
|
|
(kind == CardUpgradeKind.DrawRider ? "+1 draw on resolution." : $"+{CombatTuning.UpgradeMagnitudeBonus} effect magnitude.");
|
|
RepositoryChanged?.Invoke();
|
|
return true;
|
|
}
|
|
|
|
public bool SelectRoute(WaveRoute route)
|
|
{
|
|
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;
|
|
}
|
|
|
|
public bool EnterEndless()
|
|
{
|
|
if (!isRunActive || IsSuspended || !CampaignChoicePending) return false;
|
|
Journey.endless = true;
|
|
RepositoryChanged?.Invoke();
|
|
return true;
|
|
}
|
|
|
|
// Called exactly once by the guarded combat transition, never by UI callbacks.
|
|
public void PrepareNextEncounter(CombatantState player)
|
|
{
|
|
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;
|
|
}
|
|
|
|
public event Action RepositoryChanged;
|
|
|
|
private void OnEnable()
|
|
{
|
|
GameEvents.WaveCleared += HandleWaveCleared;
|
|
GameEvents.RunEnded += HandleRunEnded;
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
GameEvents.WaveCleared -= HandleWaveCleared;
|
|
GameEvents.RunEnded -= HandleRunEnded;
|
|
}
|
|
|
|
public void StartRun(RunConfig config)
|
|
{
|
|
CurrentConfig = config;
|
|
Performance = new();
|
|
FinalDeck = null;
|
|
Journey = RunJourney.NewCampaign();
|
|
if (config?.IsTutorial == true) Journey = new RunJourney();
|
|
RunId = Guid.NewGuid().ToString("N");
|
|
IsSuspended = false;
|
|
_repositoryRandom = new ReplayableRandom(unchecked((config?.RunSeed ?? 0) ^ 0x52E50A31));
|
|
_repositoryOffers.Clear();
|
|
_soldOfferKeys.Clear();
|
|
_repositoryVisitActive = false;
|
|
isRunActive = true;
|
|
isPlayerDead = false;
|
|
currentWaveNumber = 1;
|
|
_bits = config?.IsTutorial == true ? 12 : 0;
|
|
_rerollsThisVisit = 0;
|
|
_maxUptimeBonus = 0;
|
|
_maxCyclesBonus = 0;
|
|
_ramBonus = 0;
|
|
_packageMaxUptimeBonus = 0;
|
|
_packageMaxCyclesBonus = 0;
|
|
_packageRamBonus = 0;
|
|
_wavesCleared = 0;
|
|
_accruedBandwidth = 0;
|
|
_accruedEntropy = 0;
|
|
_rewardsSettled = false;
|
|
ApplyKernelPackageBonuses(config);
|
|
InitializeRunDeck(config);
|
|
StartCombat();
|
|
}
|
|
|
|
public void StartCombat()
|
|
{
|
|
combatManager?.StartCombat(CurrentConfig);
|
|
}
|
|
|
|
public RunCheckpoint CaptureCheckpoint(CombatManager combat)
|
|
{
|
|
if (CurrentConfig?.IsLanguageTraining == true) throw new InvalidOperationException("Language practice cannot replace a saved campaign.");
|
|
RunCheckpoint.Require(isRunActive && !IsSuspended && !_rewardsSettled && _repositoryVisitActive
|
|
&& combat != null && combat.AwaitingWaveContinue && !combat.RunLost, "Runs can only be saved in the repository.");
|
|
RunCheckpoint snapshot = new()
|
|
{
|
|
runId = RunId, savedUtc = DateTime.UtcNow.ToString("O"), distroId = CurrentConfig.Distro.Id,
|
|
distroVersion = CurrentConfig.DistroVersion, primaryLanguage = CurrentConfig.PrimaryLanguage,
|
|
secondaryLanguage = CurrentConfig.SecondaryLanguage, seed = CurrentConfig.RunSeed,
|
|
startingCards = CurrentConfig.StartingDeck.Select(card => card.Id).ToList(),
|
|
deck = _runDeck.Select(CheckpointCard.Capture).ToList(), soldKeys = _soldOfferKeys.ToList(),
|
|
wave = currentWaveNumber, wavesCleared = _wavesCleared, bits = _bits,
|
|
bandwidth = _accruedBandwidth, entropy = _accruedEntropy,
|
|
maxUptimeBonus = _maxUptimeBonus, maxCyclesBonus = _maxCyclesBonus, ramBonus = _ramBonus,
|
|
rerolls = _rerollsThisVisit, shopRandomDraws = _repositoryRandom.Draws,
|
|
version = 5, journey = Journey.Copy(), performance = Performance.Copy(),
|
|
combat = combat.CaptureBoundaryState()
|
|
};
|
|
foreach (PackageInstance package in CurrentConfig.EquippedPackages)
|
|
snapshot.packages.Add(new Meta.RunBuildPackageSaveEntry
|
|
{ packageId = package.Definition.Id, slot = package.Definition.Slot, upgradeLevel = package.UpgradeLevel });
|
|
foreach (RepositoryOffer offer in _repositoryOffers)
|
|
snapshot.offers.Add(new CheckpointOffer
|
|
{
|
|
kind = offer.Kind, cardId = offer.CardDefinition?.Id, targetId = offer.TargetCard?.InstanceId,
|
|
detachedTarget = offer.TargetCard != null && !_runDeck.Contains(offer.TargetCard) ? CheckpointCard.Capture(offer.TargetCard) : null,
|
|
cardUpgrade = offer.CardUpgradeKind, statUpgrade = offer.StatUpgradeKind, price = offer.Price, sold = offer.Sold
|
|
});
|
|
return snapshot;
|
|
}
|
|
|
|
public void MarkSuspended() => IsSuspended = true;
|
|
|
|
public void RestoreCheckpoint(ResolvedRunCheckpoint resume)
|
|
{
|
|
if (resume == null) throw new ArgumentNullException(nameof(resume));
|
|
RunCheckpoint snapshot = resume.Snapshot;
|
|
CurrentConfig = resume.Config;
|
|
Performance = snapshot.performance?.schemaVersion == 1 ? snapshot.performance.Copy() : new Meta.RunPerformanceSnapshot { complete = false };
|
|
FinalDeck = null;
|
|
Journey = snapshot.journey?.Copy() ?? new RunJourney();
|
|
RunId = snapshot.runId;
|
|
IsSuspended = false;
|
|
isRunActive = true;
|
|
isPlayerDead = false;
|
|
_rewardsSettled = false;
|
|
currentWaveNumber = snapshot.wave;
|
|
_wavesCleared = snapshot.wavesCleared;
|
|
_bits = snapshot.bits;
|
|
_accruedBandwidth = snapshot.bandwidth;
|
|
_accruedEntropy = snapshot.entropy;
|
|
_maxUptimeBonus = snapshot.maxUptimeBonus;
|
|
_maxCyclesBonus = snapshot.maxCyclesBonus;
|
|
_ramBonus = snapshot.ramBonus;
|
|
_rerollsThisVisit = snapshot.rerolls;
|
|
ApplyKernelPackageBonuses(CurrentConfig);
|
|
_repositoryRandom = new ReplayableRandom(unchecked(CurrentConfig.RunSeed ^ 0x52E50A31), snapshot.shopRandomDraws);
|
|
_runDeck.Clear();
|
|
_runDeck.AddRange(resume.Deck);
|
|
_repositoryOffers.Clear();
|
|
_repositoryOffers.AddRange(resume.Offers);
|
|
_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)
|
|
{
|
|
if (!isRunActive || amount <= 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_bits += amount;
|
|
RepositoryChanged?.Invoke();
|
|
}
|
|
|
|
public void GenerateRepositoryOffers(CardDatabase cardDatabase, LanguageDeckDatabase languageDeckDatabase)
|
|
{
|
|
_repositoryOffers.Clear();
|
|
_rerollsThisVisit = 0;
|
|
_soldOfferKeys.Clear();
|
|
FillRepositoryOffers(cardDatabase, languageDeckDatabase);
|
|
_repositoryVisitActive = true;
|
|
EnsureRouteSelection();
|
|
RepositoryChanged?.Invoke();
|
|
}
|
|
|
|
public bool RerollRepositoryOffers(CardDatabase cardDatabase, LanguageDeckDatabase languageDeckDatabase)
|
|
{
|
|
int cost = RerollCost;
|
|
if (_bits < cost)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
_bits -= cost;
|
|
_rerollsThisVisit++;
|
|
_repositoryOffers.Clear();
|
|
FillRepositoryOffers(cardDatabase, languageDeckDatabase);
|
|
_repositoryVisitActive = true;
|
|
RepositoryChanged?.Invoke();
|
|
return true;
|
|
}
|
|
|
|
public bool BuyOffer(RepositoryOffer offer, CombatantState playerState)
|
|
{
|
|
if (offer == null || offer.Sold || _bits < offer.Price)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
bool applied = offer.Kind switch
|
|
{
|
|
RepositoryOfferKind.NewCard => AddCardToRunDeck(offer.CardDefinition),
|
|
RepositoryOfferKind.CardUpgrade => ApplyCardUpgrade(offer.TargetCard, offer.CardUpgradeKind),
|
|
RepositoryOfferKind.StatUpgrade => ApplyStatUpgrade(offer.StatUpgradeKind, playerState),
|
|
_ => false
|
|
};
|
|
|
|
if (!applied)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
_bits -= offer.Price;
|
|
offer.MarkSold();
|
|
_soldOfferKeys.Add(OfferKey(offer));
|
|
RepositoryChanged?.Invoke();
|
|
return true;
|
|
}
|
|
|
|
public bool RemoveCard(CardInstance card)
|
|
{
|
|
if (card == null || _bits < CombatTuning.RemoveCardCost || _runDeck.Count <= 1)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (!_runDeck.Remove(card))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
_bits -= CombatTuning.RemoveCardCost;
|
|
RepositoryChanged?.Invoke();
|
|
return true;
|
|
}
|
|
|
|
public int EffectiveMaxUptime()
|
|
{
|
|
if (CurrentConfig?.IsLanguageTraining == true) return 60;
|
|
if (CurrentConfig?.IsTutorial == true) return Mathf.Max(60, CurrentConfig.Distro.BaseUptime) + _maxUptimeBonus;
|
|
return Mathf.Max(1, (CurrentConfig?.Distro?.BaseUptime ?? 1) + _maxUptimeBonus + _packageMaxUptimeBonus);
|
|
}
|
|
|
|
public int EffectiveRam()
|
|
{
|
|
if (CurrentConfig?.IsLanguageTraining == true) return 12;
|
|
if (CurrentConfig?.IsTutorial == true) return Mathf.Max(6, CurrentConfig.Distro.BaseRam) + _ramBonus;
|
|
return Mathf.Max(1, (CurrentConfig?.Distro?.BaseRam ?? 1) + _ramBonus + _packageRamBonus);
|
|
}
|
|
|
|
public int EffectiveMaxCycles()
|
|
{
|
|
if (CurrentConfig?.IsLanguageTraining == true) return 6;
|
|
if (CurrentConfig?.IsTutorial == true) return Mathf.Max(4, CurrentConfig.Distro.BaseCyclesPerTurn) + _maxCyclesBonus;
|
|
return Mathf.Max(1, (CurrentConfig?.Distro?.BaseCyclesPerTurn ?? 1) + _maxCyclesBonus + _packageMaxCyclesBonus);
|
|
}
|
|
|
|
public static PackageStatImpact CalculatePackageStatImpact(DistroDefinition distro, IReadOnlyList<PackageInstance> packages)
|
|
{
|
|
PackageStatImpact impact = new(
|
|
Mathf.Max(1, distro == null ? 1 : distro.BaseUptime),
|
|
Mathf.Max(1, distro == null ? 1 : distro.BaseRam),
|
|
Mathf.Max(1, distro == null ? 1 : distro.BaseCyclesPerTurn));
|
|
if (packages == null)
|
|
{
|
|
return impact;
|
|
}
|
|
|
|
for (int i = 0; i < packages.Count; i++)
|
|
{
|
|
PackageInstance package = packages[i];
|
|
if (package?.Definition == null || package.Definition.Slot != PackageSlot.Kernel)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
foreach (PackageEffectData effect in package.EffectsFor(distro?.Id))
|
|
{
|
|
int amount = Mathf.Max(0, effect.Amount);
|
|
switch (effect.Kind)
|
|
{
|
|
case PackageEffectKind.MaxUptime:
|
|
impact.AddUptime(amount, package.Definition);
|
|
break;
|
|
case PackageEffectKind.MaxCycles:
|
|
impact.AddCycles(amount, package.Definition);
|
|
break;
|
|
case PackageEffectKind.MaxRam:
|
|
impact.AddRam(amount, package.Definition);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
return impact;
|
|
}
|
|
|
|
private void ApplyKernelPackageBonuses(RunConfig config)
|
|
{
|
|
PackageStatImpact impact = CalculatePackageStatImpact(config?.Distro, config?.EquippedPackages);
|
|
_packageMaxUptimeBonus = impact.UptimeBonus;
|
|
_packageMaxCyclesBonus = impact.CyclesBonus;
|
|
_packageRamBonus = impact.RamBonus;
|
|
}
|
|
|
|
public bool TrySettleRunRewards(out int bandwidth, out int entropy)
|
|
{
|
|
bandwidth = _accruedBandwidth;
|
|
entropy = _accruedEntropy;
|
|
if (_rewardsSettled)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
_rewardsSettled = true;
|
|
return bandwidth > 0 || entropy > 0;
|
|
}
|
|
|
|
public void MarkRunRewardsSettled()
|
|
{
|
|
_rewardsSettled = true;
|
|
}
|
|
|
|
private void HandleWaveCleared(WaveClearedEvent payload)
|
|
{
|
|
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)
|
|
{
|
|
_bits += RunJourney.ChallengeBits;
|
|
CardInstance reward = _runDeck.FirstOrDefault(card => card.Definition != null
|
|
&& !card.Definition.IsToken && !card.Definition.IsJunk && card.DrawRider == 0);
|
|
if (reward != null)
|
|
{
|
|
reward.ApplyDrawRider(1);
|
|
Journey.lastReward = $"Challenge cleared: +{RunJourney.ChallengeBits} Bits; {reward.Definition.DisplayName} now draws +1 on resolution.";
|
|
}
|
|
else
|
|
{
|
|
_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;
|
|
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)
|
|
{
|
|
_accruedBandwidth += CalculateBandwidthReward(clearedWave);
|
|
_accruedEntropy += CalculateEntropyReward(clearedWave);
|
|
}
|
|
currentWaveNumber = Mathf.Max(currentWaveNumber + 1, payload.WaveNumber + 1);
|
|
EnsureRouteSelection();
|
|
_repositoryOffers.Clear();
|
|
_rerollsThisVisit = 0;
|
|
_soldOfferKeys.Clear();
|
|
_repositoryVisitActive = false;
|
|
GameEvents.RaiseWaveAdvanced(new WaveAdvancedEvent(currentWaveNumber));
|
|
}
|
|
|
|
private void HandleRunEnded(RunEndedEvent payload)
|
|
{
|
|
FinalDeck = _runDeck.Select(CheckpointCard.Capture).ToList();
|
|
isRunActive = false;
|
|
isPlayerDead = payload.PlayerDied;
|
|
_bits = 0;
|
|
_repositoryOffers.Clear();
|
|
_repositoryVisitActive = false;
|
|
_runDeck.Clear();
|
|
_maxUptimeBonus = 0;
|
|
_maxCyclesBonus = 0;
|
|
_ramBonus = 0;
|
|
RepositoryChanged?.Invoke();
|
|
}
|
|
|
|
private static int CalculateBandwidthReward(int waveNumber)
|
|
{
|
|
int safeWave = Mathf.Max(1, waveNumber);
|
|
return Mathf.Max(0, CombatTuning.BandwidthBase + ((safeWave - 1) * CombatTuning.BandwidthPerWaveStep));
|
|
}
|
|
|
|
private static int CalculateEntropyReward(int waveNumber)
|
|
{
|
|
return waveNumber >= CombatTuning.EntropyStartWave ? Mathf.Max(0, CombatTuning.EntropyPerWave) : 0;
|
|
}
|
|
|
|
private void InitializeRunDeck(RunConfig config)
|
|
{
|
|
_runDeck.Clear();
|
|
if (config?.StartingDeck == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
for (int i = 0; i < config.StartingDeck.Count; i++)
|
|
{
|
|
CardDefinition definition = config.StartingDeck[i];
|
|
if (definition != null && (!definition.IsRunOnly || config.IsLanguageTraining))
|
|
{
|
|
_runDeck.Add(new CardInstance(definition));
|
|
}
|
|
}
|
|
}
|
|
|
|
private void FillRepositoryOffers(CardDatabase cardDatabase, LanguageDeckDatabase languageDeckDatabase)
|
|
{
|
|
if (CurrentConfig?.IsTutorial == true && _repositoryOffers.Count == 0)
|
|
{
|
|
// Teach a guaranteed real purchase, independent of random shop stock.
|
|
var target = _runDeck.First(card => card.Definition.Id == "lang_rs_unwrap");
|
|
_repositoryOffers.Add(RepositoryOffer.CardUpgrade(target, CardUpgradeKind.MagnitudeUp, CombatTuning.UpgradeOfferCost));
|
|
}
|
|
int guard = 0;
|
|
while (_repositoryOffers.Count < CombatTuning.ShopSize && guard < 80)
|
|
{
|
|
guard++;
|
|
RepositoryOffer offer = CreateRandomOffer(cardDatabase, languageDeckDatabase);
|
|
if (offer == null || _soldOfferKeys.Contains(OfferKey(offer)) || _repositoryOffers.Any(existing => IsDuplicateOffer(existing, offer)))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
_repositoryOffers.Add(offer);
|
|
}
|
|
}
|
|
|
|
private RepositoryOffer CreateRandomOffer(CardDatabase cardDatabase, LanguageDeckDatabase languageDeckDatabase)
|
|
{
|
|
int roll = _repositoryRandom.Next(0, 100);
|
|
if (roll < 45)
|
|
{
|
|
return CreateCardOffer(cardDatabase, languageDeckDatabase);
|
|
}
|
|
|
|
if (roll < 75)
|
|
{
|
|
return CreateUpgradeOffer();
|
|
}
|
|
|
|
return CreateStatOffer();
|
|
}
|
|
|
|
private RepositoryOffer CreateCardOffer(CardDatabase cardDatabase, LanguageDeckDatabase languageDeckDatabase)
|
|
{
|
|
List<CardDefinition> pool = BuildCardOfferPool(cardDatabase, languageDeckDatabase);
|
|
if (pool.Count == 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
CardDefinition selected = pool[_repositoryRandom.Next(0, pool.Count)];
|
|
return RepositoryOffer.NewCard(selected, selected.IsRunOnly ? CombatTuning.NewCardOfferCost + 1 : CombatTuning.NewCardOfferCost);
|
|
}
|
|
|
|
private RepositoryOffer CreateUpgradeOffer()
|
|
{
|
|
List<CardInstance> candidates = _runDeck.Where(card => card != null && card.CanReceiveRepositoryUpgrade).ToList();
|
|
if (candidates.Count == 0)
|
|
{
|
|
return CreateStatOffer();
|
|
}
|
|
|
|
CardInstance target = candidates[_repositoryRandom.Next(0, candidates.Count)];
|
|
CardUpgradeKind kind = (CardUpgradeKind)_repositoryRandom.Next(0, 3);
|
|
if (kind == CardUpgradeKind.CostDown && CombatManager.GetCardCost(target) <= 0)
|
|
{
|
|
kind = CardUpgradeKind.MagnitudeUp;
|
|
}
|
|
|
|
return RepositoryOffer.CardUpgrade(target, kind, CombatTuning.UpgradeOfferCost);
|
|
}
|
|
|
|
private RepositoryOffer CreateStatOffer()
|
|
{
|
|
RunStatUpgradeKind kind = (RunStatUpgradeKind)_repositoryRandom.Next(0, 4);
|
|
return RepositoryOffer.StatUpgrade(kind, CombatTuning.StatUpgradeCost);
|
|
}
|
|
|
|
private List<CardDefinition> BuildCardOfferPool(CardDatabase cardDatabase, LanguageDeckDatabase languageDeckDatabase)
|
|
{
|
|
List<CardDefinition> pool = new();
|
|
AddLanguageCards(languageDeckDatabase, CurrentConfig?.PrimaryLanguage ?? Language.Python, pool, 3);
|
|
AddLanguageCards(languageDeckDatabase, CurrentConfig?.SecondaryLanguage ?? Language.JavaScript, pool, 3);
|
|
|
|
if (cardDatabase != null)
|
|
{
|
|
for (int i = 0; i < cardDatabase.AllCards.Count; i++)
|
|
{
|
|
CardDefinition card = cardDatabase.AllCards[i];
|
|
if (card == null || card.IsToken)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (card.Language == CurrentConfig.PrimaryLanguage || card.Language == CurrentConfig.SecondaryLanguage)
|
|
{
|
|
pool.Add(card);
|
|
}
|
|
}
|
|
}
|
|
|
|
return pool;
|
|
}
|
|
|
|
private static void AddLanguageCards(LanguageDeckDatabase languageDeckDatabase, Language language, List<CardDefinition> pool, int weight)
|
|
{
|
|
LanguageDeckDefinition deck = languageDeckDatabase == null ? null : languageDeckDatabase.FindByLanguage(language);
|
|
if (deck == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
for (int i = 0; i < deck.Entries.Count; i++)
|
|
{
|
|
CardDefinition card = deck.Entries[i].Card;
|
|
if (card == null || card.IsToken || card.IsRunOnly)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
for (int copy = 0; copy < Mathf.Max(1, weight); copy++)
|
|
{
|
|
pool.Add(card);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static bool IsDuplicateOffer(RepositoryOffer left, RepositoryOffer right)
|
|
{
|
|
if (left.Kind != right.Kind)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return left.Kind switch
|
|
{
|
|
RepositoryOfferKind.NewCard => left.CardDefinition == right.CardDefinition,
|
|
RepositoryOfferKind.CardUpgrade => left.TargetCard == right.TargetCard && left.CardUpgradeKind == right.CardUpgradeKind,
|
|
RepositoryOfferKind.StatUpgrade => left.StatUpgradeKind == right.StatUpgradeKind,
|
|
_ => false
|
|
};
|
|
}
|
|
|
|
private static string OfferKey(RepositoryOffer offer)
|
|
{
|
|
if (offer == null)
|
|
{
|
|
return string.Empty;
|
|
}
|
|
|
|
return offer.Kind switch
|
|
{
|
|
RepositoryOfferKind.NewCard => $"card:{offer.CardDefinition?.Id}",
|
|
RepositoryOfferKind.CardUpgrade => $"upgrade:{offer.TargetCard?.Definition?.Id}:{offer.TargetCard?.InstanceId}:{offer.CardUpgradeKind}",
|
|
RepositoryOfferKind.StatUpgrade => $"stat:{offer.StatUpgradeKind}",
|
|
_ => offer.DisplayName
|
|
};
|
|
}
|
|
|
|
private bool AddCardToRunDeck(CardDefinition card)
|
|
{
|
|
if (card == null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
_runDeck.Add(new CardInstance(card));
|
|
return true;
|
|
}
|
|
|
|
private static bool ApplyCardUpgrade(CardInstance card, CardUpgradeKind kind)
|
|
{
|
|
if (card == null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return kind switch
|
|
{
|
|
CardUpgradeKind.CostDown => card.ApplyCostUpgrade(-1),
|
|
CardUpgradeKind.MagnitudeUp => card.ApplyMagnitudeUpgrade(CombatTuning.UpgradeMagnitudeBonus),
|
|
CardUpgradeKind.DrawRider => card.ApplyDrawRider(1),
|
|
_ => false
|
|
};
|
|
}
|
|
|
|
private bool ApplyStatUpgrade(RunStatUpgradeKind kind, CombatantState playerState)
|
|
{
|
|
switch (kind)
|
|
{
|
|
case RunStatUpgradeKind.MaxCycles:
|
|
_maxCyclesBonus += CombatTuning.StatUpgradeMaxCycles;
|
|
if (playerState != null)
|
|
{
|
|
playerState.MaxCycles += CombatTuning.StatUpgradeMaxCycles;
|
|
playerState.Cycles += CombatTuning.StatUpgradeMaxCycles;
|
|
}
|
|
return true;
|
|
case RunStatUpgradeKind.MaxUptime:
|
|
int uptimeBonus = CombatTuning.ScaleStatUpgradeMaxUptime(playerState == null ? EffectiveMaxUptime() : playerState.MaxUptime);
|
|
_maxUptimeBonus += uptimeBonus;
|
|
if (playerState != null)
|
|
{
|
|
playerState.MaxUptime += uptimeBonus;
|
|
}
|
|
return true;
|
|
case RunStatUpgradeKind.Heal:
|
|
if (playerState == null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
int healAmount = CombatTuning.ScaleStatUpgradeHeal(playerState.MaxUptime);
|
|
playerState.CurrentUptime = Mathf.Min(playerState.MaxUptime, playerState.CurrentUptime + healAmount);
|
|
return true;
|
|
case RunStatUpgradeKind.Ram:
|
|
_ramBonus += CombatTuning.StatUpgradeRam;
|
|
if (playerState != null)
|
|
{
|
|
playerState.Ram += CombatTuning.StatUpgradeRam;
|
|
}
|
|
return true;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
|
|
public struct PackageStatImpact
|
|
{
|
|
private readonly List<string> _uptimeSources;
|
|
private readonly List<string> _ramSources;
|
|
private readonly List<string> _cyclesSources;
|
|
|
|
public PackageStatImpact(int baseUptime, int baseRam, int baseCycles)
|
|
{
|
|
BaseUptime = baseUptime;
|
|
BaseRam = baseRam;
|
|
BaseCycles = baseCycles;
|
|
UptimeBonus = 0;
|
|
RamBonus = 0;
|
|
CyclesBonus = 0;
|
|
_uptimeSources = new List<string>();
|
|
_ramSources = new List<string>();
|
|
_cyclesSources = new List<string>();
|
|
}
|
|
|
|
public int BaseUptime { get; }
|
|
public int BaseRam { get; }
|
|
public int BaseCycles { get; }
|
|
public int UptimeBonus { get; private set; }
|
|
public int RamBonus { get; private set; }
|
|
public int CyclesBonus { get; private set; }
|
|
public int FinalUptime => Mathf.Max(1, BaseUptime + UptimeBonus);
|
|
public int FinalRam => Mathf.Max(1, BaseRam + RamBonus);
|
|
public int FinalCycles => Mathf.Max(1, BaseCycles + CyclesBonus);
|
|
public IReadOnlyList<string> UptimeSources => _uptimeSources;
|
|
public IReadOnlyList<string> RamSources => _ramSources;
|
|
public IReadOnlyList<string> CyclesSources => _cyclesSources;
|
|
|
|
public void AddUptime(int amount, PackageDefinition source)
|
|
{
|
|
if (amount <= 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
UptimeBonus += amount;
|
|
AddSource(source, _uptimeSources);
|
|
}
|
|
|
|
public void AddRam(int amount, PackageDefinition source)
|
|
{
|
|
if (amount <= 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
RamBonus += amount;
|
|
AddSource(source, _ramSources);
|
|
}
|
|
|
|
public void AddCycles(int amount, PackageDefinition source)
|
|
{
|
|
if (amount <= 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
CyclesBonus += amount;
|
|
AddSource(source, _cyclesSources);
|
|
}
|
|
|
|
private static void AddSource(PackageDefinition source, List<string> sources)
|
|
{
|
|
string name = source == null ? null : string.IsNullOrWhiteSpace(source.DisplayName) ? source.Id : source.DisplayName;
|
|
if (!string.IsNullOrWhiteSpace(name))
|
|
{
|
|
sources.Add(name);
|
|
}
|
|
}
|
|
}
|
|
}
|