Files
SimpleFarm/farm/models.py
T
snowy-yang f8e093c98f feat: 实时通道改 SSE、服务器换 uvicorn+zttp、节奏改 40 分钟一天,并重建测试与优化热路径
三件事凑成一次不兼容变更:WebSocket 通道、Hypercorn 服务器、「手动推进一天」都消失了。

实时通道:WebSocket -> SSE
- hub 改为 SSE 订阅池,GET /api/stream 单向推送 welcome/state/day/notice/bye,
  250ms 节流 + 15s 心跳注释;写操作一律走 HTTP POST /api/actions,不再有 WS 回执。
- 停机三处一起修才干净:close_all() 发 bye + timeout_graceful_shutdown 兜底 +
  客户端 stop() 直接 shutdown 底层 socket(光 close() 会等读线程的锁,最长卡到下次心跳)。
- 网页版改 EventSource + fetch;tools/ws_demo.py 换成 tools/sse_demo.py。

服务器:Hypercorn -> uvicorn + zttp 的 HTTP/2
- 同一端口同时说 HTTP/1.1 与 HTTP/2。uvicorn 0.53 不再内置 h2,必须装 zttp 并显式
  http="zttp",否则 Config.load() 直接 raise。
- 信号接管改成子类覆盖 Server.handle_exit(0.53 没有 install_signal_handlers 可覆盖),
  不调 super()、不写 _captured_signals,退出时不重放信号;第二次信号强制退出。
- 入口启动前用 daemon.port_busy() 自检端口:Windows 上 SO_REUSEADDR 会让第二个实例
  「绑上」已监听端口并抢走新连接,所以判断「能不能连上」而不是「能不能 bind」。
- 修掉 clear_pid_file 的 Windows 真 bug:文件还开着就 os.remove 会失败且被
  except OSError 吞掉,导致每次正常退出都留 stale pid 文件。

节奏:一天 15 秒 -> 40 分钟,并整体移除「休息」
- DEFAULT_TICK_SECONDS=2400,MAX_TICK_SECONDS 放宽到 86400(旧上限会把 40 分钟夹回去)。
- engine.sleep / SLEEP_COOLDOWN / /api/sleep / TUI 的 [N]休息 / 网页版按钮全部删掉,
  时间只能自然流动;机器人改为 wait_for_next_day(timeout),CLI 加 bot --wait。
- 时长显示统一走 models.format_duration(),不再出现 2399.6s 这种写法。

键盘:修复方向键/空格/Tab/ESC 全部静默失效
- keys.py 的具名键统一小写并成为唯一来源,tui.py 一律引用 keys.XXX 而不手写字符串
  (历史 bug 就是 Windows 侧产大写 UP、TUI 里写小写 up,字母键正常所以很难发现)。
- 顺带修 POSIX 路径一次 os.read 只取首字节、其余按键静默丢弃的老毛病。

测试:重建 500 项
- test_engine 110 / test_actions 35 / test_server 131(skip 35) / test_tui_keys 75 /
  test_bot 36 / test_client 113。未安装的第三方依赖用 skipUnless 自动跳过,其余照跑,
  所以是全绿而不是靠跳过伪装。
- 被测试逼出两处真隐患并修掉:RemoteFarm._normalize() 必须「先补 scheme 再削尾斜杠」
  (顺序反了畸形端点会溜到系统代理、报一个和真实原因无关的 502);StateView 空视图要
  预置 plots/animals,否则连不上服务器时读 state.plots 直接 AttributeError。

优化:先量后改,依据与前后数字都在 tools/bench.py
- 新增 engine.brief_source():brief/summary/动作回执只要十几个标量,不再为它们序列化
  整局;to_dict 里 net_worth 只算一次。brief -76%、summary -77%、leaderboard(32) -78%、
  GET /api/world -31%、POST /api/actions?full=1 -16%。
