Files
SimpleFarm/farm/storage.py
T
snowy-yang fcd4cb4649 style: 引入 ruff,474 项告警清零
配置见 pyproject.toml:
- line-length=100:贴着现有代码定。若用默认的 88 会重排 122 行,
  噪音淹没真正有价值的修复。
- 启用 E/W/F/I/UP/B/C4/SIM/RET/PERF/RUF;**不**启用 PTH。因为本项目的路径
  多是"字符串身份"——要塞进 subprocess 命令行、写进 JSON 存档、打印给用户,
  全换 pathlib 只是包一层再拆一层,换来 70 处纯风格改动。
- 忽略 RUF001/002/003:中文全角标点是正确写法,不是"歧义字符"。
- 忽略 PERF203:剩下两处都是"逐项容错"语义(逐个牧场存档要立刻上报失败、
  收获全部要跳过失败地块)。把 try 提到循环外会毁掉"一项失败不影响其它项"
  这个行为,是错的优化。

自动修复 358 项:Dict/List/Optional 换成 PEP 585/604 写法、导入排序、
失效的 noqa、空占位 f-string 等。

手工修复的(这些是真问题,不是风格偏好):
- B904 x9:except 中 raise 补异常链。刻意区分——网络/IO 失败用 from exc 保留
  根因;参数解析失败用 from None,因为底层 ValueError 对玩家只是噪音。
- RUF012 x2:StateView 的 plots/animals 原本是**类级共享可变列表**,
  改成在 __init__ 里初始化(apply({}) 会提前返回,所以必须显式摆好)。
- F841:TUI 里一个赋值后再没用过的死变量。
- SIM105 x11:try/except/pass 统一改成 contextlib.suppress。
- SIM115:日志句柄改用 with。Popen 已把 fd 复制给子进程,父进程可安全关闭。
- E501 x7:拆超长行;main.py 那处顺手提取变量,避免超长嵌套表达式。
- E741:把 l/r 改成 left_line/right_line。
- 其余:RUF046 / PERF401 / RET504 / RUF005 / UP031 / B007。

ruff format 重排 24 个文件。

验证:97 项测试全绿。
2026-09-18 21:18:22 +08:00

130 lines
3.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""存档读写。
存档是纯 JSON,方便人工检查,也方便外部工具/AI 直接读取分析。
写入采用"临时文件 + 原子替换",避免中途崩溃导致存档损坏。
"""
from __future__ import annotations
import json
import os
import time
from typing import Any
from .models import GameState
SAVE_VERSION = 1
def default_save_path() -> str:
"""默认存档位置:项目根目录下的 saves/save.json。"""
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
return os.path.join(root, "saves", "save.json")
def save_state(state: GameState, path: str | None = None) -> str:
"""把状态写入磁盘,返回实际写入路径。"""
path = path or default_save_path()
directory = os.path.dirname(os.path.abspath(path))
os.makedirs(directory, exist_ok=True)
payload = {
"version": SAVE_VERSION,
"saved_at": time.strftime("%Y-%m-%d %H:%M:%S"),
"state": state.to_dict(),
}
# 注意:to_dict() 里的派生字段在读取时会被忽略,这里只取原始字段
payload["state"] = _raw_state(state)
tmp_path = path + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as handle:
json.dump(payload, handle, ensure_ascii=False, indent=2)
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_path, path)
return path
def _raw_state(state: GameState) -> dict[str, Any]:
"""导出可完整还原的原始字段(与 to_dict 的展示字段不同)。"""
return {
"day": state.day,
"gold": state.gold,
"level": state.level,
"exp": state.exp,
"ap": state.ap,
"feed": state.feed,
"plots": [
{
"index": p.index,
"crop": p.crop,
"growth": p.growth,
"moisture": p.moisture,
"planted_day": p.planted_day,
}
for p in state.plots
],
"animals": [
{
"id": a.aid,
"kind": a.kind,
"fed": a.fed,
"progress": a.progress,
"starve": a.starve,
"pending": a.pending,
}
for a in state.animals
],
"market": state.market,
"stats": {
"harvested": state.total_harvested,
"collected": state.total_collected,
"earned": state.total_earned,
"spent": state.total_spent,
},
}
def load_state(path: str | None = None) -> tuple[GameState | None, str]:
"""读取存档。
返回 ``(state, message)``;失败时 ``state`` 为 None 并给出原因,
调用方应当降级为"开新档"而不是崩溃。
"""
path = path or default_save_path()
if not os.path.exists(path):
return None, f"未找到存档 {path}"
try:
with open(path, encoding="utf-8") as handle:
payload = json.load(handle)
except (OSError, json.JSONDecodeError) as exc:
return None, f"存档无法解析:{exc}"
if not isinstance(payload, dict):
return None, "存档格式错误:根节点不是对象"
version = payload.get("version", 0)
if version != SAVE_VERSION:
return None, f"存档版本不兼容(文件 v{version},当前 v{SAVE_VERSION})"
raw = payload.get("state")
if not isinstance(raw, dict):
return None, "存档缺少 state 字段"
try:
state = GameState.from_dict(raw)
except (TypeError, ValueError, KeyError) as exc:
return None, f"存档内容异常:{exc}"
return state, f"已载入存档(第 {state.day} 天)"
def delete_save(path: str | None = None) -> bool:
path = path or default_save_path()
try:
os.remove(path)
return True
except OSError:
return False