"""Obstacle JSON editing, independent of Tk and the game runtime.""" import datetime import json import os from pathlib import Path import re import shutil import tempfile from client_local.utils.transparent_range import contains_point, normalize_ranges def find_project_root(path): start = Path(path).resolve() if start.is_file(): start = start.parent for parent in (start,) + tuple(start.parents): if (parent / "res/img/mapElem").is_dir() and (parent / "game/frame").is_dir(): return parent return None def frame_entries(data): result = [] for state in ("STAND", "PUSH", "DIE", "TRIGGER", "TYPE_LEN"): frames = data.get(state, {}) if not isinstance(frames, dict): continue for i, name in enumerate(frames.get("IMG", [])): try: cx, cy = frames["CX"][i], frames["CY"][i] except (KeyError, IndexError, TypeError): raise ValueError("%s 第 %d 帧缺少 CX/CY" % (state, i + 1)) result.append(dict(label="%s [%d] %s" % (state, i, name), image=name, cx=cx, cy=cy)) if not result: raise ValueError("JSON 没有可预览的 STAND / PUSH / DIE / TRIGGER / TYPE_LEN 图片帧") return result def replace_field(text, field, value): """Replace just the field's value, preserving all other text and fields.""" data = json.loads(text) if not isinstance(data, dict): raise ValueError("障碍物 JSON 顶层必须是字典") replacement = json.dumps(value, ensure_ascii=False, separators=(", ", ": ")) decoder = json.JSONDecoder() index = text.index("{") + 1 while True: while text[index].isspace(): index += 1 if text[index] == "}": break key, end = decoder.raw_decode(text, index) index = end while text[index].isspace(): index += 1 index += 1 # Colon: json.loads above has already validated the syntax. while text[index].isspace(): index += 1 value_start = index _, index = decoder.raw_decode(text, index) if key == field: return text[:value_start] + replacement + text[index:] while text[index].isspace(): index += 1 if text[index] == ",": index += 1 newline = "\r\n" if "\r\n" in text else "\n" match = re.search(r'(?m)^([ \t]+)"', text) indent = match.group(1) if match else " " end = text.rfind("}") prefix = text[:end].rstrip() return prefix + ("," if data else "") + newline + indent + json.dumps(field) + ': ' + replacement + newline + text[end:] def replace_ranges(text, ranges): return replace_field(text, "TRANSPARENT_RANGE", normalize_ranges(ranges)) class ObstacleDocument: def __init__(self, path, project_root=None): self.path = Path(path).resolve() self.original_bytes = self.path.read_bytes() self.bom = self.original_bytes.startswith(b"\xef\xbb\xbf") self.text = self.original_bytes.decode("utf-8-sig") self.data = json.loads(self.text) if not isinstance(self.data, dict): raise ValueError("障碍物 JSON 顶层必须是字典") self.ranges = normalize_ranges(self.data.get("TRANSPARENT_RANGE")) self.frames = frame_entries(self.data) self.project_root = Path(project_root).resolve() if project_root else find_project_root(self.path) def image_path(self, frame): if self.project_root is None: raise ValueError("找不到工程目录,请先选择含 game 和 res 的工程目录") library = self.data.get("TYPE", self.path.parent.name) return self.project_root / "res/img/mapElem" / library / frame["image"] def save(self, ranges, top_update=None): ranges = normalize_ranges(ranges) if self.path.read_bytes() != self.original_bytes: raise ValueError("文件已被其他程序修改,请重新打开后再保存") text = replace_ranges(self.text, ranges) if top_update is not None: if not isinstance(top_update, bool): raise ValueError("TOP_UPDATE 必须是 true 或 false") if top_update != bool(self.data.get("TOP_UPDATE", False)): text = replace_field(text, "TOP_UPDATE", top_update) payload = (b"\xef\xbb\xbf" if self.bom else b"") + text.encode("utf-8") if payload == self.original_bytes: return None backup = self.path.with_name(self.path.name + "." + datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f") + ".bak") fd, temporary = tempfile.mkstemp(prefix=".transparent_", suffix=".tmp", dir=str(self.path.parent)) try: with os.fdopen(fd, "wb") as stream: stream.write(payload) stream.flush() os.fsync(stream.fileno()) shutil.copy2(str(self.path), str(backup)) os.replace(temporary, str(self.path)) finally: if os.path.exists(temporary): os.unlink(temporary) self.original_bytes = payload self.text = text self.data["TRANSPARENT_RANGE"] = ranges if top_update is not None and (top_update or "TOP_UPDATE" in self.data): self.data["TOP_UPDATE"] = top_update self.ranges = ranges return backup