import copy import itertools import json import os class SkillComboError(ValueError): pass _OPERATORS = {"+", "-", "*", "/", "(", ")"} _SKILL_TYPES = {"single", "one_loop", "outer_product"} _MAX_RANGE_LENGTH = 10000 _MAX_EXPANDED_SKILLS = 10000 def _error(combo_name, message): return SkillComboError("技能组合 %s: %s" % (combo_name, message)) def _is_number(value): return isinstance(value, (int, float)) and not isinstance(value, bool) def _expression_variables(tokens, combo_name, field_name): if not isinstance(tokens, list) or not tokens: raise _error(combo_name, "%s 必须是非空算式列表" % field_name) variables = [] for token in tokens: if _is_number(token) or isinstance(token, str) and token in _OPERATORS: continue if not isinstance(token, str): raise _error(combo_name, "%s 含有不支持的算式元素 %r" % (field_name, token)) if token not in variables: variables.append(token) return variables class _ExpressionParser: def __init__(self, tokens, variables, combo_name, field_name): self.tokens = tokens self.variables = variables self.combo_name = combo_name self.field_name = field_name self.position = 0 def parse(self): value = self._parse_add_subtract() if self.position != len(self.tokens): raise _error( self.combo_name, "%s 在 %r 附近存在多余内容" % (self.field_name, self.tokens[self.position]), ) return value def _peek(self): if self.position >= len(self.tokens): return None return self.tokens[self.position] def _take(self): token = self._peek() self.position += 1 return token def _parse_add_subtract(self): value = self._parse_multiply_divide() while self._peek() in ("+", "-"): operator = self._take() right = self._parse_multiply_divide() value = value + right if operator == "+" else value - right return value def _parse_multiply_divide(self): value = self._parse_unary() while self._peek() in ("*", "/"): operator = self._take() right = self._parse_unary() if operator == "*": value *= right else: if right == 0: raise _error(self.combo_name, "%s 出现除以 0" % self.field_name) value /= right return value def _parse_unary(self): if self._peek() in ("+", "-"): operator = self._take() value = self._parse_unary() return value if operator == "+" else -value return self._parse_primary() def _parse_primary(self): token = self._take() if token is None: raise _error(self.combo_name, "%s 算式不完整" % self.field_name) if token == "(": value = self._parse_add_subtract() if self._take() != ")": raise _error(self.combo_name, "%s 缺少右括号" % self.field_name) return value if token == ")" or token in ("+", "-", "*", "/"): raise _error(self.combo_name, "%s 中 %r 的位置不正确" % (self.field_name, token)) if _is_number(token): return token if token not in self.variables: raise _error(self.combo_name, "%s 引用了未定义变量 %s" % (self.field_name, token)) value = self.variables[token] if not _is_number(value): raise _error(self.combo_name, "%s 中的变量 %s 不是标量数字" % (self.field_name, token)) return value def _evaluate_scalar(tokens, variables, combo_name, field_name): return _ExpressionParser(tokens, variables, combo_name, field_name).parse() def _resolve_scalar(value, variables, combo_name, field_name): if _is_number(value): return value if isinstance(value, str): if value not in variables: raise _error(combo_name, "%s 引用了未定义变量 %s" % (field_name, value)) result = variables[value] if not _is_number(result): raise _error(combo_name, "%s 中的变量 %s 不是标量数字" % (field_name, value)) return result if isinstance(value, list): return _evaluate_scalar(value, variables, combo_name, field_name) raise _error(combo_name, "%s 必须是数字、标量变量名或算式列表" % field_name) def _build_range(values, variables, combo_name, variable_name): if not isinstance(values, dict): raise _error(combo_name, "变量 %s 的 range.values 必须是字典" % variable_name) missing = [key for key in ("start", "end", "delta") if key not in values] if missing: raise _error(combo_name, "变量 %s 的 range.values 缺少 %s" % (variable_name, ", ".join(missing))) start = _resolve_scalar(values["start"], variables, combo_name, "%s.start" % variable_name) end = _resolve_scalar(values["end"], variables, combo_name, "%s.end" % variable_name) delta = _resolve_scalar(values["delta"], variables, combo_name, "%s.delta" % variable_name) if delta == 0: raise _error(combo_name, "变量 %s 的 range.delta 不能为 0" % variable_name) if start < end and delta < 0 or start > end and delta > 0: raise _error(combo_name, "变量 %s 的 range.delta 方向无法到达 end" % variable_name) result = [] current = start in_range = (lambda item: item <= end) if delta > 0 else (lambda item: item >= end) while in_range(current): result.append(current) if len(result) > _MAX_RANGE_LENGTH: raise _error(combo_name, "变量 %s 的 range 超过 %d 项" % (variable_name, _MAX_RANGE_LENGTH)) current += delta return result def _referenced_list_variables(value, variables, result=None): if result is None: result = [] if isinstance(value, str): if value in variables and isinstance(variables[value], list) and value not in result: result.append(value) elif isinstance(value, list): for item in value: _referenced_list_variables(item, variables, result) elif isinstance(value, dict): for item in value.values(): _referenced_list_variables(item, variables, result) return result def _substitute(value, variables): if isinstance(value, str) and value in variables: return copy.deepcopy(variables[value]) if isinstance(value, list): return [_substitute(item, variables) for item in value] if isinstance(value, dict): return {key: _substitute(item, variables) for key, item in value.items()} return copy.deepcopy(value) class SkillComboDefinition: def __init__(self, name, config, source_path=None): self.name = name self.source_path = source_path or name self.config = config self.params = [] self.inner_variables = [] self.skills = [] self._validate() def _validate(self): if not isinstance(self.config, dict): raise _error(self.name, "JSON 根节点必须是字典") params = self.config.get("params", []) if not isinstance(params, list) or any(not isinstance(item, str) or not item for item in params): raise _error(self.name, "params 必须是变量名字符串列表") if len(set(params)) != len(params): raise _error(self.name, "params 中存在重名变量") self.params = list(params) inner_variables = self.config.get("inner_variables", []) if not isinstance(inner_variables, list): raise _error(self.name, "inner_variables 必须是列表") known_names = set(self.params) for index, variable in enumerate(inner_variables): if not isinstance(variable, dict): raise _error(self.name, "inner_variables[%d] 必须是字典" % index) variable_name = variable.get("name") value_type = variable.get("value_type") if not isinstance(variable_name, str) or not variable_name: raise _error(self.name, "inner_variables[%d].name 必须是非空字符串" % index) if variable_name in known_names: raise _error(self.name, "变量 %s 重复定义" % variable_name) if value_type not in ("list", "range", "computed_list", "computed_scalar"): raise _error(self.name, "变量 %s 的 value_type 不受支持: %r" % (variable_name, value_type)) if "values" not in variable: raise _error(self.name, "变量 %s 缺少 values" % variable_name) if value_type == "list" and not isinstance(variable["values"], list): raise _error(self.name, "变量 %s 的 list.values 必须是列表" % variable_name) if value_type in ("computed_list", "computed_scalar"): references = _expression_variables(variable["values"], self.name, variable_name) unknown = [item for item in references if item not in known_names] if unknown: raise _error(self.name, "变量 %s 引用了尚未定义的变量 %s" % (variable_name, unknown[0])) known_names.add(variable_name) self.inner_variables.append(copy.deepcopy(variable)) skills = self.config.get("skills") if not isinstance(skills, list) or not skills: raise _error(self.name, "skills 必须是非空列表") for index, skill in enumerate(skills): if not isinstance(skill, dict): raise _error(self.name, "skills[%d] 必须是字典" % index) skill_type = skill.get("skill_type") if skill_type not in _SKILL_TYPES: raise _error(self.name, "skills[%d].skill_type 不受支持: %r" % (index, skill_type)) if not isinstance(skill.get("name"), str) or not skill["name"]: raise _error(self.name, "skills[%d].name 必须是非空字符串" % index) self.skills.append(copy.deepcopy(skill)) def _build_variables(self, call_params): if not isinstance(call_params, dict): raise _error(self.name, "调用 params 必须是字典") missing = [name for name in self.params if name not in call_params] if missing: raise _error(self.name, "调用 params 缺少变量: %s" % ", ".join(missing)) variables = {name: copy.deepcopy(call_params[name]) for name in self.params} for variable in self.inner_variables: name = variable["name"] value_type = variable["value_type"] values = variable["values"] if value_type == "list": result = copy.deepcopy(values) elif value_type == "range": result = _build_range(values, variables, self.name, name) else: references = _expression_variables(values, self.name, name) list_variables = [item for item in references if isinstance(variables.get(item), list)] if value_type == "computed_scalar": if list_variables: raise _error(self.name, "computed_scalar %s 不能引用列表变量 %s" % (name, list_variables[0])) result = _evaluate_scalar(values, variables, self.name, name) else: if len(list_variables) > 1: raise _error( self.name, "computed_list %s 最多只能引用一个列表变量,当前引用了 %s" % (name, ", ".join(list_variables)), ) if list_variables: list_name = list_variables[0] result = [] for item in variables[list_name]: scalar_variables = dict(variables) scalar_variables[list_name] = item result.append(_evaluate_scalar(values, scalar_variables, self.name, name)) else: result = [_evaluate_scalar(values, variables, self.name, name)] variables[name] = result return variables def expand(self, call_params): variables = self._build_variables(call_params) expanded = [] for index, skill in enumerate(self.skills): skill_type = skill["skill_type"] template = {key: value for key, value in skill.items() if key != "skill_type"} list_variables = _referenced_list_variables(template, variables) contexts = [] if skill_type == "single" or not list_variables: contexts = [variables] elif skill_type == "one_loop": lengths = [len(variables[name]) for name in list_variables] if len(set(lengths)) > 1: length_info = ", ".join( "%s=%d" % (name, len(variables[name])) for name in list_variables ) raise _error( self.name, "skills[%d] 的 one_loop 列表长度不一致: %s" % (index, length_info), ) for values in zip(*(variables[name] for name in list_variables)): context = dict(variables) context.update(dict(zip(list_variables, values))) contexts.append(context) else: for values in itertools.product(*(variables[name] for name in list_variables)): context = dict(variables) context.update(dict(zip(list_variables, values))) contexts.append(context) for context in contexts: expanded.append(_substitute(template, context)) if len(expanded) > _MAX_EXPANDED_SKILLS: raise _error(self.name, "展开结果超过 %d 个技能" % _MAX_EXPANDED_SKILLS) return expanded def _load_loose_combo_configs(combo_directory): configs = {} if not os.path.isdir(combo_directory): return configs for root, _, files in os.walk(combo_directory): for filename in files: if not filename.lower().endswith(".json"): continue path = os.path.normpath(os.path.join(root, filename)) with open(path, "r", encoding="utf-8-sig") as combo_file: configs[path] = json.load(combo_file) return configs def _load_packed_combo_configs(combo_directory): from client_local.file_loader import fileLoader if not fileLoader.initOK: fileLoader.init() normalized_prefix = os.path.normpath(combo_directory).lower() + os.sep configs = {} for path, config in fileLoader.allJson.items(): normalized_path = os.path.normpath(path) if normalized_path.lower().startswith(normalized_prefix) and normalized_path.lower().endswith(".json"): configs[normalized_path] = config return configs def load_skill_combos(combo_directory=os.path.join("game", "skill_combo")): packed_configs = _load_packed_combo_configs(combo_directory) configs_by_path = { path.lower(): (path, config) for path, config in packed_configs.items() } # 开发目录中的同名文件优先,便于制作者修改后立即测试。 for path, config in _load_loose_combo_configs(combo_directory).items(): configs_by_path[path.lower()] = (path, config) definitions = {} for path, config in sorted(configs_by_path.values(), key=lambda item: item[0].lower()): name = os.path.splitext(os.path.basename(path))[0] lower_name = name.lower() if lower_name in definitions: raise _error(name, "存在重名 JSON(技能组合名称忽略大小写)") definitions[lower_name] = SkillComboDefinition(name, config, path) return definitions def register_skill_combos(skill_map, combo_directory=os.path.join("game", "skill_combo")): definitions = load_skill_combos(combo_directory) existing_names = {name.lower() for name in skill_map} for definition in definitions.values(): if definition.name.lower() in existing_names: raise _error(definition.name, "名称与已有技能重复") skill_map[definition.name] = {"skill_combo": definition} existing_names.add(definition.name.lower()) return definitions def get_skill_combo(skill_name, skill_map): attributes = skill_map.get(skill_name) if attributes is not None and attributes.get("skill_combo") is not None: return attributes["skill_combo"] lower_name = skill_name.lower() for registered_name, registered_attributes in skill_map.items(): if registered_name.lower() == lower_name and registered_attributes.get("skill_combo") is not None: return registered_attributes["skill_combo"] return None class SkillComboRunner: """执行一次组合;外层组合的调度仍由 NPC 自己的技能时间轴管理。""" def __init__(self, user, definition, call_params, skill_instances, combo_stack=None, time_provider=None): self.user = user self.definition = definition self.skill_instances = skill_instances self.combo_stack = list(combo_stack or []) + [definition.name] self.skills = definition.expand(call_params) self.skill_spawns = [skill.get("spawns", []) for skill in self.skills] self.skill_spawn_orders = [ skill.get("spawn_order", index) for index, skill in enumerate(self.skills) ] self._validate_skills() if time_provider is None: import pygame time_provider = pygame.time.get_ticks self.time_provider = time_provider # 内层 init 从外层组合实际开始调用的这一刻重新计时。 self.skill_time_init = self.time_provider() self.skill_init_times = [ self.skill_time_init + skill["init"] for skill in self.skills ] self.skill_intervals = [skill["interval"] for skill in self.skills] self.skill_remains = [skill["max"] for skill in self.skills] self.skill_instances.append(self) # init=0 的内部技能随组合触发立即释放,不额外等待一帧。 self.update() def _validate_skills(self): for index, skill in enumerate(self.skills): if not isinstance(skill.get("name"), str) or not skill["name"]: raise _error(self.definition.name, "展开后的 skills[%d].name 无效" % index) for field_name in ("init", "interval"): if not _is_number(skill.get(field_name)): raise _error( self.definition.name, "展开后的 skills[%d].%s 必须是数字" % (index, field_name), ) max_count = skill.get("max") if not isinstance(max_count, int) or isinstance(max_count, bool) or max_count < -1: raise _error( self.definition.name, "展开后的 skills[%d].max 必须是 -1 或非负整数" % index, ) def update(self): if getattr(self.user, "remain_blood", 1) <= 0: self.kill() return current_time = self.time_provider() for index, skill in enumerate(self.skills): if self.skill_remains[index] == 0 or current_time < self.skill_init_times[index]: continue self.skill_init_times[index] += self.skill_intervals[index] if self.skill_remains[index] > 0: self.skill_remains[index] -= 1 self.user.using_skill_map( skill["name"], skill.get("params", []), self.skill_spawn_orders[index], self.skill_spawns, self.combo_stack, ) if all(remain == 0 for remain in self.skill_remains): self.kill() def kill(self): if self in self.skill_instances: self.skill_instances.remove(self)