Port the minimal garrison record path from 8efd447: RECORD_METRICS and metrics() gain 驻扎/garrison_arrange_count in both Python and GDScript; profile gains additive garrison state with save-first one-shot arrange count. The arrange entry point is a quiet row on the side page (where the records live) so the current skyport action layout and its 360px touch flow stay unchanged. Adds real-ScreenTouch evidence for the records summary (167), A137/A142 rows, claims and save cold read.
960 lines
42 KiB
GDScript
960 lines
42 KiB
GDScript
class_name ProfileStore
|
|
extends RefCounted
|
|
|
|
## Persistent player profile for the P3a loop.
|
|
##
|
|
## Separate from the P2 `SaveStore` smoke: this one owns the full progression
|
|
## state (rewards, hero levels, unlocked heroes and cleared nodes). Writes are
|
|
## atomic (temp file then rename) and corrupt/unknown saves fall back to a
|
|
## fresh profile instead of crashing or silently wiping without a record.
|
|
|
|
## The default path is the real player save. Tests set WINDROOST_SAVE_DIR to a
|
|
## temporary directory so automated runs never pollute the player's profile.
|
|
const SAVE_NAME := "windroost_profile.json"
|
|
const TEMP_NAME := "windroost_profile.json.tmp"
|
|
## v5 adds CH ascension soul fields (hero_souls / total_hero_souls /
|
|
## primal_souls / souls_from_ascensions / ascensions + reset receipt history).
|
|
## v6 adds the CH offline anchor/receipt book (offline_anchor_ms /
|
|
## offline_revision / offline_pending / offline_receipt).
|
|
## v7 adds the S4 source-bound relic inventory + gild book (relic_gild) and its
|
|
## per-hero WR view (gild_levels). Additive: every v6 key is carried verbatim;
|
|
## a malformed book is replaced with safe defaults without dropping the wallet.
|
|
## All four offline fields map directly
|
|
## from clicker_heroes_rebuild_ancient_limit_build25 @ 46cc8ad
|
|
## scripts/offline_book.gd (anchor_ms / revision / pending / receipt); no value
|
|
## is invented for the excluded CH fields (souls / cores / relic / seed / tail).
|
|
## v7 adds the S3 CH transcension/outsider slice as additive fields: the Ancient
|
|
## Soul wallet snapshot (`ancient_souls`, CH outsider_book.snapshot() codec),
|
|
## sacrifice inputs (`hero_souls_sacrificed` <- CH progression_state,
|
|
## `oath_souls_spent` <- CH ancients.total_spent(); WR oaths have no spend
|
|
## ledger so this is a new named field, not a guessed rename of `edicts`),
|
|
## `transcensions`, `last_transcendence` and bounded `transcendence_history`.
|
|
## v7 also adds the S5/S6 CH systems slice: mercenary quest slots, autoclicker
|
|
## allocation, clickable scheduler and the CH achievement 43 click bonus. All
|
|
## constants/IDs come from the CH authority bundle; the WR payment/consumer
|
|
## mappings are labelled in PRODUCTION/S5-S6-CH-SYSTEMS-CONTRACT.md.
|
|
## v7 also carries the L5 garrison slice additively (`garrison`,
|
|
## `garrison_arrange_count`): a single active slot plus the arrange counter that
|
|
## drives the A137/A142 驻扎 records. Older v4-v6 saves receive safe defaults;
|
|
## no value is invented for a garrison they never arranged.
|
|
## S3, S4, S5/S6 and the garrison v7 fields are all additive and migrate together.
|
|
const SCHEMA := 7
|
|
const ChRelicGild = preload("res://scripts/ch_relic_gild.gd")
|
|
const ChSystems = preload("res://scripts/ch_systems_adapter.gd")
|
|
|
|
|
|
static func save_dir() -> String:
|
|
var override := OS.get_environment("WINDROOST_SAVE_DIR")
|
|
if not override.is_empty():
|
|
return override.trim_suffix("/")
|
|
return "user://"
|
|
|
|
|
|
static func save_path() -> String:
|
|
return save_dir().path_join(SAVE_NAME)
|
|
|
|
|
|
static func temp_path() -> String:
|
|
return save_dir().path_join(TEMP_NAME)
|
|
|
|
## Offline gains follow the CH baseline: bounded at 8 hours and derived from
|
|
## the roster's output, never from wall-clock frame counts.
|
|
const OFFLINE_CAP_SECONDS := 8.0 * 3600.0
|
|
## Source-pinned CH offline book constants. Names and values are copied from
|
|
## clicker_heroes_rebuild_ancient_limit_build25 @ 46cc8ad
|
|
## scripts/offline_book.gd (CAP_MS / PAUSE_GATE_MS / LIMIT) and cross-checked
|
|
## against data/ch_numeric_authority/offline.json (cap_ms / pause_gate_ms).
|
|
const OFFLINE_CAP_MS := 28800000
|
|
const OFFLINE_PAUSE_GATE_MS := 240000
|
|
const OFFLINE_LIMIT := 9007199254740991
|
|
## Fallback only; the authoritative rate lives in mvp_battle_rules.json.
|
|
const OFFLINE_GOLD_PER_DPS_SECOND := 0.001
|
|
## First-chapter slice scale for the CH `floor(total_levels / 2000)` rebuild
|
|
## reward. The full game keeps the 2000 divisor; the slice cannot reach it.
|
|
const REBUILD_LEVELS_PER_ESSENCE := 8
|
|
const RULES_PATH := "res://data/mvp_battle_rules.json"
|
|
const OutsiderBook = preload("res://scripts/outsider_book.gd")
|
|
|
|
|
|
## The offline rate is owned by the shared rules file so the Godot runtime and
|
|
## the pacing simulator cannot drift. Falls back to the constant if unreadable.
|
|
static func offline_rate() -> float:
|
|
var file := FileAccess.open(RULES_PATH, FileAccess.READ)
|
|
if file == null:
|
|
return OFFLINE_GOLD_PER_DPS_SECOND
|
|
var parsed = JSON.parse_string(file.get_as_text())
|
|
file.close()
|
|
if not parsed is Dictionary:
|
|
return OFFLINE_GOLD_PER_DPS_SECOND
|
|
var prog: Dictionary = parsed.get("progression", {})
|
|
if not prog.has("offline_gold_per_dps_second"):
|
|
return OFFLINE_GOLD_PER_DPS_SECOND
|
|
return float(prog["offline_gold_per_dps_second"])
|
|
|
|
|
|
## Authoritative upgrade cost for a hero at the given level. Single source of
|
|
## truth so the skyport card, the actual debit and the battle HUD cannot drift
|
|
## when the rules file balance changes. Mirrors offline_rate()'s rules read.
|
|
static func upgrade_cost(level: int) -> int:
|
|
const BASE := 120.0
|
|
const GROWTH := 1.15
|
|
const INITIAL := 1
|
|
var base := BASE
|
|
var growth := GROWTH
|
|
var initial := INITIAL
|
|
var file := FileAccess.open(RULES_PATH, FileAccess.READ)
|
|
if file != null:
|
|
var parsed = JSON.parse_string(file.get_as_text())
|
|
file.close()
|
|
if parsed is Dictionary:
|
|
var prog: Dictionary = parsed.get("progression", {})
|
|
base = float(prog.get("upgrade_base_cost", BASE))
|
|
growth = float(prog.get("upgrade_cost_growth", GROWTH))
|
|
initial = int(prog.get("initial_level", INITIAL))
|
|
var steps := maxi(0, level - initial)
|
|
return int(round(base * pow(growth, float(steps))))
|
|
|
|
const DEFAULT_PROFILE := {
|
|
"schema": SCHEMA,
|
|
"gold": 0,
|
|
"crystal": 0,
|
|
"hero_levels": {},
|
|
"unlocked_heroes": ["H01", "H02", "H03"],
|
|
"completed_nodes": [],
|
|
"claimed_rewards": [],
|
|
"current_node": "R1-C01-N01",
|
|
"last_saved_at": 0,
|
|
"pending_offline_gold": 0,
|
|
"offline_report_key": "",
|
|
# CH offline book (schema v6). anchor_ms is a wall-clock high-water mark in
|
|
# milliseconds, revision increments once per noteworthy settlement, pending
|
|
# gates acknowledgement and receipt is the last settled report. The subset
|
|
# stored here (id/kind/from_ms/to_ms/applied_ms/capped/rollback/gold) is the
|
|
# part WR can carry without inventing soul/chest/item values.
|
|
"offline_anchor_ms": 0,
|
|
"offline_revision": 0,
|
|
"offline_pending": false,
|
|
"offline_receipt": {},
|
|
"rebuild_count": 0,
|
|
"seen_intro": false,
|
|
"auto_run": false,
|
|
"reduced_motion": false,
|
|
"muted": false,
|
|
"low_power": false,
|
|
# L1 growth layers (full game). Empty by default => GrowthModifiers identity.
|
|
"star_levels": {},
|
|
"talents": {},
|
|
"awakenings": {},
|
|
"relics": {},
|
|
# S4 source-bound CH relic inventory + gild book (schema v7). Additive to
|
|
# the L1 "relics" set above; "gild_levels" is the WR hero-id view consumed by
|
|
# HeroSkillLoader. No crystal or ruby value is carried here.
|
|
"relic_gild": {},
|
|
"gild_levels": {},
|
|
"oaths": {},
|
|
"edicts": {},
|
|
"emblems": {},
|
|
# L2 prestige resources.
|
|
"essence": 0, # 风之精华 (rebuild currency)
|
|
"sky_marks": 0, # 天空徽记 (new-sky currency)
|
|
"star_fragments": 0, # 遗物碎片
|
|
"war_merit": 0, # 战功
|
|
"new_sky_count": 0,
|
|
"rift_layer": 0, # 天空裂隙层数 (new-sky unlock path: layer 50)
|
|
# L3 world progress / L2 prestige source counters. These are read by the
|
|
# prestige formulas (prestige.gd) and the world engine; they MUST live in the
|
|
# default profile or _normalize() would silently drop them on every save.
|
|
"highest_node": 0,
|
|
"completed_chapters": 0,
|
|
"region_boss_first_clears": 0,
|
|
"completed_regions": 0,
|
|
"final_boss_first_clears": 0,
|
|
"total_essence_earned": 0,
|
|
# CH-derived ascension soul wallet (schema v5). Values/fields mirror
|
|
# clicker_heroes_rebuild_ancient_limit_build25 @ 46cc8ad
|
|
# progression_state.gd / hero_soul_wallet.gd. They sit beside, and do not
|
|
# replace, the WR-original essence / sky_marks currencies.
|
|
"hero_souls": 0,
|
|
"total_hero_souls": 0,
|
|
"primal_souls": 0,
|
|
"souls_from_ascensions": 0,
|
|
"ascensions": 0,
|
|
"last_ascension": {},
|
|
"soul_history": [],
|
|
# CH-derived transcension / outsider slice (schema v7). `ancient_souls`
|
|
# stores ClickerOutsiderBook.snapshot() verbatim: {wallet_codec, balance,
|
|
# total, levels} with raw-bit strings. WR's `sky_marks`/`edicts` bool layer
|
|
# is a separate display/rule system and is intentionally untouched.
|
|
"ancient_souls": {},
|
|
"hero_souls_sacrificed": 0,
|
|
"oath_souls_spent": 0,
|
|
"transcensions": 0,
|
|
"last_transcendence": {},
|
|
"transcendence_history": [],
|
|
# L5 side systems (partners / records / black market).
|
|
"battle_wins": 0,
|
|
"total_gold_earned": 0,
|
|
"partner_claims": {},
|
|
"revive_charges": 0,
|
|
"cosmetics": {},
|
|
# L5 garrison: one active slot on the highest cleared node plus the
|
|
# arrange counter feeding the A137/A142 驻扎 records. Additive v7 fields.
|
|
"garrison": {"active": false, "node_id": "", "since": 0},
|
|
"garrison_arrange_count": 0,
|
|
# L5 low-frequency interactions: supply buoy mini-game state.
|
|
"buoy": {"active": false, "taps": 0},
|
|
# L5 gear: owned this-round drops + per-slot equipped mapping.
|
|
"gear": {},
|
|
"equipped": {},
|
|
# Endless expedition (CH-style, BigValue numbers stored encoded as strings).
|
|
"endless": {},
|
|
# UI skin selection ("default" or an installed skin folder name). Parchment
|
|
# is the chosen default (matches the paper+brass art direction).
|
|
"ui_skin": "parchment",
|
|
# S5/S6 CH systems (schema v7). merc_quests holds at most five source-shaped
|
|
# quest slots; the ruby/candy/life wallets do not exist in WR, so hire/revive
|
|
# are explicit WR payment adapters. autoclick/clickable keep the CH scheduler
|
|
# fields; ch_achievements carries the one source-bound addClickDamage record.
|
|
"merc_quests": [],
|
|
"merc_rng": {"seed": 1, "uses": 0},
|
|
"merc_next_uid": 1,
|
|
"merc_hires": 0,
|
|
"autoclick": {"owned": 0, "remainder": 0.0, "timer": 0.0, "total_clicks": 0, "service_ticks": 0},
|
|
"clickable": {"spawn_seed": 1234567, "reward_seed": 7654321, "spawn_uses": 0, "reward_uses": 0,
|
|
"next_uid": 1, "active_uid": 0, "revision": 0, "phase": 0.0,
|
|
"ruby_rewards": 0, "total_claims": 0},
|
|
"ch_achievements": {"obtained": [], "click_bonus": 0, "revision": 0},
|
|
}
|
|
|
|
|
|
## A fresh profile has never been played: first-run onboarding can use this to
|
|
## avoid showing "offline report settled" to someone who never left.
|
|
static func is_first_run(profile: Dictionary) -> bool:
|
|
return not bool(profile.get("seen_intro", false))
|
|
|
|
|
|
static func mark_intro_seen(profile: Dictionary) -> void:
|
|
profile["seen_intro"] = true
|
|
|
|
|
|
static func fresh_profile() -> Dictionary:
|
|
var profile := DEFAULT_PROFILE.duplicate(true)
|
|
profile["relic_gild"] = ChRelicGild.fresh_state()
|
|
return profile
|
|
|
|
|
|
static func load_profile() -> Dictionary:
|
|
var file := FileAccess.open(save_path(), FileAccess.READ)
|
|
if file == null:
|
|
return fresh_profile()
|
|
var text := file.get_as_text()
|
|
file.close()
|
|
var parsed = JSON.parse_string(text)
|
|
if not parsed is Dictionary:
|
|
push_warning("Profile was not a JSON object; starting fresh")
|
|
return fresh_profile()
|
|
var profile: Dictionary = parsed
|
|
if int(profile.get("schema", 0)) != SCHEMA:
|
|
var migrated := _migrate(profile)
|
|
if migrated.is_empty():
|
|
push_warning("Unknown profile schema; starting fresh")
|
|
return fresh_profile()
|
|
profile = migrated
|
|
return _normalize(profile)
|
|
|
|
|
|
static func _migrate(old: Dictionary) -> Dictionary:
|
|
var schema := int(old.get("schema", 0))
|
|
# v1 only stored the minimal battle smoke fields; v2/v3 added progression;
|
|
# v4 was the full profile; v5 added the CH ascension wallet; v6 added the
|
|
# offline book. None has v7's additive slices: the S3 transcension/outsider
|
|
# fields, the S4 relic/gild book and the S5/S6 CH systems slice. All receive
|
|
# safe defaults; no value is invented for CH terms WR cannot map (additive
|
|
# fields start at zero/empty, exactly like v5).
|
|
if schema >= 1 and schema <= 6:
|
|
var migrated := fresh_profile()
|
|
if schema >= 4 and schema <= 6:
|
|
# v4 -> v5 -> v6 -> v7 are additive: carry every existing key
|
|
# forward verbatim. _normalize() still clamps malformed values.
|
|
for key in old.keys():
|
|
if migrated.has(key):
|
|
migrated[key] = old[key]
|
|
else:
|
|
for key in ["gold", "crystal", "hero_levels", "unlocked_heroes", "completed_nodes", "claimed_rewards", "rebuild_count"]:
|
|
if old.has(key):
|
|
migrated[key] = old[key]
|
|
# Preserve accessibility settings if an older save carried them.
|
|
for key in ["muted", "low_power", "reduced_motion", "auto_run"]:
|
|
if old.has(key):
|
|
migrated[key] = old[key]
|
|
# Legacy wall clock. CH restores a pre-anchor save from its `timestamp`
|
|
# (seconds) via `timestamp * 1000` (game_state.gd:2513-2514). WR's
|
|
# equivalent field is last_saved_at, so the same conversion is used here;
|
|
# no new anchor value is invented when the legacy stamp is absent.
|
|
if int(migrated.get("offline_anchor_ms", 0)) <= 0:
|
|
var legacy_sec := int(old.get("last_saved_at", 0))
|
|
if legacy_sec > 0:
|
|
migrated["offline_anchor_ms"] = mini(legacy_sec * 1000, OFFLINE_LIMIT)
|
|
# Existing saves have been played; do not show first-run onboarding.
|
|
migrated["seen_intro"] = true
|
|
migrated["schema"] = SCHEMA
|
|
return migrated
|
|
return {}
|
|
|
|
|
|
## Strict validation of the v6 offline book. Mirrors CH
|
|
## ClickerOfflineBook.restore() (offline_book.gd:37-56) over the subset WR
|
|
## carries: anchor/revision bounds, id==revision, monotonic from/to, bounded
|
|
## applied_ms, known kind and boolean flags. A corrupt book is replaced with
|
|
## safe defaults instead of being allowed to pay out; the rest of the profile
|
|
## survives, matching the repository's corrupt-save policy.
|
|
static func _normalize_offline_book(result: Dictionary) -> void:
|
|
var anchor := int(result.get("offline_anchor_ms", 0))
|
|
var revision := int(result.get("offline_revision", 0))
|
|
var pending = result.get("offline_pending", false)
|
|
var receipt = result.get("offline_receipt", {})
|
|
var valid := anchor >= 0 and anchor <= OFFLINE_LIMIT \
|
|
and revision >= 0 and revision <= OFFLINE_LIMIT \
|
|
and pending is bool and receipt is Dictionary
|
|
if valid:
|
|
var row: Dictionary = receipt
|
|
if row.is_empty():
|
|
# CH: an empty receipt may not carry a pending flag or a revision.
|
|
if pending or revision != 0:
|
|
valid = false
|
|
else:
|
|
for key in ["id", "from_ms", "to_ms", "applied_ms"]:
|
|
if not (row.get(key) is int) or int(row[key]) < 0 or int(row[key]) > OFFLINE_LIMIT:
|
|
valid = false
|
|
break
|
|
if valid:
|
|
var gold_val = row.get("gold")
|
|
valid = int(row.id) == revision \
|
|
and int(row.to_ms) <= anchor \
|
|
and int(row.to_ms) >= int(row.from_ms) \
|
|
and int(row.applied_ms) <= OFFLINE_CAP_MS \
|
|
and str(row.get("kind", "")) in ["startup", "pause"] \
|
|
and row.get("capped") is bool \
|
|
and row.get("rollback") is bool \
|
|
and (gold_val is int or gold_val is float)
|
|
if not valid:
|
|
var legacy_sec := mini(maxi(int(result.get("last_saved_at", 0)), 0), int(OFFLINE_LIMIT / 1000))
|
|
result["offline_anchor_ms"] = legacy_sec * 1000
|
|
result["offline_revision"] = 0
|
|
result["offline_pending"] = false
|
|
result["offline_receipt"] = {}
|
|
result["pending_offline_gold"] = 0
|
|
result["offline_report_key"] = ""
|
|
return
|
|
result["offline_anchor_ms"] = anchor
|
|
result["offline_revision"] = revision
|
|
result["offline_pending"] = pending
|
|
result["offline_receipt"] = (receipt as Dictionary).duplicate(true)
|
|
|
|
|
|
## Strict validation of the v7 Ancient Soul / outsider book. Mirrors CH
|
|
## ClickerOutsiderBook.restore() (outsider_book.gd:96-117): codec must match,
|
|
## balance/total must be exact raw-bit strings in the bounded domain, every
|
|
## level must be integral and within its source cap. A tampered book is dropped
|
|
## to a fresh one; it must never pay out an invented Ancient Soul balance.
|
|
static func _normalize_transcendence_book(result: Dictionary) -> void:
|
|
var data: Variant = result.get("ancient_souls", {})
|
|
if not data is Dictionary or (data as Dictionary).is_empty():
|
|
result["ancient_souls"] = {}
|
|
return
|
|
var probe := OutsiderBook.new()
|
|
if not probe.restore(data as Dictionary, false):
|
|
result["ancient_souls"] = {}
|
|
|
|
|
|
static func _normalize(profile: Dictionary) -> Dictionary:
|
|
var result := fresh_profile()
|
|
for key in result.keys():
|
|
if profile.has(key):
|
|
result[key] = profile[key]
|
|
if not result.has("hero_levels") or not result["hero_levels"] is Dictionary:
|
|
result["hero_levels"] = {}
|
|
else:
|
|
# A typed-but-out-of-range level (e.g. -50 or 1e9 from a tampered save)
|
|
# makes upgrade cost 0 or inf -> free levels / currency overflow. Clamp
|
|
# to a sane range and drop non-numeric values.
|
|
var safe_levels: Dictionary = {}
|
|
for hid in result["hero_levels"].keys():
|
|
var raw = result["hero_levels"][hid]
|
|
if raw is int or raw is float:
|
|
safe_levels[str(hid)] = clampi(int(raw), 1, 10000)
|
|
result["hero_levels"] = safe_levels
|
|
if not result["completed_nodes"] is Array:
|
|
result["completed_nodes"] = []
|
|
if not result["claimed_rewards"] is Array:
|
|
result["claimed_rewards"] = []
|
|
if not result["unlocked_heroes"] is Array:
|
|
result["unlocked_heroes"] = ["H01", "H02", "H03"]
|
|
else:
|
|
# Dedupe: a save with repeated ids counted the same hero's DPS multiple
|
|
# times in roster_dps and offline gains. Preserve order, drop non-strings.
|
|
var seen: Dictionary = {}
|
|
var safe_roster: Array = []
|
|
for h in result["unlocked_heroes"]:
|
|
if not (h is String) or seen.has(h):
|
|
continue
|
|
seen[h] = true
|
|
safe_roster.append(h)
|
|
if safe_roster.is_empty():
|
|
safe_roster = ["H01", "H02", "H03"]
|
|
result["unlocked_heroes"] = safe_roster
|
|
# Full-game growth dicts must be dictionaries; a malformed save with e.g.
|
|
# "talents": 5 would crash GrowthModifiers.compute() on next launch.
|
|
for key in ["star_levels", "talents", "awakenings", "relics", "oaths", "edicts", "emblems",
|
|
"partner_claims", "cosmetics", "gear", "equipped", "last_ascension",
|
|
"last_transcendence", "gild_levels"]:
|
|
if not (result[key] is Dictionary):
|
|
result[key] = {}
|
|
# S4: strict, additive validation of the CH relic/gild book. A corrupt book
|
|
# is replaced wholesale; every other profile field survives unchanged.
|
|
ChRelicGild.normalize(result)
|
|
# CH ascension reset receipt history is bounded to the source's 100 entries.
|
|
if not (result["soul_history"] is Array):
|
|
result["soul_history"] = []
|
|
else:
|
|
var safe_history: Array = []
|
|
for receipt in result["soul_history"]:
|
|
if receipt is Dictionary:
|
|
safe_history.append(receipt)
|
|
result["soul_history"] = safe_history.slice(-100)
|
|
# v7 transcendence receipts: same bounded 100-entry history rule as CH
|
|
# progression.last_reset and the v5 soul_history.
|
|
if not (result["transcendence_history"] is Array):
|
|
result["transcendence_history"] = []
|
|
else:
|
|
var safe_trans: Array = []
|
|
for receipt in result["transcendence_history"]:
|
|
if receipt is Dictionary:
|
|
safe_trans.append(receipt)
|
|
result["transcendence_history"] = safe_trans.slice(-100)
|
|
_normalize_transcendence_book(result)
|
|
# UI skin must be a known id or the default (a tampered value could point at
|
|
# a missing resource folder and break every frame lookup).
|
|
var skin := str(result.get("ui_skin", "parchment"))
|
|
const VALID_SKINS := ["default", "parchment"]
|
|
result["ui_skin"] = skin if VALID_SKINS.has(skin) else "default"
|
|
# Endless run: BigValue numbers are stored encoded strings; keep the dict
|
|
# shape safe so a tampered save cannot crash the endless engine.
|
|
var endless: Dictionary = result["endless"] if result["endless"] is Dictionary else {}
|
|
result["endless"] = {
|
|
"zone": clampi(int(endless.get("zone", 1)), 1, 2147483647),
|
|
"level": clampi(int(endless.get("level", 1)), 1, 1000000000),
|
|
"essence": clampi(int(endless.get("essence", 0)), 0, 1000000000),
|
|
"gild": maxf(1.0, float(endless.get("gild", 1.0))),
|
|
"gold": str(endless.get("gold", "0:0")),
|
|
"rebuilds": clampi(int(endless.get("rebuilds", 0)), 0, 1000000000),
|
|
"elapsed": maxf(0.0, float(endless.get("elapsed", 0.0))),
|
|
"fails_since_rebuild": clampi(int(endless.get("fails_since_rebuild", 0)), 0, 100),
|
|
"total_kills": clampi(int(endless.get("total_kills", 0)), 0, 2147483647),
|
|
}
|
|
# Buoy must be a dict with bool active + bounded taps, or tap_buoy would
|
|
# crash on a tampered save.
|
|
var buoy: Dictionary = result["buoy"] if result["buoy"] is Dictionary else {}
|
|
result["buoy"] = {
|
|
"active": bool(buoy.get("active", false)),
|
|
"taps": clampi(int(buoy.get("taps", 0)), 0, 5),
|
|
}
|
|
# Garrison is additive: a slot pointing at a node no longer in
|
|
# completed_nodes (or with no node at all) is deactivated on load, so a
|
|
# stale/empty save can never report an active garrison. The arrange counter
|
|
# is preserved verbatim (clamped below) so already-earned 驻扎 records stay
|
|
# reachable across reload.
|
|
var garrison: Dictionary = result["garrison"] if result["garrison"] is Dictionary else {}
|
|
var g_node := str(garrison.get("node_id", ""))
|
|
var g_active := bool(garrison.get("active", false)) and not g_node.is_empty() \
|
|
and (result["completed_nodes"] as Array).has(g_node)
|
|
result["garrison"] = {
|
|
"active": g_active,
|
|
"node_id": g_node if g_active else "",
|
|
"since": clampi(int(garrison.get("since", 0)), 0, 2147483647),
|
|
}
|
|
# Prestige/resource counters must be non-negative numbers.
|
|
for key in ["essence", "sky_marks", "star_fragments", "war_merit", "new_sky_count",
|
|
"highest_node", "completed_chapters", "region_boss_first_clears",
|
|
"completed_regions", "final_boss_first_clears", "total_essence_earned",
|
|
"rebuild_count", "battle_wins", "total_gold_earned", "revive_charges", "rift_layer",
|
|
"garrison_arrange_count",
|
|
"hero_souls", "total_hero_souls", "primal_souls", "souls_from_ascensions", "ascensions",
|
|
"hero_souls_sacrificed", "oath_souls_spent", "transcensions"]:
|
|
var v = result[key]
|
|
if not (v is int or v is float) or float(v) < 0.0:
|
|
result[key] = 0
|
|
_normalize_offline_book(result)
|
|
_normalize_ch_systems(result)
|
|
return result
|
|
|
|
|
|
## Strict validation of the v7 CH systems slice. Mirrors the CH books' restore()
|
|
## discipline: bounded slot count, unique UIDs, valid RNG domains, non-negative
|
|
## timers, phase in [0,1) and known achievement IDs. A corrupt subsystem is
|
|
## replaced with safe defaults instead of being allowed to pay out; the rest of
|
|
## the profile survives, matching the repository's corrupt-save policy.
|
|
static func _normalize_ch_systems(result: Dictionary) -> void:
|
|
# Mercenary RNG: CH valid_rng (seed 1..MODULUS-1, uses 0..2^32-1).
|
|
var rng: Dictionary = result.get("merc_rng", {}) if result.get("merc_rng") is Dictionary else {}
|
|
var seed := int(rng.get("seed", -1))
|
|
var uses := int(rng.get("uses", -1))
|
|
if not ChSystems.valid_rng({"seed": seed, "uses": uses}):
|
|
rng = {"seed": 1, "uses": 0}
|
|
result["merc_rng"] = {"seed": seed if ChSystems.valid_rng({"seed": seed, "uses": uses}) else 1,
|
|
"uses": uses if ChSystems.valid_rng({"seed": seed, "uses": uses}) else 0}
|
|
var next_uid := int(result.get("merc_next_uid", 1))
|
|
result["merc_next_uid"] = next_uid if next_uid >= 1 else 1
|
|
var hires := int(result.get("merc_hires", 0))
|
|
result["merc_hires"] = hires if hires >= 0 else 0
|
|
# Up to five slots (CH effective cap). A slot must be a dictionary with a
|
|
# source-shaped quest; anything else is dropped, never half-trusted.
|
|
var slots: Array = result.get("merc_quests", []) if result.get("merc_quests") is Array else []
|
|
var safe_slots: Array = []
|
|
var seen: Dictionary = {}
|
|
for slot in slots:
|
|
if not slot is Dictionary or safe_slots.size() >= 5:
|
|
continue
|
|
var row: Dictionary = slot
|
|
var uid := int(row.get("uid", 0))
|
|
if uid < 1 or uid >= int(result["merc_next_uid"]) or seen.has(uid):
|
|
continue
|
|
seen[uid] = true
|
|
var level := clampi(int(row.get("level", 1)), 1, ChSystems.REVIVAL_LEVEL_CAP)
|
|
var quest: Dictionary = row.get("quest", {}) if row.get("quest") is Dictionary else {}
|
|
var qstart := int(quest.get("start", 0))
|
|
var qduration := int(quest.get("duration", 0))
|
|
var qkind := int(quest.get("reward", 0))
|
|
var qty := int(quest.get("quantity", 0))
|
|
if not quest.is_empty():
|
|
if qstart <= 0 or qstart > 9007199254740991 or qduration != ChSystems.QUEST_DURATION_SEC \
|
|
or qkind != ChSystems.GOLD_REWARD_TYPE or qty < 0 or qty > 100:
|
|
quest = {}
|
|
else:
|
|
quest = {"reward": qkind, "duration_id": ChSystems.QUEST_DURATION_ID,
|
|
"duration": qduration, "start": qstart, "quantity": qty,
|
|
"death": clampi(int(quest.get("death", 0)), 0, qduration)}
|
|
var experience := float(row.get("experience", 0.0))
|
|
var slot_rng = row.get("rng", {})
|
|
if not ChSystems.valid_rng(slot_rng):
|
|
slot_rng = ChSystems.fresh_rng(uid)
|
|
safe_slots.append({"uid": uid, "level": level,
|
|
"experience": clampf(experience, 0.0, 0.99) if is_finite(experience) else 0.0,
|
|
"rng": {"seed": int((slot_rng as Dictionary).get("seed", 1)),
|
|
"uses": int((slot_rng as Dictionary).get("uses", 0))},
|
|
"quest": quest})
|
|
result["merc_quests"] = safe_slots
|
|
|
|
# Autoclicker: owned >= 0, remainder in [0,1), timer finite >= 0, counters
|
|
# bounded. CH restore() uses the same shape.
|
|
var auto: Dictionary = result.get("autoclick", {}) if result.get("autoclick") is Dictionary else {}
|
|
var owned := int(auto.get("owned", 0))
|
|
var remainder := float(auto.get("remainder", 0.0))
|
|
var timer := float(auto.get("timer", 0.0))
|
|
var total_clicks := int(auto.get("total_clicks", 0))
|
|
var service_ticks := int(auto.get("service_ticks", 0))
|
|
var auto_valid := owned >= 0 and is_finite(remainder) and remainder >= 0.0 and remainder < 1.0 \
|
|
and is_finite(timer) and timer >= 0.0 and total_clicks >= 0 and service_ticks >= 0
|
|
result["autoclick"] = {
|
|
"owned": owned if auto_valid else 0,
|
|
"remainder": remainder if auto_valid else 0.0,
|
|
"timer": timer if auto_valid else 0.0,
|
|
"total_clicks": total_clicks if auto_valid else 0,
|
|
"service_ticks": service_ticks if auto_valid else 0,
|
|
}
|
|
|
|
# Clickable: CH restore() bounds seeds, UIDs, phase and counters; an active
|
|
# UID beyond next_uid is corrupt and the entitlement is dropped.
|
|
var click: Dictionary = result.get("clickable", {}) if result.get("clickable") is Dictionary else {}
|
|
var cseed := int(click.get("spawn_seed", 1))
|
|
var rseed := int(click.get("reward_seed", 1))
|
|
var cnext := int(click.get("next_uid", 1))
|
|
var active := int(click.get("active_uid", 0))
|
|
var phase := float(click.get("phase", 0.0))
|
|
var claims := int(click.get("total_claims", 0))
|
|
var rubies := int(click.get("ruby_rewards", 0))
|
|
var crev := int(click.get("revision", 0))
|
|
var clicked_valid := cseed >= 1 and cseed <= 2147483646 and rseed >= 1 and rseed <= 2147483646 \
|
|
and cnext >= 1 and active >= 0 and active <= cnext and claims >= 0 and rubies >= 0 and rubies <= claims \
|
|
and crev >= 0 and is_finite(phase) and phase >= 0.0 and phase < 1.0
|
|
if not clicked_valid:
|
|
cseed = 1234567
|
|
rseed = 7654321
|
|
cnext = 1
|
|
active = 0
|
|
phase = 0.0
|
|
claims = 0
|
|
rubies = 0
|
|
crev = 0
|
|
result["clickable"] = {
|
|
"spawn_seed": cseed, "reward_seed": rseed,
|
|
"spawn_uses": clampi(int(click.get("spawn_uses", 0)), 0, 4294967295),
|
|
"reward_uses": clampi(int(click.get("reward_uses", 0)), 0, 4294967295),
|
|
"next_uid": cnext, "active_uid": active, "revision": crev, "phase": phase,
|
|
"ruby_rewards": rubies, "total_claims": claims,
|
|
}
|
|
|
|
# Achievement 43 is the only source-bound record in this slice.
|
|
var ach: Dictionary = result.get("ch_achievements", {}) if result.get("ch_achievements") is Dictionary else {}
|
|
var obtained: Array = ach.get("obtained", []) if ach.get("obtained") is Array else []
|
|
var safe_obtained: Array = []
|
|
for id in obtained:
|
|
if int(id) == ChSystems.CLICK_BONUS_ACHIEVEMENT_ID and not safe_obtained.has(int(id)):
|
|
safe_obtained.append(int(id))
|
|
var bonus := int(ach.get("click_bonus", 0))
|
|
if safe_obtained.is_empty():
|
|
bonus = 0
|
|
else:
|
|
bonus = ChSystems.CLICK_BONUS_AMOUNT
|
|
result["ch_achievements"] = {"obtained": safe_obtained, "click_bonus": bonus,
|
|
"revision": maxi(0, int(ach.get("revision", 0)))}
|
|
|
|
|
|
## Test hook: normalize a profile dict (used after prestige apply so reset
|
|
## fields get concrete safe defaults rather than being absent until reload).
|
|
static func normalize_for_test(profile: Dictionary) -> Dictionary:
|
|
return _normalize(profile)
|
|
|
|
|
|
static func save_profile(profile: Dictionary) -> bool:
|
|
var data := _normalize(profile)
|
|
data["schema"] = SCHEMA
|
|
data["last_saved_at"] = Time.get_unix_time_from_system()
|
|
# CH game_state.gd:2383 touch_anchor: the wall-clock high-water mark
|
|
# advances on every save and never moves backward. last_saved_at remains in
|
|
# seconds for the existing report/UI contract; the anchor is its ms analogue.
|
|
var now_ms := mini(int(data["last_saved_at"]) * 1000, OFFLINE_LIMIT)
|
|
data["offline_anchor_ms"] = maxi(int(data.get("offline_anchor_ms", 0)), now_ms)
|
|
var temp := FileAccess.open(temp_path(), FileAccess.WRITE)
|
|
if temp == null:
|
|
push_error("Could not open profile temp file for writing")
|
|
return false
|
|
temp.store_string(JSON.stringify(data, "\t", true))
|
|
temp.close()
|
|
var dir := DirAccess.open(save_dir())
|
|
if dir == null:
|
|
return false
|
|
# rename() is atomic on the same filesystem; the old save stays intact if
|
|
# the process dies before the swap.
|
|
var error := dir.rename(TEMP_NAME, SAVE_NAME)
|
|
if error != OK:
|
|
push_error("Profile rename failed: %d" % error)
|
|
return false
|
|
return true
|
|
|
|
|
|
## Compute a bounded offline report for a returning player. The report is
|
|
## stored rather than applied immediately, so claiming is explicit and a
|
|
## repeated claim cannot pay twice.
|
|
##
|
|
## v6 adds the CH settlement book: a wall-clock high-water mark (anchor_ms),
|
|
## an 8h cap, a 240s pause gate, rollback detection and a revision-stamped
|
|
## receipt. All constants and field names come from CH @ 46cc8ad
|
|
## offline_book.gd / game_state.gd::settle_offline. WR keeps its own gold rate
|
|
## and claim UI; CH souls/cores/relic/seed/tail have no WR offline consumer and
|
|
## are deliberately not carried (no value is invented for them).
|
|
const PartnerPerks = preload("res://scripts/partner_perks.gd")
|
|
|
|
|
|
static func _clear_offline_report(profile: Dictionary) -> void:
|
|
profile["pending_offline_gold"] = 0
|
|
profile["offline_report_key"] = ""
|
|
profile["offline_pending"] = false
|
|
|
|
|
|
static func build_offline_report(profile: Dictionary, roster_dps: float,
|
|
now_ms: int = -1, kind: String = "startup", pause_from_ms: int = 0) -> Dictionary:
|
|
# An unclaimed report is earned currency; a later save must not erase it.
|
|
var pending := int(profile.get("pending_offline_gold", 0))
|
|
var pending_key := str(profile.get("offline_report_key", ""))
|
|
if (pending > 0 and not pending_key.is_empty()) or bool(profile.get("offline_pending", false)):
|
|
return {}
|
|
if not kind in ["startup", "pause"] or pause_from_ms < 0 or pause_from_ms > OFFLINE_LIMIT:
|
|
return {}
|
|
if now_ms < 0:
|
|
now_ms = Time.get_unix_time_from_system() * 1000
|
|
now_ms = mini(maxi(now_ms, 0), OFFLINE_LIMIT)
|
|
var anchor := int(profile.get("offline_anchor_ms", 0))
|
|
if anchor <= 0:
|
|
# Legacy save: CH restores a pre-anchor stamp as timestamp * 1000.
|
|
anchor = mini(maxi(int(profile.get("last_saved_at", 0)), 0) * 1000, OFFLINE_LIMIT)
|
|
var from_ms := anchor if kind == "startup" else maxi(anchor, pause_from_ms)
|
|
if from_ms <= 0:
|
|
_clear_offline_report(profile)
|
|
return {}
|
|
var elapsed := maxi(0, now_ms - from_ms)
|
|
var rollback := now_ms < from_ms
|
|
var applied := mini(elapsed, OFFLINE_CAP_MS)
|
|
var capped := elapsed > OFFLINE_CAP_MS
|
|
# The anchor always advances, even when the settlement grants no reward.
|
|
profile["offline_anchor_ms"] = maxi(from_ms, now_ms)
|
|
# CH gate: a pause settlement below PAUSE_GATE_MS only moves the anchor.
|
|
if kind == "pause" and elapsed < OFFLINE_PAUSE_GATE_MS:
|
|
_clear_offline_report(profile)
|
|
return {}
|
|
var seconds := float(applied) / 1000.0
|
|
var base := int(floor(seconds * maxf(0.0, roster_dps) * offline_rate()))
|
|
# Partner P01 (航海员) specialty: offline payout scales with its level.
|
|
var gold := PartnerPerks.apply_offline(profile, base)
|
|
if gold <= 0 and not capped and not rollback:
|
|
_clear_offline_report(profile)
|
|
return {}
|
|
var revision := int(profile.get("offline_revision", 0))
|
|
if revision >= OFFLINE_LIMIT:
|
|
return {}
|
|
revision += 1
|
|
var receipt := {
|
|
"id": revision, "kind": kind, "from_ms": from_ms,
|
|
"to_ms": int(profile["offline_anchor_ms"]), "applied_ms": applied,
|
|
"capped": capped, "rollback": rollback, "gold": gold,
|
|
}
|
|
profile["offline_revision"] = revision
|
|
profile["offline_receipt"] = receipt
|
|
# WR's claim button is gold-gated. A zero-value cap/rollback receipt is
|
|
# recorded for inspection but never left pending, so the book cannot wedge.
|
|
profile["offline_pending"] = gold > 0
|
|
profile["pending_offline_gold"] = gold
|
|
profile["offline_report_key"] = ("offline_%d" % revision) if gold > 0 else ""
|
|
return receipt
|
|
|
|
|
|
static func claim_offline(profile: Dictionary) -> int:
|
|
var gold := int(profile.get("pending_offline_gold", 0))
|
|
var key := str(profile.get("offline_report_key", ""))
|
|
if gold <= 0 or key.is_empty():
|
|
return 0
|
|
# CH acknowledge_offline(id): a v6 receipt must match the book revision.
|
|
# A pre-v6 save carries a pending gold/key but no receipt; it stays claimable
|
|
# so migration never strands earned currency.
|
|
if bool(profile.get("offline_pending", false)):
|
|
var id := int(profile.get("offline_revision", -1))
|
|
var receipt: Dictionary = profile.get("offline_receipt", {})
|
|
if int(receipt.get("id", -1)) != id:
|
|
return 0
|
|
var claimed := profile.duplicate(true)
|
|
if not claim_once(claimed, key):
|
|
return 0
|
|
claimed["gold"] = int(claimed.get("gold", 0)) + gold
|
|
claimed["pending_offline_gold"] = 0
|
|
claimed["offline_report_key"] = ""
|
|
claimed["offline_pending"] = false
|
|
# Save-first: the claimed state reaches disk before the in-memory profile
|
|
# adopts it. A failed write leaves both the pending report and the wallet
|
|
# untouched, so a retry cannot double-pay.
|
|
if not save_profile(claimed):
|
|
return 0
|
|
profile["gold"] = claimed["gold"]
|
|
profile["claimed_rewards"] = claimed["claimed_rewards"]
|
|
profile["pending_offline_gold"] = 0
|
|
profile["offline_report_key"] = ""
|
|
profile["offline_pending"] = false
|
|
return gold
|
|
|
|
|
|
static func claim_once(profile: Dictionary, reward_id: String) -> bool:
|
|
var claimed: Array = profile.get("claimed_rewards", [])
|
|
if claimed.has(reward_id):
|
|
return false
|
|
claimed.append(reward_id)
|
|
profile["claimed_rewards"] = claimed
|
|
return true
|
|
|
|
|
|
## ---- S5/S6 CH systems operations -------------------------------------------
|
|
## All CH constants/IDs are read from ChSystems (source-bound). WR payments are
|
|
## explicit adapters: crystal for ruby prices, revive_charges for ruby/candy,
|
|
## crystal for clickable ruby tiers, auto-click output for addClickDamage.
|
|
|
|
static func ch_slots(profile: Dictionary) -> Array:
|
|
return profile.get("merc_quests", []) if profile.get("merc_quests") is Array else []
|
|
|
|
|
|
static func ch_slot(profile: Dictionary, uid: int) -> Dictionary:
|
|
for item in ch_slots(profile):
|
|
var row: Dictionary = item
|
|
if int(row.get("uid", 0)) == uid:
|
|
return row
|
|
return {}
|
|
|
|
|
|
static func hire_merc(profile: Dictionary) -> Dictionary:
|
|
if ch_slots(profile).size() >= 5:
|
|
return {"ok": false, "reason": "full"}
|
|
if int(profile.get("crystal", 0)) < ChSystems.HIRE_COST:
|
|
return {"ok": false, "reason": "no_crystal"}
|
|
var rng: Dictionary = profile.get("merc_rng", {})
|
|
var uid := int(profile.get("merc_next_uid", 1))
|
|
if uid < 1:
|
|
return {"ok": false, "reason": "bad_uid"}
|
|
profile["crystal"] = int(profile.get("crystal", 0)) - ChSystems.HIRE_COST
|
|
profile["merc_rng"] = rng
|
|
profile["merc_next_uid"] = uid + 1
|
|
profile["merc_hires"] = int(profile.get("merc_hires", 0)) + 1
|
|
var private_rng := ChSystems.fresh_rng(ChSystems.rng_step(rng))
|
|
var slots := ch_slots(profile)
|
|
slots.append({"uid": uid, "level": 1, "experience": 0.0, "quest": {}, "rng": private_rng})
|
|
profile["merc_quests"] = slots
|
|
return {"ok": true, "uid": uid, "crystal": ChSystems.HIRE_COST}
|
|
|
|
|
|
static func start_quest(profile: Dictionary, uid: int, now_ms: int = -1) -> Dictionary:
|
|
var slot := ch_slot(profile, uid)
|
|
if slot.is_empty() or not (slot.get("quest", {}) as Dictionary).is_empty():
|
|
return {"ok": false, "reason": "busy"}
|
|
if now_ms < 0:
|
|
now_ms = Time.get_unix_time_from_system() * 1000
|
|
var rng: Dictionary = slot.get("rng", ChSystems.fresh_rng(int(profile.get("merc_next_uid", 1))))
|
|
var quest := ChSystems.make_quest(now_ms, int(slot.get("level", 1)), rng)
|
|
var life := ChSystems.generate_life(rng)
|
|
quest["death"] = life if life > 0 and life <= ChSystems.QUEST_DURATION_SEC else 0
|
|
slot["rng"] = rng
|
|
slot["quest"] = quest
|
|
return {"ok": true, "quest": quest}
|
|
|
|
|
|
static func finish_quest(profile: Dictionary, uid: int, now_ms: int = -1) -> Dictionary:
|
|
var slot := ch_slot(profile, uid)
|
|
if slot.is_empty():
|
|
return {"ok": false, "reason": "no_merc"}
|
|
var quest: Dictionary = slot.get("quest", {})
|
|
if now_ms < 0:
|
|
now_ms = Time.get_unix_time_from_system() * 1000
|
|
if ChSystems.quest_status(quest, now_ms) != "ready":
|
|
return {"ok": false, "reason": "not_ready"}
|
|
var gold := maxi(0, int(quest.get("quantity", 0)))
|
|
var key := "ch_merc_quest_%d_%d" % [uid, int(quest.get("start", 0))]
|
|
var claimed := profile.duplicate(true)
|
|
if not claim_once(claimed, key):
|
|
return {"ok": false, "reason": "already_claimed"}
|
|
claimed["gold"] = int(claimed.get("gold", 0)) + gold
|
|
claimed["total_gold_earned"] = int(claimed.get("total_gold_earned", 0)) + gold
|
|
for row in ch_slots(claimed):
|
|
var r: Dictionary = row
|
|
if int(r.get("uid", 0)) != uid:
|
|
continue
|
|
var xp := float(r.get("experience", 0.0)) + float(ChSystems.QUEST_DURATION_SEC) / 86400.0
|
|
while xp > 0.99:
|
|
r["level"] = int(r.get("level", 1)) + 1
|
|
xp -= 1.0
|
|
r["experience"] = xp
|
|
r["quest"] = {}
|
|
break
|
|
# Save-first: the paid state reaches disk before the caller's in-memory copy.
|
|
if not save_profile(claimed):
|
|
return {"ok": false, "reason": "save_failed"}
|
|
for key_name in ["gold", "total_gold_earned", "claimed_rewards", "merc_quests", "merc_rng"]:
|
|
profile[key_name] = claimed[key_name]
|
|
return {"ok": true, "gold": gold}
|
|
|
|
|
|
static func revive_merc(profile: Dictionary, uid: int, now_ms: int = -1) -> Dictionary:
|
|
var slot := ch_slot(profile, uid)
|
|
if slot.is_empty():
|
|
return {"ok": false, "reason": "no_merc"}
|
|
var quest: Dictionary = slot.get("quest", {})
|
|
if now_ms < 0:
|
|
now_ms = Time.get_unix_time_from_system() * 1000
|
|
if ChSystems.quest_status(quest, now_ms) != "dead":
|
|
return {"ok": false, "reason": "not_dead"}
|
|
var cost := ChSystems.revival_cost(int(slot.get("level", 1)))
|
|
if cost < 0:
|
|
return {"ok": false, "reason": "level_cap"}
|
|
if int(profile.get("revive_charges", 0)) < 1:
|
|
return {"ok": false, "reason": "no_charge"}
|
|
var rng: Dictionary = slot.get("rng", profile.get("merc_rng", ChSystems.fresh_rng(1)))
|
|
var life := ChSystems.generate_life(rng)
|
|
if life < 1:
|
|
return {"ok": false, "reason": "life_failed"}
|
|
profile["revive_charges"] = int(profile.get("revive_charges", 0)) - 1
|
|
slot["rng"] = rng
|
|
quest["start"] = now_ms - int(quest.get("death", 0)) * 1000
|
|
quest["life"] = int(quest.get("duration", 0)) + life
|
|
quest["death"] = 0
|
|
slot["quest"] = quest
|
|
return {"ok": true, "cost": cost, "charges": 1}
|
|
|
|
|
|
static func dismiss_merc(profile: Dictionary, uid: int) -> Dictionary:
|
|
var slots := ch_slots(profile)
|
|
for i in slots.size():
|
|
var row: Dictionary = slots[i]
|
|
if int(row.get("uid", 0)) != uid:
|
|
continue
|
|
var quest: Dictionary = row.get("quest", {})
|
|
if not quest.is_empty():
|
|
return {"ok": false, "reason": "busy"}
|
|
slots.remove_at(i)
|
|
profile["merc_quests"] = slots
|
|
return {"ok": true}
|
|
return {"ok": false, "reason": "no_merc"}
|
|
|
|
|
|
static func buy_autoclicker(profile: Dictionary) -> Dictionary:
|
|
var auto: Dictionary = profile.get("autoclick", {})
|
|
var owned := int(auto.get("owned", 0))
|
|
var price := ChSystems.autoclicker_price(owned)
|
|
if price < 0 or int(profile.get("gold", 0)) < price:
|
|
return {"ok": false, "reason": "no_gold", "price": price}
|
|
profile["gold"] = int(profile.get("gold", 0)) - price
|
|
auto["owned"] = owned + 1
|
|
profile["autoclick"] = auto
|
|
return {"ok": true, "price": price, "owned": owned + 1}
|
|
|
|
|
|
## Auto-click output as a WR-original dps-equivalent consumer. CH has no gold
|
|
## conversion for autoclicks; WR adds the rate (plus the CH achievement 43
|
|
## click bonus) to the existing offline DPS input instead of editing battle rules.
|
|
static func ch_auto_dps(profile: Dictionary) -> float:
|
|
var auto: Dictionary = profile.get("autoclick", {}) if profile.get("autoclick") is Dictionary else {}
|
|
var ach: Dictionary = profile.get("ch_achievements", {}) if profile.get("ch_achievements") is Dictionary else {}
|
|
return ChSystems.autoclicker_rate(int(auto.get("owned", 0))) + float(ach.get("click_bonus", 0))
|
|
|
|
|
|
## Advance the live schedulers. Returns change flags; the caller decides when
|
|
## to persist. Long absences are capped inside ChSystems.clickable_advance().
|
|
static func tick_ch_services(profile: Dictionary, delta: float, unlocked: bool) -> Dictionary:
|
|
var auto: Dictionary = profile.get("autoclick", {}) if profile.get("autoclick") is Dictionary else {}
|
|
var advanced := ChSystems.autoclicker_advance(auto, delta)
|
|
profile["autoclick"] = auto
|
|
var clicks := int(advanced.get("clicks", 0))
|
|
var service := bool(advanced.get("service", false))
|
|
if clicks > 0:
|
|
auto["total_clicks"] = int(auto.get("total_clicks", 0)) + clicks
|
|
if service:
|
|
auto["service_ticks"] = int(auto.get("service_ticks", 0)) + 1
|
|
var click: Dictionary = profile.get("clickable", {}) if profile.get("clickable") is Dictionary else {}
|
|
var spawned := ChSystems.clickable_advance(click, delta, unlocked)
|
|
profile["clickable"] = click
|
|
var ach: Dictionary = profile.get("ch_achievements", {}) if profile.get("ch_achievements") is Dictionary else {}
|
|
var stats := {"numWorldResets": int(profile.get("rebuild_count", 0)),
|
|
"click_bonus": int(ach.get("click_bonus", 0))}
|
|
var scan := ChSystems.achievement_scan(stats, ach.get("obtained", []))
|
|
var achievement_changed := not (scan["unlocked"] as Array).is_empty()
|
|
if achievement_changed:
|
|
ach["obtained"] = scan["obtained"]
|
|
ach["click_bonus"] = scan["click_bonus"]
|
|
ach["revision"] = int(ach.get("revision", 0)) + 1
|
|
profile["ch_achievements"] = ach
|
|
return {"clicks": clicks, "service": service, "spawned": spawned,
|
|
"achievement": achievement_changed}
|
|
|
|
|
|
static func claim_clickable(profile: Dictionary, uid: int) -> Dictionary:
|
|
var click: Dictionary = profile.get("clickable", {}) if profile.get("clickable") is Dictionary else {}
|
|
var reward := ChSystems.clickable_reward(click, uid)
|
|
if reward.is_empty():
|
|
return {"ok": false, "reason": "no_clickable"}
|
|
var tier := int(reward.get("tier", 0))
|
|
var crystal := int(reward.get("crystal", 0))
|
|
var key := "ch_clickable_%d" % uid
|
|
var claimed := profile.duplicate(true)
|
|
if not claim_once(claimed, key):
|
|
return {"ok": false, "reason": "already_claimed"}
|
|
claimed["crystal"] = int(claimed.get("crystal", 0)) + crystal
|
|
claimed["clickable"] = click
|
|
if not save_profile(claimed):
|
|
return {"ok": false, "reason": "save_failed"}
|
|
for key_name in ["crystal", "claimed_rewards", "clickable"]:
|
|
profile[key_name] = claimed[key_name]
|
|
return {"ok": true, "tier": tier, "crystal": crystal}
|