page_definition.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. from __future__ import annotations
  2. """页面与边定义模型。"""
  3. from dataclasses import dataclass, field
  4. from typing import Iterable, Union
  5. from tasks.GameUi.common import ActionLike, RecognizerLike, infer_category, infer_page_key_and_name
  6. from tasks.GameUi.matcher import Matcher, ensure_matcher
  7. from tasks.GameUi.registry import PageRegistry
  8. from module.logger import logger
  9. def _clamp_priority(value: int, page_key: str) -> int:
  10. """将页面优先级约束到合法范围。"""
  11. priority = max(1, min(100, value))
  12. if priority != value:
  13. logger.warning(f"Page priority out of range: key={page_key}, value={value}, clamped={priority}")
  14. return priority
  15. def sort_pages_by_priority(indexed_pages: Iterable[tuple[int, "Page"]]) -> list["Page"]:
  16. """按优先级降序、注册顺序升序稳定排序页面候选。"""
  17. ordered_pages = sorted(indexed_pages, key=lambda item: (-item[1].priority, item[0]))
  18. return [page for _, page in ordered_pages]
  19. @dataclass
  20. class Transition:
  21. """页面间的一条有向边。
  22. Attributes:
  23. source: 起点页面。
  24. destination: 终点页面。
  25. action: 从起点前往终点时执行的动作。
  26. cost: 边的额外代价。
  27. key: 边的唯一标识;为空时自动生成。
  28. on_enter_success: 到达终点成功后的边级 hook。
  29. on_enter_failure: 到达终点失败后的边级 hook。
  30. on_leave_success: 成功离开起点后的边级 hook。
  31. on_leave_failure: 离开起点失败后的边级 hook。
  32. """
  33. source: "Page"
  34. destination: "Page"
  35. action: ActionLike
  36. cost: float = 0.0
  37. key: str | None = None
  38. on_enter_success: list[ActionLike] = field(default_factory=list)
  39. on_enter_failure: list[ActionLike] = field(default_factory=list)
  40. on_leave_success: list[ActionLike] = field(default_factory=list)
  41. on_leave_failure: list[ActionLike] = field(default_factory=list)
  42. def __post_init__(self):
  43. """补齐未显式提供的边 key。"""
  44. if self.key is None:
  45. self.key = f"{self.source.key}->{self.destination.key}#{len(self.source.transitions)}"
  46. def hooks(self, stage: str) -> list[ActionLike]:
  47. """按阶段读取边级 hook 列表。
  48. Args:
  49. stage: hook 阶段名。
  50. Returns:
  51. 对应阶段的 hook 列表。
  52. """
  53. return getattr(self, stage)
  54. class Page:
  55. """页面定义对象。
  56. 页面定义只描述静态信息:识别条件、页面分类、进入/离开 hook 与可达边。
  57. 运行时状态会在 `NavigatorSession` 中保存。
  58. """
  59. def __init__(
  60. self,
  61. recognizer: Union[Matcher, RecognizerLike, Iterable[RecognizerLike]],
  62. *,
  63. key: str | None = None,
  64. name: str | None = None,
  65. category: str | None = None,
  66. priority: int = 50,
  67. cost: float = 1.0,
  68. register: bool = True,
  69. ):
  70. """初始化页面定义。
  71. Args:
  72. recognizer: 页面识别条件,可以是 `Matcher`、Rule 元对象、自定义函数或可迭代集合。
  73. key: 页面唯一标识;为空时根据页面变量名自动推断。
  74. name: 页面展示名称;为空时根据页面变量名自动推断。
  75. category: 页面分类;为空时根据文件路径自动推断。
  76. priority: 页面识别优先级,范围 1-100。
  77. cost: 页面代价,供 Dijkstra 路径规划使用。
  78. register: 是否注册到全局 `PageRegistry`。动态页面应传入 `False`。
  79. """
  80. inferred_key, inferred_name = infer_page_key_and_name()
  81. # 页面唯一标识,用于 session 拷贝、路由和日志。
  82. self.key = key or inferred_key
  83. # 页面展示名称,用于日志输出。
  84. self.name = name or inferred_name
  85. # 页面所属分类,`tasks/GameUi` 内默认归类为 global。
  86. self.category = category or infer_category()
  87. # 页面识别优先级,越大越先参与复验。
  88. self.priority = _clamp_priority(priority, self.key)
  89. # 页面进入该节点的基础代价。
  90. self.cost = cost
  91. # 规范化后的页面识别条件。
  92. self.recognizer = ensure_matcher(recognizer)
  93. # 从当前页面出发的所有有向边。
  94. self.transitions: list[Transition] = []
  95. # 识别到当前页面并稳定进入后的页面级 hook。
  96. self.on_enter_success: list[ActionLike] = []
  97. # 目标页面进入失败后的页面级 hook。
  98. self.on_enter_failure: list[ActionLike] = []
  99. # 成功离开当前页面后的页面级 hook。
  100. self.on_leave_success: list[ActionLike] = []
  101. # 离开当前页面失败后的页面级 hook。
  102. self.on_leave_failure: list[ActionLike] = []
  103. if register:
  104. PageRegistry.register(self)
  105. def __eq__(self, other):
  106. """按页面 key 判断相等性。"""
  107. return isinstance(other, Page) and self.key == other.key
  108. def __hash__(self):
  109. """使页面对象可作为字典 key 或集合元素。"""
  110. return hash(self.key)
  111. def __str__(self):
  112. """返回页面展示名称。"""
  113. return self.name
  114. def connect(
  115. self,
  116. destination: "Page",
  117. action: ActionLike,
  118. *,
  119. cost: float = 0.0,
  120. key: str | None = None,
  121. on_enter_success: Iterable[ActionLike] = None,
  122. on_enter_failure: Iterable[ActionLike] = None,
  123. on_leave_success: Iterable[ActionLike] = None,
  124. on_leave_failure: Iterable[ActionLike] = None,
  125. ) -> Transition:
  126. """声明从当前页面到目标页面的一条边。
  127. Args:
  128. destination: 边的终点页面。
  129. action: 尝试跳转时执行的动作。
  130. cost: 边的额外代价。
  131. key: 边的唯一标识;为空时自动生成。
  132. on_enter_success: 边级进入成功 hook。
  133. on_enter_failure: 边级进入失败 hook。
  134. on_leave_success: 边级离开成功 hook。
  135. on_leave_failure: 边级离开失败 hook。
  136. Returns:
  137. 新建或替换后的 `Transition` 对象。
  138. """
  139. transition = Transition(
  140. source=self,
  141. destination=destination,
  142. action=action,
  143. cost=cost,
  144. key=key,
  145. on_enter_success=list(on_enter_success or []),
  146. on_enter_failure=list(on_enter_failure or []),
  147. on_leave_success=list(on_leave_success or []),
  148. on_leave_failure=list(on_leave_failure or []),
  149. )
  150. if transition.key is not None:
  151. self.transitions = [item for item in self.transitions if item.key != transition.key]
  152. self.transitions.append(transition)
  153. return transition
  154. def remove_transition(self, *, destination: "Page | None" = None, key: str | None = None) -> None:
  155. """删除页面边。
  156. Args:
  157. destination: 按目标页面删除边。
  158. key: 按边 key 删除边。
  159. """
  160. remained = []
  161. for transition in self.transitions:
  162. if key is not None and transition.key == key:
  163. continue
  164. if destination is not None and transition.destination == destination:
  165. continue
  166. remained.append(transition)
  167. self.transitions = remained
  168. def clear_transitions(self) -> None:
  169. """清空当前页面的所有出边。"""
  170. self.transitions = []
  171. def hooks(self, stage: str) -> list[ActionLike]:
  172. """按阶段读取页面级 hook 列表。
  173. Args:
  174. stage: hook 阶段名。
  175. Returns:
  176. 对应阶段的 hook 列表。
  177. """
  178. return getattr(self, stage)
  179. def add_hooks(self, stage: str, *actions: ActionLike):
  180. """为指定阶段追加 hook。
  181. Args:
  182. stage: hook 阶段名。
  183. *actions: 需要追加的动作。
  184. Returns:
  185. 当前页面对象,便于链式调用。
  186. """
  187. hooks = self.hooks(stage)
  188. hooks.extend(action for action in actions if action is not None)
  189. return self
  190. def add_enter_success_hooks(self, *actions: ActionLike):
  191. """追加进入成功 hook。"""
  192. return self.add_hooks("on_enter_success", *actions)
  193. def add_enter_failure_hooks(self, *actions: ActionLike):
  194. """追加进入失败 hook。"""
  195. return self.add_hooks("on_enter_failure", *actions)
  196. def add_leave_success_hooks(self, *actions: ActionLike):
  197. """追加离开成功 hook。"""
  198. return self.add_hooks("on_leave_success", *actions)
  199. def add_leave_failure_hooks(self, *actions: ActionLike):
  200. """追加离开失败 hook。"""
  201. return self.add_hooks("on_leave_failure", *actions)
  202. def clone(self) -> "Page":
  203. """拷贝一个不注册到全局表的页面副本。
  204. Returns:
  205. 仅复制静态定义和页面级 hook 的页面副本。
  206. """
  207. page = Page(
  208. self.recognizer,
  209. key=self.key,
  210. name=self.name,
  211. category=self.category,
  212. priority=self.priority,
  213. cost=self.cost,
  214. register=False,
  215. )
  216. page.on_enter_success = list(self.on_enter_success)
  217. page.on_enter_failure = list(self.on_enter_failure)
  218. page.on_leave_success = list(self.on_leave_success)
  219. page.on_leave_failure = list(self.on_leave_failure)
  220. return page