895 lines
44 KiB
C#
895 lines
44 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Text.Json;
|
||
|
||
namespace GladiatorIdle
|
||
{
|
||
public enum GameEventType { FightStarted, FightWon, FightLost, LevelUp, Purchased, ArenaUnlocked, FreedomEarned,
|
||
CharLevelUp, Loot, LootSold, ExpeditionDone, EventStarted }
|
||
|
||
/// Ereignis für Anzeige/Ton. A/B: Beträge (Gold, Ruhm, Stufe …), Key: Gegner/Wert/Upgrade.
|
||
internal readonly record struct GameEvent(GameEventType Type, double A = 0, double B = 0, string? Key = null);
|
||
|
||
/// Ein freigelassener Gladiator in der Ehrenhalle.
|
||
internal sealed record Legend(string Name, GladiatorClass Class, int Number, int Wins, double Fame, double RunSeconds, DateTime DateUtc,
|
||
int Level = 0, double Power = 0);
|
||
|
||
/// Was während der Abwesenheit passiert ist.
|
||
internal sealed record OfflineReport(double Seconds, double Gold, double Fame, int Wins, int Losses, int LevelUps);
|
||
|
||
/// <summary>
|
||
/// Der ganze Spielstand und die Spiel-Logik (ohne Grafik). Die Anzeige ruft
|
||
/// <see cref="Tick"/> im Takt auf, leitet Klicks/Käufe weiter und liest <see cref="Events"/>.
|
||
/// Ein Leben = ein Gladiator vom Sklaven bis zur Freiheit; das Profil (Götter, Ehrenhalle)
|
||
/// bleibt über alle Leben.
|
||
/// </summary>
|
||
internal sealed class GameState
|
||
{
|
||
// ── Profil (bleibt über die Freiheit hinaus) ────────────────
|
||
public int Freedoms { get; private set; }
|
||
public int GodFavor { get; private set; }
|
||
public int[] GodLevels { get; private set; } = new int[6];
|
||
public List<Legend> Legends { get; private set; } = new();
|
||
public double LifetimeFame { get; private set; }
|
||
/// Legenden (Nummern), die im Duell schon besiegt wurden (Lohn nur beim ersten Sieg).
|
||
public HashSet<int> LegendsBeaten { get; private set; } = new();
|
||
|
||
// ── Dieses Leben ────────────────────────────────────────────
|
||
public string Name { get; private set; } = "";
|
||
public GladiatorClass Class { get; private set; }
|
||
/// Aussehen des eigenen Gladiators (Erstellung); bleibt über Leben hinweg.
|
||
public Appearance Look { get; set; } = new();
|
||
/// Zusätzliche Fähigkeitspunkte (Startfähigkeit bei der Erstellung).
|
||
public int ExtraSkillPoints { get; private set; }
|
||
public int[] StatLevels { get; private set; } = new int[4];
|
||
public double[] StatXp { get; private set; } = new double[4];
|
||
public Dictionary<string, int> Upgrades { get; private set; } = new();
|
||
public double Gold { get; private set; }
|
||
public double GoldEarnedRun { get; private set; }
|
||
public double FameRun { get; private set; }
|
||
public double Crowd { get; private set; }
|
||
public int Arena { get; private set; }
|
||
public int Rank { get; private set; }
|
||
public bool FreedomEarned { get; private set; }
|
||
public int Wins { get; private set; }
|
||
public int Losses { get; private set; }
|
||
public double RunSeconds { get; private set; }
|
||
|
||
// Gladiator-Stufe und Attributpunkte (Kampf-Erfahrung, je Stufe frei verteilbar)
|
||
public int CharLevel { get; private set; }
|
||
public double CharXp { get; private set; }
|
||
public int AttrPoints { get; private set; }
|
||
public int[] StatBonus { get; private set; } = new int[4];
|
||
/// Gelernte Fähigkeiten (Rang je Id).
|
||
public Dictionary<string, int> SkillRanks { get; private set; } = new();
|
||
|
||
// Ausrüstung: angelegt (je Slot), Inventar
|
||
public Item?[] Equipped { get; private set; } = new Item?[5];
|
||
/// Verstärkung je Slot beim Schmied (bleibt beim Wechsel des Gegenstands).
|
||
public int[] SlotLevels { get; private set; } = new int[5];
|
||
public List<Item> Inventory { get; private set; } = new();
|
||
long _nextItemId = 1;
|
||
|
||
// Expedition, Ereignisse, Segen
|
||
public Expedition? Away { get; private set; }
|
||
/// Bericht der letzten Expedition, bis der Spieler ihn bestätigt (auch nach Offline-Zeit).
|
||
public ExpeditionReport? ExpeditionResult { get; private set; }
|
||
/// Ereignis, das auf eine Entscheidung wartet (Anzeige hält das Spiel an).
|
||
public string? PendingEvent { get; private set; }
|
||
public double EventIn { get; private set; } = Adventures.EVENT_MIN;
|
||
public List<ActiveBuff> Buffs { get; private set; } = new();
|
||
string? _lastEvent;
|
||
|
||
// ── Laufend (nicht gespeichert) ─────────────────────────────
|
||
/// Erholung nach einer Niederlage: so lange kein Kampf.
|
||
public double Recovery { get; private set; }
|
||
public List<GameEvent> Events { get; } = new();
|
||
/// Aus = keine Ereignis-Listen (Offline-Rechnung, Bot).
|
||
public bool CollectEvents { get; set; } = true;
|
||
|
||
int _lossStreak;
|
||
double _pendingInherit;
|
||
readonly Random _rng;
|
||
|
||
public GameState(int? seed = null) => _rng = seed is int s ? new Random(s) : new Random();
|
||
|
||
public ClassDef ClassDef => ClassDef.Of(Class);
|
||
/// Wirksame Stufe eines Werts: trainiert + verteilte Attributpunkte.
|
||
public int Level(Stat s) => StatLevels[(int)s] + StatBonus[(int)s];
|
||
public int UpgradeLevel(string id) => Upgrades.TryGetValue(id, out int l) ? l : 0;
|
||
public int GodLevel(God g) => GodLevels[(int)g];
|
||
public int Tier => Arena * Balance.RANKS_PER_ARENA + Math.Min(Rank, Balance.RANKS_PER_ARENA - 1);
|
||
public bool IsLastArena => Arena == Balance.ARENA_COUNT - 1;
|
||
|
||
/// Neues Leben (erstes Spiel oder nach der Freiheit). Profil bleibt.
|
||
public void NewRun(string name, GladiatorClass cls)
|
||
{
|
||
Name = name; Class = cls;
|
||
StatLevels = (int[])ClassDef.Of(cls).StartLevels.Clone();
|
||
StatXp = new double[4];
|
||
Upgrades = new();
|
||
Gold = _pendingInherit; _pendingInherit = 0;
|
||
GoldEarnedRun = FameRun = Crowd = RunSeconds = 0;
|
||
Arena = Rank = Wins = Losses = _lossStreak = 0;
|
||
FreedomEarned = false;
|
||
Recovery = 0;
|
||
CharLevel = 0; CharXp = 0; AttrPoints = 0; StatBonus = new int[4]; SkillRanks = new(); ExtraSkillPoints = 0;
|
||
Equipped = new Item?[5];
|
||
SlotLevels = new int[5];
|
||
Away = null; ExpeditionResult = null; PendingEvent = null; Buffs = new();
|
||
EventIn = Adventures.EVENT_MIN;
|
||
Inventory = new();
|
||
foreach (var b in Items.StartKit(cls))
|
||
{
|
||
var it = new Item { Id = _nextItemId++, Base = b, Rarity = Rarity.Common, Level = 0 };
|
||
Equipped[(int)it.Slot] = it;
|
||
}
|
||
}
|
||
|
||
// ── Erstellung ──────────────────────────────────────────────
|
||
|
||
/// Punkte, die bei der Erstellung frei auf die Werte verteilt werden.
|
||
public const int CREATE_POINTS = 5;
|
||
|
||
/// Fähigkeiten, aus denen bei der Erstellung eine gewählt wird (erste Stufe je Zweig).
|
||
public static System.Collections.Generic.IEnumerable<SkillDef> StartSkills(GladiatorClass c) =>
|
||
SkillDef.For(c).Where(s => s.Tier == 0);
|
||
|
||
/// Eigener Gladiator: neues Leben mit Aussehen, verteilten Startpunkten und Startfähigkeit.
|
||
public void Create(string name, GladiatorClass cls, Appearance look, int[] bonus, string? startSkill)
|
||
{
|
||
NewRun(name, cls);
|
||
Look = look;
|
||
for (int i = 0; i < 4 && i < bonus.Length; i++) StatBonus[i] += System.Math.Max(0, bonus[i]);
|
||
if (startSkill != null && StartSkills(cls).Any(s => s.Id == startSkill))
|
||
{
|
||
ExtraSkillPoints = 1;
|
||
Learn(startSkill);
|
||
}
|
||
}
|
||
|
||
// ── Stufe & Attributpunkte ──────────────────────────────────
|
||
|
||
public double CharXpToNext => Balance.CharXpToNext(CharLevel);
|
||
|
||
void AddCharXp(double xp)
|
||
{
|
||
CharXp += xp * Gear.XpMult * BuffMult(BuffKind.Xp);
|
||
while (CharXp >= CharXpToNext)
|
||
{
|
||
CharXp -= CharXpToNext;
|
||
CharLevel++;
|
||
AttrPoints += Balance.POINTS_PER_LEVEL;
|
||
Emit(new GameEvent(GameEventType.CharLevelUp, CharLevel));
|
||
}
|
||
}
|
||
|
||
// ── Fähigkeiten ─────────────────────────────────────────────
|
||
|
||
public int SkillRank(string id) => SkillRanks.TryGetValue(id, out int r) ? r : 0;
|
||
public int SkillPointsTotal => CharLevel / 2 + ExtraSkillPoints;
|
||
public int SkillPoints => SkillPointsTotal - SkillRanks.Values.Sum();
|
||
public int BranchPoints(SkillBranch b) => SkillRanks.Where(kv => SkillDef.Get(kv.Key).Branch == b).Sum(kv => kv.Value);
|
||
public SkillPerks Perks => SkillPerks.From(SkillRank);
|
||
|
||
public bool CanLearn(SkillDef s) =>
|
||
SkillPoints > 0 && SkillRank(s.Id) < s.MaxRank && (s.Class == null || s.Class == Class)
|
||
&& BranchPoints(s.Branch) >= s.Requires;
|
||
|
||
/// Gibt es gerade etwas zu lernen? (Anzeige freier Punkte)
|
||
public int LearnablePoints => SkillDef.For(Class).Any(CanLearn) ? SkillPoints : 0;
|
||
|
||
public bool Learn(string id)
|
||
{
|
||
var s = SkillDef.Get(id);
|
||
if (!CanLearn(s)) return false;
|
||
SkillRanks[id] = SkillRank(id) + 1;
|
||
return true;
|
||
}
|
||
|
||
/// Alle Fähigkeiten verlernen (Punkte zurück) gegen Gold.
|
||
public double SkillResetCost => 20 * Balance.GoldPerWin(Tier);
|
||
|
||
public bool ResetSkills()
|
||
{
|
||
if (SkillRanks.Count == 0 || Gold < SkillResetCost) return false;
|
||
Gold -= SkillResetCost;
|
||
SkillRanks = new();
|
||
return true;
|
||
}
|
||
|
||
public bool SpendPoint(Stat s)
|
||
{
|
||
if (AttrPoints <= 0) return false;
|
||
AttrPoints--;
|
||
StatBonus[(int)s]++;
|
||
return true;
|
||
}
|
||
|
||
// ── Ausrüstung ──────────────────────────────────────────────
|
||
|
||
public GearStats Gear => Items.Stats(Equipped, SlotLevels);
|
||
|
||
/// Produkt aller laufenden Segen einer Art (1 = keiner).
|
||
public double BuffMult(BuffKind k)
|
||
{
|
||
double m = 1;
|
||
foreach (var b in Buffs) if (b.Kind == k) m *= b.Mult;
|
||
return m;
|
||
}
|
||
|
||
/// Kampfkraft als eine Zahl (zum Vergleichen): Schaden × Krit × wirksames Leben, Wurzel gezogen.
|
||
public double Power(Combatant? c = null)
|
||
{
|
||
var p = c ?? PlayerCombat();
|
||
return Math.Sqrt(p.Damage * (1 + p.Crit * (p.CritMult - 1)) * p.MaxHp / p.DamageTakenMult);
|
||
}
|
||
|
||
/// Kampfkraft, wenn <paramref name="item"/> statt des jetzigen Gegenstands im Slot läge.
|
||
public double PowerWith(Item item)
|
||
{
|
||
var old = Equipped[(int)item.Slot];
|
||
Equipped[(int)item.Slot] = item;
|
||
double p = Power();
|
||
Equipped[(int)item.Slot] = old;
|
||
return p;
|
||
}
|
||
|
||
public Item? FindItem(long id) => Inventory.FirstOrDefault(i => i.Id == id);
|
||
|
||
/// Gegenstand aus dem Inventar anlegen; der bisherige kommt ins Inventar.
|
||
public bool Equip(long id)
|
||
{
|
||
var it = FindItem(id);
|
||
if (it == null) return false;
|
||
Inventory.Remove(it);
|
||
var old = Equipped[(int)it.Slot];
|
||
Equipped[(int)it.Slot] = it;
|
||
if (old != null) Inventory.Add(old);
|
||
return true;
|
||
}
|
||
|
||
public bool Sell(long id)
|
||
{
|
||
var it = FindItem(id);
|
||
if (it == null) return false;
|
||
Inventory.Remove(it);
|
||
EarnGold(Items.SellValue(it), "sell");
|
||
return true;
|
||
}
|
||
|
||
/// Wert aller Stücke im Inventar beim Verkauf.
|
||
public double InventoryValue => Inventory.Sum(Items.SellValue);
|
||
|
||
/// Ganzes Inventar verkaufen (angelegte Ausrüstung bleibt). Liefert den Erlös.
|
||
public double SellAll()
|
||
{
|
||
double total = InventoryValue;
|
||
Inventory.Clear();
|
||
if (total > 0) EarnGold(total, "sell");
|
||
return total;
|
||
}
|
||
|
||
/// Schmied: einen Slot verstärken (gilt für jeden Gegenstand, der dort liegt).
|
||
public double UpgradeSlotCost(ItemSlot slot) => Items.SlotCost(SlotLevels[(int)slot]);
|
||
|
||
public bool UpgradeSlot(ItemSlot slot)
|
||
{
|
||
double cost = UpgradeSlotCost(slot);
|
||
if (Gold < cost) return false;
|
||
Gold -= cost;
|
||
SlotLevels[(int)slot]++;
|
||
Emit(new GameEvent(GameEventType.Purchased, SlotLevels[(int)slot], cost, "slot." + slot.ToString().ToLowerInvariant()));
|
||
return true;
|
||
}
|
||
|
||
/// Für jeden Slot das Stück mit der höchsten Kampfkraft anlegen (Knopf "Bestes anlegen", Bot).
|
||
public int EquipBest()
|
||
{
|
||
int changed = 0;
|
||
foreach (ItemSlot slot in Enum.GetValues<ItemSlot>())
|
||
{
|
||
double best = Power();
|
||
Item? pick = null;
|
||
foreach (var it in Inventory.Where(i => i.Slot == slot))
|
||
{
|
||
double p = PowerWith(it);
|
||
if (p > best * 1.0001) { best = p; pick = it; }
|
||
}
|
||
if (pick != null && Equip(pick.Id)) changed++;
|
||
}
|
||
return changed;
|
||
}
|
||
|
||
void AddLoot(Item it)
|
||
{
|
||
if (Inventory.Count >= Items.INVENTORY)
|
||
{
|
||
// voll: das schwächste Stück (nach Wert) wird automatisch verkauft
|
||
var worst = Inventory.Append(it).OrderBy(Items.Value).First();
|
||
if (worst != it) { Inventory.Remove(worst); Inventory.Add(it); }
|
||
EarnGold(Items.SellValue(worst), "sell");
|
||
Emit(new GameEvent(GameEventType.LootSold, Items.SellValue(worst), (int)worst.Rarity, worst.Base));
|
||
if (worst == it) return;
|
||
}
|
||
else Inventory.Add(it);
|
||
Emit(new GameEvent(GameEventType.Loot, it.Level, (int)it.Rarity, it.Base));
|
||
}
|
||
|
||
// ── Abgeleitete Werte ───────────────────────────────────────
|
||
|
||
double AllMult => Gods.AllMult(GodLevel(God.Jupiter));
|
||
|
||
public double XpMult(Stat s) =>
|
||
ClassDef.XpMult[(int)s] * (1 + 0.15 * UpgradeLevel("building.kitchen"))
|
||
* Gods.XpMult(GodLevel(God.Minerva)) * AllMult * Gear.XpMult * BuffMult(BuffKind.Xp);
|
||
|
||
/// XP pro Sekunde der Ausbilder für diesen Wert (mit allen Boni).
|
||
public double TrainerXpPerSec(Stat s)
|
||
{
|
||
int t = UpgradeLevel(UpgradeDef.TrainerFor(s).Id);
|
||
return t == 0 ? 0 : 0.6 * t * Math.Pow(1.08, t) * XpMult(s);
|
||
}
|
||
|
||
/// Tägliches Training im Ludus (feste Aufteilung): XP/s für diesen Wert, wächst mit den Ausbildern.
|
||
public double DrillXpPerSec(Stat s)
|
||
{
|
||
double trainers = 0;
|
||
for (int i = 0; i < 4; i++) trainers += TrainerXpPerSec((Stat)i);
|
||
return (Balance.DRILL_BASE * XpMult(s) + Balance.DRILL_TRAINER_SHARE * trainers) * Balance.DRILL_SPLIT[(int)s];
|
||
}
|
||
|
||
/// Gesamt-XP/s eines Werts (früheres passives Training; nur noch Anzeige/Bot-Vergleich).
|
||
public double XpPerSec(Stat s) => TrainerXpPerSec(s) + DrillXpPerSec(s);
|
||
|
||
// ── Training im Ludus (aktiv) ───────────────────────────────
|
||
|
||
/// Trainingsenergie (0 … 5), eine Einheit je Übung, füllt sich mit der Zeit (auch offline).
|
||
public double TrainEnergy { get; private set; } = Balance.TRAIN_ENERGY_MAX;
|
||
public bool CanTrain => TrainEnergy >= 1 && Away == null;
|
||
/// Sekunden bis zur nächsten vollen Einheit (0 = voll).
|
||
public double TrainEnergyNextIn => TrainEnergy >= Balance.TRAIN_ENERGY_MAX ? 0 : (1 - TrainEnergy % 1) * Balance.TRAIN_ENERGY_SECONDS;
|
||
public double TrainFactor(Stat s) => (1 + Balance.TRAIN_TRAINER_BONUS * UpgradeLevel(UpgradeDef.TrainerFor(s).Id)) * XpMult(s);
|
||
/// XP je gelungener Aktion für diesen Wert (wächst mit der Stufe, den Ausbildern und Boni).
|
||
public double TrainXpPerAction(Stat s) => Balance.XpToNext(Level(s)) * Balance.TRAIN_LEVEL_PER_ACTION * TrainFactor(s);
|
||
|
||
/// Übung abgeschlossen: Energie verbrauchen, XP gutschreiben. Liefert die XP.
|
||
public double Train(Stat s, int actions)
|
||
{
|
||
if (TrainEnergy < 1) return 0;
|
||
TrainEnergy -= 1;
|
||
double xp = 0;
|
||
for (int i = 0; i < actions; i++) { double x = TrainXpPerAction(s); AddXp(s, x); xp += x; }
|
||
return xp;
|
||
}
|
||
|
||
public double XpToNext(Stat s) => Balance.XpToNext(Level(s));
|
||
|
||
public Combatant PlayerCombat()
|
||
{
|
||
var gear = Gear;
|
||
var perks = Perks;
|
||
double agi = Math.Max(0, Level(Stat.Agility) + gear.Agility + perks.AgiAdd);
|
||
double block = gear.Block + perks.BlockAdd;
|
||
return new Combatant(
|
||
MaxHp: Balance.BaseHp(Level(Stat.Endurance)) * gear.HpMult
|
||
* (1 + 0.08 * UpgradeLevel("building.medicus")) * Gods.HpMult(GodLevel(God.Apollo)) * BuffMult(BuffKind.Health) * perks.HpMult,
|
||
Damage: Balance.BaseDamage(Level(Stat.Strength)) * gear.DmgMult * Gods.DamageMult(GodLevel(God.Mars)) * BuffMult(BuffKind.Damage) * perks.DmgMult,
|
||
Agility: agi,
|
||
Crit: Math.Min(0.75, Balance.CritChance(agi) + ClassDef.CritBonus + Gods.CritBonus(GodLevel(God.Fortuna)) + gear.Crit + perks.CritAdd),
|
||
DamageTakenMult: (1 - 0.5 * block / (block + 8.0)) * perks.TakenMult,
|
||
CritMult: perks.CritMult, Execute: perks.Execute, SecondWind: perks.SecondWind);
|
||
}
|
||
|
||
public double GoldMult => Balance.CrowdMult(Crowd) * Gods.GoldMult(GodLevel(God.Fortuna)) * AllMult * Gear.GoldMult * BuffMult(BuffKind.Gold);
|
||
public double FameMult => Balance.CrowdMult(Crowd) * Balance.FameMult(Level(Stat.Showmanship)) * AllMult;
|
||
|
||
public double RecoveryTime =>
|
||
Balance.RECOVERY_TIME * Math.Pow(0.88, UpgradeLevel("building.baths")) * Gods.RecoveryMult(GodLevel(God.Apollo)) * Perks.RecoveryMult;
|
||
|
||
public double FameRequired => Balance.FameRequired(Arena) * Balance.MANUAL_FAME[Arena];
|
||
public bool CanChallenge => !FreedomEarned && FameRun >= FameRequired;
|
||
|
||
// ── Takt ────────────────────────────────────────────────────
|
||
|
||
public void Tick(double dt)
|
||
{
|
||
RunSeconds += dt;
|
||
Crowd = Math.Max(0, Crowd - Balance.CROWD_DECAY * Gods.CrowdDecayMult(GodLevel(God.Bacchus)) * dt);
|
||
TrainEnergy = Math.Min(Balance.TRAIN_ENERGY_MAX, TrainEnergy + dt / Balance.TRAIN_ENERGY_SECONDS);
|
||
Recovery = Math.Max(0, Recovery - dt);
|
||
for (int i = Buffs.Count - 1; i >= 0; i--)
|
||
if ((Buffs[i].Left -= dt) <= 0) Buffs.RemoveAt(i);
|
||
// Ereignisse nur beim aktiven Spielen (nicht offline, nicht unterwegs)
|
||
if (CollectEvents && Away == null && PendingEvent == null && (EventIn -= dt) <= 0) StartEvent();
|
||
if (Away != null && (Away.Left -= dt) <= 0) FinishExpedition(); // unterwegs: kein Kampf, Training läuft weiter
|
||
}
|
||
|
||
/// Ergebnis eines Duells: Lohn, Aufstieg bzw. Niederlage.
|
||
/// <paramref name="bonus"/>: Faktor auf Gold/Ruhm/Erfahrung (Wahl des Gegners).
|
||
void ApplyResult(Enemy enemy, bool won, double bonus)
|
||
{
|
||
var f = (Enemy: enemy, Won: won);
|
||
if (f.Won)
|
||
{
|
||
Wins++; _lossStreak = 0;
|
||
double reward = (f.Enemy.IsChampion ? Balance.CHAMPION_REWARD : 1) * bonus;
|
||
double gold = Balance.GoldPerWin(f.Enemy.Tier) * Balance.FIGHT_GOLD * reward * GoldMult;
|
||
double fame = Balance.FamePerWin(f.Enemy.Tier) * reward * FameMult;
|
||
EarnGold(gold, "fight");
|
||
FameRun += fame;
|
||
Crowd = Math.Min(100, Crowd + Balance.CROWD_WIN * CrowdGain);
|
||
Emit(new GameEvent(GameEventType.FightWon, gold, fame, f.Enemy.NameKey));
|
||
AddCharXp(Balance.CharXpPerWin(f.Enemy.Tier) * reward);
|
||
if (Items.Drop(_rng, f.Enemy.Tier, f.Enemy.IsChampion || bonus > 1, _nextItemId) is Item loot) { _nextItemId++; AddLoot(loot); }
|
||
if (f.Enemy.IsChampion)
|
||
{
|
||
if (IsLastArena)
|
||
{
|
||
FreedomEarned = true;
|
||
Emit(new GameEvent(GameEventType.FreedomEarned));
|
||
}
|
||
else
|
||
{
|
||
Arena++; Rank = 0;
|
||
Emit(new GameEvent(GameEventType.ArenaUnlocked, Arena));
|
||
}
|
||
}
|
||
else if (Rank < Balance.RANKS_PER_ARENA - 1) Rank++;
|
||
}
|
||
else
|
||
{
|
||
Losses++;
|
||
Crowd = Math.Max(0, Crowd - Balance.CROWD_LOSS);
|
||
Recovery = RecoveryTime;
|
||
// zweimal hintereinander verloren: eine Stufe leichter, damit Idle weiterläuft
|
||
if (++_lossStreak >= 2 && !f.Enemy.IsChampion && Rank > 0) { Rank--; _lossStreak = 0; }
|
||
Emit(new GameEvent(GameEventType.FightLost, 0, 0, f.Enemy.NameKey));
|
||
}
|
||
}
|
||
|
||
void EarnGold(double g, string source = "other") { Gold += g; GoldEarnedRun += g; GoldBySource[source] = GoldBySource.GetValueOrDefault(source) + g; }
|
||
/// Einnahmen je Quelle in diesem Spiel (nicht gespeichert; Balance-Bot).
|
||
public Dictionary<string, double> GoldBySource { get; } = new();
|
||
|
||
/// Gewinn an Gunst der Menge: Showtalent, Bacchus, Ausrüstung.
|
||
double CrowdGain => Balance.CrowdGainMult(Level(Stat.Showmanship)) * Gods.CrowdGainMult(GodLevel(God.Bacchus)) * Gear.CrowdMult;
|
||
|
||
void AddXp(Stat s, double xp)
|
||
{
|
||
int i = (int)s;
|
||
StatXp[i] += xp;
|
||
while (StatXp[i] >= Balance.XpToNext(StatLevels[i]))
|
||
{
|
||
StatXp[i] -= Balance.XpToNext(StatLevels[i]);
|
||
StatLevels[i]++;
|
||
Emit(new GameEvent(GameEventType.LevelUp, StatLevels[i], 0, s.ToString()));
|
||
}
|
||
}
|
||
|
||
void Emit(GameEvent e) { if (CollectEvents) Events.Add(e); }
|
||
|
||
// ── Aktionen des Spielers ───────────────────────────────────
|
||
|
||
// ── Expeditionen ────────────────────────────────────────────
|
||
|
||
public bool RegionOpen(RegionDef r) => Arena >= r.Unlock;
|
||
public double ExpeditionChance(RegionDef r) => Adventures.Chance(Power(), r);
|
||
|
||
/// Aufbrechen (ein laufender normaler Kampf wird abgebrochen, ohne Folgen).
|
||
public bool StartExpedition(string region, int duration)
|
||
{
|
||
var r = RegionDef.Get(region);
|
||
if (Away != null || !RegionOpen(r) || FreedomEarned) return false;
|
||
Recovery = 0;
|
||
Away = new Expedition { Region = region, Duration = duration, Left = Adventures.Durations[duration], Chance = ExpeditionChance(r) };
|
||
return true;
|
||
}
|
||
|
||
/// Zurückrufen: sofort zurück, ohne Belohnung.
|
||
public void Recall() { Away = null; }
|
||
|
||
void FinishExpedition()
|
||
{
|
||
var a = Away!;
|
||
Away = null;
|
||
var r = RegionDef.Get(a.Region);
|
||
bool ok = DevExpeditionOutcome ?? _rng.NextDouble() < a.Chance;
|
||
// Lohn in "Siegen" der Region: weniger, als man in der Zeit selbst erkämpfen würde – Hauptlohn ist die Beute
|
||
double fights = Adventures.Wins[a.Duration];
|
||
double share = ok ? 1 : 0.5;
|
||
var rep = new ExpeditionReport
|
||
{
|
||
Region = a.Region, Success = ok,
|
||
Gold = Balance.GoldPerWin(r.Tier) * GoldMult * fights * Balance.EXPEDITION_GOLD * share,
|
||
Fame = Balance.FamePerWin(r.Tier) * FameMult * fights * 0.5 * share,
|
||
Xp = Balance.CharXpPerWin(r.Tier) * fights * 0.8 * share,
|
||
};
|
||
EarnGold(rep.Gold, "expedition");
|
||
FameRun += rep.Fame;
|
||
AddCharXp(rep.Xp);
|
||
if (ok)
|
||
for (int i = 0; i < 1 + 2 * a.Duration; i++)
|
||
{
|
||
var it = Items.Create(_rng, Items.DropLevel(r.Tier, _rng) + 2,
|
||
(Rarity)Math.Min(4, 1 + (_rng.NextDouble() < 0.35 ? 1 : 0) + (_rng.NextDouble() < 0.12 ? 1 : 0) + (_rng.NextDouble() < 0.04 ? 1 : 0)),
|
||
id: _nextItemId++);
|
||
rep.Loot.Add(it);
|
||
AddLoot(it);
|
||
}
|
||
else Recovery = RecoveryTime * 3;
|
||
rep.Log = Enumerable.Range(1, Adventures.LOG_LINES).OrderBy(_ => _rng.Next()).Take(2 + a.Duration).ToList();
|
||
ExpeditionResult = rep;
|
||
Emit(new GameEvent(GameEventType.ExpeditionDone, ok ? 1 : 0, 0, a.Region));
|
||
}
|
||
|
||
public void DismissExpeditionResult() => ExpeditionResult = null;
|
||
|
||
// ── Ereignisse ──────────────────────────────────────────────
|
||
|
||
void StartEvent()
|
||
{
|
||
var pool = Adventures.Events.Where(e => e.Id != _lastEvent).ToArray();
|
||
PendingEvent = pool[_rng.Next(pool.Length)].Id;
|
||
_lastEvent = PendingEvent;
|
||
EventIn = Adventures.EVENT_MIN + _rng.NextDouble() * (Adventures.EVENT_MAX - Adventures.EVENT_MIN);
|
||
Emit(new GameEvent(GameEventType.EventStarted, 0, 0, PendingEvent));
|
||
}
|
||
|
||
/// Testläufe: ein bestimmtes Ereignis sofort auslösen.
|
||
internal void DevEvent(string id) { PendingEvent = id; }
|
||
|
||
public double ChoiceCost(EventChoice c) => c.Cost * Balance.GoldPerWin(Tier);
|
||
|
||
/// Entscheidung treffen: Folgen anwenden, Text-Key des Ausgangs zurückgeben (null = nicht möglich).
|
||
public string? Choose(int index)
|
||
{
|
||
if (PendingEvent == null) return null;
|
||
var ev = Adventures.GetEvent(PendingEvent);
|
||
var c = ev.Choices[index];
|
||
double cost = ChoiceCost(c);
|
||
if (Gold < cost) return null;
|
||
Gold -= cost;
|
||
bool ok = c.Chance >= 1 || _rng.NextDouble() < c.Chance;
|
||
foreach (var e in ok ? c.Ok : c.Fail ?? Array.Empty<EventEffect>()) Apply(e);
|
||
PendingEvent = null;
|
||
return c.Chance >= 1 ? ev.OutcomeKey(c, true) : ev.OutcomeKey(c, ok);
|
||
}
|
||
|
||
void Apply(EventEffect e)
|
||
{
|
||
switch (e.Kind)
|
||
{
|
||
case EffectKind.Gold:
|
||
double g = e.Amount * Balance.GoldPerWin(Tier);
|
||
if (g >= 0) EarnGold(g, "event"); else Gold = Math.Max(0, Gold + g);
|
||
break;
|
||
case EffectKind.Fame: FameRun = Math.Max(0, FameRun + e.Amount * Balance.FamePerWin(Tier)); break;
|
||
case EffectKind.Crowd: Crowd = Math.Clamp(Crowd + e.Amount, 0, 100); break;
|
||
case EffectKind.Xp: AddCharXp(e.Amount * Balance.CharXpPerWin(Tier)); break;
|
||
case EffectKind.Item: AddLoot(Items.Create(_rng, Items.DropLevel(Tier, _rng) + 3, e.Rarity, e.Slot, _nextItemId++)); break;
|
||
case EffectKind.Buff: Buffs.Add(new ActiveBuff { Kind = e.Buff, Mult = e.Amount, Left = e.Seconds }); break;
|
||
case EffectKind.Recovery:
|
||
Recovery = Math.Max(Recovery, e.Amount);
|
||
break;
|
||
}
|
||
}
|
||
|
||
// ── Echtzeit-Duelle ─────────────────────────────────────────
|
||
|
||
/// Kampfkraft eines Gegners im selben Maß wie <see cref="Power"/> (Duell-Verhältnis).
|
||
public static double EnemyPower(Enemy e) => Balance.DUEL_POWER_SCALE * Math.Sqrt(e.Damage * e.Hp);
|
||
|
||
public double DuelRatio(Enemy e) => Power() / (EnemyPower(e) * EnemyWeight(e));
|
||
|
||
/// Gegner zählen je Arena stärker (Abstimmung); Legenden bleiben, wie sie waren.
|
||
double EnemyWeight(Enemy e) =>
|
||
e.Display == null ? Balance.MANUAL_ENEMY[Math.Clamp(e.Tier / Balance.RANKS_PER_ARENA, 0, Balance.ARENA_COUNT - 1)] : 1;
|
||
|
||
public Enemy ChampionEnemy => Enemy.Create(Arena, Rank, true);
|
||
/// Kampf-Einführung gesehen (oder übersprungen); in den Einstellungen wieder einschaltbar.
|
||
public bool TutorialDone { get; set; }
|
||
|
||
/// Gegner zur Wahl: leichter (weniger Lohn, kein Aufstieg), ebenbürtig, stärker (mehr Lohn,
|
||
/// zwei Ränge Aufstieg) und — mit genug Ruhm — der Champion der Arena.
|
||
public IReadOnlyList<Offer> Offers()
|
||
{
|
||
var list = new List<Offer>();
|
||
int max = Balance.RANKS_PER_ARENA - 1;
|
||
if (Rank > 0) list.Add(new Offer(Enemy.Create(Arena, Rank - 1, false), Balance.OFFER_EASY, OfferKind.Easy));
|
||
list.Add(new Offer(Enemy.Create(Arena, Rank, false), Balance.OFFER_EVEN, OfferKind.Even));
|
||
if (Rank < max) list.Add(new Offer(Enemy.Create(Arena, Math.Min(Rank + 2, max), false), Balance.OFFER_HARD, OfferKind.Hard));
|
||
if (CanChallenge) list.Add(new Offer(ChampionEnemy, 1, OfferKind.Champion));
|
||
return list;
|
||
}
|
||
|
||
public bool CanFight => Recovery <= 0 && Away == null && !FreedomEarned;
|
||
|
||
/// Ergebnis eines selbst gekämpften Duells; Rang je nach Wahl.
|
||
public void ResolveFight(Offer o, bool won)
|
||
{
|
||
int rank = Rank;
|
||
ApplyResult(o.Enemy, won, o.Reward);
|
||
if (won && !o.Enemy.IsChampion)
|
||
Rank = Math.Min(Balance.RANKS_PER_ARENA - 1, o.Kind switch
|
||
{
|
||
OfferKind.Easy => rank,
|
||
OfferKind.Hard => rank + 2,
|
||
_ => rank + 1
|
||
});
|
||
Emit(new GameEvent(won ? GameEventType.FightWon : GameEventType.FightLost, 0, 0, o.Enemy.NameKey));
|
||
}
|
||
|
||
/// Gnadenstoß nach einem Sieg: Wahl wie das Publikum → +50 % Ruhm des Kampfs und Gunst +20;
|
||
/// Gnade gegen den Wunsch → +10 % Ruhm, Gunst −15; Ende gegen den Wunsch → Gunst −15.
|
||
/// Liefert den zusätzlichen Ruhm.
|
||
public double ApplyMissio(bool mercy, bool crowdWanted, double fightFame)
|
||
{
|
||
double bonus = 0;
|
||
if (mercy == crowdWanted) { bonus = fightFame * 0.5; Crowd = Math.Min(100, Crowd + 20); }
|
||
else
|
||
{
|
||
if (mercy) bonus = fightFame * 0.1;
|
||
Crowd = Math.Max(0, Crowd - 15);
|
||
}
|
||
FameRun += bonus;
|
||
return bonus;
|
||
}
|
||
|
||
/// Urteil des Publikums nach einer Niederlage: verschont → Erholung halbiert, sonst verdoppelt.
|
||
public void ApplyVerdict(bool spared) => Recovery *= spared ? 0.5 : 2;
|
||
|
||
/// Lohn eines Sieges (Vorschau auf der Gegnerkarte).
|
||
public (double Gold, double Fame, double Xp) RewardPreview(Offer o)
|
||
{
|
||
double r = (o.Enemy.IsChampion ? Balance.CHAMPION_REWARD : 1) * o.Reward;
|
||
return (Balance.GoldPerWin(o.Enemy.Tier) * Balance.FIGHT_GOLD * r * GoldMult, Balance.FamePerWin(o.Enemy.Tier) * r * FameMult,
|
||
Balance.CharXpPerWin(o.Enemy.Tier) * r);
|
||
}
|
||
|
||
// ── Ehrenhalle ──────────────────────────────────────────────
|
||
|
||
public const int LEGEND_FAVOR = 2;
|
||
|
||
/// Gegner für ein Duell gegen eine Legende: so stark, wie sie bei ihrer Freiheit war.
|
||
public static Enemy LegendEnemy(Legend l)
|
||
{
|
||
double p = Math.Max(1, l.Power) * 1.1 / Balance.DUEL_POWER_SCALE; // √(Schaden × Leben) = p
|
||
// Leben/Schaden ≈ 36 wie bei Spielern
|
||
return new Enemy("legend", 0, true, p * 6, p / 6, 10) { Display = l.Name, Art = Art.Fighter(l.Class) };
|
||
}
|
||
|
||
/// Ergebnis eines Duells gegen eine Legende: erster Sieg bringt Gunst der Götter.
|
||
public bool ResolveLegendDuel(Legend l, bool won)
|
||
{
|
||
if (!won || !LegendsBeaten.Add(l.Number)) return false;
|
||
GodFavor += LEGEND_FAVOR;
|
||
return true;
|
||
}
|
||
|
||
/// Testlauf: Gladiator-Stufe direkt setzen (Fähigkeitspunkte für den Duell-Test).
|
||
public void DevLevel(int level) => CharLevel = level;
|
||
|
||
/// Testlauf: direkt in Arena <paramref name="arena"/> (Kulisse prüfen).
|
||
public void DevArena(int arena) { Arena = Math.Clamp(arena, 0, Balance.ARENA_COUNT - 1); Rank = 0; }
|
||
|
||
/// Testlauf: Ausgang der nächsten Expedition festlegen (null = Zufall).
|
||
public bool? DevExpeditionOutcome { get; set; }
|
||
|
||
/// Testlauf: Freiheit sofort verdienen (Aufnahmen des Freiheits-Bildschirms).
|
||
public void DevFreedom() => FreedomEarned = true;
|
||
|
||
public double UpgradeCost(string id) => UpgradeDef.Get(id).Cost(UpgradeLevel(id));
|
||
|
||
public bool Buy(string id)
|
||
{
|
||
double cost = UpgradeCost(id);
|
||
if (Gold < cost) return false;
|
||
Gold -= cost;
|
||
Upgrades[id] = UpgradeLevel(id) + 1;
|
||
Emit(new GameEvent(GameEventType.Purchased, Upgrades[id], cost, id));
|
||
return true;
|
||
}
|
||
|
||
public bool BuyGod(God g)
|
||
{
|
||
int cost = Gods.Cost(GodLevel(g));
|
||
if (GodFavor < cost) return false;
|
||
GodFavor -= cost;
|
||
GodLevels[(int)g]++;
|
||
return true;
|
||
}
|
||
|
||
/// Freiheit annehmen: Gladiator kommt in die Ehrenhalle, Gunst der Götter gutgeschrieben.
|
||
/// Danach <see cref="NewRun"/> für den nächsten Sklaven. Liefert die erhaltene Gunst.
|
||
public int TakeFreedom()
|
||
{
|
||
if (!FreedomEarned) return 0;
|
||
int favor = Balance.FavorForFreedom(FameRun);
|
||
GodFavor += favor;
|
||
Freedoms++;
|
||
LifetimeFame += FameRun;
|
||
Legends.Add(new Legend(Name, Class, Freedoms, Wins, FameRun, RunSeconds, DateTime.UtcNow, CharLevel, Power()));
|
||
_pendingInherit = Balance.InheritGold(GoldEarnedRun, Freedoms);
|
||
FreedomEarned = false;
|
||
return favor;
|
||
}
|
||
|
||
// ── Offline ─────────────────────────────────────────────────
|
||
|
||
public double OfflineCapSeconds => Gods.OfflineHours(GodLevel(God.Jupiter)) * 3600;
|
||
|
||
/// Abwesenheit nachrechnen (gedeckelt): Training, Erholung und eine laufende Expedition.
|
||
public OfflineReport ApplyOffline(double seconds)
|
||
{
|
||
seconds = Math.Clamp(seconds, 0, OfflineCapSeconds);
|
||
double gold = GoldEarnedRun, fame = FameRun;
|
||
int wins = Wins, losses = Losses, levels = StatLevels.Sum();
|
||
// nur Zeit läuft weiter: Reise, Erholung, Trainingsenergie – kein Training, keine Kämpfe
|
||
TrainEnergy = Math.Min(Balance.TRAIN_ENERGY_MAX, TrainEnergy + seconds / Balance.TRAIN_ENERGY_SECONDS);
|
||
Recovery = Math.Max(0, Recovery - seconds);
|
||
for (int i = Buffs.Count - 1; i >= 0; i--)
|
||
if ((Buffs[i].Left -= seconds) <= 0) Buffs.RemoveAt(i);
|
||
if (Away != null && (Away.Left -= seconds) <= 0) FinishExpedition();
|
||
return new OfflineReport(seconds, GoldEarnedRun - gold, FameRun - fame, Wins - wins, Losses - losses,
|
||
StatLevels.Sum() - levels);
|
||
}
|
||
|
||
// ── Speichern ───────────────────────────────────────────────
|
||
|
||
/// Dateiname des Spielstands (das neue Spiel nutzt einen eigenen, neben dem alten).
|
||
public static string SaveFile { get; set; } = "save.json";
|
||
|
||
static string SavePath => Path.Combine(
|
||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "GladiatorIdle", SaveFile);
|
||
|
||
public static bool HasSave => File.Exists(SavePath);
|
||
|
||
/// Gespeicherter Stand als Datenobjekt (öffentliche Felder für System.Text.Json).
|
||
internal sealed class SaveData
|
||
{
|
||
public int Version { get; set; } = 1;
|
||
public DateTime SavedUtc { get; set; }
|
||
public int Freedoms { get; set; }
|
||
public int GodFavor { get; set; }
|
||
public int[] GodLevels { get; set; } = new int[6];
|
||
public List<Legend> Legends { get; set; } = new();
|
||
public HashSet<int> LegendsBeaten { get; set; } = new();
|
||
public Appearance? Look { get; set; }
|
||
public int ExtraSkillPoints { get; set; }
|
||
public bool TutorialDone { get; set; }
|
||
public double LifetimeFame { get; set; }
|
||
public string Name { get; set; } = "";
|
||
public GladiatorClass Class { get; set; }
|
||
public int[] StatLevels { get; set; } = new int[4];
|
||
public double[] StatXp { get; set; } = new double[4];
|
||
public Dictionary<string, int> Upgrades { get; set; } = new();
|
||
public double Gold { get; set; }
|
||
public double GoldEarnedRun { get; set; }
|
||
public double FameRun { get; set; }
|
||
public double Crowd { get; set; }
|
||
public int Arena { get; set; }
|
||
public int Rank { get; set; }
|
||
public bool FreedomEarned { get; set; }
|
||
public int Wins { get; set; }
|
||
public int Losses { get; set; }
|
||
public double RunSeconds { get; set; }
|
||
public double PendingInherit { get; set; }
|
||
public int CharLevel { get; set; }
|
||
public double CharXp { get; set; }
|
||
public int AttrPoints { get; set; }
|
||
public int[] StatBonus { get; set; } = new int[4];
|
||
public Item?[] Equipped { get; set; } = new Item?[5];
|
||
public int[] SlotLevels { get; set; } = new int[5];
|
||
public List<Item> Inventory { get; set; } = new();
|
||
public long NextItemId { get; set; } = 1;
|
||
public Expedition? Away { get; set; }
|
||
public double TrainEnergy { get; set; } = Balance.TRAIN_ENERGY_MAX;
|
||
public Dictionary<string, double>? GoldBySource { get; set; }
|
||
public ExpeditionReport? ExpeditionResult { get; set; }
|
||
public string? PendingEvent { get; set; }
|
||
public double EventIn { get; set; } = Adventures.EVENT_MIN;
|
||
public List<ActiveBuff> Buffs { get; set; } = new();
|
||
public Dictionary<string, int> SkillRanks { get; set; } = new();
|
||
}
|
||
|
||
public SaveData ToSave() => new()
|
||
{
|
||
SavedUtc = DateTime.UtcNow,
|
||
Freedoms = Freedoms, GodFavor = GodFavor, GodLevels = GodLevels, Legends = Legends, LifetimeFame = LifetimeFame,
|
||
LegendsBeaten = LegendsBeaten, Look = Look, ExtraSkillPoints = ExtraSkillPoints, TutorialDone = TutorialDone,
|
||
Name = Name, Class = Class, StatLevels = StatLevels, StatXp = StatXp, Upgrades = Upgrades,
|
||
Gold = Gold, GoldEarnedRun = GoldEarnedRun, FameRun = FameRun, Crowd = Crowd,
|
||
Arena = Arena, Rank = Rank, FreedomEarned = FreedomEarned, Wins = Wins, Losses = Losses,
|
||
RunSeconds = RunSeconds, PendingInherit = _pendingInherit,
|
||
CharLevel = CharLevel, CharXp = CharXp, AttrPoints = AttrPoints, StatBonus = StatBonus,
|
||
Equipped = Equipped, SlotLevels = SlotLevels, Inventory = Inventory,
|
||
NextItemId = _nextItemId,
|
||
Away = Away, ExpeditionResult = ExpeditionResult, PendingEvent = PendingEvent, EventIn = EventIn, Buffs = Buffs,
|
||
SkillRanks = SkillRanks, TrainEnergy = TrainEnergy, GoldBySource = GoldBySource
|
||
};
|
||
|
||
public static GameState FromSave(SaveData d, int? seed = null)
|
||
{
|
||
var g = new GameState(seed)
|
||
{
|
||
Freedoms = d.Freedoms, GodFavor = d.GodFavor, LifetimeFame = d.LifetimeFame,
|
||
GodLevels = Fit(d.GodLevels, 6), Legends = d.Legends ?? new(), LegendsBeaten = d.LegendsBeaten ?? new(), Look = d.Look ?? new(), ExtraSkillPoints = d.ExtraSkillPoints, TutorialDone = d.TutorialDone,
|
||
Name = d.Name, Class = d.Class, StatLevels = Fit(d.StatLevels, 4), StatXp = Fit(d.StatXp, 4),
|
||
// nur bekannte Gebäude (die Taberna gibt es nicht mehr)
|
||
Upgrades = (d.Upgrades ?? new()).Where(kv => UpgradeDef.All.Any(u => u.Id == kv.Key)).ToDictionary(kv => kv.Key, kv => kv.Value),
|
||
Gold = d.Gold, GoldEarnedRun = d.GoldEarnedRun, FameRun = d.FameRun, Crowd = Math.Clamp(d.Crowd, 0, 100),
|
||
Arena = Math.Clamp(d.Arena, 0, Balance.ARENA_COUNT - 1),
|
||
Rank = Math.Clamp(d.Rank, 0, Balance.RANKS_PER_ARENA - 1),
|
||
FreedomEarned = d.FreedomEarned, Wins = d.Wins, Losses = d.Losses, RunSeconds = d.RunSeconds
|
||
};
|
||
g._pendingInherit = d.PendingInherit;
|
||
g.TrainEnergy = Math.Clamp(d.TrainEnergy, 0, Balance.TRAIN_ENERGY_MAX);
|
||
if (d.GoldBySource != null) foreach (var kv in d.GoldBySource) g.GoldBySource[kv.Key] = kv.Value;
|
||
g.CharLevel = d.CharLevel; g.CharXp = d.CharXp; g.AttrPoints = d.AttrPoints; g.StatBonus = Fit(d.StatBonus, 4);
|
||
g.Equipped = Fit(d.Equipped, 5);
|
||
g.SlotLevels = Fit(d.SlotLevels, 5);
|
||
g.Inventory = d.Inventory ?? new();
|
||
g._nextItemId = Math.Max(1, d.NextItemId);
|
||
// ältere Spielstände ohne Ausrüstung: Startausrüstung der Klasse
|
||
if (g.Equipped.All(e => e == null))
|
||
foreach (var b in Items.StartKit(g.Class))
|
||
{
|
||
var it = new Item { Id = g._nextItemId++, Base = b };
|
||
g.Equipped[(int)it.Slot] = it;
|
||
}
|
||
g.Away = d.Away; g.ExpeditionResult = d.ExpeditionResult; g.Buffs = d.Buffs ?? new();
|
||
g.SkillRanks = (d.SkillRanks ?? new()).Where(kv => SkillDef.All.Any(s => s.Id == kv.Key)).ToDictionary(kv => kv.Key, kv => kv.Value);
|
||
g.PendingEvent = d.PendingEvent != null && Adventures.Events.Any(e => e.Id == d.PendingEvent) ? d.PendingEvent : null;
|
||
g.EventIn = d.EventIn > 0 ? d.EventIn : Adventures.EVENT_MIN;
|
||
return g;
|
||
}
|
||
|
||
static T[] Fit<T>(T[]? a, int n)
|
||
{
|
||
var r = new T[n];
|
||
if (a != null) Array.Copy(a, r, Math.Min(n, a.Length));
|
||
return r;
|
||
}
|
||
|
||
static readonly JsonSerializerOptions _json = new() { WriteIndented = true };
|
||
|
||
/// Speichern (Testläufe nie). Schreibt erst eine Temp-Datei, dann umbenennen.
|
||
public void Save()
|
||
{
|
||
if (DevShot.Active) return;
|
||
try
|
||
{
|
||
Directory.CreateDirectory(Path.GetDirectoryName(SavePath)!);
|
||
string tmp = SavePath + ".tmp";
|
||
File.WriteAllText(tmp, JsonSerializer.Serialize(ToSave(), _json));
|
||
File.Move(tmp, SavePath, overwrite: true);
|
||
}
|
||
catch { /* nicht speicherbar → nächster Versuch beim nächsten Speichern */ }
|
||
}
|
||
|
||
/// Laden; null, wenn kein (lesbarer) Spielstand da ist. <paramref name="savedUtc"/> für Offline.
|
||
public static GameState? Load(out DateTime savedUtc)
|
||
{
|
||
savedUtc = DateTime.UtcNow;
|
||
try
|
||
{
|
||
if (!File.Exists(SavePath)) return null;
|
||
var d = JsonSerializer.Deserialize<SaveData>(File.ReadAllText(SavePath));
|
||
if (d == null) return null;
|
||
savedUtc = d.SavedUtc;
|
||
return FromSave(d);
|
||
}
|
||
catch { return null; }
|
||
}
|
||
|
||
public static void DeleteSave()
|
||
{
|
||
if (DevShot.Active) return;
|
||
try { File.Delete(SavePath); } catch { }
|
||
}
|
||
}
|
||
}
|