- 拆掉三个巨型函数:create_app 475->32 行(_Services + _register_*)、
  build_parser 与 available_actions 分组、__main__.main 160->7 行。
- 消除重复:等级门槛 5 处 -> _is_locked/_require_level/_newly_unlocked;hub 的
  broadcast/broadcast_all/close_all -> _push_many;daemon.probe/world -> _get_json;
  main.py 的 _add_endpoint_args/_leaderboard_lines。
- tools/bench.py 作为长期性能守卫(含调用计数器),谁把轻量路径改回 snapshot() 会立刻报警。

门禁:ruff format/check 全绿、pyright 0 错误、500 项测试 OK(skip 35)。
2026-09-19 12:55:45 +08:00

351 lines
12 KiB
Python

"""游戏数据模型。
设计原则:模型只负责"持有数据 + 结构化转换",所有规则判定放在 engine.py。
这样 HTTP 层和 TUI 层都能拿到同一份状态快照。
"""
from __future__ import annotations
import itertools
from typing import Any
from . import config
def clamp(value: float, low: float, high: float) -> float:
"""把 value 限制在 [low, high] 区间内。"""
return max(low, min(high, value))
def format_duration(seconds: float | None) -> str:
"""把秒数写成人看的时长:``45s`` / ``39:58`` / ``1:05:00``。
一天默认 40 分钟(2400 秒),直接显示秒数是一串难读的大数,
所以 TUI 头部、``main.py state`` 这类地方都走这个函数。
"""
if seconds is None:
return "—"
total = int(max(0.0, seconds))
if total < 60:
return f"{total}s"
hours, rest = divmod(total, 3600)
minutes, secs = divmod(rest, 60)
if hours:
return f"{hours}:{minutes:02d}:{secs:02d}"
return f"{minutes}:{secs:02d}"
def next_goal_after(index: int) -> dict[str, Any] | None:
"""给定目标序号,返回"下一个目标"。已到最后一个则返回 None。"""
nxt = index + 1
if nxt >= len(config.GOALS):
return None
amount, text = config.GOALS[nxt]
return {"amount": amount, "text": text}
class Plot:
"""一块土地。"""
__slots__ = ("crop", "growth", "index", "moisture", "planted_day")
def __init__(self, index: int) -> None:
self.index = index # 0-based 下标,对外展示用 index+1
self.crop: str | None = None
self.growth: float = 0.0 # 已生长天数
self.moisture: int = 0 # 剩余可支撑天数
self.planted_day: int = 0
# ---------------------------------------------------------------- 查询
@property
def is_empty(self) -> bool:
return self.crop is None
@property
def grow_days(self) -> int:
if self.crop is None:
return 0
return int(config.CROPS[self.crop]["grow_days"])
@property
def is_ripe(self) -> bool:
return self.crop is not None and self.growth >= self.grow_days
@property
def days_left(self) -> int:
if self.crop is None:
return 0
return max(0, self.grow_days - int(self.growth))
@property
def stage(self) -> str:
"""人类可读的生长阶段。"""
if self.crop is None:
return "空地"
progress = self.growth / max(1, self.grow_days)
name = "已播种"
for threshold, label in config.GROWTH_STAGES:
if progress >= threshold:
name = label
return name
# ---------------------------------------------------------------- 序列化
def to_dict(self) -> dict[str, Any]:
info = config.CROPS.get(self.crop) if self.crop else None
return {
"index": self.index,
"position": self.index + 1,
"crop": self.crop,
"crop_name": info["name"] if info else None,
"growth": round(self.growth, 2),
"grow_days": self.grow_days,
"days_left": self.days_left,
"is_ripe": self.is_ripe,
"is_empty": self.is_empty,
"moisture": self.moisture,
"water_capacity": config.WATER_CAPACITY,
"stage": self.stage,
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> Plot:
plot = cls(int(data.get("index", 0)))
crop = data.get("crop")
# 校验存档里的作物名仍然合法,避免旧存档导致 KeyError
plot.crop = crop if crop in config.CROPS else None
plot.growth = float(data.get("growth", 0.0))
plot.moisture = int(data.get("moisture", 0))
plot.planted_day = int(data.get("planted_day", 0))
return plot
class Animal:
"""一只牲畜。"""
_id_counter = itertools.count(1)
__slots__ = ("aid", "fed", "kind", "pending", "progress", "starve")
def __init__(self, kind: str, aid: int | None = None) -> None:
self.aid = aid if aid is not None else next(Animal._id_counter)
self.kind = kind
self.fed = False # 今天是否已喂食
self.progress = 0 # 距下次产出的累计天数
self.starve = 0 # 连续未进食天数
self.pending = 0 # 待收集的产出数量
# ---------------------------------------------------------------- 查询
@property
def info(self) -> dict[str, Any]:
return config.ANIMALS[self.kind]
@property
def name(self) -> str:
return self.info["name"]
@property
def product(self) -> str:
return self.info["product"]
@property
def cycle(self) -> int:
return int(self.info["cycle"])
@property
def days_to_product(self) -> int:
return max(0, self.cycle - self.progress)
@property
def is_sick(self) -> bool:
"""连续 2 天没吃东西,进入"虚弱"状态。"""
return self.starve >= 2
# ---------------------------------------------------------------- 序列化
def to_dict(self) -> dict[str, Any]:
return {
"id": self.aid,
"kind": self.kind,
"name": self.name,
"product": self.product,
"fed": self.fed,
"progress": self.progress,
"cycle": self.cycle,
"days_to_product": self.days_to_product,
"pending": self.pending,
"starve": self.starve,
"is_sick": self.is_sick,
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> Animal | None:
kind = data.get("kind")
if kind not in config.ANIMALS:
return None
animal = cls(kind, int(data.get("id", 0)) or None)
animal.fed = bool(data.get("fed", False))
animal.progress = int(data.get("progress", 0))
animal.starve = int(data.get("starve", 0))
animal.pending = int(data.get("pending", 0))
# 恢复 id 计数器,避免新动物与旧动物 id 冲突
Animal._id_counter = itertools.count(max(animal.aid + 1, next(Animal._id_counter)))
return animal
class GameState:
"""完整的游戏状态。所有字段都必须是可 JSON 序列化的。"""
def __init__(self) -> None:
self.day: int = 1
self.gold: int = config.START_GOLD
self.level: int = config.START_LEVEL
self.exp: int = 0
self.ap: int = config.START_AP
self.feed: int = config.START_FEED
self.plots: list[Plot] = [Plot(i) for i in range(config.BASE_PLOTS)]
self.animals: list[Animal] = []
self.log: list[dict[str, Any]] = []
# 市场价格(每天波动):key -> 当前单价
self.market: dict[str, float] = {
key: float(info["base_price"]) for key, info in config.CROPS.items()
}
for key, info in config.ANIMALS.items():
self.market[f"animal:{key}"] = float(info["base_price"])
# 统计
self.total_harvested: int = 0
self.total_collected: int = 0
self.total_earned: int = 0
self.total_spent: int = 0
self.plots_bought: int = 0
# ---------------------------------------------------------------- 派生属性
@property
def max_ap(self) -> int:
return config.START_AP
@property
def max_plots(self) -> int:
"""当前等级允许持有的土地上限。"""
allowed = config.BASE_PLOTS + config.PLOTS_PER_LEVEL * (self.level - 1)
return int(clamp(allowed, config.BASE_PLOTS, config.MAX_PLOTS))
@property
def next_plot_price(self) -> int:
"""下一块土地的价格;已达上限时返回 -1。"""
if len(self.plots) >= self.max_plots:
return -1
return int(config.PLOT_BASE_PRICE * (config.PLOT_PRICE_GROWTH**self.plots_bought))
@property
def exp_needed(self) -> int:
return config.exp_to_next(self.level)
@property
def inventory_value(self) -> float:
return self.feed * config.FEED_UNIT_PRICE
@property
def livestock_value(self) -> float:
return sum(
a.pending * self.market.get(f"animal:{a.kind}", 0) + a.info["cost"] * 0.5
for a in self.animals
)
@property
def net_worth(self) -> float:
"""净资产:金币 + 已购地价 + 牲畜折价 + 库存 + 地里未收的作物。"""
land = sum(
config.PLOT_BASE_PRICE * (config.PLOT_PRICE_GROWTH**i) for i in range(self.plots_bought)
)
crops = 0.0
for plot in self.plots:
if plot.crop:
crops += self.market.get(plot.crop, 0) * (plot.growth / max(1, plot.grow_days))
return self.gold + land + self.livestock_value + self.inventory_value + crops
@property
def goal_index(self) -> int:
return config.goal_index(self.net_worth)
@property
def next_goal(self) -> dict[str, Any] | None:
return next_goal_after(self.goal_index)
# ---------------------------------------------------------------- 序列化
def to_dict(self) -> dict[str, Any]:
# net_worth 要遍历地块与牲畜,是这里最贵的一项;下面三处都要用它,
# 所以只算一次再分发给 net_worth / goal_index / next_goal。
worth = self.net_worth
goal = config.goal_index(worth)
return {
"day": self.day,
"gold": self.gold,
"level": self.level,
"exp": self.exp,
"exp_needed": self.exp_needed,
"ap": self.ap,
"max_ap": self.max_ap,
"feed": self.feed,
"plots": [p.to_dict() for p in self.plots],
"plot_count": len(self.plots),
"max_plots": self.max_plots,
"next_plot_price": self.next_plot_price,
"animals": [a.to_dict() for a in self.animals],
"animal_count": len(self.animals),
"max_animals": config.MAX_ANIMALS,
"market": {k: round(v, 2) for k, v in self.market.items()},
"net_worth": round(worth, 2),
"goal_index": goal,
"next_goal": next_goal_after(goal),
"stats": {
"harvested": self.total_harvested,
"collected": self.total_collected,
"earned": self.total_earned,
"spent": self.total_spent,
},
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> GameState:
state = cls()
state.day = max(1, int(data.get("day", 1)))
state.gold = max(0, int(data.get("gold", config.START_GOLD)))
state.level = max(1, int(data.get("level", 1)))
state.exp = max(0, int(data.get("exp", 0)))
state.feed = max(0, int(data.get("feed", 0)))
state.ap = int(clamp(int(data.get("ap", state.max_ap)), 0, state.max_ap))
plots = [Plot.from_dict(p) for p in data.get("plots", []) if isinstance(p, dict)]
# 保证至少有初始土地,且不超过硬上限
count = int(clamp(len(plots) or config.BASE_PLOTS, config.BASE_PLOTS, config.MAX_PLOTS))
if len(plots) < count:
plots.extend(Plot(i) for i in range(len(plots), count))
state.plots = plots[: config.MAX_PLOTS]
for i, plot in enumerate(state.plots):
plot.index = i
animals: list[Animal] = []
for item in data.get("animals", [])[: config.MAX_ANIMALS]:
if isinstance(item, dict):
animal = Animal.from_dict(item)
if animal is not None:
animals.append(animal)
state.animals = animals
market = data.get("market", {})
for key in list(state.market.keys()):
try:
value = float(market.get(key, state.market[key]))
except (TypeError, ValueError):
continue
state.market[key] = clamp(value, 1.0, 100000.0)
stats = data.get("stats", {})
state.total_harvested = max(0, int(stats.get("harvested", 0)))
state.total_collected = max(0, int(stats.get("collected", 0)))
state.total_earned = max(0, int(stats.get("earned", 0)))
state.total_spent = max(0, int(stats.get("spent", 0)))
state.plots_bought = max(0, len(state.plots) - config.BASE_PLOTS)
return state