72 lines
3.3 KiB
Python
72 lines
3.3 KiB
Python
"""Client-equivalent player level and natural stamina settlement."""
|
|
import time
|
|
|
|
from .model import seconds
|
|
|
|
|
|
class MasterSync:
|
|
def __init__(self, catalog):
|
|
self.catalog = catalog
|
|
self.attempts = {}
|
|
self.level = 0
|
|
self.stamina = None
|
|
|
|
def apply(self, snapshot):
|
|
master = dict(snapshot.raw["master"])
|
|
snapshot.raw["master"] = master
|
|
# A confirmed level cannot regress within this role's session.
|
|
master["level"] = max(int(master.get("level") or 1), self.level)
|
|
if self.stamina:
|
|
before, after, expires = self.stamina
|
|
pair = (master.get("ti"), master.get("timeTi"))
|
|
if pair == before and time.monotonic() < expires:
|
|
master.update(ti=after[0], timeTi=after[1])
|
|
else:
|
|
self.stamina = None
|
|
|
|
def pending(self, snapshot):
|
|
if snapshot is None:
|
|
return []
|
|
master = snapshot.raw["master"]
|
|
settings = self.catalog.data.get("game_setting", {})
|
|
level = int(master.get("level") or 1)
|
|
threshold = self.catalog.data.get("farm_level", {}).get(str(level + 1))
|
|
paths = []
|
|
if (level < int(settings.get("masterMaxLevel", 70)) and threshold is not None
|
|
and float(master.get("exp") or 0) >= float(threshold)):
|
|
paths.append("masterService/masterLevelUpdate")
|
|
timestamp = seconds(master.get("timeTi"))
|
|
cooldown = float(settings.get("tiCD") or 150)
|
|
if timestamp > 0 and snapshot.now - timestamp >= cooldown:
|
|
paths.append("masterService/masterCheckTiAdd")
|
|
now = time.monotonic()
|
|
return [path for path in paths if now >= self.attempts.get(path, 0)]
|
|
|
|
def settle(self, client, snapshot):
|
|
master = snapshot.raw["master"]
|
|
updated = []
|
|
for path in self.pending(snapshot):
|
|
# Includes failures and unchanged replies; never spin on a stale value.
|
|
self.attempts[path] = time.monotonic() + 30
|
|
response = client.call(path, {})
|
|
if path.endswith("masterLevelUpdate"):
|
|
value = response.get("level")
|
|
if isinstance(value, bool) or not isinstance(value, (int, float)) or int(value) != value or value < int(master["level"]):
|
|
raise ValueError("升级响应缺少有效的角色等级")
|
|
self.level = int(value)
|
|
master["level"] = self.level
|
|
updated.append("等级")
|
|
else:
|
|
ti, timestamp = response.get("ti"), response.get("timeTi")
|
|
if (isinstance(ti, bool) or not isinstance(ti, (int, float)) or int(ti) != ti or ti < 0
|
|
or not isinstance(timestamp, (int, float)) or isinstance(timestamp, bool) or timestamp <= 0):
|
|
raise ValueError("体力恢复响应缺少有效的 ti / timeTi")
|
|
before = (master.get("ti"), master.get("timeTi"))
|
|
after = (int(ti), timestamp)
|
|
# Apply only over the exact pre-settlement pair, for a bounded
|
|
# period. A new cost/reward from the server always takes priority.
|
|
self.stamina = (before, after, time.monotonic() + 60)
|
|
master.update(ti=after[0], timeTi=after[1])
|
|
updated.append("体力")
|
|
return updated
|