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:
1 parent
c7c8a6308a
commit
fcd4cb4649
25 files changed
+1204
-794
No files matched your search
+23
-20
@@ -19,7 +19,7 @@ from __future__ import annotations
|
||||
import random
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any
|
||||
|
||||
from .engine import GameError
|
||||
|
||||
@@ -27,13 +27,14 @@ from .engine import GameError
|
||||
class RuleBot:
|
||||
"""一个会种地、会养殖、会投资的规则机器人。"""
|
||||
|
||||
def __init__(self, client, verbose: bool = True, pause: float = 0.25,
|
||||
name: str = "bot") -> None:
|
||||
self.client = client # 任何与 RemoteFarm 接口一致的对象
|
||||
def __init__(
|
||||
self, client, verbose: bool = True, pause: float = 0.25, name: str = "bot"
|
||||
) -> None:
|
||||
self.client = client # 任何与 RemoteFarm 接口一致的对象
|
||||
self.verbose = verbose
|
||||
self.pause = pause
|
||||
self.name = name
|
||||
self.done: List[str] = []
|
||||
self.done: list[str] = []
|
||||
self.failures = 0
|
||||
self.actions_executed = 0
|
||||
self._stop = threading.Event()
|
||||
@@ -51,8 +52,9 @@ class RuleBot:
|
||||
return self._stop.is_set()
|
||||
|
||||
# ------------------------------------------------------------ 打分
|
||||
def score(self, action: Dict[str, Any], state: Dict[str, Any],
|
||||
catalog: Dict[str, Any]) -> float:
|
||||
def score(
|
||||
self, action: dict[str, Any], state: dict[str, Any], catalog: dict[str, Any]
|
||||
) -> float:
|
||||
"""给一个候选动作打分。分数越高越先执行。
|
||||
|
||||
这张表就是整个"策略":先做免费的,再喂饱牲畜,再补水,再扩张。
|
||||
@@ -90,15 +92,16 @@ class RuleBot:
|
||||
return 34.0
|
||||
return 4.0
|
||||
if name == "buy_animal":
|
||||
info = next((a for a in catalog.get("animals", [])
|
||||
if a["key"] == params.get("kind")), None)
|
||||
info = next(
|
||||
(a for a in catalog.get("animals", []) if a["key"] == params.get("kind")), None
|
||||
)
|
||||
cost = info["cost"] if info else 0
|
||||
if cost and gold >= cost * 3 and ap >= 1:
|
||||
return 30.0 + (info.get("profit_per_day", 0) if info else 0)
|
||||
return 3.0
|
||||
return 1.0
|
||||
|
||||
def choose(self) -> Optional[Dict[str, Any]]:
|
||||
def choose(self) -> dict[str, Any] | None:
|
||||
"""在服务器给出的合法动作里挑一个最优的。"""
|
||||
actions = self.client.available_actions()
|
||||
if not actions:
|
||||
@@ -111,7 +114,7 @@ class RuleBot:
|
||||
return best
|
||||
|
||||
# ------------------------------------------------------------ 单步
|
||||
def step(self) -> Optional[str]:
|
||||
def step(self) -> str | None:
|
||||
"""执行一个动作,返回动作名;没得做或做不了返回 None。"""
|
||||
action = self.choose()
|
||||
if action is None:
|
||||
@@ -119,7 +122,7 @@ class RuleBot:
|
||||
name = action["action"]
|
||||
params = action.get("params") or {}
|
||||
try:
|
||||
result = self.client._action(name, params) # 走通用动作入口
|
||||
result = self.client._action(name, params) # 走通用动作入口
|
||||
except GameError as exc:
|
||||
self.failures += 1
|
||||
if exc.code == "cooldown":
|
||||
@@ -151,8 +154,7 @@ class RuleBot:
|
||||
return True
|
||||
|
||||
# ------------------------------------------------------------ 主循环
|
||||
def run(self, rounds: int = 0, max_minutes: float = 0.0,
|
||||
idle_limit: int = 8) -> Dict[str, Any]:
|
||||
def run(self, rounds: int = 0, max_minutes: float = 0.0, idle_limit: int = 8) -> dict[str, Any]:
|
||||
"""跑机器人。
|
||||
|
||||
``rounds`` 为 0 表示不限轮数;``max_minutes`` 为 0 表示不限时间。
|
||||
@@ -161,8 +163,7 @@ class RuleBot:
|
||||
start_day = self.client.snapshot().get("day", 1)
|
||||
idle = 0
|
||||
round_no = 0
|
||||
self.say(f"机器人 {self.name} 上线(第 {start_day} 天,"
|
||||
f"{self.client.transport_label()})")
|
||||
self.say(f"机器人 {self.name} 上线(第 {start_day} 天,{self.client.transport_label()})")
|
||||
|
||||
while not self._stop.is_set():
|
||||
round_no += 1
|
||||
@@ -199,8 +200,10 @@ class RuleBot:
|
||||
"net_worth": self.client.snapshot().get("net_worth"),
|
||||
"gold": self.client.snapshot().get("gold"),
|
||||
}
|
||||
self.say(f"机器人 {self.name} 下线:跑了 {summary['days']} 天、"
|
||||
f"执行 {summary['actions']} 个动作、净资产 {summary['net_worth']}")
|
||||
self.say(
|
||||
f"机器人 {self.name} 下线:跑了 {summary['days']} 天、"
|
||||
f"执行 {summary['actions']} 个动作、净资产 {summary['net_worth']}"
|
||||
)
|
||||
return summary
|
||||
|
||||
|
||||
@@ -209,13 +212,13 @@ def random_bot(client, **kwargs) -> RuleBot:
|
||||
bot = RuleBot(client, **kwargs)
|
||||
original = bot.choose
|
||||
|
||||
def choose() -> Optional[Dict[str, Any]]:
|
||||
def choose() -> dict[str, Any] | None:
|
||||
actions = client.available_actions()
|
||||
if not actions:
|
||||
return None
|
||||
return random.choice(actions)
|
||||
|
||||
bot.choose = choose # type: ignore[assignment]
|
||||
bot.choose = choose # type: ignore[assignment]
|
||||
bot.name = kwargs.get("name", "random")
|
||||
del original
|
||||
return bot
|
||||
Reference in new issue
Block a user