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 项测试全绿。
This commit is contained in:
snowy-yang committed 2026-09-18 21:18:22 +08:00
1 parent c7c8a6308a
commit fcd4cb4649
25 files changed
+1204 -794

No files matched your search

+28 -29
View File
@@ -7,7 +7,7 @@
from __future__ import annotations
import itertools
from typing import Any, Dict, List, Optional
from typing import Any
from . import config
@@ -20,13 +20,13 @@ def clamp(value: float, low: float, high: float) -> float:
class Plot:
"""一块土地。"""
__slots__ = ("index", "crop", "growth", "moisture", "planted_day")
__slots__ = ("crop", "growth", "index", "moisture", "planted_day")
def __init__(self, index: int) -> None:
self.index = index # 0-based 下标,对外展示用 index+1
self.crop: Optional[str] = None
self.growth: float = 0.0 # 已生长天数
self.moisture: int = 0 # 剩余可支撑天数
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
# ---------------------------------------------------------------- 查询
@@ -63,7 +63,7 @@ class Plot:
return name
# ---------------------------------------------------------------- 序列化
def to_dict(self) -> Dict[str, Any]:
def to_dict(self) -> dict[str, Any]:
info = config.CROPS.get(self.crop) if self.crop else None
return {
"index": self.index,
@@ -81,7 +81,7 @@ class Plot:
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "Plot":
def from_dict(cls, data: dict[str, Any]) -> Plot:
plot = cls(int(data.get("index", 0)))
crop = data.get("crop")
# 校验存档里的作物名仍然合法,避免旧存档导致 KeyError
@@ -97,19 +97,19 @@ class Animal:
_id_counter = itertools.count(1)
__slots__ = ("aid", "kind", "fed", "progress", "starve", "pending")
__slots__ = ("aid", "fed", "kind", "pending", "progress", "starve")
def __init__(self, kind: str, aid: Optional[int] = None) -> None:
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 # 待收集的产出数量
self.fed = False # 今天是否已喂食
self.progress = 0 # 距下次产出的累计天数
self.starve = 0 # 连续未进食天数
self.pending = 0 # 待收集的产出数量
# ---------------------------------------------------------------- 查询
@property
def info(self) -> Dict[str, Any]:
def info(self) -> dict[str, Any]:
return config.ANIMALS[self.kind]
@property
@@ -134,7 +134,7 @@ class Animal:
return self.starve >= 2
# ---------------------------------------------------------------- 序列化
def to_dict(self) -> Dict[str, Any]:
def to_dict(self) -> dict[str, Any]:
return {
"id": self.aid,
"kind": self.kind,
@@ -150,7 +150,7 @@ class Animal:
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> Optional["Animal"]:
def from_dict(cls, data: dict[str, Any]) -> Animal | None:
kind = data.get("kind")
if kind not in config.ANIMALS:
return None
@@ -174,12 +174,12 @@ class GameState:
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]] = []
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] = {
self.market: dict[str, float] = {
key: float(info["base_price"]) for key, info in config.CROPS.items()
}
for key, info in config.ANIMALS.items():
@@ -208,7 +208,7 @@ class GameState:
"""下一块土地的价格;已达上限时返回 -1。"""
if len(self.plots) >= self.max_plots:
return -1
return int(config.PLOT_BASE_PRICE * (config.PLOT_PRICE_GROWTH ** self.plots_bought))
return int(config.PLOT_BASE_PRICE * (config.PLOT_PRICE_GROWTH**self.plots_bought))
@property
def exp_needed(self) -> int:
@@ -229,8 +229,7 @@ class GameState:
def net_worth(self) -> float:
"""净资产:金币 + 已购地价 + 牲畜折价 + 库存 + 地里未收的作物。"""
land = sum(
config.PLOT_BASE_PRICE * (config.PLOT_PRICE_GROWTH ** i)
for i in range(self.plots_bought)
config.PLOT_BASE_PRICE * (config.PLOT_PRICE_GROWTH**i) for i in range(self.plots_bought)
)
crops = 0.0
for plot in self.plots:
@@ -243,7 +242,7 @@ class GameState:
return config.goal_index(self.net_worth)
@property
def next_goal(self) -> Optional[Dict[str, Any]]:
def next_goal(self) -> dict[str, Any] | None:
nxt = self.goal_index + 1
if nxt >= len(config.GOALS):
return None
@@ -251,7 +250,7 @@ class GameState:
return {"amount": amount, "text": text}
# ---------------------------------------------------------------- 序列化
def to_dict(self) -> Dict[str, Any]:
def to_dict(self) -> dict[str, Any]:
return {
"day": self.day,
"gold": self.gold,
@@ -281,7 +280,7 @@ class GameState:
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "GameState":
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)))
@@ -295,11 +294,11 @@ class GameState:
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]
state.plots = plots[: config.MAX_PLOTS]
for i, plot in enumerate(state.plots):
plot.index = i
animals: List[Animal] = []
animals: list[Animal] = []
for item in data.get("animals", [])[: config.MAX_ANIMALS]:
if isinstance(item, dict):
animal = Animal.from_dict(item)