skill_combo.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. import copy
  2. import itertools
  3. import json
  4. import os
  5. class SkillComboError(ValueError):
  6. pass
  7. _OPERATORS = {"+", "-", "*", "/", "(", ")"}
  8. _SKILL_TYPES = {"single", "one_loop", "outer_product"}
  9. _MAX_RANGE_LENGTH = 10000
  10. _MAX_EXPANDED_SKILLS = 10000
  11. def _error(combo_name, message):
  12. return SkillComboError("技能组合 %s: %s" % (combo_name, message))
  13. def _is_number(value):
  14. return isinstance(value, (int, float)) and not isinstance(value, bool)
  15. def _expression_variables(tokens, combo_name, field_name):
  16. if not isinstance(tokens, list) or not tokens:
  17. raise _error(combo_name, "%s 必须是非空算式列表" % field_name)
  18. variables = []
  19. for token in tokens:
  20. if _is_number(token) or isinstance(token, str) and token in _OPERATORS:
  21. continue
  22. if not isinstance(token, str):
  23. raise _error(combo_name, "%s 含有不支持的算式元素 %r" % (field_name, token))
  24. if token not in variables:
  25. variables.append(token)
  26. return variables
  27. class _ExpressionParser:
  28. def __init__(self, tokens, variables, combo_name, field_name):
  29. self.tokens = tokens
  30. self.variables = variables
  31. self.combo_name = combo_name
  32. self.field_name = field_name
  33. self.position = 0
  34. def parse(self):
  35. value = self._parse_add_subtract()
  36. if self.position != len(self.tokens):
  37. raise _error(
  38. self.combo_name,
  39. "%s 在 %r 附近存在多余内容" % (self.field_name, self.tokens[self.position]),
  40. )
  41. return value
  42. def _peek(self):
  43. if self.position >= len(self.tokens):
  44. return None
  45. return self.tokens[self.position]
  46. def _take(self):
  47. token = self._peek()
  48. self.position += 1
  49. return token
  50. def _parse_add_subtract(self):
  51. value = self._parse_multiply_divide()
  52. while self._peek() in ("+", "-"):
  53. operator = self._take()
  54. right = self._parse_multiply_divide()
  55. value = value + right if operator == "+" else value - right
  56. return value
  57. def _parse_multiply_divide(self):
  58. value = self._parse_unary()
  59. while self._peek() in ("*", "/"):
  60. operator = self._take()
  61. right = self._parse_unary()
  62. if operator == "*":
  63. value *= right
  64. else:
  65. if right == 0:
  66. raise _error(self.combo_name, "%s 出现除以 0" % self.field_name)
  67. value /= right
  68. return value
  69. def _parse_unary(self):
  70. if self._peek() in ("+", "-"):
  71. operator = self._take()
  72. value = self._parse_unary()
  73. return value if operator == "+" else -value
  74. return self._parse_primary()
  75. def _parse_primary(self):
  76. token = self._take()
  77. if token is None:
  78. raise _error(self.combo_name, "%s 算式不完整" % self.field_name)
  79. if token == "(":
  80. value = self._parse_add_subtract()
  81. if self._take() != ")":
  82. raise _error(self.combo_name, "%s 缺少右括号" % self.field_name)
  83. return value
  84. if token == ")" or token in ("+", "-", "*", "/"):
  85. raise _error(self.combo_name, "%s 中 %r 的位置不正确" % (self.field_name, token))
  86. if _is_number(token):
  87. return token
  88. if token not in self.variables:
  89. raise _error(self.combo_name, "%s 引用了未定义变量 %s" % (self.field_name, token))
  90. value = self.variables[token]
  91. if not _is_number(value):
  92. raise _error(self.combo_name, "%s 中的变量 %s 不是标量数字" % (self.field_name, token))
  93. return value
  94. def _evaluate_scalar(tokens, variables, combo_name, field_name):
  95. return _ExpressionParser(tokens, variables, combo_name, field_name).parse()
  96. def _resolve_scalar(value, variables, combo_name, field_name):
  97. if _is_number(value):
  98. return value
  99. if isinstance(value, str):
  100. if value not in variables:
  101. raise _error(combo_name, "%s 引用了未定义变量 %s" % (field_name, value))
  102. result = variables[value]
  103. if not _is_number(result):
  104. raise _error(combo_name, "%s 中的变量 %s 不是标量数字" % (field_name, value))
  105. return result
  106. if isinstance(value, list):
  107. return _evaluate_scalar(value, variables, combo_name, field_name)
  108. raise _error(combo_name, "%s 必须是数字、标量变量名或算式列表" % field_name)
  109. def _build_range(values, variables, combo_name, variable_name):
  110. if not isinstance(values, dict):
  111. raise _error(combo_name, "变量 %s 的 range.values 必须是字典" % variable_name)
  112. missing = [key for key in ("start", "end", "delta") if key not in values]
  113. if missing:
  114. raise _error(combo_name, "变量 %s 的 range.values 缺少 %s" % (variable_name, ", ".join(missing)))
  115. start = _resolve_scalar(values["start"], variables, combo_name, "%s.start" % variable_name)
  116. end = _resolve_scalar(values["end"], variables, combo_name, "%s.end" % variable_name)
  117. delta = _resolve_scalar(values["delta"], variables, combo_name, "%s.delta" % variable_name)
  118. if delta == 0:
  119. raise _error(combo_name, "变量 %s 的 range.delta 不能为 0" % variable_name)
  120. if start < end and delta < 0 or start > end and delta > 0:
  121. raise _error(combo_name, "变量 %s 的 range.delta 方向无法到达 end" % variable_name)
  122. result = []
  123. current = start
  124. in_range = (lambda item: item <= end) if delta > 0 else (lambda item: item >= end)
  125. while in_range(current):
  126. result.append(current)
  127. if len(result) > _MAX_RANGE_LENGTH:
  128. raise _error(combo_name, "变量 %s 的 range 超过 %d 项" % (variable_name, _MAX_RANGE_LENGTH))
  129. current += delta
  130. return result
  131. def _referenced_list_variables(value, variables, result=None):
  132. if result is None:
  133. result = []
  134. if isinstance(value, str):
  135. if value in variables and isinstance(variables[value], list) and value not in result:
  136. result.append(value)
  137. elif isinstance(value, list):
  138. for item in value:
  139. _referenced_list_variables(item, variables, result)
  140. elif isinstance(value, dict):
  141. for item in value.values():
  142. _referenced_list_variables(item, variables, result)
  143. return result
  144. def _substitute(value, variables):
  145. if isinstance(value, str) and value in variables:
  146. return copy.deepcopy(variables[value])
  147. if isinstance(value, list):
  148. return [_substitute(item, variables) for item in value]
  149. if isinstance(value, dict):
  150. return {key: _substitute(item, variables) for key, item in value.items()}
  151. return copy.deepcopy(value)
  152. class SkillComboDefinition:
  153. def __init__(self, name, config, source_path=None):
  154. self.name = name
  155. self.source_path = source_path or name
  156. self.config = config
  157. self.params = []
  158. self.inner_variables = []
  159. self.skills = []
  160. self._validate()
  161. def _validate(self):
  162. if not isinstance(self.config, dict):
  163. raise _error(self.name, "JSON 根节点必须是字典")
  164. params = self.config.get("params", [])
  165. if not isinstance(params, list) or any(not isinstance(item, str) or not item for item in params):
  166. raise _error(self.name, "params 必须是变量名字符串列表")
  167. if len(set(params)) != len(params):
  168. raise _error(self.name, "params 中存在重名变量")
  169. self.params = list(params)
  170. inner_variables = self.config.get("inner_variables", [])
  171. if not isinstance(inner_variables, list):
  172. raise _error(self.name, "inner_variables 必须是列表")
  173. known_names = set(self.params)
  174. for index, variable in enumerate(inner_variables):
  175. if not isinstance(variable, dict):
  176. raise _error(self.name, "inner_variables[%d] 必须是字典" % index)
  177. variable_name = variable.get("name")
  178. value_type = variable.get("value_type")
  179. if not isinstance(variable_name, str) or not variable_name:
  180. raise _error(self.name, "inner_variables[%d].name 必须是非空字符串" % index)
  181. if variable_name in known_names:
  182. raise _error(self.name, "变量 %s 重复定义" % variable_name)
  183. if value_type not in ("list", "range", "computed_list", "computed_scalar"):
  184. raise _error(self.name, "变量 %s 的 value_type 不受支持: %r" % (variable_name, value_type))
  185. if "values" not in variable:
  186. raise _error(self.name, "变量 %s 缺少 values" % variable_name)
  187. if value_type == "list" and not isinstance(variable["values"], list):
  188. raise _error(self.name, "变量 %s 的 list.values 必须是列表" % variable_name)
  189. if value_type in ("computed_list", "computed_scalar"):
  190. references = _expression_variables(variable["values"], self.name, variable_name)
  191. unknown = [item for item in references if item not in known_names]
  192. if unknown:
  193. raise _error(self.name, "变量 %s 引用了尚未定义的变量 %s" % (variable_name, unknown[0]))
  194. known_names.add(variable_name)
  195. self.inner_variables.append(copy.deepcopy(variable))
  196. skills = self.config.get("skills")
  197. if not isinstance(skills, list) or not skills:
  198. raise _error(self.name, "skills 必须是非空列表")
  199. for index, skill in enumerate(skills):
  200. if not isinstance(skill, dict):
  201. raise _error(self.name, "skills[%d] 必须是字典" % index)
  202. skill_type = skill.get("skill_type")
  203. if skill_type not in _SKILL_TYPES:
  204. raise _error(self.name, "skills[%d].skill_type 不受支持: %r" % (index, skill_type))
  205. if not isinstance(skill.get("name"), str) or not skill["name"]:
  206. raise _error(self.name, "skills[%d].name 必须是非空字符串" % index)
  207. self.skills.append(copy.deepcopy(skill))
  208. def _build_variables(self, call_params):
  209. if not isinstance(call_params, dict):
  210. raise _error(self.name, "调用 params 必须是字典")
  211. missing = [name for name in self.params if name not in call_params]
  212. if missing:
  213. raise _error(self.name, "调用 params 缺少变量: %s" % ", ".join(missing))
  214. variables = {name: copy.deepcopy(call_params[name]) for name in self.params}
  215. for variable in self.inner_variables:
  216. name = variable["name"]
  217. value_type = variable["value_type"]
  218. values = variable["values"]
  219. if value_type == "list":
  220. result = copy.deepcopy(values)
  221. elif value_type == "range":
  222. result = _build_range(values, variables, self.name, name)
  223. else:
  224. references = _expression_variables(values, self.name, name)
  225. list_variables = [item for item in references if isinstance(variables.get(item), list)]
  226. if value_type == "computed_scalar":
  227. if list_variables:
  228. raise _error(self.name, "computed_scalar %s 不能引用列表变量 %s" % (name, list_variables[0]))
  229. result = _evaluate_scalar(values, variables, self.name, name)
  230. else:
  231. if len(list_variables) > 1:
  232. raise _error(
  233. self.name,
  234. "computed_list %s 最多只能引用一个列表变量,当前引用了 %s"
  235. % (name, ", ".join(list_variables)),
  236. )
  237. if list_variables:
  238. list_name = list_variables[0]
  239. result = []
  240. for item in variables[list_name]:
  241. scalar_variables = dict(variables)
  242. scalar_variables[list_name] = item
  243. result.append(_evaluate_scalar(values, scalar_variables, self.name, name))
  244. else:
  245. result = [_evaluate_scalar(values, variables, self.name, name)]
  246. variables[name] = result
  247. return variables
  248. def expand(self, call_params):
  249. variables = self._build_variables(call_params)
  250. expanded = []
  251. for index, skill in enumerate(self.skills):
  252. skill_type = skill["skill_type"]
  253. template = {key: value for key, value in skill.items() if key != "skill_type"}
  254. list_variables = _referenced_list_variables(template, variables)
  255. contexts = []
  256. if skill_type == "single" or not list_variables:
  257. contexts = [variables]
  258. elif skill_type == "one_loop":
  259. lengths = [len(variables[name]) for name in list_variables]
  260. if len(set(lengths)) > 1:
  261. length_info = ", ".join(
  262. "%s=%d" % (name, len(variables[name])) for name in list_variables
  263. )
  264. raise _error(
  265. self.name,
  266. "skills[%d] 的 one_loop 列表长度不一致: %s" % (index, length_info),
  267. )
  268. for values in zip(*(variables[name] for name in list_variables)):
  269. context = dict(variables)
  270. context.update(dict(zip(list_variables, values)))
  271. contexts.append(context)
  272. else:
  273. for values in itertools.product(*(variables[name] for name in list_variables)):
  274. context = dict(variables)
  275. context.update(dict(zip(list_variables, values)))
  276. contexts.append(context)
  277. for context in contexts:
  278. expanded.append(_substitute(template, context))
  279. if len(expanded) > _MAX_EXPANDED_SKILLS:
  280. raise _error(self.name, "展开结果超过 %d 个技能" % _MAX_EXPANDED_SKILLS)
  281. return expanded
  282. def _load_loose_combo_configs(combo_directory):
  283. configs = {}
  284. if not os.path.isdir(combo_directory):
  285. return configs
  286. for root, _, files in os.walk(combo_directory):
  287. for filename in files:
  288. if not filename.lower().endswith(".json"):
  289. continue
  290. path = os.path.normpath(os.path.join(root, filename))
  291. with open(path, "r", encoding="utf-8-sig") as combo_file:
  292. configs[path] = json.load(combo_file)
  293. return configs
  294. def _load_packed_combo_configs(combo_directory):
  295. from client_local.file_loader import fileLoader
  296. if not fileLoader.initOK:
  297. fileLoader.init()
  298. normalized_prefix = os.path.normpath(combo_directory).lower() + os.sep
  299. configs = {}
  300. for path, config in fileLoader.allJson.items():
  301. normalized_path = os.path.normpath(path)
  302. if normalized_path.lower().startswith(normalized_prefix) and normalized_path.lower().endswith(".json"):
  303. configs[normalized_path] = config
  304. return configs
  305. def load_skill_combos(combo_directory=os.path.join("game", "skill_combo")):
  306. packed_configs = _load_packed_combo_configs(combo_directory)
  307. configs_by_path = {
  308. path.lower(): (path, config) for path, config in packed_configs.items()
  309. }
  310. # 开发目录中的同名文件优先,便于制作者修改后立即测试。
  311. for path, config in _load_loose_combo_configs(combo_directory).items():
  312. configs_by_path[path.lower()] = (path, config)
  313. definitions = {}
  314. for path, config in sorted(configs_by_path.values(), key=lambda item: item[0].lower()):
  315. name = os.path.splitext(os.path.basename(path))[0]
  316. lower_name = name.lower()
  317. if lower_name in definitions:
  318. raise _error(name, "存在重名 JSON(技能组合名称忽略大小写)")
  319. definitions[lower_name] = SkillComboDefinition(name, config, path)
  320. return definitions
  321. def register_skill_combos(skill_map, combo_directory=os.path.join("game", "skill_combo")):
  322. definitions = load_skill_combos(combo_directory)
  323. existing_names = {name.lower() for name in skill_map}
  324. for definition in definitions.values():
  325. if definition.name.lower() in existing_names:
  326. raise _error(definition.name, "名称与已有技能重复")
  327. skill_map[definition.name] = {"skill_combo": definition}
  328. existing_names.add(definition.name.lower())
  329. return definitions
  330. def get_skill_combo(skill_name, skill_map):
  331. attributes = skill_map.get(skill_name)
  332. if attributes is not None and attributes.get("skill_combo") is not None:
  333. return attributes["skill_combo"]
  334. lower_name = skill_name.lower()
  335. for registered_name, registered_attributes in skill_map.items():
  336. if registered_name.lower() == lower_name and registered_attributes.get("skill_combo") is not None:
  337. return registered_attributes["skill_combo"]
  338. return None
  339. class SkillComboRunner:
  340. """执行一次组合;外层组合的调度仍由 NPC 自己的技能时间轴管理。"""
  341. def __init__(self, user, definition, call_params, skill_instances, combo_stack=None, time_provider=None):
  342. self.user = user
  343. self.definition = definition
  344. self.skill_instances = skill_instances
  345. self.combo_stack = list(combo_stack or []) + [definition.name]
  346. self.skills = definition.expand(call_params)
  347. self.skill_spawns = [skill.get("spawns", []) for skill in self.skills]
  348. self.skill_spawn_orders = [
  349. skill.get("spawn_order", index) for index, skill in enumerate(self.skills)
  350. ]
  351. self._validate_skills()
  352. if time_provider is None:
  353. import pygame
  354. time_provider = pygame.time.get_ticks
  355. self.time_provider = time_provider
  356. # 内层 init 从外层组合实际开始调用的这一刻重新计时。
  357. self.skill_time_init = self.time_provider()
  358. self.skill_init_times = [
  359. self.skill_time_init + skill["init"] for skill in self.skills
  360. ]
  361. self.skill_intervals = [skill["interval"] for skill in self.skills]
  362. self.skill_remains = [skill["max"] for skill in self.skills]
  363. self.skill_instances.append(self)
  364. # init=0 的内部技能随组合触发立即释放,不额外等待一帧。
  365. self.update()
  366. def _validate_skills(self):
  367. for index, skill in enumerate(self.skills):
  368. if not isinstance(skill.get("name"), str) or not skill["name"]:
  369. raise _error(self.definition.name, "展开后的 skills[%d].name 无效" % index)
  370. for field_name in ("init", "interval"):
  371. if not _is_number(skill.get(field_name)):
  372. raise _error(
  373. self.definition.name,
  374. "展开后的 skills[%d].%s 必须是数字" % (index, field_name),
  375. )
  376. max_count = skill.get("max")
  377. if not isinstance(max_count, int) or isinstance(max_count, bool) or max_count < -1:
  378. raise _error(
  379. self.definition.name,
  380. "展开后的 skills[%d].max 必须是 -1 或非负整数" % index,
  381. )
  382. def update(self):
  383. if getattr(self.user, "remain_blood", 1) <= 0:
  384. self.kill()
  385. return
  386. current_time = self.time_provider()
  387. for index, skill in enumerate(self.skills):
  388. if self.skill_remains[index] == 0 or current_time < self.skill_init_times[index]:
  389. continue
  390. self.skill_init_times[index] += self.skill_intervals[index]
  391. if self.skill_remains[index] > 0:
  392. self.skill_remains[index] -= 1
  393. self.user.using_skill_map(
  394. skill["name"],
  395. skill.get("params", []),
  396. self.skill_spawn_orders[index],
  397. self.skill_spawns,
  398. self.combo_stack,
  399. )
  400. if all(remain == 0 for remain in self.skill_remains):
  401. self.kill()
  402. def kill(self):
  403. if self in self.skill_instances:
  404. self.skill_instances.remove(self)