Stage 2: accounts, characters, permadeath, levels and experience
ci / verify (push) Successful in 47s
ci / verify (push) Successful in 47s
Identity is shaped like Steamworks so swapping to it is one subclass and no schema change: the client presents an opaque ticket, the server validates it into a stable 64-bit account id, and nothing downstream sees anything else. LocalAuthProvider takes any ticket at face value -- insecure on purpose, and labelled as such everywhere, because the point is the shape rather than the security. Do not ship it. Characters persist as JSON keyed by account. Account ids are written as decimal strings because they are 64-bit and JSON numbers are doubles, which would silently round them. A corrupt store aborts the server rather than starting empty: starting empty looks like it worked and then saves over every character on the first level-up. Levels 1-15, +10 max health each, level DERIVED from lifetime experience rather than stored beside it, so a hand-edited save cannot produce a level 12 character with a level 3's experience. Experience is shared undivided across everyone alive in the instance -- splitting it would make bringing a friend cost you progress. A level-up heals by what it added, so gaining one mid-fight is relief rather than a bar that moved further from full. Death is permanent and unbinds the character entirely: no "return to the hub as the character who just died", because the run is over. The record is retired, never deleted. The five-character cap counts LIVING characters only -- counting the dead would lock a player out of their own account after five deaths. Verified by tools/diag_progression.tscn, which drives the real server through kill -> xp -> level -> health and death -> retire -> roster. The bot smoke test cannot cover that: bots are poor shots and rarely kill anything. Writing it caught two real ordering bugs -- the death event was dispatched before the payload that tells the player they died, and the dead character stayed bound to the peer. Also added --account and --store so several clients and test runs can coexist on one machine. The smoke test now uses a scratch store; without it a rerun resumed the previous run's characters and "a character was created" quietly stopped being true. 193 tests. check.sh, test.sh, smoke.sh, diag_progression and diag_prediction all pass.
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
class_name CharacterStore
|
||||
extends RefCounted
|
||||
## Server-side persistence for accounts and their characters.
|
||||
##
|
||||
## JSON on disk, because the shape is small, the write rate is low (a level-up
|
||||
## or a death, not a tick), and a save file you can open in a text editor is
|
||||
## worth a great deal while a game is still being built. If this ever becomes a
|
||||
## bottleneck the interface is narrow enough to put a database behind.
|
||||
##
|
||||
## Keyed by account id -- a 64-bit integer, deliberately the same shape as a
|
||||
## SteamID64 so swapping [AuthProvider] for a real Steam one needs no migration.
|
||||
|
||||
const SAVE_PATH := "user://characters.json"
|
||||
const FORMAT_VERSION := 1
|
||||
## Live characters an account may hold at once. Retired ones do not count: a
|
||||
## player who has died five times must not be locked out of their own account.
|
||||
const MAX_ACTIVE := 5
|
||||
|
||||
## account_id -> { "characters": Array[Character], "last_played": String }
|
||||
var _accounts: Dictionary[int, Dictionary] = {}
|
||||
var _path: String = SAVE_PATH
|
||||
var _rng := RandomNumberGenerator.new()
|
||||
|
||||
|
||||
func _init(path: String = SAVE_PATH) -> void:
|
||||
_path = path
|
||||
_rng.randomize()
|
||||
|
||||
|
||||
# --- Queries ----------------------------------------------------------------
|
||||
|
||||
func characters_for(account_id: int) -> Array[Character]:
|
||||
var entry: Dictionary = _accounts.get(account_id, {})
|
||||
var out: Array[Character] = []
|
||||
for c in entry.get("characters", []):
|
||||
out.append(c)
|
||||
return out
|
||||
|
||||
|
||||
func active_characters(account_id: int) -> Array[Character]:
|
||||
var out: Array[Character] = []
|
||||
for c in characters_for(account_id):
|
||||
if c.active:
|
||||
out.append(c)
|
||||
return out
|
||||
|
||||
|
||||
func get_character(account_id: int, character_id: String) -> Character:
|
||||
for c in characters_for(account_id):
|
||||
if c.id == character_id:
|
||||
return c
|
||||
return null
|
||||
|
||||
|
||||
## The character to select on login: the last one played if it is still alive,
|
||||
## otherwise the newest living one, otherwise nothing.
|
||||
func last_played(account_id: int) -> Character:
|
||||
var entry: Dictionary = _accounts.get(account_id, {})
|
||||
var wanted := String(entry.get("last_played", ""))
|
||||
var c := get_character(account_id, wanted)
|
||||
if c != null and c.active:
|
||||
return c
|
||||
var living := active_characters(account_id)
|
||||
if living.is_empty():
|
||||
return null
|
||||
var newest: Character = living[0]
|
||||
for candidate in living:
|
||||
if candidate.created_unix > newest.created_unix:
|
||||
newest = candidate
|
||||
return newest
|
||||
|
||||
|
||||
func can_create(account_id: int) -> bool:
|
||||
return active_characters(account_id).size() < MAX_ACTIVE
|
||||
|
||||
|
||||
# --- Mutations --------------------------------------------------------------
|
||||
|
||||
## Returns null when the account is already at its living-character limit.
|
||||
func create_character(account_id: int, character_name: String) -> Character:
|
||||
if not can_create(account_id):
|
||||
return null
|
||||
var c := Character.create(character_name, _rng)
|
||||
var entry: Dictionary = _accounts.get(account_id, {"characters": [], "last_played": ""})
|
||||
entry["characters"].append(c)
|
||||
entry["last_played"] = c.id
|
||||
_accounts[account_id] = entry
|
||||
save()
|
||||
return c
|
||||
|
||||
|
||||
func set_last_played(account_id: int, character_id: String) -> void:
|
||||
var entry: Dictionary = _accounts.get(account_id, {"characters": [], "last_played": ""})
|
||||
entry["last_played"] = character_id
|
||||
_accounts[account_id] = entry
|
||||
save()
|
||||
|
||||
|
||||
## Death. The record stays; only its active flag changes.
|
||||
func retire_character(account_id: int, character_id: String) -> void:
|
||||
var c := get_character(account_id, character_id)
|
||||
if c == null or not c.active:
|
||||
return
|
||||
c.retire()
|
||||
save()
|
||||
|
||||
|
||||
func grant_xp(account_id: int, character_id: String, amount: int) -> int:
|
||||
var c := get_character(account_id, character_id)
|
||||
if c == null:
|
||||
return 0
|
||||
var gained := c.grant_xp(amount)
|
||||
if gained > 0:
|
||||
save()
|
||||
return gained
|
||||
|
||||
|
||||
# --- Persistence ------------------------------------------------------------
|
||||
|
||||
func save() -> void:
|
||||
var accounts := {}
|
||||
for account_id in _accounts:
|
||||
var entry: Dictionary = _accounts[account_id]
|
||||
var chars := []
|
||||
for c in entry["characters"]:
|
||||
chars.append(c.to_dict())
|
||||
# JSON object keys are strings; account ids are 64-bit and would lose
|
||||
# precision as JSON numbers, so they are written as decimal strings.
|
||||
accounts[str(account_id)] = {
|
||||
"characters": chars,
|
||||
"last_played": entry.get("last_played", ""),
|
||||
}
|
||||
var f := FileAccess.open(_path, FileAccess.WRITE)
|
||||
if f == null:
|
||||
GameLog.error("store", "cannot write %s (error %d)" % [_path, FileAccess.get_open_error()])
|
||||
return
|
||||
f.store_string(JSON.stringify({"version": FORMAT_VERSION, "accounts": accounts}, "\t"))
|
||||
f.close()
|
||||
|
||||
|
||||
## A missing file is a new server, not an error. A corrupt one is refused
|
||||
## loudly and left alone rather than silently overwritten -- losing every
|
||||
## character to a stray byte would be far worse than refusing to start.
|
||||
func load_from_disk() -> bool:
|
||||
_accounts.clear()
|
||||
if not FileAccess.file_exists(_path):
|
||||
return true
|
||||
var f := FileAccess.open(_path, FileAccess.READ)
|
||||
if f == null:
|
||||
GameLog.error("store", "cannot read %s" % _path)
|
||||
return false
|
||||
var text := f.get_as_text()
|
||||
f.close()
|
||||
# JSON.new().parse() rather than JSON.parse_string(): it reports where the
|
||||
# file is malformed instead of just returning null, which is the difference
|
||||
# between a usable error and a mystery when someone's save will not load.
|
||||
var json := JSON.new()
|
||||
if json.parse(text) != OK or typeof(json.data) != TYPE_DICTIONARY:
|
||||
GameLog.error("store", "%s is not valid JSON (line %d: %s); refusing to overwrite it"
|
||||
% [_path, json.get_error_line(), json.get_error_message()])
|
||||
return false
|
||||
var data: Dictionary = json.data
|
||||
var accounts: Dictionary = data.get("accounts", {})
|
||||
for key in accounts:
|
||||
var account_id := int(str(key))
|
||||
var entry: Dictionary = accounts[key]
|
||||
var chars: Array[Character] = []
|
||||
for raw in entry.get("characters", []):
|
||||
chars.append(Character.from_dict(raw))
|
||||
_accounts[account_id] = {
|
||||
"characters": chars,
|
||||
"last_played": String(entry.get("last_played", "")),
|
||||
}
|
||||
GameLog.info("store", "loaded %d account(s) from %s" % [_accounts.size(), _path])
|
||||
return true
|
||||
Reference in New Issue
Block a user