为什么:游戏的时间(40 分钟一天、只能自然流动)本身就是唯一的行动节奏 阀门,再叠一层"每天 10 点行动点"纯属重复惩罚——浇水还要体力既不拟真 也不好玩。删掉之后,稀缺的只剩时间本身,放置玩法的定位反而更纯粹。 改动范围(引擎到界面连根拔): - config 删 START_AP/AP_COST;models 删 ap 字段与 max_ap,存档 payload 里的旧 ap 键被 from_dict 自然忽略; - engine 删 _spend_ap 与全部 8 个调用点、每日恢复逻辑与日志; available_actions 不再按行动点筛,cost 只剩金币; - storage 建表去掉 ap 列,老库在 connect() 里 ALTER TABLE DROP COLUMN 无痛迁移(实测 saves/farm.db 已自动迁完); - bot 删 AP 分支(无 AP 后 available_actions 恒可用);client/TUI/CLI/ README/帮助文本同步清理。 网页端顺带两件事: - "下一天"倒计时改为客户端本地走秒——SSE 只在有变化时推送,以前倒计时 只在推送瞬间跳变,现在每秒都在动(记基点 + 1s 定时器补齐); - 字体优化:页面字体栈补齐 MiSans/HarmonyOS Sans/PingFang,正文字号 14→15,统计数字 tabular-nums;canvas 小字统一字体栈并加粗提对比度。 测试适配:删 2 个 AP 专属用例(无 AP 可测)、改名/收敛 5 个, 532 项全绿(skip 39),ruff/pyright 干净。真机验证:老库迁移、 统计条无行动点、倒计时逐秒递减(39:04→39:02)、动作不再报 no_ap。
421 lines
15 KiB
Python
421 lines
15 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.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
|
|
|
|
# 谷仓:收获先进这里,卖不卖、什么时候卖由玩家决定。
|
|
# 键与 self.market 完全同构(作物用 "wheat",畜产品用 "animal:chicken"),
|
|
# 这样定价、序列化、存档校验都只有一套规则。
|
|
self.inventory: dict[str, int] = {}
|
|
# 建筑:key -> 已建座数(0 表示还没造)
|
|
self.buildings: dict[str, int] = dict.fromkeys(config.BUILDINGS, 0)
|
|
# 天气:今天与明天。掷骰在 engine 里做,模型层只持有结果,
|
|
# 这样"存/读档"不需要重放随机序列就能复原当天的天气。
|
|
self.weather: str = config.DEFAULT_WEATHER
|
|
self.forecast: str = config.DEFAULT_WEATHER
|
|
|
|
# ---------------------------------------------------------------- 派生属性
|
|
@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))
|
|
stored = self.goods_value
|
|
return self.gold + land + self.livestock_value + self.inventory_value + crops + stored
|
|
|
|
@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)
|
|
|
|
@property
|
|
def granary_capacity(self) -> int:
|
|
"""仓储上限:基础值 + 等级成长 + 谷仓建筑。"""
|
|
cap = (
|
|
config.GRANARY_BASE
|
|
+ config.GRANARY_PER_LEVEL * (self.level - 1)
|
|
+ config.GRANARY_PER_UPGRADE * self.building_count("granary")
|
|
)
|
|
return int(clamp(cap, config.GRANARY_BASE, config.MAX_GRANARY))
|
|
|
|
@property
|
|
def storage_used(self) -> int:
|
|
return sum(self.inventory.values())
|
|
|
|
@property
|
|
def granary_free(self) -> int:
|
|
return max(0, self.granary_capacity - self.storage_used)
|
|
|
|
@property
|
|
def goods_value(self) -> float:
|
|
"""谷仓存货按**当前市价**的估值(会随市场波动,这正是囤货的风险与收益)。"""
|
|
return sum(count * self.market.get(key, 0.0) for key, count in self.inventory.items())
|
|
|
|
def building_count(self, key: str) -> int:
|
|
return int(self.buildings.get(key, 0))
|
|
|
|
# ---------------------------------------------------------------- 序列化
|
|
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,
|
|
"weather": self.weather,
|
|
"weather_name": config.weather_info(self.weather)["name"],
|
|
"weather_desc": config.weather_info(self.weather)["desc"],
|
|
"forecast": self.forecast,
|
|
"forecast_name": config.weather_info(self.forecast)["name"],
|
|
"gold": self.gold,
|
|
"level": self.level,
|
|
"exp": self.exp,
|
|
"exp_needed": self.exp_needed,
|
|
"feed": self.feed,
|
|
"inventory": dict(sorted(self.inventory.items())),
|
|
"storage_used": self.storage_used,
|
|
"granary_capacity": self.granary_capacity,
|
|
"granary_free": self.granary_free,
|
|
"buildings": dict(self.buildings),
|
|
"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)))
|
|
|
|
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
|
|
|
|
raw_buildings = data.get("buildings", {})
|
|
if isinstance(raw_buildings, dict):
|
|
for key, info in config.BUILDINGS.items():
|
|
try:
|
|
owned = int(raw_buildings.get(key, 0))
|
|
except (TypeError, ValueError):
|
|
continue
|
|
state.buildings[key] = int(clamp(owned, 0, info["max_level"]))
|
|
|
|
weather = data.get("weather")
|
|
if isinstance(weather, str) and weather in config.WEATHER:
|
|
state.weather = weather
|
|
forecast = data.get("forecast")
|
|
if isinstance(forecast, str) and forecast in config.WEATHER:
|
|
state.forecast = forecast
|
|
|
|
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)
|
|
|
|
# 存货键必须存在于 market:顺手挡住"手改存档塞进来的野键",
|
|
# 否则它会一直躺在谷仓里、既卖不掉也算不进净资产。
|
|
raw_inventory = data.get("inventory", {})
|
|
if isinstance(raw_inventory, dict):
|
|
for key, count in raw_inventory.items():
|
|
if key not in state.market:
|
|
continue
|
|
try:
|
|
amount = int(count)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
if amount > 0:
|
|
state.inventory[key] = amount
|
|
|
|
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
|