跳到主要内容

大肥鱼星露谷自学习采集

收藏0

让 AI 玩星露谷时记住哪儿能翻垃圾桶、哪儿会结果莓子,路过顺手捡走。其他收集品采集原模组有,需自行安装 BlindWhaleFarmer 模组。

让 AI 安装

暮色鼠鼠最新版本 0.1.1更新于 2026-11-13下载 0 次

forage_memory/memory.py

5.9 KB
1# -*- coding: utf-8 -*-
2"""地图记忆:把「哪张图上哪个坐标有个垃圾桶 / 会结果的灌木」存下来,下次路过直接去。
3
4存储格式和 _setup/runs/memory.json 完全一致,可以和现有 day.py 共用一个文件:
5
6 {"maps": {"Town": {"trash": {"47,70": {...}}, "bush": {...}, "visited": 131}}}
7
8设计上的三个硬约束(都是踩过坑以后加的):
9 1. 写盘必须原子(tmp + os.replace),中途崩了不能把记忆写坏;
10 坏文件自动退回 .bak。
11 2. 带 schema 版本,以后加字段能平滑迁移,不用清记忆。
12 3. 只在「真的成功」时记:灌木戳了没反应 = 这丛不结果,绝不记。
13"""
14from __future__ import annotations
15
16import json
17import os
18
19SCHEMA = 1
20BUSH_TTL = 40 # 记了 40 天还没采到一次的灌木,大概率是不结果的那种,忘掉
21TRASH_TTL = 60 # 记了 60 天一次都没翻开的垃圾桶,可能被地图改动弄没了,忘掉
22
23
24class Memory:
25 def __init__(self, path: str):
26 self.path = path
27 self.data = self._load()
28
29 # -------------------------------------------------------------- 读写
30 def _load(self) -> dict:
31 for p in (self.path, self.path + ".bak"):
32 if not os.path.exists(p):
33 continue
34 try:
35 with open(p, encoding="utf-8") as f:
36 d = json.load(f)
37 if not isinstance(d, dict):
38 raise ValueError("not a dict")
39 d.setdefault("maps", {})
40 d["schema"] = SCHEMA # 旧文件(没有 schema)直接就地升级
41 return d
42 except Exception:
43 continue # 坏了就试下一个
44 return {"schema": SCHEMA, "maps": {}}
45
46 def save(self) -> None:
47 os.makedirs(os.path.dirname(os.path.abspath(self.path)), exist_ok=True)
48 tmp = self.path + ".tmp"
49 with open(tmp, "w", encoding="utf-8") as f:
50 json.dump(self.data, f, ensure_ascii=False, indent=2)
51 if os.path.exists(self.path):
52 try:
53 os.replace(self.path, self.path + ".bak") # 留一份上一版
54 except OSError:
55 pass
56 os.replace(tmp, self.path)
57
58 # -------------------------------------------------------------- 基础
59 def node(self, loc: str, kind: str) -> dict:
60 m = self.data.setdefault("maps", {}).setdefault(loc, {})
61 return m.setdefault(kind, {})
62
63 @staticmethod
64 def key(pos) -> str:
65 return f"{int(pos[0])},{int(pos[1])}"
66
67 def entries(self, loc: str, kind: str) -> list:
68 """[(x, y, last_ok_day, ok_count, first_seen)]"""
69 out = []
70 for c in self.node(loc, kind).values():
71 out.append((int(c["x"]), int(c["y"]),
72 int(c.get("last_ok", c.get("last_dig", c.get("last_pick", 0)))),
73 int(c.get("ok", c.get("dug", c.get("picked", 0)))),
74 int(c.get("first_seen", 0))))
75 return out
76
77 def note(self, loc: str, kind: str, pos, day: int) -> bool:
78 """看见一个点就记下来(不做任何游戏动作)。返回是不是新记的。"""
79 n = self.node(loc, kind)
80 k = self.key(pos)
81 if k in n:
82 n[k]["last_seen"] = day
83 return False
84 n[k] = {"x": int(pos[0]), "y": int(pos[1]), "first_seen": day,
85 "last_seen": day, "last_ok": 0, "ok": 0}
86 return True
87
88 def mark(self, loc: str, kind: str, pos, day: int, ok: bool) -> None:
89 """只有成功了才写 last_ok / ok+1;失败只更新 last_seen。"""
90 n = self.node(loc, kind)
91 k = self.key(pos)
92 rec = n.setdefault(k, {"x": int(pos[0]), "y": int(pos[1]), "first_seen": day,
93 "last_seen": day, "last_ok": 0, "ok": 0})
94 rec["last_seen"] = day
95 if ok:
96 rec["last_ok"] = day
97 rec["ok"] = int(rec.get("ok", 0)) + 1
98
99 def visited(self, loc: str, day: int) -> None:
100 self.data.setdefault("maps", {}).setdefault(loc, {})["visited"] = day
101
102 # -------------------------------------------------------------- 选点
103 def candidates(self, loc: str, kind: str, me, day: int, radius: int) -> list:
104 """记忆里这张图上、今天还没成功过、距离 <= radius 的点:[(距离, 坐标)]"""
105 out = []
106 for x, y, last_ok, _cnt, _first in self.entries(loc, kind):
107 if last_ok >= day:
108 continue # 今天已经处理过了
109 pos = (x, y)
110 d = abs(pos[0] - me[0]) + abs(pos[1] - me[1])
111 if d <= radius:
112 out.append((d, pos))
113 out.sort()
114 return out
115
116 def done_today(self, loc: str, kind: str, day: int) -> set:
117 return {(x, y) for x, y, last_ok, _c, _f in self.entries(loc, kind) if last_ok >= day}
118
119 # -------------------------------------------------------------- 维护
120 def prune(self, day: int, bush_ttl: int = BUSH_TTL, trash_ttl: int = TRASH_TTL) -> int:
121 """忘掉长期没结果的点:一次都没成功过、又记了很久的,留着只会白跑。"""
122 dropped = 0
123 for loc, node in (self.data.get("maps") or {}).items():
124 for kind, ttl in (("bush", bush_ttl), ("trash", trash_ttl)):
125 table = node.get(kind) or {}
126 for k in list(table):
127 rec = table[k]
128 if int(rec.get("ok", 0)) > 0:
129 continue
130 if day - int(rec.get("first_seen", 0)) > ttl:
131 table.pop(k, None)
132 dropped += 1
133 if dropped:
134 self.save()
135 return dropped
136
137 def stats(self) -> dict:
138 out = {}
139 for loc, node in (self.data.get("maps") or {}).items():
140 out[loc] = {k: len(node.get(k) or {}) for k in ("trash", "bush")}
141 out[loc]["visited"] = node.get("visited", 0)
142 return out

文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。