فهرست منبع

feat: sync recent gameplay improvements and authoring tools

Add skill combos, runtime and rendering optimizations, indexed bomb queries, cached boss bars and avatar fixes. Include character entry updates, recovered map editor sources, animation resource tools, documentation and regression tests.
detopoi 1 ماه پیش
والد
کامیت
412c905dfe
60فایلهای تغییر یافته به همراه7901 افزوده شده و 121 حذف شده
  1. 249 0
      SkillCombo社区配置说明.md
  2. 6 6
      client_local/algo/blender.py
  3. 3 1
      client_local/control.py
  4. 117 77
      client_local/level/level.py
  5. 43 0
      client_local/skill/parametric2_skill.py
  6. 465 0
      client_local/skill/skill_combo.py
  7. 5 0
      client_local/skill/skill_map.py
  8. 39 0
      client_local/sprite/bomb_instance.py
  9. 37 13
      client_local/sprite/npc.py
  10. 53 22
      client_local/ui/game/blood_bar.py
  11. 1 1
      client_local/ui/game/game_top.py
  12. 14 0
      recovered_map_editor/launch.py
  13. 4 0
      recovered_map_editor/requirements.txt
  14. 246 0
      recovered_map_editor/source/asset_library.py
  15. 5 0
      recovered_map_editor/source/const/__init__.py
  16. 11 0
      recovered_map_editor/source/const/color.py
  17. 20 0
      recovered_map_editor/source/const/window.py
  18. 513 0
      recovered_map_editor/source/district_overlay.py
  19. 358 0
      recovered_map_editor/source/editor_menu.py
  20. 67 0
      recovered_map_editor/source/exe_entry.py
  21. 269 0
      recovered_map_editor/source/extra_tools.py
  22. 5 0
      recovered_map_editor/source/game/__init__.py
  23. 5 0
      recovered_map_editor/source/game/frame/__init__.py
  24. 15 0
      recovered_map_editor/source/game/frame/floor.py
  25. 12 0
      recovered_map_editor/source/game/frame/frame.py
  26. 44 0
      recovered_map_editor/source/game/frame/obstacle.py
  27. 49 0
      recovered_map_editor/source/game/frame/obstacle_instance.py
  28. 593 0
      recovered_map_editor/source/main.py
  29. 227 0
      recovered_map_editor/source/map_settings.py
  30. 61 0
      recovered_map_editor/source/npc_preview.py
  31. 104 0
      recovered_map_editor/source/placement.py
  32. 4 0
      recovered_map_editor/source/runtime_paths.py
  33. 146 0
      recovered_map_editor/source/selection.py
  34. 209 0
      recovered_map_editor/source/tool_panel.py
  35. 148 0
      recovered_map_editor/verify_authoring.py
  36. 118 0
      recovered_map_editor/verify_districts.py
  37. 149 0
      recovered_map_editor/verify_extra_tools.py
  38. 63 0
      recovered_map_editor/verify_library.py
  39. 140 0
      recovered_map_editor/verify_menu.py
  40. 72 0
      recovered_map_editor/verify_open.py
  41. 73 0
      recovered_map_editor/verify_placement.py
  42. 92 0
      recovered_map_editor/verify_recovery.py
  43. 103 0
      recovered_map_editor/verify_selection.py
  44. 101 0
      recovered_map_editor/verify_settings.py
  45. 129 0
      recovered_map_editor/verify_tools.py
  46. 37 0
      resource_tool/README.md
  47. 246 0
      resource_tool/core.py
  48. 33 0
      resource_tool/deepseek_character/README.md
  49. 132 0
      resource_tool/deepseek_character/build_assets.py
  50. 206 0
      resource_tool/deepseek_character/build_assets_v2.py
  51. 152 0
      resource_tool/deepseek_character/verify_runtime.py
  52. 602 0
      resource_tool/main.py
  53. 2 0
      resource_tool/requirements.txt
  54. 70 0
      resource_tool/smoke_test.py
  55. 430 0
      resource_tool/test_tool.py
  56. 2 1
      test_menu.py
  57. 217 0
      tests/test_bomb_index_and_boss_cache.py
  58. 368 0
      tests/test_render_optimizations.py
  59. 199 0
      tests/test_skill_combo.py
  60. 18 0
      试玩蓝色大肥鱼.py

+ 249 - 0
SkillCombo社区配置说明.md

@@ -0,0 +1,249 @@
+# Skill Combo 技能组合配置说明
+
+Skill Combo 用来把多个普通技能组合成一个可复用的大技能,也可以通过列表变量批量生成参数略有不同的技能。
+
+组合配置放在:
+
+```text
+game/skill_combo/
+```
+
+JSON 文件名就是技能名。例如:
+
+```text
+game/skill_combo/TestSprayFireball.json
+```
+
+会注册为技能 `TestSprayFireball`,NPC 的 `skills` 可以直接使用该名字。
+
+## 一、NPC 调用方式
+
+组合技能和普通技能一样,保留外层的 `init`、`interval` 和 `max`:
+
+```json
+{
+  "name": "TestSprayFireball",
+  "init": 5000,
+  "interval": 10000,
+  "params": {
+    "combo_angle": 0,
+    "combo_damage": 500,
+    "combo_init": 0,
+    "combo_interval": 400
+  },
+  "max": -1
+}
+```
+
+- `init`:NPC 进入战斗后,第一次调用整个组合的等待时间。
+- `interval`:整个组合两次调用之间的间隔。
+- `max`:整个组合最多调用几次,`-1` 表示无限次。
+- `params`:传给组合 JSON 的变量字典,变量名由组合设计者自由决定。
+
+组合 JSON 顶层 `params` 中声明的变量都必须由调用方传入。
+
+## 二、外层和内层时间
+
+外层 NPC 技能和组合内部技能拥有各自独立的时间轴。
+
+假设 NPC 的组合技能在第 `5000ms` 被调用:
+
+- 内部技能 `init: 0` 会在第 `5000ms` 释放。
+- 内部技能 `init: 400` 会在第 `5400ms` 释放。
+- 下一次外层组合被调用时,内部时间会重新从 `0` 开始计算。
+
+组合内部每个技能的字段含义:
+
+- `init`:从本次组合开始调用起,等待多久释放。
+- `interval`:该内部技能重复释放的间隔。
+- `max`:该内部技能在本次组合中释放几次。
+
+注意:内部技能设置 `max: 1` 时只释放一次,此时 `interval` 不会产生效果。想依次在 `0/300/600/900ms` 启动四个技能,应分别设置它们的 `init`,而不是 `interval`。
+
+## 三、完整的环形火球示例
+
+创建 `game/skill_combo/CommunitySprayFireball.json`:
+
+```json
+{
+  "info": "按指定起始角度发射一圈火球",
+  "params": [
+    "combo_angle",
+    "combo_damage"
+  ],
+  "inner_variables": [
+    {
+      "name": "i",
+      "value_type": "range",
+      "values": {"start": 0, "end": 5, "delta": 1}
+    },
+    {
+      "name": "angle",
+      "value_type": "computed_list",
+      "values": [60, "*", "i", "+", "combo_angle"]
+    }
+  ],
+  "skills": [
+    {
+      "skill_type": "one_loop",
+      "name": "CustomTrackingDirectionLaserFireBallEffect",
+      "init": 0,
+      "interval": 0,
+      "params": [
+        "combo_damage",
+        "angle",
+        12000,
+        1000,
+        3000,
+        2,
+        0.5,
+        0.12,
+        0,
+        "fire_ball_laser"
+      ],
+      "max": 1
+    }
+  ]
+}
+```
+
+NPC 调用:
+
+```json
+{
+  "name": "CommunitySprayFireball",
+  "init": 5000,
+  "interval": 10000,
+  "params": {
+    "combo_angle": 30,
+    "combo_damage": 500
+  },
+  "max": -1
+}
+```
+
+最终会生成六颗火球,角度分别为:
+
+```text
+30, 90, 150, 210, 270, 330
+```
+
+## 四、inner_variables 变量类型
+
+### list
+
+直接声明一个列表:
+
+```json
+{"name": "angle", "value_type": "list", "values": [0, 60, 120, 180, 240, 300]}
+```
+
+### range
+
+按范围生成列表,`end` 包含在结果中:
+
+```json
+{"name": "angle", "value_type": "range", "values": {"start": 0, "end": 300, "delta": 60}}
+```
+
+结果为 `[0, 60, 120, 180, 240, 300]`。`delta` 不能为 `0`,正负方向必须能够到达 `end`。
+
+### computed_scalar
+
+通过算式生成一个标量,不能引用任何列表变量:
+
+```json
+{
+  "name": "fire_ball_init",
+  "value_type": "computed_scalar",
+  "values": ["combo_init", "+", 400]
+}
+```
+
+### computed_list
+
+通过算式生成列表,算式中最多只能出现一个列表变量,会逐项计算:
+
+```json
+{
+  "name": "angle",
+  "value_type": "computed_list",
+  "values": [60, "*", "i", "+", "combo_angle"]
+}
+```
+
+变量按 `inner_variables` 中的顺序创建,后面的变量可以引用调用参数以及前面已经创建的变量。
+
+算式支持:
+
+```text
++  -  *  /  (  )
+```
+
+算式必须写成 JSON 列表。例如 `(damage + 100) * 2` 应写为:
+
+```json
+["(", "damage", "+", 100, ")", "*", 2]
+```
+
+## 五、skill_type 展开方式
+
+### single
+
+只生成一个技能,不遍历列表变量。如果引用了列表变量,会把整个列表作为参数传入。
+
+### one_loop
+
+所有被当前技能引用的列表变量一起按下标遍历,列表长度必须相同。
+
+例如 `x=[1,2]`、`y=[10,20]`,最终组合为:
+
+```text
+(1, 10), (2, 20)
+```
+
+### outer_product
+
+对当前技能引用的列表变量生成全组合。
+
+例如 `x=[1,2]`、`y=[10,20]`,最终组合为:
+
+```text
+(1, 10), (1, 20), (2, 10), (2, 20)
+```
+
+## 六、组合中调用另一个组合
+
+内部技能的 `name` 也可以填写另一个 Skill Combo,实现组合复用:
+
+```json
+{
+  "skill_type": "single",
+  "name": "CommunitySprayFireball",
+  "init": 300,
+  "interval": 0,
+  "params": {
+    "combo_angle": 10,
+    "combo_damage": "combo_damage"
+  },
+  "max": 1
+}
+```
+
+这里表示外层组合开始后的 `300ms` 调用一次 `CommunitySprayFireball`。系统会阻止组合直接或间接循环调用自己。
+
+## 七、常见错误
+
+1. 变量名必须完全一致。
+
+   例如声明的是 `combo_ball_move_time`,却写成 `combo_move_time`,后者会被当成普通字符串传给技能,可能在运行时产生类型错误。
+
+2. `one_loop` 引用的列表长度必须相同。
+
+3. `computed_scalar` 不能引用列表;`computed_list` 最多引用一个列表。
+
+4. JSON 的逗号、引号和括号必须完整。
+
+5. 内部使用 `max: -1` 会让该内部技能永久运行。外层组合还会重复调用时,可能不断叠加新的永久技能,通常建议内部使用有限次数。
+
+6. 一次组合最多展开 10000 个技能,避免 `outer_product` 产生过大的组合。

+ 6 - 6
client_local/algo/blender.py

@@ -73,14 +73,14 @@ def color_overlay(target_surface, color, package_surface):
 
 
 def blit(source, source_alpha, dest, blend_at, blend_mode):
-
-    ra = pygame.Rect((0, 0, dest.get_size()[0], dest.get_size()[1]))
-    rb = pygame.Rect((blend_at[0], blend_at[1], source.get_size()[0], source.get_size()[1]))
-    ra_b = ra.clip(rb)
-    if ra_b.w == 0:
+    # surfarray 不会自动遵守 Surface 的裁剪范围,必须在像素运算前裁剪。
+    rb = source.get_rect(topleft=blend_at)
+    ra_b = dest.get_clip().clip(rb)
+    if ra_b.w == 0 or ra_b.h == 0:
         return
 
-    fg_x, fg_dx, fg_y, fg_dy = max(0, -blend_at[0]), dest.get_size()[0] - blend_at[0], max(0, -blend_at[1]), dest.get_size()[1] - blend_at[1]
+    fg_x, fg_y = ra_b.x - rb.x, ra_b.y - rb.y
+    fg_dx, fg_dy = fg_x + ra_b.w, fg_y + ra_b.h
     a3d_item = pygame.surfarray.pixels3d(source)[fg_x: fg_dx, fg_y: fg_dy]
     source_alpha = source_alpha[fg_x: fg_dx, fg_y: fg_dy]
 

+ 3 - 1
client_local/control.py

@@ -277,6 +277,8 @@ class Control:
         )
 
     def update(self):
+        # 同一个 Clock 才能把本帧更新、绘制的耗时计入限帧间隔。
+        clock = pygame.time.Clock()
         # 事件处理
         while True:
             for event in pygame.event.get():
@@ -311,7 +313,7 @@ class Control:
             pygame.display.flip()
 
             # 设置帧率
-            pygame.time.Clock().tick(self.frame_rate)
+            clock.tick(self.frame_rate)
 
     def key_pressed(self):
         # 键盘事件检测

+ 117 - 77
client_local/level/level.py

@@ -78,6 +78,7 @@ def get_light_npc_coordinates():
 
 
 _last_light_states = None
+_last_colour_light_states = None
 
 
 # def get_player_mask(mask_surface, bgl):
@@ -110,7 +111,26 @@ _last_light_states = None
 #     return mask_surface
 
 
-def get_player_mask(mask_surface, bgl):
+def _render_light_mask(mask_surface, colour, lights, origin, previous_key):
+    """只缓存、绘制会影响视口的光源;保留重复光源原有的叠加亮度。"""
+    view_x, view_y = origin
+    bounds = mask_surface.get_rect()
+    visible = []
+    for x, y, light in lights:
+        cm = circleMasks[light]
+        r = light * MASK_STEP
+        pos = (int(x - view_x - r), int(y - view_y - r - 15))
+        if bounds.colliderect(cm.get_rect(topleft=pos)):
+            visible.append((pos, light))
+    key = (id(current_level), id(mask_surface), mask_surface.get_size(), colour, tuple(visible))
+    if key != previous_key:
+        mask_surface.fill((*colour, 0))
+        for pos, light in visible:
+            mask_surface.blit(circleMasks[light], pos, special_flags=pygame.BLEND_RGBA_ADD)
+    return key
+
+
+def get_player_mask(mask_surface, bgl, source_origin=(0, 0)):
     global _last_light_states
     # 收集当前所有光源状态 (x, y, light)
     curr = []
@@ -123,61 +143,40 @@ def get_player_mask(mask_surface, bgl):
     for p in current_level.obstacle_instances.values():
         if p.light:
             curr.append((p.x_pos, p.y_pos, p.light))
-    curr_key = (
-        id(current_level),
-        current_level.scroll_x_pos,
-        current_level.scroll_y_pos,
-        mask_surface.get_width(),
-        mask_surface.get_height(),
-        bgl,
-        tuple(curr),
-    )
-    if curr_key == _last_light_states:
-        return mask_surface
-    _last_light_states = curr_key
-    bgl = max(0, min(bgl, 255))
-    fill = mask_surface.fill
-    blit = mask_surface.blit
-    masks = circleMasks
-    # 先把整表清空为 bgl 灰底
-    fill((bgl, bgl, bgl, 0))
-    # ---- 新增:计算屏幕视口,并在后面用 inflate 方式做相交测试 ----
-    from client_local.const import game as G
-    # world-space 下的视口矩形
+    # 旧版先画到整图大小的局部遮罩,再由震屏移动遮罩;保持原来的取整顺序。
+    local_lights = []
     view_rect = pygame.Rect(
-        current_level.scroll_x_pos,
-        current_level.scroll_y_pos,
-        G.MAIN_AREA_X_POS,
-        G.MAIN_AREA_Y_POS
+        current_level.scroll_x_pos, current_level.scroll_y_pos,
+        G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS
     )
-    # ---------------------------------------------------------
-    view_x, view_y = current_level.scroll_x_pos, current_level.scroll_y_pos
     for x, y, light in curr:
-        r  = light * MASK_STEP
-        sx = x - view_x - r           # ← 世界 → 屏幕
-        sy = y - view_y - r - 15
-        cm = masks[light]
-        # 膨胀法:把视口向外各扩 r(水平方向)和 (r+15)(垂直方向)
-        if not view_rect.inflate(2*r, 2*(r+15)).collidepoint(x, y):
+        r = light * MASK_STEP
+        if not view_rect.inflate(2 * r, 2 * (r + 15)).collidepoint(x, y):
             continue
-        # 叠加亮度
-        mask_surface.blit(cm, (sx, sy), special_flags=pygame.BLEND_RGBA_ADD)
+        local_lights.append((
+            int(x - current_level.scroll_x_pos - r) + r,
+            int(y - current_level.scroll_y_pos - r - 15) + r + 15,
+            light
+        ))
+    bgl = max(0, min(bgl, 255))
+    _last_light_states = _render_light_mask(
+        mask_surface, (bgl, bgl, bgl), local_lights, source_origin, _last_light_states
+    )
     return mask_surface
 
 
-def special_colour_mask(mask_surface, rgb):
-    r = min(max(rgb[0], 0), 255)
-    g = min(max(rgb[1], 0), 255)
-    b = min(max(rgb[2], 0), 255)
-    mask_surface.fill((r, g, b, 0))  # 初始
+def special_colour_mask(mask_surface, rgb, origin):
+    global _last_colour_light_states
+    colour = tuple(min(max(rgb[i], 0), 255) for i in range(3))
+    curr = []
     for player in [current_level.me] + current_level.npcs + list(current_level.obstacle_instances.values()):
-        x, y = player.x_pos, player.y_pos
-        if player.light == 0:
-            continue
-        circleMask = circleMasks[player.light]
-        circle_radius = player.light*MASK_STEP
-        # 叠加亮度
-        mask_surface.blit(circleMask, (x-circle_radius, y-circle_radius-15),special_flags=pygame.BLEND_RGBA_ADD)    # 15是补偿值(大概是角色中心)
+        if player.light:
+            # 原彩色遮罩先在世界坐标中 blit,再截取;保留浮点坐标的取整顺序。
+            r = player.light * MASK_STEP
+            curr.append((int(player.x_pos - r) + r, int(player.y_pos - r - 15) + r + 15, player.light))
+    _last_colour_light_states = _render_light_mask(
+        mask_surface, colour, curr, origin, _last_colour_light_states
+    )
     return mask_surface
 
 
@@ -209,10 +208,13 @@ class MainArea(pygame.Surface):
         super().__init__(size, flags)
 
     def blit(self, source, dest, area=None, special_flags=0):
-        relative_y = dest[1] - current_level.scroll_y_pos - G.MAIN_AREA_Y_POS//2
-        scale_bias_value = relative_y * (1 - Y_SCALE_FACTOR)
-        dest = (dest[0], int(dest[1] - scale_bias_value))
-        super().blit(source, dest, area, special_flags)
+        if Y_SCALE_FACTOR == 1:
+            dest = (dest[0], int(dest[1]))
+        else:
+            relative_y = dest[1] - current_level.scroll_y_pos - G.MAIN_AREA_Y_POS//2
+            scale_bias_value = relative_y * (1 - Y_SCALE_FACTOR)
+            dest = (dest[0], int(dest[1] - scale_bias_value))
+        return super().blit(source, dest, area, special_flags)
 
 
 class Level:
@@ -363,7 +365,9 @@ class Level:
         if self.is_transport:
             self.resource_bar.set_max_blood(G.TOTAL_TRANSPORT)
 
-        self.mask_surface = pygame.Surface((self.map_x_pos, self.map_y_pos), pygame.SRCALPHA).convert_alpha()
+        # 遮罩只覆盖视口;彩色/黑暗模式使用独立缓存,避免同时开启时互相污染。
+        self.mask_surface = pygame.Surface((G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS), pygame.SRCALPHA).convert_alpha()
+        self.colour_mask_surface = pygame.Surface((G.MAIN_AREA_X_POS + 1, G.MAIN_AREA_Y_POS), pygame.SRCALPHA).convert_alpha()
 
         self.haunt_Mode = False
         self.bg_light = 0
@@ -387,8 +391,9 @@ class Level:
                 EnvironmentEffect(self.effects_screen, en)
         self.haunt_Mode = self.map_json["basic"].get("haunted", False)
         self.bg_light = self.map_json["basic"].get("bg_light", 0)
-        global _last_light_states
+        global _last_light_states, _last_colour_light_states
         _last_light_states = None
+        _last_colour_light_states = None
         self.mask_surface.fill((self.bg_light, self.bg_light, self.bg_light, 0))
         self.sunny = bool(self.map_json["basic"].get("sunny", False))
         self.underwater = self.map_json["basic"].get("underwater", False)
@@ -474,6 +479,8 @@ class Level:
         self.obstacle_instances = dict()
         self.obstacle_instances_update = list()
         self.bomb_instances = list()
+        self._bomb_position_index = {}
+        self._bomb_index_dirty = True
         self.ui_instances_bot = list()
         self.ui_instances_top = list()
         self.block = np.zeros((2, self.map_x + 1, self.map_y + 1), dtype=np.int64)
@@ -776,6 +783,44 @@ class Level:
         obstacle_ref = self.obstacle_instances.get((cell_x, cell_y))
         return obstacle_ref is not None and getattr(obstacle_ref, "water_reflect", False)
 
+    def get_render_view_rect(self):
+        # 最终画面从 scroll_x_pos - 1 截取,保留这一列及原光照视口的右边界。
+        return pygame.Rect(
+            self.scroll_x_pos - 1, self.scroll_y_pos,
+            G.MAIN_AREA_X_POS + 1, G.MAIN_AREA_Y_POS
+        ).clip(self.main_area.get_rect())
+
+    def apply_light_masks(self):
+        quake_y = int((self.scroll_y_pos + G.MAIN_AREA_Y_POS // 2) * (1 - Y_SCALE_FACTOR))
+        if self.special_rgb:
+            # 旧版整图遮罩在 MainArea.blit 中也受震屏偏移影响。
+            # 反推可见的源区域,再以原生 blit 合成,避免重复施加偏移。
+            source_rect = self.get_render_view_rect().move(0, -quake_y).clip(self.main_area.get_rect())
+            if source_rect.w and source_rect.h:
+                special_colour_mask(self.colour_mask_surface, self.rgb_light, source_rect.topleft)
+                pygame.Surface.blit(
+                    self.main_area, self.colour_mask_surface,
+                    (source_rect.x, source_rect.y + quake_y),
+                    (0, 0, source_rect.w, source_rect.h),
+                    special_flags=pygame.BLEND_RGBA_MULT
+                )
+
+        if self.haunt_Mode:
+            view_rect = pygame.Rect(
+                self.scroll_x_pos, self.scroll_y_pos,
+                G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS
+            ).clip(self.main_area.get_rect())
+            # subsurface 仍是 MainArea,旧版局部遮罩 blit 也带有 quake_y 偏移。
+            source_rect = pygame.Rect(0, -quake_y, view_rect.w, view_rect.h).clip(self.main_area.get_rect())
+            if source_rect.w and source_rect.h:
+                get_player_mask(self.mask_surface, self.bg_light, source_rect.topleft)
+                pygame.Surface.blit(
+                    self.main_area, self.mask_surface,
+                    (view_rect.x + source_rect.x, view_rect.y + source_rect.y + quake_y),
+                    (0, 0, source_rect.w, source_rect.h),
+                    special_flags=pygame.BLEND_RGBA_MULT
+                )
+
     def draw_dynamic_object(self, obj):
         if not self.should_draw_water_submerged(obj):
             obj.draw(self.main_area)
@@ -1410,6 +1455,11 @@ class Level:
         for u in self.ui_instances_bot:
             u.update()
 
+        # 只裁剪绘制,不跳过 update/draw 中的状态处理。
+        # 原生 blit 会在震屏坐标变换后裁剪;自定义 blender 同样遵守此范围。
+        previous_clip = self.main_area.get_clip()
+        self.main_area.set_clip(self.get_render_view_rect())
+
         if Y_SCALE_FACTOR != 1:
             MAX_BIAS = G.MAIN_AREA_Y_POS * (1-Y_SCALE_FACTOR)//2
             # 上下MAX_BIAS区域填充(0,0,0,0)
@@ -1519,28 +1569,14 @@ class Level:
             self.draw_dynamic_object(B[j][2])
             j += 1
 
-        if self.special_rgb:
-            self.mask_surface = special_colour_mask(self.mask_surface, self.rgb_light)
-            self.main_area.blit(self.mask_surface, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
-
-        if self.haunt_Mode:
-            # 只在 get_player_mask 检测到状态变化时才重绘 mask_surface
-            get_player_mask(self.mask_surface, self.bg_light)
-            view_rect = pygame.Rect(
-                self.scroll_x_pos,
-                self.scroll_y_pos,
-                G.MAIN_AREA_X_POS,
-                G.MAIN_AREA_Y_POS
-            ).clip(self.main_area.get_rect())
-            # 取 main_area 的子 Surface(不拷贝像素,O(1))
-            sub_main = self.main_area.subsurface(view_rect)
-            # 将 mask_surface 乘进子 Surface,而不是整张 main_area
-            sub_main.blit(self.mask_surface, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
+        self.apply_light_masks()
 
         # 显示顶层特效
         for e in self.effects_front:
             e.draw(self.main_area)
 
+        self.main_area.set_clip(previous_clip)
+
         # 显示下ui
         for u in self.ui_instances_bot:
             u.draw(screen)
@@ -1725,12 +1761,16 @@ class Level:
         DistrictAlarm(self.effects_behind)
 
     def get_bomb_instance(self, x, y):
-        # 获取(x, y)处的所有糖泡list
-        bs = list()
-        for b in self.bomb_instances:
-            if b.x == x and b.y == y and not b.throwing:
-                bs.append(b)
-        return bs
+        # 同一次位置变化后的所有查询共享索引;保持原列表中的同格糖泡顺序。
+        if self._bomb_index_dirty:
+            positions = {}
+            for bomb in self.bomb_instances:
+                if not bomb.throwing:
+                    positions.setdefault((bomb.x, bomb.y), []).append(bomb)
+            self._bomb_position_index = positions
+            self._bomb_index_dirty = False
+        # 调用者可能在遍历中引爆/删除糖泡,不能把索引内部的列表暴露出去。
+        return list(self._bomb_position_index.get((x, y), ()))
 
     def get_an_npc(self, name, point):
         return Npc(name, point)

+ 43 - 0
client_local/skill/parametric2_skill.py

@@ -3030,3 +3030,46 @@ class CustomSetDamageUpperBound(Skill):
         super().__init__(user, to, skill_instances)
         self.params = params
         self.user.total_damage_bound = self.params.get("total_damage_bound", inf)
+
+
+# "params": {"character": "Character17901", "time": 5000}
+class CustomHenshin(Skill):
+
+    def __init__(self, user, to, params, skill_instances):
+        super().__init__(user, to, skill_instances)
+        self.loaded = True
+        self.character = params.get("character", "Character17901")
+        self.time = params.get("time", 5000)
+
+    def load(self):
+        super().load()
+
+    def update(self):
+        super().update()
+        if self.loaded:
+            self.loaded = False
+            self.user.align_xy()
+            sound_player.play("launch")
+            self.effect_instances.append(
+                EffectInstance("fire_charge", self.user, False, self.user.effects_front)
+            )
+            for to in [level.current_level.me]:
+                to.polymorph_for(max(1, self.time - 20), self.character)
+                self.effect_instances.append(
+                    EffectInstance("dizzy_explode", to, False, to.effects_front)
+                )
+            self.kill()
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+ 465 - 0
client_local/skill/skill_combo.py

@@ -0,0 +1,465 @@
+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)

+ 5 - 0
client_local/skill/skill_map.py

@@ -11,6 +11,7 @@ from client_local.skill.cool_machine_skill import *
 from client_local.skill.parametric2_skill import *
 from client_local.skill.parametric3_skill import *
 from client_local.skill.level_skill import *
+from client_local.skill.skill_combo import register_skill_combos
 
 
 skill_map = {
@@ -333,6 +334,7 @@ skill_map = {
     "ChessQueenMoveMode": {"skill": ChessQueenMoveMode, "target": "me", "param": True, "effect": "self"},
     "EdenMouthSkill": {"skill": EdenMouthSkill, "target": "me", "param": True, "effect": "cl"},
     "CustomSetDamageUpperBound": {"skill": CustomSetDamageUpperBound, "target": "me", "param": True, "effect": "self"},
+    "CustomHenshin": {"skill": CustomHenshin, "target": "me", "param": True, "effect": "self"},
 
     "CustomLevelVariableOperation": {"skill": CustomLevelVariableOperation, "target": "me", "param": True, "effect": "self"},
     "CustomConditionBasedSkill": {"skill": CustomConditionBasedSkill, "target": "me", "param": True, "effect": "self"},
@@ -359,3 +361,6 @@ skill_map = {
     "Tundra_Skill21018": {"skill": Tundra_Skill21018, "target": "me", "param": None, "effect": "self"},
     "Tundra_MinionChase": {"skill": Tundra_MinionChase, "target": "me", "param": None, "effect": "self"}
 }
+
+
+skill_combo_map = register_skill_combos(skill_map)

+ 39 - 0
client_local/sprite/bomb_instance.py

@@ -29,6 +29,38 @@ class BombInstance(Throwable):
 
     sound_played = False  # 当前帧播放了爆炸音效 不再重复播放(每帧会重置为False)
 
+    def _set_indexed_value(self, name, value):
+        old = getattr(self, name, None)
+        setattr(self, name, value)
+        owner = getattr(self, "_bomb_index_owner", None)
+        if owner is not None and old != value:
+            owner._bomb_index_dirty = True
+
+    # 在属性边界失效,覆盖传送带、投掷、落地和技能直接修改格坐标的路径。
+    @property
+    def x(self):
+        return self._x
+
+    @x.setter
+    def x(self, value):
+        self._set_indexed_value("_x", value)
+
+    @property
+    def y(self):
+        return self._y
+
+    @y.setter
+    def y(self, value):
+        self._set_indexed_value("_y", value)
+
+    @property
+    def throwing(self):
+        return self._throwing
+
+    @throwing.setter
+    def throwing(self, value):
+        self._set_indexed_value("_throwing", value)
+
     def __init__(self, x, y, bomb_instances_list: list, bomb, power, damage, player=None):
 
         super(BombInstance, self).__init__(x, y)
@@ -60,6 +92,10 @@ class BombInstance(Throwable):
 
     def setup(self):
         self.bomb_instances_list.append(self)
+        cl = level.current_level
+        self._bomb_index_owner = cl if self.bomb_instances_list is cl.bomb_instances else None
+        if self._bomb_index_owner is not None:
+            self._bomb_index_owner._bomb_index_dirty = True
         level.current_level.recal_npc_paths = True
 
     def update(self):
@@ -317,6 +353,9 @@ class BombInstance(Throwable):
 
     def uninstall(self):
         self.bomb_instances_list.remove(self)
+        if self._bomb_index_owner is not None:
+            self._bomb_index_owner._bomb_index_dirty = True
+            self._bomb_index_owner = None
         level.current_level.recal_npc_paths = True
         if self.player is not None:
             self.player.restore_a_bomb()

+ 37 - 13
client_local/sprite/npc.py

@@ -4,6 +4,7 @@ import os
 import pygame
 from math import inf
 from client_local.skill.skill_map import skill_map
+from client_local.skill.skill_combo import SkillComboError, SkillComboRunner, get_skill_combo
 from client_local.algo import aStar
 from client_local.const import color as C
 from client_local.const import game as G
@@ -250,6 +251,7 @@ class Npc(Player, Throwable):
         self.chs_name_text = self.chs_name_font.render(self.chs_name, True, (255, 255, 0))
         self.chs_name_text_shadow = self.chs_name_font.render(self.chs_name, True, (0, 0, 0))
         self.chs_name_text_half_width = self.chs_name_text.get_width() // 2
+        self._name_display_cache_key = (self.chs_name_font, self.chs_name)
         self.character = self.load_character(
             self.npc_json["character"], color, self.load_decorations()
         )
@@ -295,14 +297,16 @@ class Npc(Player, Throwable):
             self.throw()
 
     def update_npc_blood_display(self, current_time):
-        if G.DISPLAY_NPC_NAME_CARD and G.DISPLAY_NPC_BLOOD:
-            self.chs_name_text = self.chs_name_font.render(str(self.remain_blood-self.fake_blood), True, (255, 255, 0))
-            self.chs_name_text_shadow = self.chs_name_font.render(str(self.remain_blood-self.fake_blood), True, (0, 0, 0))
-            self.chs_name_text_half_width = self.chs_name_text.get_width() // 2
-        else:
-            self.chs_name_text = self.chs_name_font.render(self.chs_name, True, (255, 255, 0))
-            self.chs_name_text_shadow = self.chs_name_font.render(self.chs_name, True, (0, 0, 0))
-            self.chs_name_text_half_width = self.chs_name_text.get_width() // 2
+        if not G.DISPLAY_NPC_NAME_CARD:
+            return
+        text = str(self.remain_blood - self.fake_blood) if G.DISPLAY_NPC_BLOOD else self.chs_name
+        cache_key = (self.chs_name_font, text)
+        if cache_key == self._name_display_cache_key:
+            return
+        self.chs_name_text = self.chs_name_font.render(text, True, (255, 255, 0))
+        self.chs_name_text_shadow = self.chs_name_font.render(text, True, (0, 0, 0))
+        self.chs_name_text_half_width = self.chs_name_text.get_width() // 2
+        self._name_display_cache_key = cache_key
 
     def wander_and_detect(self, current_time):
         # 游走并检测玩家距离
@@ -736,11 +740,25 @@ class Npc(Player, Throwable):
         for i, digit in enumerate(energy_str):
             render_digit(screen, int(digit), self.x_pos, self.y_pos, self.temporary_alpha, x_pos_offset + 10 * i)
 
-    def using_skill_map(self, skill_name, param, spawn_order):
-        cl = level.current_level
-        if skill_name not in skill_map.keys():
-            return
+    def using_skill_map(self, skill_name, param, spawn_order, skill_spawns=None, combo_stack=None):
         try:
+            combo_definition = get_skill_combo(skill_name, skill_map)
+            if combo_definition is not None:
+                combo_stack = list(combo_stack or [])
+                if combo_definition.name.lower() in (name.lower() for name in combo_stack):
+                    chain = combo_stack + [combo_definition.name]
+                    raise SkillComboError("技能组合检测到循环引用: %s" % " -> ".join(chain))
+                SkillComboRunner(
+                    self,
+                    combo_definition,
+                    param,
+                    self.skill_instances,
+                    combo_stack,
+                )
+                return
+            if skill_name not in skill_map:
+                return
+            cl = level.current_level
             skill_attributes = skill_map[skill_name]
             skill_class = skill_attributes["skill"]
             skill_target = skill_attributes.get("target")
@@ -751,7 +769,13 @@ class Npc(Player, Throwable):
             effect_target_map = {"self": self.skill_instances, "cl": cl.skill_instances}
             effect_target = effect_target_map.get(skill_attributes.get("effect"))
             if skill_attributes.get("old_spawn"):
-                skill_class(self, final_target, self.skill_spawns, spawn_order, effect_target)  # 旧版召唤
+                skill_class(
+                    self,
+                    final_target,
+                    self.skill_spawns if skill_spawns is None else skill_spawns,
+                    spawn_order,
+                    effect_target,
+                )  # 旧版召唤
             elif skill_target is not None:
                 if not skill_attributes.get("param"):
                     skill_class(self, final_target, effect_target)  # 有目标无参数

+ 53 - 22
client_local/ui/game/blood_bar.py

@@ -175,6 +175,38 @@ class ResourceBloodBar(UIInstance):
             self.sheet.blit(self.blood_slice_img, (i, 6))
 
 
+def _render_boss_blood_sheet(bar):
+    """缓存重叠切片;分别复制前缀和末端,保留半透明右边缘的原始像素。"""
+    image = bar.blood_slice_img
+    capacity = max(0, bar.rect.width - 2)
+    length = max(0, min(bar.blood_slice_idx, capacity))
+    strip_key = (image, bar.rect.size)
+    if getattr(bar, "_boss_strip_key", None) != strip_key:
+        strip = pygame.Surface((capacity + image.get_width() - 1, image.get_height()), pygame.SRCALPHA, 32)
+        for i in range(capacity):
+            strip.blit(image, (i, 0))
+        bar._boss_strip = strip
+        bar._boss_strip_key = strip_key
+        bar._boss_sheet_key = None
+    sheet_key = (bar.sheet, length)
+    if getattr(bar, "_boss_sheet_key", None) == sheet_key:
+        return
+    if bar.sheet.get_size() != bar.rect.size:
+        bar.sheet = pygame.Surface(bar.rect.size, pygame.SRCALPHA, 32)
+    else:
+        bar.sheet.fill((0, 0, 0, 0))
+    tail_width = image.get_width() - 1
+    if length < tail_width:
+        # 很短的血条不能复用完整条的重叠尾部。
+        for i in range(length):
+            bar.sheet.blit(image, (i + 2, 4))
+    elif length:
+        bar.sheet.blit(bar._boss_strip, (2, 4), (0, 0, length, image.get_height()))
+        if tail_width:
+            bar.sheet.blit(bar._boss_strip, (length + 2, 4), (capacity, 0, tail_width, image.get_height()))
+    bar._boss_sheet_key = (bar.sheet, length)
+
+
 class BossBloodBar(UIInstance):
 
     UI_IMG_GAME_ROOT = "res/img/ui/game/"
@@ -201,7 +233,6 @@ class BossBloodBar(UIInstance):
         if current_time - self.blood_slice_last_update_time > 100:  # 每100ms刷新一次动画
             # print('draw', self.user.chs_name)
             self.blood_slice_last_update_time = current_time
-            self.sheet = pygame.Surface(self.rect.size, pygame.SRCALPHA, 32)
             self.current_blood = self.user.remain_blood - self.user.fake_blood
             self.set_blood(self.current_blood)
             # 动画改变血条长度
@@ -219,9 +250,7 @@ class BossBloodBar(UIInstance):
         self.set_blood(self.current_blood)
 
     def set_blood(self, blood: int):
-        blood = min(max(0, blood), self.max_blood)
-        for i in range(self.blood_slice_idx):
-            self.sheet.blit(self.blood_slice_img, (i+2, 4))
+        _render_boss_blood_sheet(self)
 
 
 class BossLongBloodBar(UIInstance):
@@ -249,7 +278,6 @@ class BossLongBloodBar(UIInstance):
         if current_time - self.blood_slice_last_update_time > 50:  # 每100ms刷新一次动画
             # print('draw', self.user.chs_name)
             self.blood_slice_last_update_time = current_time
-            self.sheet = pygame.Surface(self.rect.size, pygame.SRCALPHA, 32)
             self.current_blood = self.user.remain_blood - self.user.fake_blood
             self.set_blood(self.current_blood)
             # 动画改变血条长度
@@ -269,9 +297,7 @@ class BossLongBloodBar(UIInstance):
         self.set_blood(self.current_blood)
 
     def set_blood(self, blood: int):
-        blood = min(max(0, blood), self.max_blood)
-        for i in range(self.blood_slice_idx):
-            self.sheet.blit(self.blood_slice_img, (i+2, 4))
+        _render_boss_blood_sheet(self)
 
 
 class MapBloodBar(UIInstance):
@@ -391,30 +417,35 @@ class BossHead(UIInstance):
         self.init()
 
     def init(self):
+        self._render_head()
+
+    def _render_head(self):
         self.sheet = pygame.Surface(self.rect.size, pygame.SRCALPHA, 32)
+        self.surf = pygame.Surface((34, 33), pygame.SRCALPHA, 32)
+        stand_frames = self.user.character["STAND_D"]
+        face_frames = stand_frames.get("Face")
+        face_anchor = face_frames[0] if face_frames else None
+
         for component in character.CHARACTER_COMPONENTS["D"]:
-            if component not in self.user.character["STAND_D"].keys():
+            if component not in stand_frames:
                 continue
-            frame = self.user.character["STAND_D"][component][0]
+            frame = stand_frames[component][0]
             frame.image.set_alpha(255)
             if self.user.head_cx != -100000:
-                self.surf.blit(frame.image, (self.user.head_cx, self.user.head_cy))
+                if face_anchor is not None:
+                    # HEAD_POS 是头像中 Face 层的位置;其他层保留相对 Face 的原始偏移。
+                    x = self.user.head_cx + frame.cx - face_anchor.cx
+                    y = self.user.head_cy + frame.cy - face_anchor.cy
+                    self.surf.blit(frame.image, (x, y))
+                else:
+                    # 单张整图的怪物没有 Face 层,保持原来的定位方式。
+                    self.surf.blit(frame.image, (self.user.head_cx, self.user.head_cy))
             else:
                 self.surf.blit(frame.image, (-frame.cx-34, -frame.cy//2-12))
         self.sheet.blit(self.surf, (2, 3))
 
     def renew(self):
-        self.sheet = pygame.Surface(self.rect.size, pygame.SRCALPHA, 32)
-        for component in character.CHARACTER_COMPONENTS["D"]:
-            if component not in self.user.character["STAND_D"].keys():
-                continue
-            frame = self.user.character["STAND_D"][component][0]
-            frame.image.set_alpha(255)
-            if self.user.head_cx != -100000:
-                self.surf.blit(frame.image, (self.user.head_cx, self.user.head_cy))
-            else:
-                self.surf.blit(frame.image, (-frame.cx-34, -frame.cy//2-12))
-        self.sheet.blit(self.surf, (2, 3))
+        self._render_head()
 
     def update(self):
         self.redraw_trigger = True

+ 1 - 1
client_local/ui/game/game_top.py

@@ -15,7 +15,7 @@ class GameTop(UIInstance):
     def __init__(self):
         super().__init__("game", "gameTop")
         self.font = pygame.font.Font(FONT_PATH, 16)
-        self.rend = self.font.render("v20260905", True, (0, 196, 255))
+        self.rend = self.font.render("v20261031", True, (0, 196, 255))
 
     def draw(self, screen: pygame.Surface):
         super().draw(screen)

+ 14 - 0
recovered_map_editor/launch.py

@@ -0,0 +1,14 @@
+"""Run the recovered editor against the project resources, backing up map.json."""
+from pathlib import Path
+import os
+import runpy
+import sys
+
+HERE = Path(__file__).resolve().parent
+ROOT = HERE.parent
+
+if __name__ == "__main__":
+    sys.path.insert(0, str(ROOT / ".codex_build" / "map_editor_runtime"))
+    sys.path.insert(0, str(HERE / "source"))
+    os.chdir(str(ROOT))
+    runpy.run_path(str(HERE / "source" / "main.py"), run_name="__main__")

+ 4 - 0
recovered_map_editor/requirements.txt

@@ -0,0 +1,4 @@
+pygame-ce==2.5.2
+pyperclip==1.11.0
+numpy
+Pillow

+ 246 - 0
recovered_map_editor/source/asset_library.py

@@ -0,0 +1,246 @@
+"""Background asset decoding; all Pygame surfaces stay on the UI thread."""
+import json
+import re
+from pathlib import Path
+from runtime_paths import PROJECT_ROOT
+from concurrent.futures import ThreadPoolExecutor
+from PIL import Image
+import pygame
+from const.window import WINDOW_W, WINDOW_H, TOOL_PANEL_WIDTH
+from game.frame import floor, obstacle
+from game.frame.frame import Frame
+
+
+def scan(root, library):
+    directory = root / 'res/img/mapElem' / library
+    entries = []
+    for path in directory.iterdir():
+        match = re.fullmatch(r'(elem\d+)(\.png|_stand_0_0\.png)', path.name, re.I)
+        if not match:
+            continue
+        name, suffix = match.groups()
+        kind = 'floor' if suffix.lower() == '.png' else 'obstacle'
+        registration = None
+        if kind == 'obstacle':
+            registration = next((root / 'game/frame' / folder / library / (name+'.json')
+                                 for folder in ('obstacle', 'obstacles')
+                                 if (root / 'game/frame' / folder / library / (name+'.json')).is_file()), None)
+            if registration is None:
+                continue
+        entries.append(dict(type=library, name=name, elem_type=kind, path=path, registration=registration))
+    return sorted(entries, key=lambda n: (int(n['name'][4:]), n['elem_type']))
+
+
+def decode(root, entry, full=False):
+    entry = dict(entry)
+    path = entry['path']
+    width = height = 1
+    cx = cy = 0
+    if entry['registration']:
+        config = json.loads(entry['registration'].read_text(encoding='utf-8-sig'))
+        width, height = config['WIDTH'], config['HEIGHT']
+        if not isinstance(width, int) or not isinstance(height, int) or width < 1 or height < 1:
+            raise ValueError('无效占地尺寸')
+        stand = config['STAND']
+        path = root / 'res/img/mapElem' / config['TYPE'] / stand['IMG'][0]
+        cx, cy = stand['CX'][0], stand['CY'][0]
+    with Image.open(path) as source:
+        img = source.convert('RGBA')
+    entry.update(width=width, height=height, cx=cx, cy=cy)
+    if full:
+        return entry, img.size, img.tobytes()
+    # Fit the sprite and its offset relative to the occupied cells together.
+    left, top = min(0, cx), min(0, cy)
+    right, bottom = max(width*40, cx+img.width), max(height*40, cy+img.height)
+    scale = min(1, 112/(right-left), 88/(bottom-top))
+    size = (max(1, round(img.width*scale)), max(1, round(img.height*scale)))
+    img = img.resize(size, Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS)
+    thumb = Image.new('RGBA', (112, 88))
+    thumb.alpha_composite(img, (round((112-(right-left)*scale)/2+(cx-left)*scale),
+                                round((88-(bottom-top)*scale)/2+(cy-top)*scale)))
+    return entry, thumb.size, thumb.tobytes()
+
+
+class AssetLibrary:
+    def __init__(self, app):
+        self.app = app
+        self.root = PROJECT_ROOT
+        self.pool = ThreadPoolExecutor(max_workers=4, thread_name_prefix='map-assets')
+        self.visible = False
+        self.libraries = []
+        self.directory_job = self.pool.submit(lambda: sorted(p.name for p in (self.root/'res/img/mapElem').iterdir() if p.is_dir()))
+        self.scan_job = None
+        self.jobs = {}
+        self.pending = []
+        self.entries = []
+        self.selected_job = None
+        self.library = None
+        self.dropdown = False
+        self.folder_offset = self.offset = self.failed = 0
+        self.header = pygame.Rect(WINDOW_W+12, 44, TOOL_PANEL_WIDTH-24, 32)
+        self.button = pygame.Rect(616, 2, 86, 28)
+
+    def toggle(self):
+        self.visible = not self.visible
+        if not self.visible and self.selected_job:
+            self.selected_job.cancel()
+            self.selected_job = None
+        self.app.menu.active = None
+        self.app.menu.block_pointer = True
+        self.app.settings.focus = None
+        pygame.key.stop_text_input()
+        if self.visible:
+            self.app.tools.visible = True
+            self.app.tools.regions.finish_drag()
+            self.app.tools.choose('paint')
+            self.app.tools.regions.enabled = False
+
+    def choose_library(self, name):
+        for job in self.jobs:
+            job.cancel()
+        if self.selected_job:
+            self.selected_job.cancel()
+        self.selected_job = None
+        self.jobs.clear()
+        self.pending = []
+        self.entries = []
+        self.offset = self.failed = 0
+        self.library = name
+        self.dropdown = False
+        self.scan_job = self.pool.submit(scan, self.root, name)
+
+    def update(self):
+        if self.directory_job and self.directory_job.done():
+            try:
+                self.libraries = self.directory_job.result()
+            except Exception as error:
+                self.app.menu.notify('素材目录读取失败:'+str(error))
+            self.directory_job = None
+        if self.visible and self.library is None and self.libraries:
+            self.choose_library(self.libraries[0])
+        if self.scan_job and self.scan_job.done():
+            try:
+                self.pending = self.scan_job.result()
+            except Exception as error:
+                self.app.menu.notify('素材扫描失败:'+str(error))
+            self.scan_job = None
+        for job in list(self.jobs):
+            if job.done():
+                del self.jobs[job]
+                try:
+                    entry, size, pixels = job.result()
+                    entry['thumbnail'] = pygame.image.fromstring(pixels, size, 'RGBA').convert_alpha()
+                    self.entries.append(entry)
+                except Exception:
+                    self.failed += 1
+        self.entries.sort(key=lambda n: (int(n['name'][4:]), n['elem_type']))
+        while self.pending and len(self.jobs) < 8:
+            entry = self.pending.pop(0)
+            self.jobs[self.pool.submit(decode, self.root, entry)] = True
+        if self.selected_job and self.selected_job.done() and not self.app.placement.active:
+            job, self.selected_job = self.selected_job, None
+            try:
+                entry, size, pixels = job.result()
+                img = pygame.image.fromstring(pixels, size, 'RGBA').convert_alpha()
+                kind, library, name = entry['elem_type'], entry['type'], entry['name']
+                if kind == 'floor':
+                    floor.floors.setdefault(library, {})[name] = img
+                else:
+                    obstacle.obstacles.setdefault(library, {})[name] = dict(TYPE=library, NAME=name,
+                        WIDTH=entry['width'], HEIGHT=entry['height'], STAND=[Frame(img, entry['cx'], entry['cy'])])
+                    self.app.show_obstacle = True
+                self.app.tools.choose('paint')
+                self.app.current_elem = dict(elem_type=kind, type=library, name=name)
+                selection = self.app.selection
+                selection.group = [dict(layer=kind, type=library, name=name, x=0, y=0)]
+                selection.clipboard_text = selection.read_clipboard()
+                self.app.redraw_floor_obstacle_trigger = True
+                self.app.menu.notify('已选择 '+library+'/'+name+';左键放置')
+            except Exception as error:
+                self.app.menu.notify('素材读取失败:'+str(error))
+
+    def handle_event(self, event):
+        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and self.button.collidepoint(event.pos):
+            self.toggle()
+            return True
+        if not self.visible:
+            return False
+        pos = getattr(event, 'pos', pygame.mouse.get_pos())
+        if pos[0] < WINDOW_W:
+            if event.type == pygame.MOUSEBUTTONDOWN:
+                self.dropdown = False
+            return False
+        if event.type == pygame.MOUSEBUTTONDOWN:
+            self.app.menu.block_pointer = True
+            if event.button in (4, 5):
+                self.scroll(-1 if event.button == 4 else 1)
+            elif event.button == 1:
+                if self.header.collidepoint(pos):
+                    self.dropdown = not self.dropdown
+                elif self.dropdown:
+                    index = (pos[1]-80)//30 + self.folder_offset
+                    if 80 <= pos[1] < 80+min(18, len(self.libraries)-self.folder_offset)*30 and 0 <= index < len(self.libraries):
+                        self.choose_library(self.libraries[index])
+                    else:
+                        self.dropdown = False
+                elif 112 <= pos[1] < WINDOW_H:
+                    col, row = (pos[0]-WINDOW_W-12)//154, (pos[1]-112)//144
+                    index = (self.offset+row)*3+col
+                    if 0 <= col < 3 and 0 <= row < 5 and 0 <= index < len(self.entries):
+                        if self.selected_job:
+                            self.selected_job.cancel()
+                        self.selected_job = self.pool.submit(decode, self.root, self.entries[index], True)
+            return True
+        if event.type == pygame.MOUSEWHEEL:
+            self.scroll(-event.y)
+        return event.type in (pygame.MOUSEWHEEL, pygame.MOUSEMOTION, pygame.MOUSEBUTTONUP)
+
+    def scroll(self, delta):
+        if self.dropdown:
+            self.folder_offset = max(0, min(max(0, len(self.libraries)-18), self.folder_offset+delta))
+        else:
+            self.offset = max(0, min(max(0, (len(self.entries)+2)//3-5), self.offset+delta))
+
+    def draw_button(self):
+        screen, font = self.app.screen, self.app.text_font
+        pygame.draw.rect(screen, (22, 26, 33) if self.visible else (53, 61, 74), self.button)
+        pygame.draw.rect(screen, (144, 155, 173), self.button, 1)
+        text = font.render('素材库', True, (237, 240, 245))
+        screen.blit(text, text.get_rect(center=self.button.center))
+
+    def draw(self):
+        screen, font = self.app.screen, self.app.text_font
+        pygame.draw.rect(screen, (35, 39, 46), (WINDOW_W, 32, TOOL_PANEL_WIDTH, WINDOW_H-32))
+        pygame.draw.rect(screen, (144, 155, 173), self.header, 1)
+        screen.blit(font.render((self.library or '选择素材子库')+'  ▼', True, (235, 235, 240)), (self.header.x+8, self.header.y+6))
+        loading = self.scan_job or self.jobs or self.pending
+        status = '%d 个素材%s%s' % (len(self.entries), ' · 加载中…' if loading else '', ' · 跳过 %d 个无效素材' % self.failed if self.failed else '')
+        screen.blit(font.render(status, True, (170, 185, 200)), (WINDOW_W+12, 86))
+        for i, entry in enumerate(self.entries[self.offset*3:self.offset*3+15]):
+            rect = pygame.Rect(WINDOW_W+12+(i%3)*154, 112+(i//3)*144, 146, 136)
+            selected = self.app.current_elem == {k: entry[k] for k in ('elem_type', 'type', 'name')}
+            pygame.draw.rect(screen, (22, 26, 33) if selected else (52, 59, 70), rect)
+            pygame.draw.rect(screen, (245, 195, 80) if selected else (120, 135, 150), rect, 2 if selected else 1)
+            screen.blit(entry['thumbnail'], (rect.x+17, rect.y+4))
+            label = font.render(entry['name'], True, (235, 238, 245))
+            screen.blit(label, label.get_rect(center=(rect.centerx, rect.y+104)))
+            label = font.render('%s %d×%d' % ('地板' if entry['elem_type']=='floor' else '障碍', entry['width'], entry['height']), True, (175, 190, 205))
+            screen.blit(label, label.get_rect(center=(rect.centerx, rect.y+124)))
+        rows = (len(self.entries)+2)//3
+        if rows > 5:
+            track = pygame.Rect(WINDOW_W+TOOL_PANEL_WIDTH-12, 112, 6, 712)
+            pygame.draw.rect(screen, (22, 26, 33), track)
+            height = max(24, round(track.height*5/rows))
+            pygame.draw.rect(screen, (145, 160, 180), (track.x, track.y+round((track.height-height)*self.offset/(rows-5)), track.width, height))
+        screen.blit(font.render('滚轮浏览素材 · 再点“素材库”返回工具栏', True, (170, 185, 200)), (WINDOW_W+12, 845))
+        if self.dropdown:
+            for i, name in enumerate(self.libraries[self.folder_offset:self.folder_offset+18]):
+                rect = pygame.Rect(WINDOW_W+12, 80+i*30, TOOL_PANEL_WIDTH-24, 30)
+                pygame.draw.rect(screen, (65, 77, 93) if name == self.library else (28, 33, 40), rect)
+                pygame.draw.rect(screen, (110, 125, 140), rect, 1)
+                screen.blit(font.render(name, True, (235, 235, 240)), (rect.x+8, rect.y+5))
+
+    def close(self):
+        for job in self.jobs:
+            job.cancel()
+        self.pool.shutdown(wait=False)

+ 5 - 0
recovered_map_editor/source/const/__init__.py

@@ -0,0 +1,5 @@
+# decompyle3 version 3.9.3
+# Python bytecode version base 3.7.0 (3394)
+# Decompiled from: Python 3.13.1 (tags/v3.13.1:0671451, Dec  3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)]
+# Embedded file name: -
+pass

+ 11 - 0
recovered_map_editor/source/const/color.py

@@ -0,0 +1,11 @@
+# decompyle3 version 3.9.3
+# Python bytecode version base 3.7.0 (3394)
+# Decompiled from: Python 3.13.1 (tags/v3.13.1:0671451, Dec  3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)]
+# Embedded file name: const\color.py
+COLOR_WHITE = (255, 255, 255)
+COLOR_RED = (255, 0, 0)
+COLOR_GREEN = (0, 255, 0)
+COLOR_BLUE = (0, 0, 255)
+COLOR_YELLOW = (255, 255, 0)
+COLOR_CYAN = (0, 255, 255)
+COLOR_BLACK = (0, 0, 0)

+ 20 - 0
recovered_map_editor/source/const/window.py

@@ -0,0 +1,20 @@
+# decompyle3 version 3.9.3
+# Python bytecode version base 3.7.0 (3394)
+# Decompiled from: Python 3.13.1 (tags/v3.13.1:0671451, Dec  3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)]
+# Embedded file name: const\window.py
+MENU_HEIGHT = 32
+MAP_AT = (200, 40 + MENU_HEIGHT)
+PREVIEW_AT = (20, 120 + MENU_HEIGHT)
+HINT_AT = (20, 520 + MENU_HEIGHT)
+GAME_SQUARE = 40
+HALF_GAME_SQUARE = GAME_SQUARE // 2
+MAP_GRID_SIZE = MAP_GRID_X, MAP_GRID_Y = (27, 20)
+MAP_SIZE = MAP_W, MAP_H = (MAP_GRID_X * GAME_SQUARE, MAP_GRID_Y * GAME_SQUARE)
+WINDOW_W, WINDOW_H = (MAP_AT[0] + MAP_W, MAP_AT[1] + MAP_H)
+TOOL_PANEL_WIDTH = 496
+WINDOW_SIZE = (WINDOW_W + TOOL_PANEL_WIDTH, WINDOW_H)
+WINDOW_CAPTION = "QQTPVE地图编辑器v2.0(By:永恒/100の雨女)"
+WINDOW_UPDATE_RATE = 30
+COORDINATOR_FONT_SIZE = 16
+MAP_JSON_FILE_NAME = "map.json"
+AUTO_SAVE_DURATION = 30000

+ 513 - 0
recovered_map_editor/source/district_overlay.py

@@ -0,0 +1,513 @@
+"""District boundaries, editable corners, NPC movement and scrollable controls."""
+import pygame
+import colorsys
+import copy
+from npc_preview import NpcPreview
+from const.window import WINDOW_W, TOOL_PANEL_WIDTH, MAP_AT, MAP_W, MAP_H, GAME_SQUARE
+
+
+class DistrictOverlay:
+    COLORS = [(100, 200, 255), (255, 190, 85), (180, 140, 255), (100, 235, 155), (255, 130, 170)]
+    TOP = 524
+    PAGE_SIZE = 6
+
+    def __init__(self, app):
+        self.app = app
+        self.enabled = False
+        self.hidden = set()
+        self.offset = 0
+        self.expanded = set()
+        self.editing = None
+        self.moving_npc = None
+        self.drag = None
+        self.drag_before = None
+        self.scroll_drag = False
+        self.scroll_grab = 0
+        self.create_mode = None
+        self.create_start = None
+        self.create_end = None
+        self.render_models = False
+        self.solo_npc = None
+        self.models = NpcPreview(app)
+        self.hidden_before_focus = None
+
+    def toggle(self):
+        self.enabled = not self.enabled
+        if self.enabled:
+            self.app.tools.visible = True
+            self.app.tools.choose("paint")
+        else:
+            self.finish_drag()
+            self.editing = self.moving_npc = None
+            self.create_mode = self.create_start = self.create_end = None
+
+    def toggle_models(self):
+        if not self.enabled:
+            self.toggle()
+        self.render_models = not self.render_models
+        self.solo_npc = None
+
+    def focus_region(self, index):
+        self.solo_npc = None
+        self.finish_drag()
+        closing = index in self.expanded
+        if self.hidden_before_focus is not None:
+            self.hidden = self.hidden_before_focus
+            self.hidden_before_focus = None
+        self.expanded = set() if closing else {index}
+        if not closing:
+            self.hidden_before_focus = set(self.hidden)
+            self.hidden.discard(index)
+        self.offset = 0
+        self.editing = self.moving_npc = None
+        self.create_mode = self.create_start = self.create_end = None
+        self.app.selection.cancel()
+
+    def add_rect(self):
+        return pygame.Rect(WINDOW_W + 12, self.TOP + 326, TOOL_PANEL_WIDTH - 44, 20)
+
+    def start_add(self):
+        self.npc_template = None
+        self.finish_drag()
+        self.create_mode = ("npc", next(iter(self.expanded))) if self.expanded else ("region", None)
+        self.create_start = self.create_end = None
+        self.editing = self.moving_npc = None
+        self.app.selection.cancel()
+        self.app.menu.notify("点击地图放置怪物,然后输入名称" if self.expanded else "在地图拖动框选新区域;Esc 取消")
+
+    def ask_name(self, initial=""):
+        name = self.app.menu.dialog("askstring", title="怪物名称", prompt="输入 game/npc 中的怪物名称(不含 .json):", initialvalue=initial)
+        if name is None:
+            return None
+        name = name.strip()
+        if not name:
+            self.app.menu.notify("名称不能为空,未修改")
+            return None
+        return name
+
+    @staticmethod
+    def copy_rect(rect):
+        return pygame.Rect(rect.right - 188, rect.y + 8, 28, 28)
+
+    def copy_npc(self, index, n):
+        self.finish_drag()
+        self.npc_template = copy.deepcopy(self.app.map_json["districts"][index]["npcs"][n])
+        self.create_mode = ("npc", index)
+        self.editing = self.moving_npc = None
+        self.app.menu.notify("点击地图放置怪物副本;Esc 取消")
+
+    def rename_npc(self, index, n):
+        npc = self.app.map_json["districts"][index]["npcs"][n]
+        name = self.ask_name(npc.get("name", ""))
+        if name is not None:
+            self.app.menu.edit(lambda: npc.update(name=name))
+            self.models.errors.pop(name, None)
+
+    @staticmethod
+    def npc_color(index, n):
+        hue = (n * 0.61803398875 + index * 0.19) % 1
+        return tuple(round(c * 255) for c in colorsys.hsv_to_rgb(hue, 0.65, 1))
+
+    @staticmethod
+    def delete_rect(rect):
+        return pygame.Rect(rect.right - 100, rect.y + 8, 28, 28)
+
+    def delete_entry(self, kind, index, value=None):
+        self.solo_npc = None
+        self.finish_drag()
+        self.app.menu.finish_stroke()
+        if kind == "region":
+            self.app.menu.edit(lambda: self.app.map_json["districts"].pop(index))
+            self.expanded.clear()
+            self.hidden.clear()
+            self.hidden_before_focus = None
+            self.editing = None
+            self.app.menu.notify("已删除区域及其怪物;Ctrl+Z 撤销")
+        else:
+            self.app.menu.edit(lambda: self.app.map_json["districts"][index]["npcs"].pop(value))
+            self.app.menu.notify("已删除怪物;Ctrl+Z 撤销")
+        self.moving_npc = None
+        self.create_mode = self.create_start = self.create_end = None
+        self.list_rows()
+
+    @staticmethod
+    def solo_rect(rect):
+        return pygame.Rect(rect.right - 154, rect.y + 8, 48, 28)
+
+    def toggle_solo(self, index, n):
+        self.finish_drag()
+        self.solo_npc = None if self.solo_npc == (index, n) else (index, n)
+        self.moving_npc = None
+        self.app.menu.notify("显示全部怪物" if self.solo_npc is None else "仅显示怪物 %d;再次点击恢复全部" % (n + 1))
+
+    def npc_visible(self, index, n):
+        return not self.render_models or self.solo_npc is None or self.solo_npc == (index, n)
+
+    def entries(self):
+        districts = self.app.map_json.get("districts", [])
+        self.expanded.intersection_update(range(len(districts)))
+        if self.editing is not None and self.editing >= len(districts):
+            self.editing = None
+        if self.moving_npc is not None:
+            i, n = self.moving_npc
+            if i >= len(districts) or n >= len(districts[i].get("npcs", [])):
+                self.moving_npc = None
+        if self.create_mode is not None and self.create_mode[0] == "npc" and self.create_mode[1] >= len(districts):
+            self.create_mode = None
+        result = []
+        for index, district in enumerate(self.app.map_json.get("districts", [])):
+            try:
+                square = district["square"]
+                coords = tuple(int(square[k]) for k in ("x1", "y1", "x2", "y2"))
+                if coords[0] > coords[2] or coords[1] > coords[3]:
+                    continue
+                result.append((index, coords))
+            except (KeyError, TypeError, ValueError):
+                continue
+        return result
+
+    def list_entries(self):
+        result = []
+        for index, coords in self.entries():
+            if self.expanded and index not in self.expanded:
+                continue
+            result.append(("region", index, coords))
+            if index in self.expanded:
+                for n, npc in enumerate(self.app.map_json["districts"][index].get("npcs", [])):
+                    result.append(("npc", index, n))
+        return result
+
+    def list_rows(self):
+        entries = self.list_entries()
+        self.offset = max(0, min(self.offset, max(0, len(entries) - self.PAGE_SIZE)))
+        return [(kind, index, value, pygame.Rect(WINDOW_W + 12 + (24 if kind == "npc" else 0), self.TOP + 34 + i * 48, TOOL_PANEL_WIDTH - 44 - (24 if kind == "npc" else 0), 44))
+                for i, (kind, index, value) in enumerate(entries[self.offset:self.offset + self.PAGE_SIZE])]
+
+    def rows(self):
+        return [(index, value, rect) for kind, index, value, rect in self.list_rows() if kind == "region"]
+
+    def interacting(self):
+        return self.enabled and (self.editing is not None or self.moving_npc is not None or self.drag is not None or self.create_mode is not None)
+
+    def corners(self, index):
+        square = self.app.map_json["districts"][index]["square"]
+        sx, sy = self.app.scroll_grid_at
+        return [(xkey, ykey, pygame.Rect(
+            MAP_AT[0] + (square[xkey] + (xkey == "x2") - sx) * GAME_SQUARE - 6,
+            MAP_AT[1] + (square[ykey] + (ykey == "y2") - sy) * GAME_SQUARE - 6, 12, 12))
+            for xkey, ykey in [("x1", "y1"), ("x2", "y1"), ("x1", "y2"), ("x2", "y2")]]
+
+    def npc_rect(self, index, n):
+        npc = self.app.map_json["districts"][index]["npcs"][n]
+        sx, sy = self.app.scroll_grid_at
+        return pygame.Rect(MAP_AT[0] + (npc["x"] - sx) * GAME_SQUARE + 8,
+                           MAP_AT[1] + (npc["y"] - sy) * GAME_SQUARE + 8, 24, 24)
+
+    def finish_drag(self, cancel=False):
+        if self.drag_before is not None:
+            before = self.drag_before
+            self.drag_before = self.drag = None
+            if cancel:
+                self.app.restore_document(before)
+            else:
+                self.app.menu.record(before)
+
+    def handle_map_event(self, event):
+        if not self.enabled:
+            return False
+        self.entries()
+        if self.scroll_drag:
+            if event.type == pygame.MOUSEMOTION:
+                self.scroll_to(event.pos[1] - self.scroll_grab)
+            elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
+                self.scroll_drag = False
+                self.app.menu.block_pointer = True
+            return True
+        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+            self.finish_drag(cancel=True)
+            self.editing = self.moving_npc = None
+            self.create_mode = self.create_start = self.create_end = None
+            return True
+        if self.create_mode is not None:
+            kind, index = self.create_mode
+            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
+                cell = self.app.selection.cell(event.pos)
+                if cell is None:
+                    return False
+                if kind == "region":
+                    self.create_start = self.create_end = cell
+                else:
+                    template = getattr(self, "npc_template", None)
+                    name = template.get("name", "") if template is not None else self.ask_name()
+                    if name is not None:
+                        node = copy.deepcopy(template) if template is not None else dict(name=name)
+                        node.update(x=cell[0], y=cell[1])
+                        self.app.menu.edit(lambda: self.app.map_json["districts"][index].setdefault("npcs", []).append(node))
+                        self.models.errors.pop(name, None)
+                        self.offset = max(0, len(self.list_entries()) - self.PAGE_SIZE)
+                    self.npc_template = None
+                    self.create_mode = None
+                    self.app.menu.block_pointer = True
+                return True
+            if kind == "region" and self.create_start is not None and event.type in (pygame.MOUSEMOTION, pygame.MOUSEBUTTONUP):
+                self.create_end = self.app.selection.cell(event.pos, clamp=True)
+                if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
+                    x1, x2 = sorted((self.create_start[0], self.create_end[0]))
+                    y1, y2 = sorted((self.create_start[1], self.create_end[1]))
+                    self.app.menu.edit(lambda: self.app.map_json.setdefault("districts", []).append(dict(square=dict(x1=x1, y1=y1, x2=x2, y2=y2), npcs=[])))
+                    self.create_mode = self.create_start = self.create_end = None
+                    self.offset = max(0, len(self.list_entries()) - self.PAGE_SIZE)
+                    self.app.menu.block_pointer = True
+                return True
+        if self.drag is not None:
+            if event.type in (pygame.MOUSEMOTION, pygame.MOUSEBUTTONUP):
+                if event.type == pygame.MOUSEBUTTONUP and event.button != 1:
+                    return True
+                if self.drag[0] == "corner":
+                    _, index, xkey, ykey = self.drag
+                    square = self.app.map_json["districts"][index]["square"]
+                    for axis, key, origin, scroll, limit in [
+                        (0, xkey, MAP_AT[0], self.app.scroll_grid_at[0], self.app.map_size[0]),
+                        (1, ykey, MAP_AT[1], self.app.scroll_grid_at[1], self.app.map_size[1])]:
+                        value = round((event.pos[axis] - origin) / GAME_SQUARE) + scroll - (key.endswith("2"))
+                        low = 0 if key.endswith("1") else square[key[0] + "1"]
+                        high = square[key[0] + "2"] if key.endswith("1") else limit - 1
+                        square[key] = max(low, min(high, value))
+                else:
+                    _, index, n = self.drag
+                    cell = self.app.selection.cell(event.pos, clamp=True)
+                    npc = self.app.map_json["districts"][index]["npcs"][n]
+                    npc["x"], npc["y"] = cell
+                if event.type == pygame.MOUSEBUTTONUP:
+                    self.finish_drag()
+                    self.app.menu.block_pointer = True
+                return True
+            if event.type == pygame.KEYDOWN:
+                return True
+        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
+            if not pygame.Rect(MAP_AT, (MAP_W, MAP_H)).collidepoint(event.pos):
+                return False
+            drag = None
+            if self.editing is not None and self.editing not in self.hidden:
+                for xkey, ykey, rect in self.corners(self.editing):
+                    if rect.collidepoint(event.pos):
+                        drag = ("corner", self.editing, xkey, ykey)
+                        break
+            if self.moving_npc is not None:
+                index, n = self.moving_npc
+                if index not in self.hidden and self.npc_visible(index, n) and self.npc_rect(index, n).collidepoint(event.pos):
+                    drag = ("npc", index, n)
+            if drag:
+                self.app.menu.finish_stroke()
+                self.drag_before = self.app.document_snapshot()
+                self.drag = drag
+            return self.interacting()
+        return False
+
+    def handle_event(self, event):
+        if not self.enabled:
+            return False
+        pos = getattr(event, "pos", pygame.mouse.get_pos())
+        if pos[0] < WINDOW_W or pos[1] < self.TOP:
+            return False
+        if event.type == pygame.MOUSEWHEEL:
+            self.offset -= event.y
+            self.rows()
+            return True
+        if event.type == pygame.MOUSEBUTTONDOWN:
+            if event.button == 1 and self.add_rect().collidepoint(pos):
+                self.start_add()
+                return True
+            track, thumb = self.scrollbar()
+            if event.button == 1 and track.collidepoint(pos):
+                self.scroll_drag = True
+                self.scroll_grab = pos[1] - thumb.y if thumb.collidepoint(pos) else thumb.height // 2
+                self.scroll_to(pos[1] - self.scroll_grab)
+                return True
+            if event.button in (4, 5):
+                self.offset += -1 if event.button == 4 else 1
+                self.rows()
+            elif event.button == 1:
+                for kind, index, value, rect in self.list_rows():
+                    if rect.collidepoint(pos):
+                        if self.delete_rect(rect).collidepoint(pos):
+                            self.delete_entry(kind, index, value)
+                            return True
+                        if kind == "npc":
+                            if self.copy_rect(rect).collidepoint(pos):
+                                self.copy_npc(index, value)
+                                return True
+                            if self.render_models and self.solo_rect(rect).collidepoint(pos):
+                                self.toggle_solo(index, value)
+                                return True
+                            if pos[0] >= rect.right - 34:
+                                self.moving_npc = (index, value)
+                                self.editing = None
+                                self.hidden.discard(index)
+                                self.app.selection.cancel()
+                            else:
+                                self.rename_npc(index, value)
+                        elif pos[0] >= rect.right - 34:
+                            self.focus_region(index)
+                        elif pos[0] >= rect.right - 68:
+                            self.editing = None if self.editing == index else index
+                            self.moving_npc = None
+                            self.hidden.discard(index)
+                            self.app.selection.cancel()
+                        else:
+                            if index in self.hidden:
+                                self.hidden.remove(index)
+                            else:
+                                self.hidden.add(index)
+            return True
+        return False
+
+    def scrollbar(self):
+        self.list_rows()
+        total = len(self.list_entries())
+        track = pygame.Rect(WINDOW_W + TOOL_PANEL_WIDTH - 22, self.TOP + 34, 12, self.PAGE_SIZE * 48 - 4)
+        height = max(24, int(track.height * min(1, self.PAGE_SIZE / max(1, total))))
+        y = track.y + round((track.height - height) * self.offset / max(1, total - self.PAGE_SIZE))
+        return track, pygame.Rect(track.x, y, track.width, height)
+
+    def scroll_to(self, top):
+        track, thumb = self.scrollbar()
+        maximum = max(0, len(self.list_entries()) - self.PAGE_SIZE)
+        fraction = (top - track.y) / max(1, track.height - thumb.height)
+        self.offset = round(max(0, min(1, fraction)) * maximum)
+
+    def draw_map(self):
+        if not self.enabled:
+            return
+        overlay = pygame.Surface((MAP_W, MAP_H), pygame.SRCALPHA)
+        sx, sy = self.app.scroll_grid_at
+        for index, (x1, y1, x2, y2) in self.entries():
+            if index in self.hidden or self.expanded and index not in self.expanded:
+                continue
+            color = self.COLORS[index % len(self.COLORS)]
+            # Coordinates are inclusive grid-cell bounds, as used by the game.
+            rect = pygame.Rect((x1 - sx) * GAME_SQUARE, (y1 - sy) * GAME_SQUARE,
+                               (x2 - x1 + 1) * GAME_SQUARE, (y2 - y1 + 1) * GAME_SQUARE)
+            pygame.draw.rect(overlay, color + (20,), rect)
+            pygame.draw.rect(overlay, color + (240,), rect, 3)
+            visible = rect.clip(overlay.get_rect())
+            if visible.width > 48 and visible.height > 24:
+                label = self.app.text_font.render("区域 %d" % (index + 1), True, color)
+                overlay.blit(label, (visible.x + 5, visible.y + 5))
+            if index == self.editing:
+                for xkey, ykey, handle in self.corners(index):
+                    pygame.draw.rect(overlay, color, handle.move(-MAP_AT[0], -MAP_AT[1]))
+            if index in self.expanded:
+                for n, npc in sorted(enumerate(self.app.map_json["districts"][index].get("npcs", [])), key=lambda pair: pair[1].get("y", 0)):
+                    if not self.npc_visible(index, n):
+                        continue
+                    icon = self.npc_rect(index, n).move(-MAP_AT[0], -MAP_AT[1])
+                    npc_color = self.npc_color(index, n) if self.render_models else color
+                    rendered = self.render_models and self.models.draw(overlay, npc, (sx, sy), npc_color)
+                    if not rendered:
+                        self.monster_icon(overlay, icon, color)
+                    if self.moving_npc == (index, n):
+                        pygame.draw.rect(overlay, (255, 255, 255), icon.inflate(6, 6), 2)
+                    overlay.blit(self.app.text_font.render(str(n + 1), True, npc_color), (icon.right + 3, icon.top))
+            if self.render_models:
+                pygame.draw.rect(overlay, (8, 12, 18, 255), rect.inflate(4, 4), 10)
+                pygame.draw.rect(overlay, color + (255,), rect, 6)
+                pygame.draw.rect(overlay, (245, 250, 255, 255), rect, 1)
+        if self.create_mode is not None:
+            if self.create_mode[0] == "region" and self.create_start is not None:
+                x1, x2 = sorted((self.create_start[0], self.create_end[0]))
+                y1, y2 = sorted((self.create_start[1], self.create_end[1]))
+                rect = pygame.Rect((x1 - sx) * GAME_SQUARE, (y1 - sy) * GAME_SQUARE,
+                                   (x2 - x1 + 1) * GAME_SQUARE, (y2 - y1 + 1) * GAME_SQUARE)
+                pygame.draw.rect(overlay, (255, 220, 70, 50), rect)
+                pygame.draw.rect(overlay, (255, 220, 70), rect, 2)
+            elif self.create_mode[0] == "npc":
+                cell = self.app.selection.cell(pygame.mouse.get_pos())
+                if cell is not None:
+                    icon = pygame.Rect((cell[0] - sx) * GAME_SQUARE + 8, (cell[1] - sy) * GAME_SQUARE + 8, 24, 24)
+                    self.monster_icon(overlay, icon, (255, 220, 60))
+        self.app.screen.blit(overlay, MAP_AT)
+
+    @staticmethod
+    def monster_icon(surface, icon, color):
+        pygame.draw.rect(surface, color, icon, border_radius=5)
+        pygame.draw.polygon(surface, color, [(icon.left, icon.top + 6), (icon.left - 3, icon.top - 5), (icon.left + 8, icon.top)])
+        pygame.draw.polygon(surface, color, [(icon.right, icon.top + 6), (icon.right + 3, icon.top - 5), (icon.right - 8, icon.top)])
+        for dx in (-5, 5):
+            pygame.draw.circle(surface, (25, 30, 38), (icon.centerx + dx, icon.centery - 2), 3)
+
+    def draw_panel(self):
+        if not self.enabled:
+            return
+        screen, font = self.app.screen, self.app.text_font
+        title = "区域显示(坐标含两端格)"
+        screen.blit(font.render(title, True, (235, 238, 243)), (WINDOW_W + 12, self.TOP))
+        if not self.entries():
+            screen.blit(font.render("当前地图没有 districts 区域", True, (170, 180, 195)), (WINDOW_W + 12, self.TOP + 40))
+        for kind, index, value, rect in self.list_rows():
+            color = self.COLORS[index % len(self.COLORS)]
+            if kind == "npc" and self.render_models:
+                color = self.npc_color(index, value)
+            pygame.draw.rect(screen, (48, 54, 65), rect)
+            if kind == "region":
+                x1, y1, x2, y2 = value
+                box = pygame.Rect(rect.x + 8, rect.y + 14, 16, 16)
+                pygame.draw.rect(screen, color, box, 1)
+                if index not in self.hidden:
+                    pygame.draw.lines(screen, color, False, [(box.x + 3, box.y + 8), (box.x + 6, box.y + 12), (box.x + 13, box.y + 3)], 2)
+                label = "区域 %d (%d,%d)-(%d,%d)" % (index + 1, x1, y1, x2, y2)
+                screen.blit(font.render(label, True, color), (rect.x + 32, rect.y + 14), pygame.Rect(0, 0, rect.width - 134, 18))
+                edit = pygame.Rect(rect.right - 66, rect.y + 8, 28, 28)
+                expand = pygame.Rect(rect.right - 32, rect.y + 8, 28, 28)
+                pygame.draw.rect(screen, (22, 26, 33) if self.editing == index else (60, 68, 80), edit)
+                pygame.draw.rect(screen, color, edit, 1)
+                pygame.draw.rect(screen, color, (edit.x + 6, edit.y + 6, 16, 16), 1)
+                for dx, dy in [(4, 4), (19, 4), (4, 19), (19, 19)]:
+                    pygame.draw.rect(screen, color, (edit.x + dx, edit.y + dy, 5, 5))
+                pygame.draw.rect(screen, color, expand, 1)
+                cx, cy = expand.center
+                points = [(cx - 6, cy + 3), (cx + 6, cy + 3), (cx, cy - 4)] if index in self.expanded else [(cx - 6, cy - 3), (cx + 6, cy - 3), (cx, cy + 4)]
+                pygame.draw.polygon(screen, color, points)
+            else:
+                npc = self.app.map_json["districts"][index]["npcs"][value]
+                label = "%d. %s" % (value + 1, npc.get("name", "NPC"))
+                image = font.render(label, True, color)
+                screen.blit(image, (rect.x + 14, rect.y + 4), pygame.Rect(0, 0, rect.width - 200, 18))
+                if self.render_models:
+                    solo = self.solo_rect(rect)
+                    selected = self.solo_npc == (index, value)
+                    pygame.draw.rect(screen, (22, 26, 33) if selected else (60, 68, 80), solo)
+                    pygame.draw.rect(screen, color, solo, 1)
+                    caption = font.render("全部" if selected else "单显", True, color)
+                    screen.blit(caption, caption.get_rect(center=solo.center))
+                screen.blit(font.render("(%s, %s)" % (npc.get("x"), npc.get("y")), True, color), (rect.x + 14, rect.y + 23))
+                button = self.copy_rect(rect)
+                pygame.draw.rect(screen, color, button, 1)
+                pygame.draw.rect(screen, color, (button.x+6, button.y+6, 12, 12), 1)
+                pygame.draw.rect(screen, color, (button.x+10, button.y+10, 12, 12), 1)
+                rename = pygame.Rect(rect.right - 66, rect.y + 8, 28, 28)
+                pygame.draw.rect(screen, color, rename, 1)
+                pygame.draw.line(screen, color, (rename.x + 7, rename.y + 21), (rename.x + 21, rename.y + 7), 3)
+                move = pygame.Rect(rect.right - 32, rect.y + 8, 28, 28)
+                pygame.draw.rect(screen, (22, 26, 33) if self.moving_npc == (index, value) else (60, 68, 80), move)
+                pygame.draw.rect(screen, color, move, 1)
+                cx, cy = move.center
+                pygame.draw.line(screen, color, (cx - 8, cy), (cx + 8, cy), 2)
+                pygame.draw.line(screen, color, (cx, cy - 8), (cx, cy + 8), 2)
+                for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
+                    pygame.draw.polygon(screen, color, [(cx + dx * 10, cy + dy * 10), (cx + dx * 5 - dy * 3, cy + dy * 5 + dx * 3), (cx + dx * 5 + dy * 3, cy + dy * 5 - dx * 3)])
+            delete = self.delete_rect(rect)
+            red = (255, 135, 135)
+            pygame.draw.rect(screen, (70, 38, 44), delete)
+            pygame.draw.rect(screen, red, delete, 1)
+            pygame.draw.rect(screen, red, (delete.x + 8, delete.y + 10, 12, 12), 1)
+            pygame.draw.line(screen, red, (delete.x + 6, delete.y + 7), (delete.x + 22, delete.y + 7), 2)
+            pygame.draw.line(screen, red, (delete.x + 11, delete.y + 4), (delete.x + 17, delete.y + 4), 2)
+        track, thumb = self.scrollbar()
+        pygame.draw.rect(screen, (20, 24, 30), track)
+        pygame.draw.rect(screen, (130, 147, 169), thumb, border_radius=3)
+        add = self.add_rect()
+        pygame.draw.rect(screen, (53, 65, 81), add)
+        pygame.draw.rect(screen, (145, 164, 187), add, 1)
+        image = font.render("[+] 添加怪物" if self.expanded else "[+] 添加区域", True, (230, 235, 245))
+        screen.blit(image, image.get_rect(center=add.center))

+ 358 - 0
recovered_map_editor/source/editor_menu.py

@@ -0,0 +1,358 @@
+"""Pygame menu bar and document history; compatible with Python 3.8."""
+from pathlib import Path
+from datetime import datetime
+import json
+
+import pygame
+from const.window import MENU_HEIGHT, WINDOW_W, MAP_AT, MAP_W, MAP_H, GAME_SQUARE
+
+
+class EditorMenu:
+    ROW_HEIGHT = 32
+    WIDTH = 288
+    HISTORY_LIMIT = 100
+
+    def __init__(self, app):
+        self.app = app
+        self.default_map_path = Path(app.map_path).resolve()
+        self.open_backed_up = False
+        self.active = None
+        self.pressed = None
+        self.undo_stack = []
+        self.redo_stack = []
+        self.stroke = None
+        self.block_pointer = False
+        self.status = ""
+        self.status_until = 0
+        self.show_grid = False
+        self.buttons = [(name, pygame.Rect(8 + i * 86, 2, 82, MENU_HEIGHT - 4))
+                        for i, name in enumerate(("文件", "编辑", "undo", "redo", "工具"))]
+
+    def notify(self, text):
+        self.status = text
+        self.status_until = pygame.time.get_ticks() + 5000
+
+    def snapshot(self):
+        return self.app.document_snapshot()
+
+    def record(self, before):
+        if before != self.snapshot():
+            self.undo_stack.append(before)
+            del self.undo_stack[:-self.HISTORY_LIMIT]
+            self.redo_stack.clear()
+
+    def edit(self, action):
+        before = self.snapshot() if self.stroke is None else None
+        action()
+        if before is not None:
+            self.record(before)
+
+    def finish_stroke(self):
+        if self.stroke is not None:
+            before, self.stroke = self.stroke, None
+            self.record(before)
+
+    def undo(self):
+        self.finish_stroke()
+        if self.undo_stack:
+            state = self.undo_stack[-1]
+            current = self.snapshot()
+            self.app.restore_document(state)
+            self.undo_stack.pop()
+            self.redo_stack.append(current)
+            self.notify("已撤销")
+
+    def redo(self):
+        self.finish_stroke()
+        if self.redo_stack:
+            state = self.redo_stack[-1]
+            current = self.snapshot()
+            self.app.restore_document(state)
+            self.redo_stack.pop()
+            self.undo_stack.append(current)
+            self.notify("已重做")
+
+    def dialog(self, kind, **kwargs):
+        import tkinter as tk
+        from tkinter import filedialog, messagebox, simpledialog
+        root = tk.Tk()
+        root.withdraw()
+        root.attributes("-topmost", True)
+        try:
+            module = simpledialog if kind == "askstring" else messagebox if kind in ("showinfo", "showerror") else filedialog
+            return getattr(module, kind)(parent=root, **kwargs)
+        finally:
+            root.destroy()
+
+    def save(self):
+        self.app.save_map_json()
+        self.notify("已保存:" + Path(self.app.map_path).name)
+
+    def open_map(self):
+        path = self.dialog('askopenfilename', title='打开地图',
+                           initialdir=str(self.default_map_path.parent),
+                           filetypes=[('地图 JSON', '*.json')])
+        if not path:
+            return
+        try:
+            data = json.loads(Path(path).read_text(encoding='utf-8-sig'))
+        except UnicodeDecodeError:
+            data = json.loads(Path(path).read_text(encoding='gbk'))
+        basic = data['basic']
+        width, height = basic['width'], basic['height']
+        if not isinstance(width, int) or not isinstance(height, int) or not (1 <= width <= 256 and 1 <= height <= 256 and width*height <= 10000):
+            raise ValueError('地图尺寸无效:单边最多 256 格,总格数最多 10000')
+        basic.setdefault('scroll', [0, 0])
+        basic.setdefault('begin', [0, 0])
+        basic.setdefault('finish', [width-1, height-1])
+        for key in ('scroll', 'begin', 'finish'):
+            if len(basic[key]) != 2 or not all(isinstance(v, int) for v in basic[key]):
+                raise ValueError('地图坐标无效:' + key)
+        from game.frame import floor, obstacle
+        for layer in ('floor', 'obstacle'):
+            for node in data.setdefault(layer, []):
+                asset = floor.get_floor(node['type'], node['name']) if layer == 'floor' else obstacle.get_obstacle(node['type'], node['name'])
+                for point in node['points']:
+                    x, y = point['x'], point['y']
+                    # Existing maps may intentionally extend scenery beyond the
+                    # canvas. Preserve those coordinates when opening/saving;
+                    # the renderer clips them, as the original loader does.
+                    if not isinstance(x, int) or not isinstance(y, int):
+                        raise ValueError('地图元素坐标必须为整数:%s/%s (%r, %r)' %
+                                         (node['type'], node['name'], x, y))
+        for region in data.setdefault('districts', []):
+            if not all(isinstance(region['square'][k], (int, float)) for k in ('x1', 'x2', 'y1', 'y2')):
+                raise ValueError('区域坐标无效')
+            for npc in region.get('npcs', []):
+                if not all(isinstance(npc[k], (int, float)) for k in ('x', 'y')):
+                    raise ValueError('怪物坐标无效')
+        self.finish_stroke()
+        before = self.snapshot()
+        camera = list(self.app.scroll_grid_at)
+        try:
+            self.app.scroll_grid_at = list(basic['scroll'])
+            self.app.restore_document(data)
+            if not self.open_backed_up and self.default_map_path.exists():
+                backup = self.default_map_path.with_name('map_' + datetime.now().strftime('%Y%m%d_%H%M%S_%f') + '.json')
+                self.default_map_path.rename(backup)
+        except Exception:
+            self.app.scroll_grid_at = camera
+            self.app.restore_document(before)
+            raise
+        self.open_backed_up = True
+        self.app.map_path = str(self.default_map_path)
+        self.app.tools.choose('paint')
+        regions = self.app.tools.regions
+        regions.expanded.clear()
+        regions.hidden.clear()
+        regions.hidden_before_focus = None
+        regions.editing = regions.moving_npc = regions.drag = None
+        regions.create_mode = regions.create_start = regions.create_end = None
+        regions.offset = 0
+        self.undo_stack.clear()
+        self.redo_stack.clear()
+        self.app.timer = pygame.time.get_ticks()
+        self.notify('已打开:' + Path(path).name + ';保存到 map.json')
+
+    def save_as(self):
+        path = self.dialog("asksaveasfilename", title="地图另存为", defaultextension=".json",
+                           initialdir=str(Path(self.app.map_path).resolve().parent),
+                           filetypes=[("地图 JSON", "*.json")])
+        if path:
+            previous = self.app.map_path
+            try:
+                self.app.map_path = path
+                self.save()
+            except Exception:
+                self.app.map_path = previous
+                raise
+
+    def toggle_obstacles(self):
+        self.app.show_obstacle = not self.app.show_obstacle
+        self.app.redraw_floor_obstacle_trigger = True
+
+    def toggle_grid(self):
+        self.show_grid = not self.show_grid
+
+    def go_origin(self):
+        self.app.scroll_grid_at = [0, 0]
+        self.app.redraw_floor_obstacle_trigger = True
+
+    def help(self):
+        self.dialog("showinfo", title="编辑器操作", message=(
+            "左键放置,右键删除,Shift + 左键拖动框选复制\n"
+            "显示障碍时复制障碍物,隐藏障碍时复制地板\n"
+            "整组放置:冲突格红色,其余灰色;有冲突整组不放,Esc 取消\n"
+            "工具快捷栏含两种橡皮擦,可选 1x1 至 15x15,左键拖动擦除\n"
+            "WASD / 方向键 / 滚轮移动视野\nB 设置起点,F 设置终点\n"
+            "空格切换障碍物显示\nCtrl+S 保存,Ctrl+Shift+S 另存为\n"
+            "Ctrl+Z 撤销,Ctrl+Y / Ctrl+Shift+Z 重做\n"
+            "连续拖动算一次编辑,最多保留 100 步\nEsc 关闭下拉菜单\n"
+            "每 30 秒及退出时自动保存到当前文件"))
+
+    def items(self, name):
+        undo = ("撤销上一步", "Ctrl+Z", self.undo, bool(self.undo_stack))
+        redo = ("重做上一步", "Ctrl+Y", self.redo, bool(self.redo_stack))
+        if name == "文件":
+            return [("打开", "", self.open_map, True), ("保存", "Ctrl+S", self.save, True),
+                    ("另存为…", "Ctrl+Shift+S", self.save_as, True),
+                    ("保存并退出", "", lambda: pygame.event.post(pygame.event.Event(pygame.QUIT)), True)]
+        if name == "编辑":
+            return [undo, redo, ("隐藏障碍物" if self.app.show_obstacle else "显示障碍物",
+                                "Space", self.toggle_obstacles, True)]
+        return [("隐藏网格" if self.show_grid else "显示网格", "", self.toggle_grid, True),
+                ("视野回到左上角", "", self.go_origin, True),
+                ("操作说明", "", self.help, True),
+                ("显示工具快捷栏", "", self.app.tools.toggle, True),
+                ("显示区域", "", self.app.tools.regions.toggle, True),
+                ("怪物渲染", "", self.app.tools.regions.toggle_models, True),
+                ("地板橡皮擦", "", lambda: self.app.tools.choose("floor"), True),
+                ("障碍物橡皮擦", "", lambda: self.app.tools.choose("obstacle"), True)]
+
+    def popup_rect(self):
+        button = next(rect for name, rect in self.buttons if name == self.active)
+        return pygame.Rect(button.x, MENU_HEIGHT, self.WIDTH, len(self.items(self.active)) * self.ROW_HEIGHT)
+
+    def invoke(self, action):
+        self.finish_stroke()
+        try:
+            action()
+        except Exception as error:
+            self.notify("操作失败:" + str(error))
+            self.dialog("showerror", title="操作失败", message=str(error))
+
+    def handle_event(self, event):
+        if event.type == pygame.KEYDOWN:
+            if event.key == pygame.K_ESCAPE:
+                self.active = None
+                return True
+            mods = getattr(event, "mod", 0)
+            if mods & pygame.KMOD_CTRL:
+                action = None
+                if event.key == pygame.K_z:
+                    action = self.redo if mods & pygame.KMOD_SHIFT else self.undo
+                elif event.key == pygame.K_y:
+                    action = self.redo
+                elif event.key == pygame.K_s:
+                    action = self.save_as if mods & pygame.KMOD_SHIFT else self.save
+                if action:
+                    self.active = None
+                    self.invoke(action)
+                return True
+        if event.type == pygame.MOUSEBUTTONUP and event.button in (1, 3):
+            self.pressed = None
+            self.finish_stroke()
+            # Kept until the next frame, so menu dismissal cannot paint the map.
+            return self.active is not None or self.block_pointer
+        if event.type == pygame.MOUSEMOTION and self.active is not None:
+            for name, rect in self.buttons:
+                if name not in ("undo", "redo") and rect.collidepoint(event.pos):
+                    self.active = name
+                    break
+            return True
+        if event.type == pygame.MOUSEBUTTONDOWN:
+            if event.pos[1] < MENU_HEIGHT:
+                self.finish_stroke()
+                self.block_pointer = True
+                if event.button == 1:
+                    selected = next((name for name, rect in self.buttons if rect.collidepoint(event.pos)), None)
+                    if selected in ("undo", "redo"):
+                        self.active = None
+                        if self.button_enabled(selected):
+                            self.pressed = selected
+                            self.invoke(self.undo if selected == "undo" else self.redo)
+                    else:
+                        self.pressed = selected
+                        self.active = None if selected == self.active else selected
+                return True
+            if self.active is not None:
+                popup = self.popup_rect()
+                items = self.items(self.active)
+                self.active = None
+                self.block_pointer = True
+                if event.button == 1 and popup.collidepoint(event.pos):
+                    item = items[(event.pos[1] - popup.y) // self.ROW_HEIGHT]
+                    if item[3]:
+                        self.invoke(item[2])
+                return True
+            if event.button in (1, 3) and not self.block_pointer:
+                if pygame.Rect(MAP_AT, (MAP_W, MAP_H)).collidepoint(event.pos) and self.stroke is None:
+                    self.stroke = self.snapshot()
+        return self.active is not None
+
+    def begin_frame(self):
+        if not any(pygame.mouse.get_pressed()):
+            self.pressed = None
+            self.block_pointer = False
+            self.finish_stroke()
+
+    def blocks_editing(self):
+        return self.active is not None or self.block_pointer or bool(pygame.key.get_mods() & pygame.KMOD_CTRL)
+
+    def draw_grid(self):
+        if self.show_grid:
+            grid = pygame.Surface((MAP_W, MAP_H), pygame.SRCALPHA)
+            for x in range(0, MAP_W, GAME_SQUARE):
+                pygame.draw.line(grid, (190, 205, 220, 65), (x, 0), (x, MAP_H))
+            for y in range(0, MAP_H, GAME_SQUARE):
+                pygame.draw.line(grid, (190, 205, 220, 65), (0, y), (MAP_W, y))
+            self.app.screen.blit(grid, MAP_AT)
+
+    def button_enabled(self, name):
+        if name == "undo":
+            return bool(self.undo_stack)
+        if name == "redo":
+            return bool(self.redo_stack)
+        return True
+
+    def draw_arrow(self, rect, name, color):
+        # Draw the icons directly so missing font glyphs cannot produce boxes.
+        cx, cy = rect.center
+        points = [(-10, -4), (2, -4), (8, 0), (8, 7)]
+        head = [(-10, -4), (-3, -10), (-3, 2)]
+        direction = 1 if name == "undo" else -1
+        convert = lambda p: (cx + direction * p[0], cy + p[1])
+        pygame.draw.lines(self.app.screen, color, False, [convert(p) for p in points], 3)
+        pygame.draw.polygon(self.app.screen, color, [convert(p) for p in head])
+
+    def draw(self):
+        screen, font = self.app.screen, self.app.text_font
+        mouse = pygame.mouse.get_pos()
+        pygame.draw.rect(screen, (35, 39, 46), (0, 0, screen.get_width(), MENU_HEIGHT))
+        for name, rect in self.buttons:
+            enabled = self.button_enabled(name)
+            dark = not enabled or name == self.active or name == self.pressed
+            background = (22, 26, 33) if dark else (72, 82, 98) if rect.collidepoint(mouse) else (53, 61, 74)
+            pygame.draw.rect(screen, background, rect)
+            pygame.draw.rect(screen, (144, 155, 173), rect, 1)
+            color = (237, 240, 245) if enabled else (119, 128, 143)
+            if name in ("undo", "redo"):
+                self.draw_arrow(rect, name, color)
+            else:
+                label = font.render(name, True, color)
+                screen.blit(label, label.get_rect(center=rect.center))
+        text = self.status if pygame.time.get_ticks() < self.status_until else Path(self.app.map_path).name
+        status = font.render(text, True, (166, 177, 193))
+        screen.blit(status, (714, 8), pygame.Rect(0, 0, WINDOW_W - 726, MENU_HEIGHT))
+        if self.active is None:
+            return
+        rect = self.popup_rect()
+        pygame.draw.rect(screen, (14, 17, 22), rect.move(3, 3))
+        pygame.draw.rect(screen, (43, 48, 57), rect)
+        for i, (label, shortcut, action, enabled) in enumerate(self.items(self.active)):
+            row = pygame.Rect(rect.x, rect.y + i * self.ROW_HEIGHT, rect.width, self.ROW_HEIGHT)
+            if enabled and row.collidepoint(mouse):
+                pygame.draw.rect(screen, (60, 88, 125), row)
+            color = (236, 240, 246) if enabled else (116, 123, 135)
+            label_image = font.render(label, True, color)
+            label_x = row.x + 12
+            if label in ("显示工具快捷栏", "显示区域", "怪物渲染"):
+                box = pygame.Rect(row.x + 10, row.centery - 6, 12, 12)
+                pygame.draw.rect(screen, color, box, 1)
+                if (self.app.tools.visible if label == "显示工具快捷栏" else self.app.tools.regions.render_models if label == "怪物渲染" else self.app.tools.regions.enabled):
+                    pygame.draw.lines(screen, color, False, [(box.x + 2, box.y + 6), (box.x + 5, box.y + 9), (box.x + 10, box.y + 2)], 2)
+                label_x = row.x + 30
+            screen.blit(label_image, label_image.get_rect(midleft=(label_x, row.centery)))
+            hint = font.render(shortcut, True, color)
+            screen.blit(hint, hint.get_rect(midright=(row.right - 12, row.centery)))
+        pygame.draw.rect(screen, (80, 90, 105), rect, 1)

+ 67 - 0
recovered_map_editor/source/exe_entry.py

@@ -0,0 +1,67 @@
+"""Packaged entry point. Game resources remain beside the executable."""
+import os
+import sys
+import json
+import shutil
+import tempfile
+import time
+from pathlib import Path
+from datetime import datetime
+from runtime_paths import PROJECT_ROOT
+
+os.chdir(str(PROJECT_ROOT))
+if '--self-test' in sys.argv:
+    os.environ['SDL_VIDEODRIVER'] = 'dummy'
+    os.environ['SDL_AUDIODRIVER'] = 'dummy'
+import main
+
+
+def run():
+    if '--self-test' in sys.argv:
+        with tempfile.TemporaryDirectory(prefix='editor_exe_test_') as tmp:
+            target = Path(tmp) / 'map.json'
+            target.write_text(json.dumps(dict(basic=dict(name='test', width=40, height=40,
+                scroll=[0, 0], begin=[0, 0], finish=[39, 39]), floor=[], obstacle=[], districts=[])))
+            main.MAP_JSON_FILE_NAME = str(target)
+            main.MapBuilder.update = lambda self: None
+            app = main.MapBuilder()
+            try:
+                app.library.visible = True
+                app.library.choose_library('crimson_manor')
+                deadline = time.monotonic()+30
+                while app.library.scan_job or app.library.pending or app.library.jobs:
+                    app.library.update()
+                    if time.monotonic() > deadline:
+                        raise RuntimeError('素材加载超时')
+                    time.sleep(.01)
+                assert app.library.entries
+                assert app.tools.regions.models.load('CrimsonManorDTeddy') is not None, app.tools.regions.models.errors
+                app.draw_floors_and_obstacles()
+                app.draw_map_area()
+                app.library.draw()
+                app.save_map_json()
+                result = dict(ok=True, assets=len(app.library.entries), root=str(PROJECT_ROOT))
+                Path(sys.argv[sys.argv.index('--self-test')+1]).write_text(json.dumps(result), encoding='utf-8')
+            finally:
+                app.library.close()
+                main.pygame.quit()
+        return
+    original = PROJECT_ROOT / 'map.json'
+    if original.exists():
+        backup = PROJECT_ROOT / 'recovered_map_editor' / 'backups' / (datetime.now().strftime('%Y%m%d_%H%M%S_%f')+'_map.json')
+        backup.parent.mkdir(parents=True, exist_ok=True)
+        shutil.copy2(str(original), str(backup))
+    main.MapBuilder()
+
+
+if __name__ == '__main__':
+    try:
+        run()
+    except Exception:
+        import traceback
+        error = traceback.format_exc()
+        (PROJECT_ROOT / 'map_editor_error.log').write_text(error, encoding='utf-8')
+        if '--self-test' not in sys.argv:
+            import ctypes
+            ctypes.windll.user32.MessageBoxW(0, error, '地图编辑器启动失败', 16)
+        sys.exit(1)

+ 269 - 0
recovered_map_editor/source/extra_tools.py

@@ -0,0 +1,269 @@
+"""Move, spray, directional expansion and clean map export."""
+import random
+from datetime import datetime
+from pathlib import Path
+from runtime_paths import PROJECT_ROOT
+import pygame
+from const.window import WINDOW_W, MAP_AT, GAME_SQUARE
+from game.frame import floor, obstacle
+
+
+class ExtraTools:
+    def __init__(self, app):
+        self.app = app
+        self.values = dict(radius='3', density='30', left='0', top='0')
+        self.reset()
+
+    def reset(self):
+        self.focus = None
+        self.start = self.end = None
+        self.sources = []
+
+    def fields(self):
+        names = [('radius', '半径(格)'), ('density', '密度(%)')] if self.app.tools.tool == 'spray' else [('left', '向左拓展'), ('top', '向上拓展')]
+        return [(key, label, pygame.Rect(WINDOW_W + 130, 308 + i*44, 100, 32)) for i, (key, label) in enumerate(names)]
+
+    def expand(self, left, top):
+        if left < 0 or top < 0:
+            raise ValueError('拓展格数不能为负数')
+        data = self.app.document_snapshot()
+        basic = data['basic']
+        width, height = basic['width'] + left, basic['height'] + top
+        if width > 256 or height > 256 or width*height > 10000:
+            raise ValueError('地图最多 256×256,且总格数不超过 10000')
+        basic.update(width=width, height=height)
+        for key in ('begin', 'finish', 'scroll'):
+            if key in basic:
+                basic[key] = [basic[key][0]+left, basic[key][1]+top]
+        for layer in ('floor', 'obstacle'):
+            for node in data[layer]:
+                for point in node['points']:
+                    point['x'] += left
+                    point['y'] += top
+        for region in data.get('districts', []):
+            square = region['square']
+            for key in ('x1', 'x2'):
+                square[key] += left
+            for key in ('y1', 'y2'):
+                square[key] += top
+            for npc in region.get('npcs', []):
+                npc['x'] += left
+                npc['y'] += top
+        self.app.menu.edit(lambda: self.app.restore_document(data))
+        self.app.selection.cancel()
+        self.app.menu.notify('地图已拓展,所有元素和初始视野已平移;Ctrl+Z 撤销')
+
+    def spray(self, cell):
+        app = self.app
+        brush = app.current_elem
+        if len(app.selection.group) == 1:
+            node = app.selection.group[0]
+            brush = dict(elem_type=node['layer'], type=node['type'], name=node['name'])
+        if len(app.selection.group) > 1 or not brush.get('elem_type'):
+            raise ValueError('请选择单个 1×1 障碍物或地板')
+        if brush['elem_type'] == 'obstacle':
+            obs = obstacle.get_obstacle(brush['type'], brush['name'])
+            if obs['WIDTH'] != 1 or obs['HEIGHT'] != 1:
+                raise ValueError('喷溅笔只支持 1×1 障碍物')
+        radius, density = int(self.values['radius']), int(self.values['density'])
+        if not 1 <= radius <= 50 or not 0 <= density <= 100:
+            raise ValueError('半径须为 1–50 格,密度须为 0–100%')
+        candidates = [(x, y) for x in range(max(0, cell[0]-radius), min(app.map_size[0], cell[0]+radius+1))
+                      for y in range(max(0, cell[1]-radius), min(app.map_size[1], cell[1]+radius+1))
+                      if (x-cell[0])**2+(y-cell[1])**2 <= radius**2 and
+                      (brush['elem_type'] == 'floor' or (x, y) not in app.map_obstacles_dict)]
+        points = random.sample(candidates, round(len(candidates)*density/100))
+        previous = app.current_elem
+        def action():
+            app.current_elem = brush
+            try:
+                for point in points:
+                    app.add_elem(point)
+            finally:
+                app.current_elem = previous
+        app.menu.edit(action)
+
+    def move_to(self, cell):
+        app = self.app
+        app.menu.finish_stroke()
+        before = app.document_snapshot()
+        sources = {app.map_obstacles_dict.get(pos) for pos in self.source_positions}
+        if None in sources:
+            self.sources = []
+            app.selection.cancel()
+            app.menu.notify('原选区已改变,请重新框选')
+            return False
+        for obj in sources:
+            obj.uninstall()
+        if not app.selection.place(cell):
+            app.restore_document(before)
+            self.sources = [app.map_obstacles_dict[pos] for pos in self.source_positions]
+            return False
+        app.menu.record(before)
+        self.sources = []
+        app.selection.cancel()
+        return True
+
+    def export_buttons(self):
+        return [(False, '只导出地图', pygame.Rect(WINDOW_W+12, 308, 180, 38)),
+                (True, '包含区域和怪物', pygame.Rect(WINDOW_W+204, 308, 230, 38))]
+
+    def export(self, include_regions=False):
+        app = self.app
+        surface = pygame.Surface((app.map_size[0]*GAME_SQUARE, app.map_size[1]*GAME_SQUARE), pygame.SRCALPHA)
+        for node in app.map_json['floor']:
+            tile = floor.get_floor(node['type'], node['name'])
+            for point in node['points']:
+                surface.blit(tile, (point['x']*GAME_SQUARE, point['y']*GAME_SQUARE))
+        for obj in sorted(set(app.map_obstacles_dict.values()), key=lambda obj: obj.get_y()):
+            obj.draw(surface)
+        missing = set()
+        if include_regions:
+            regions = app.tools.regions
+            npcs = []
+            for index, region in enumerate(app.map_json.get('districts', [])):
+                square = region['square']
+                x1, x2 = sorted((square['x1'], square['x2']))
+                y1, y2 = sorted((square['y1'], square['y2']))
+                rect = pygame.Rect(x1*GAME_SQUARE, y1*GAME_SQUARE,
+                                   (x2-x1+1)*GAME_SQUARE, (y2-y1+1)*GAME_SQUARE)
+                color = regions.COLORS[index % len(regions.COLORS)]
+                pygame.draw.rect(surface, (12, 16, 22), rect, 7)
+                pygame.draw.rect(surface, color, rect, 3)
+                surface.blit(app.text_font.render('区域 %d' % (index+1), True, color), (rect.x+6, rect.y+6))
+                npcs.extend((npc, regions.npc_color(index, n)) for n, npc in enumerate(region.get('npcs', [])))
+            for npc, color in sorted(npcs, key=lambda item: item[0].get('y', 0)):
+                if not regions.models.draw(surface, npc, (0, 0), color, frame_index=0, show_vision=False):
+                    missing.add(npc.get('name', ''))
+                    regions.monster_icon(surface, pygame.Rect(npc['x']*GAME_SQUARE+8, npc['y']*GAME_SQUARE+8, 24, 24), color)
+        directory = PROJECT_ROOT / 'map_editor_eport'
+        directory.mkdir(exist_ok=True)
+        path = directory / ('map_%s_%dx%d.png' % (datetime.now().strftime('%Y%m%d_%H%M%S_%f'), *app.map_size))
+        pygame.image.save(surface, str(path))
+        app.menu.notify('已导出:' + path.name + (';%d 种怪物模型缺失,已用图标代替' % len(missing) if missing else ''))
+        return path
+
+    def handle_event(self, event):
+        app = self.app
+        tool = app.tools.tool
+        if tool not in ('move', 'spray', 'expand', 'export'):
+            return False
+        if tool == 'export':
+            if app.tools.visible and event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
+                for include_regions, label, rect in self.export_buttons():
+                    if rect.collidepoint(event.pos):
+                        app.menu.invoke(lambda: self.export(include_regions))
+                        app.menu.block_pointer = True
+                        return True
+            return False
+        if self.focus is not None and event.type == pygame.KEYDOWN:
+            value = self.values[self.focus]
+            keypad = {getattr(pygame, 'K_KP%d' % n): str(n) for n in range(10)}
+            digit = keypad.get(event.key, getattr(event, 'unicode', ''))
+            if event.key in (pygame.K_RETURN, pygame.K_KP_ENTER, pygame.K_ESCAPE):
+                self.focus = None
+            elif event.key in (pygame.K_LEFT, pygame.K_RIGHT, pygame.K_HOME, pygame.K_END):
+                if event.key == pygame.K_HOME:
+                    self.cursor = 0
+                elif event.key == pygame.K_END:
+                    self.cursor = len(value)
+                else:
+                    self.cursor = max(0, min(len(value), self.cursor + (-1 if event.key == pygame.K_LEFT else 1)))
+                self.select_all = False
+            elif event.key in (pygame.K_BACKSPACE, pygame.K_DELETE):
+                if self.select_all:
+                    self.values[self.focus], self.cursor = '', 0
+                elif event.key == pygame.K_BACKSPACE and self.cursor:
+                    self.values[self.focus] = value[:self.cursor-1]+value[self.cursor:]
+                    self.cursor -= 1
+                elif event.key == pygame.K_DELETE:
+                    self.values[self.focus] = value[:self.cursor]+value[self.cursor+1:]
+                self.select_all = False
+            elif digit.isdigit():
+                if self.select_all:
+                    value, self.cursor = '', 0
+                self.values[self.focus] = value[:self.cursor]+digit+value[self.cursor:]
+                self.cursor += len(digit)
+                self.select_all = False
+            return True
+        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
+            self.focus = None
+            if app.tools.visible and tool in ('spray', 'expand'):
+                for key, label, rect in self.fields():
+                    if rect.collidepoint(event.pos):
+                        self.focus, self.select_all = key, True
+                        self.cursor = len(self.values[key])
+                        return True
+                if tool == 'expand' and pygame.Rect(WINDOW_W+245, 352, 110, 32).collidepoint(event.pos):
+                    app.menu.invoke(lambda: self.expand(int(self.values['left']), int(self.values['top'])))
+                    return True
+            cell = app.selection.cell(event.pos)
+            if cell is None:
+                return False
+            if tool == 'spray':
+                app.menu.finish_stroke()
+                app.menu.invoke(lambda: self.spray(cell))
+            elif tool == 'move':
+                app.menu.finish_stroke()
+                if self.sources:
+                    self.move_to(cell)
+                else:
+                    self.start = self.end = cell
+            return True
+        if tool == 'move' and self.start is not None:
+            if event.type in (pygame.MOUSEMOTION, pygame.MOUSEBUTTONUP):
+                self.end = app.selection.cell(event.pos, clamp=True)
+                if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
+                    app.selection.copy_rectangle(self.start, self.end, 'obstacle')
+                    x0, x1 = sorted((self.start[0], self.end[0]))
+                    y0, y1 = sorted((self.start[1], self.end[1]))
+                    self.sources = list({obj for (x, y), obj in app.map_obstacles_dict.items() if x0 <= x <= x1 and y0 <= y <= y1})
+                    self.source_positions = [(obj.x, obj.y) for obj in self.sources]
+                    self.start = self.end = None
+            return True
+        return False
+
+    def draw(self):
+        if self.app.tools.tool == 'export':
+            for include_regions, label, rect in self.export_buttons():
+                pygame.draw.rect(self.app.screen, (53, 61, 74), rect)
+                pygame.draw.rect(self.app.screen, (145, 155, 170), rect, 1)
+                text = self.app.text_font.render(label, True, (235, 235, 235))
+                self.app.screen.blit(text, text.get_rect(center=rect.center))
+            return
+        if self.app.tools.tool not in ('spray', 'expand'):
+            return
+        for key, label, rect in self.fields():
+            self.app.screen.blit(self.app.text_font.render(label, True, (230, 230, 235)), (WINDOW_W+12, rect.y+6))
+            pygame.draw.rect(self.app.screen, (24, 28, 34), rect)
+            pygame.draw.rect(self.app.screen, (240, 195, 80) if self.focus == key else (145, 155, 170), rect, 1)
+            value = self.values[key]
+            if self.focus == key:
+                value = value[:self.cursor] + '|' + value[self.cursor:]
+            self.app.screen.blit(self.app.text_font.render(value, True, (235, 235, 235)), (rect.x+8, rect.y+6))
+        if self.app.tools.tool == 'expand':
+            rect = pygame.Rect(WINDOW_W+245, 352, 110, 32)
+            pygame.draw.rect(self.app.screen, (145, 155, 170), rect, 1)
+            text = self.app.text_font.render('确认拓展', True, (235, 235, 235))
+            self.app.screen.blit(text, text.get_rect(center=rect.center))
+
+    def draw_preview(self):
+        if self.app.tools.tool == 'spray':
+            cell = self.app.selection.cell(pygame.mouse.get_pos())
+            if cell is not None:
+                try:
+                    radius = max(1, min(50, int(self.values['radius'])))
+                except ValueError:
+                    radius = 1
+                clip = self.app.screen.get_clip()
+                from const.window import MAP_W, MAP_H
+                self.app.screen.set_clip(pygame.Rect(MAP_AT, (MAP_W, MAP_H)))
+                pygame.draw.circle(self.app.screen, (255, 205, 70),
+                    (MAP_AT[0]+(cell[0]-self.app.scroll_grid_at[0])*GAME_SQUARE+GAME_SQUARE//2,
+                     MAP_AT[1]+(cell[1]-self.app.scroll_grid_at[1])*GAME_SQUARE+GAME_SQUARE//2), radius*GAME_SQUARE, 2)
+                self.app.screen.set_clip(clip)
+        if self.start is not None:
+            x0, x1 = sorted((self.start[0], self.end[0]))
+            y0, y1 = sorted((self.start[1], self.end[1]))
+            pygame.draw.rect(self.app.screen, (255, 205, 70), (MAP_AT[0]+(x0-self.app.scroll_grid_at[0])*GAME_SQUARE,
+                MAP_AT[1]+(y0-self.app.scroll_grid_at[1])*GAME_SQUARE, (x1-x0+1)*GAME_SQUARE, (y1-y0+1)*GAME_SQUARE), 3)

+ 5 - 0
recovered_map_editor/source/game/__init__.py

@@ -0,0 +1,5 @@
+# decompyle3 version 3.9.3
+# Python bytecode version base 3.7.0 (3394)
+# Decompiled from: Python 3.13.1 (tags/v3.13.1:0671451, Dec  3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)]
+# Embedded file name: -
+pass

+ 5 - 0
recovered_map_editor/source/game/frame/__init__.py

@@ -0,0 +1,5 @@
+# decompyle3 version 3.9.3
+# Python bytecode version base 3.7.0 (3394)
+# Decompiled from: Python 3.13.1 (tags/v3.13.1:0671451, Dec  3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)]
+# Embedded file name: -
+pass

+ 15 - 0
recovered_map_editor/source/game/frame/floor.py

@@ -0,0 +1,15 @@
+# decompyle3 version 3.9.3
+# Python bytecode version base 3.7.0 (3394)
+# Decompiled from: Python 3.13.1 (tags/v3.13.1:0671451, Dec  3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)]
+# Embedded file name: game\frame\floor.py
+import pygame
+FLOOR_IMG_ROOT = "res/img/mapElem/"
+floors = {}
+
+def get_floor(type, name):
+    if type not in floors.keys():
+        floors[type] = dict()
+    if name not in floors[type].keys():
+        img = pygame.image.load(FLOOR_IMG_ROOT + type + "/" + name + ".png").convert()
+        floors[type][name] = img
+    return floors[type][name]

+ 12 - 0
recovered_map_editor/source/game/frame/frame.py

@@ -0,0 +1,12 @@
+# decompyle3 version 3.9.3
+# Python bytecode version base 3.7.0 (3394)
+# Decompiled from: Python 3.13.1 (tags/v3.13.1:0671451, Dec  3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)]
+# Embedded file name: game\frame\frame.py
+import pygame
+
+class Frame:
+
+    def __init__(self, image: pygame.Surface, cx, cy):
+        self.image = image
+        self.cx = cx
+        self.cy = cy

+ 44 - 0
recovered_map_editor/source/game/frame/obstacle.py

@@ -0,0 +1,44 @@
+# decompyle3 version 3.9.3
+# Python bytecode version base 3.7.0 (3394)
+# Decompiled from: Python 3.13.1 (tags/v3.13.1:0671451, Dec  3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)]
+# Embedded file name: game\frame\obstacle.py
+import json, pygame
+from pathlib import Path
+from game.frame.frame import Frame
+OBSTACLE_FRAME_ROOT = "game/frame/obstacle/"
+OBSTACLE_IMG_ROOT = "res/img/mapElem/"
+obstacles = {}
+
+def get_obstacle(type, name):
+    if type not in obstacles.keys():
+        obstacles[type] = dict()
+    if name not in obstacles[type].keys():
+        obstacles[type][name] = load_obstacle(type, name)
+    return obstacles[type][name]
+
+
+def load_obstacle(type, name):
+    an_obstacle = {}
+    path = Path(OBSTACLE_FRAME_ROOT) / type / (name + ".json")
+    if not path.is_file():
+        path = Path("game/frame/obstacles") / type / (name + ".json")
+    with path.open(encoding="utf-8-sig") as f:
+        obstacle_json = json.load(f)
+    an_obstacle["TYPE"] = type
+    an_obstacle["NAME"] = name
+    an_obstacle["WIDTH"] = obstacle_json["WIDTH"]
+    an_obstacle["HEIGHT"] = obstacle_json["HEIGHT"]
+    append_obstacle(obstacle_json, an_obstacle, "STAND")
+    return an_obstacle
+
+
+def append_obstacle(obstacle_json, an_obstacle, state: str):
+    if state in obstacle_json:
+        an_obstacle[state] = list()
+        frames = obstacle_json[state]
+        size = len(frames["IMG"])
+        for i in range(size):
+            img = pygame.image.load(OBSTACLE_IMG_ROOT + obstacle_json["TYPE"] + "/" + frames["IMG"][i]).convert_alpha()
+            cx = frames["CX"][i]
+            cy = frames["CY"][i]
+            an_obstacle[state].append(Frame(img, cx, cy))

+ 49 - 0
recovered_map_editor/source/game/frame/obstacle_instance.py

@@ -0,0 +1,49 @@
+# decompyle3 version 3.9.3
+# Python bytecode version base 3.7.0 (3394)
+# Decompiled from: Python 3.13.1 (tags/v3.13.1:0671451, Dec  3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)]
+# Embedded file name: game\frame\obstacle_instance.py
+import pygame
+from const.window import GAME_SQUARE
+
+class ObstacleInstance:
+
+    def __init__(self, x, y, obstacle_instances_dict: dict, obstacle):
+        self.x = x
+        self.y = y
+        self.image = pygame.Surface((1, 1))
+        self.rect = self.image.get_rect()
+        self.obstacle = obstacle
+        self.obstacle_instances_dict = obstacle_instances_dict
+        self.has_drawn = False
+        self.setup()
+        self.update()
+
+    def setup(self):
+        for x in range(self.obstacle["WIDTH"]):
+            for y in range(self.obstacle["HEIGHT"]):
+                p = (x + self.x, y + self.y)
+                if p in self.obstacle_instances_dict.keys():
+                    self.obstacle_instances_dict[p].uninstall()
+                self.obstacle_instances_dict[p] = self
+
+        self.image = self.obstacle["STAND"][0].image
+        self.rect.x = self.x * GAME_SQUARE + self.obstacle["STAND"][0].cx
+        self.rect.y = self.y * GAME_SQUARE + self.obstacle["STAND"][0].cy
+
+    def update(self):
+        self.has_drawn = False
+
+    def draw(self, screen: pygame.Surface):
+        if not self.has_drawn:
+            self.has_drawn = True
+            screen.blit(self.image, self.rect)
+
+    def get_y(self):
+        return self.y
+
+    def uninstall(self):
+        for x in range(self.obstacle["WIDTH"]):
+            for y in range(self.obstacle["HEIGHT"]):
+                p = (x + self.x, y + self.y)
+                if p in self.obstacle_instances_dict.keys():
+                    self.obstacle_instances_dict.pop(p)

+ 593 - 0
recovered_map_editor/source/main.py

@@ -0,0 +1,593 @@
+# decompyle3 version 3.9.3
+# Python bytecode version base 3.7.0 (3394)
+# Decompiled from: Python 3.13.1 (tags/v3.13.1:0671451, Dec  3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)]
+# Embedded file name: main.py
+import os, sys, json, copy
+from pathlib import Path
+
+# Support direct execution from an IDE as well as launch.py.
+from runtime_paths import PROJECT_ROOT
+sys.path.append(str(PROJECT_ROOT))
+sys.path.insert(0, str(PROJECT_ROOT / ".codex_build" / "map_editor_runtime"))
+import pygame, pyperclip
+from const.color import *
+from const.window import *
+from game.frame import floor, obstacle
+from game.frame.obstacle_instance import ObstacleInstance
+from editor_menu import EditorMenu
+from selection import Selection
+from tool_panel import ToolPanel
+from map_settings import MapSettings
+from placement import Placement
+from asset_library import AssetLibrary
+
+def check_clipboard():
+    try:
+        return pyperclip.paste()
+    except TypeError:
+        return ""
+
+
+def get_y(elem):
+    return elem.get_y()
+
+
+class MapBuilder:
+
+    def __init__(self):
+        self.map_path = MAP_JSON_FILE_NAME
+        self.timer = 0
+        self.screen = None
+        self.map_json = None
+        self.map_area = None
+        self.map_hint_area = None
+        self.map_size = None
+        self.keys_state = None
+        self.key_space_state = None
+        self.key_b_state = None
+        self.key_f_state = None
+        self.mouse_button_0_state = None
+        self.mouse_button_1_state = None
+        self.pan_anchor = None
+        self.scroll_grid_at = [0, 0]
+        self.begin_at = (0, 0)
+        self.finish_at = (39, 39)
+        self.text_font = None
+        self.redraw_floor_obstacle_trigger = True
+        self.show_obstacle = True
+        self.current_elem = None
+        self.spawnPoint1_img = None
+        self.spawnPoint2_img = None
+        self.map_floors_dict = dict()
+        self.map_obstacles_dict = dict()
+        self.initialize()
+        self.menu = EditorMenu(self)
+        self.selection = Selection(self, check_clipboard)
+        self.tools = ToolPanel(self)
+        self.settings = MapSettings(self)
+        self.placement = Placement(self)
+        self.library = AssetLibrary(self)
+        self.update()
+
+    def initialize(self):
+        pygame.init()
+        pygame.display.set_caption(WINDOW_CAPTION)
+        self.screen = pygame.display.set_mode(WINDOW_SIZE)
+        self.timer = pygame.time.get_ticks()
+        pygame.display.set_icon(pygame.image.load("res/img/ui/icon_editor.ico").convert_alpha())
+        self.keys_state = {(pygame.K_UP): 0, (pygame.K_DOWN): 0, (pygame.K_LEFT): 0, (pygame.K_RIGHT): 0, 
+         (pygame.K_w): 0, (pygame.K_s): 0, (pygame.K_a): 0, (pygame.K_d): 0}
+        self.key_space_state = 0
+        self.key_b_state = 0
+        self.key_f_state = 0
+        self.mouse_button_0_state = 0
+        self.mouse_button_1_state = 0
+        self.text_font = pygame.font.Font("res/font/simsun.ttc", COORDINATOR_FONT_SIZE)
+        self.current_elem = {'elem_type':None,  'type':None,  'name':None}
+        self.spawnPoint1_img = pygame.image.load("res/img/ui/spawnPoint1.png").convert_alpha()
+        self.spawnPoint2_img = pygame.image.load("res/img/ui/spawnPoint2.png").convert_alpha()
+        self.load_map_json()
+        self.blank_map_area()
+        self.blank_map_hint_area()
+
+    def load_map_json(self):
+        if os.path.exists(self.map_path):
+            with open(self.map_path, "r") as f:
+                self.map_json = json.load(f)
+                self.map_size = (self.map_json["basic"]["width"], self.map_json["basic"]["height"])
+                self.scroll_grid_at = [int(self.map_json["basic"]["scroll"][0]), int(self.map_json["basic"]["scroll"][1])]
+                self.begin_at = [int(self.map_json["basic"]["begin"][0]), int(self.map_json["basic"]["begin"][1])]
+                self.finish_at = [int(self.map_json["basic"]["finish"][0]), int(self.map_json["basic"]["finish"][1])]
+                for o in self.map_json["obstacle"]:
+                    obs = obstacle.get_obstacle(o["type"], o["name"])
+                    for point in o["points"]:
+                        ObstacleInstance(point["x"], point["y"], self.map_obstacles_dict, obs)
+
+        else:
+            self.map_json = {'basic':{'name':"map", 
+              'width':40,  'height':40,  'scroll':[0, 0],  'music':"none.ogg",  'begin':self.begin_at,  'finish':self.finish_at}, 
+             'floors':[],  'floor':[],  'obstacles':[],  'obstacle':[],  'districts':[]}
+            self.map_size = (40, 40)
+
+        for axis, visible in enumerate(MAP_GRID_SIZE):
+            self.scroll_grid_at[axis] = max(0, min(self.scroll_grid_at[axis], self.map_size[axis] - visible))
+
+    def document_snapshot(self):
+        data = copy.deepcopy(self.map_json)
+        data["basic"]["begin"] = list(self.begin_at)
+        data["basic"]["finish"] = list(self.finish_at)
+        groups = {}
+        seen = set()
+        for instance in self.map_obstacles_dict.values():
+            if id(instance) in seen:
+                continue
+            seen.add(id(instance))
+            key = (instance.obstacle["TYPE"], instance.obstacle["NAME"])
+            groups.setdefault(key, []).append({"x": instance.x, "y": instance.y})
+        data["obstacle"] = [dict(type=t, name=n, points=points) for (t, n), points in groups.items()]
+        return data
+
+    def restore_document(self, data):
+        if hasattr(self, "tools"):
+            self.tools.regions.solo_npc = None
+        data = copy.deepcopy(data)
+        instances = {}
+        for node in data["obstacle"]:
+            obs = obstacle.get_obstacle(node["type"], node["name"])
+            for point in node["points"]:
+                ObstacleInstance(point["x"], point["y"], instances, obs)
+        self.map_json = data
+        self.map_obstacles_dict = instances
+        self.map_size = (data["basic"]["width"], data["basic"]["height"])
+        self.begin_at = list(data["basic"]["begin"])
+        self.finish_at = list(data["basic"]["finish"])
+        for axis, visible in enumerate(MAP_GRID_SIZE):
+            self.scroll_grid_at[axis] = max(0, min(self.scroll_grid_at[axis], self.map_size[axis] - visible))
+        self.blank_map_hint_area()
+        self.redraw_floor_obstacle_trigger = True
+        if hasattr(self, "settings"):
+            self.settings.sync()
+
+    def save_map_json(self):
+        data = self.document_snapshot()
+        with open(self.map_path, "w") as f:
+            json.dump(data, f, indent=2)
+        self.timer = pygame.time.get_ticks()
+
+    def blank_map_area(self):
+        self.map_area = pygame.Surface((self.map_size[0] * GAME_SQUARE, self.map_size[1] * GAME_SQUARE), flags=(pygame.SRCALPHA))
+
+    def blank_map_hint_area(self):
+        self.map_hint_area = pygame.Surface((self.map_size[0] * GAME_SQUARE, self.map_size[1] * GAME_SQUARE), flags=(pygame.SRCALPHA))
+
+    def update(self):
+        while 1:
+            self.menu.begin_frame()
+            for event in pygame.event.get():
+                if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
+                    self.tools.dragging = False
+                    self.tools.last = None
+                if event.type == pygame.QUIT:
+                    self.placement.finish()
+                    self.tools.regions.finish_drag()
+                    self.menu.finish_stroke()
+                    try:
+                        self.save_map_json()
+                    except Exception as error:
+                        self.menu.dialog("showerror", title="保存失败", message=str(error))
+                        continue
+                    self.library.close()
+                    pygame.display.quit()
+                    pygame.quit()
+                    sys.exit()
+                if self.handle_pan(event):
+                    continue
+                if self.placement.active and self.placement.handle_event(event):
+                    continue
+                if self.library.handle_event(event):
+                    continue
+                if self.tools.extra.focus is not None and self.tools.extra.handle_event(event):
+                    continue
+                if self.settings.handle_event(event):
+                    continue
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_v and not (getattr(event, "mod", 0) & pygame.KMOD_CTRL) and self.menu.active is None:
+                    cell = self.selection.cell(pygame.mouse.get_pos())
+                    if cell is not None:
+                        self.settings.set_scroll(cell)
+                    continue
+                if self.menu.active is None and self.tools.regions.handle_map_event(event):
+                    continue
+                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                    self.selection.cancel()
+                    self.tools.choose("paint")
+                if self.selection.start is not None and self.selection.handle_event(event):
+                    continue
+                if self.menu.handle_event(event):
+                    continue
+                if self.tools.handle_event(event):
+                    continue
+                if self.placement.handle_event(event):
+                    continue
+                if self.tools.tool == "paint" and self.selection.handle_event(event):
+                    continue
+                if event.type == pygame.MOUSEBUTTONDOWN:
+                    if pygame.Rect(MAP_AT, MAP_SIZE).collidepoint(event.pos):
+                        self.mouse_scroll(event.button, event.pos)
+
+            if self.pan_anchor is None and not self.menu.blocks_editing() and self.settings.focus is None and self.tools.extra.focus is None:
+                self.key_pressed()
+                self.mouse_pressed()
+            self.library.update()
+            self.update_obstacles()
+            self.update_clip_board()
+            self.draw_coordinators()
+            self.draw_floors_and_obstacles()
+            self.draw_map_area()
+            self.menu.draw_grid()
+            self.tools.regions.draw_map()
+            self.settings.draw_view()
+            self.selection.draw()
+            self.placement.draw()
+            self.tools.draw_preview()
+            self.do_show_statement()
+            if self.library.visible:
+                self.library.draw()
+            else:
+                self.tools.draw()
+            self.menu.draw()
+            self.settings.draw_speaker()
+            self.library.draw_button()
+            pygame.display.update()
+            pygame.time.Clock().tick(WINDOW_UPDATE_RATE)
+            self.screen.fill(COLOR_BLACK)
+            self.update_timer()
+
+    def handle_pan(self, event):
+        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 2:
+            if not pygame.Rect(MAP_AT, MAP_SIZE).collidepoint(event.pos):
+                return False
+            # Complete current editing gestures before moving the camera.
+            self.placement.finish()
+            self.tools.regions.finish_drag()
+            self.menu.finish_stroke()
+            self.tools.dragging = False
+            self.tools.last = None
+            self.selection.start = self.selection.end = None
+            self.tools.extra.start = self.tools.extra.end = None
+            self.pan_anchor = (event.pos, tuple(self.scroll_grid_at))
+            self.blank_map_hint_area()
+            return True
+        if self.pan_anchor is None:
+            return False
+        if event.type == pygame.MOUSEMOTION:
+            origin, camera = self.pan_anchor
+            for axis, visible in enumerate(MAP_GRID_SIZE):
+                delta = int((origin[axis] - event.pos[axis]) / GAME_SQUARE)
+                self.scroll_grid_at[axis] = max(0, min(camera[axis] + delta, max(0, self.map_size[axis] - visible)))
+            self.redraw_floor_obstacle_trigger = True
+        elif (event.type == pygame.MOUSEBUTTONUP and event.button == 2) or event.type == pygame.WINDOWFOCUSLOST:
+            self.pan_anchor = None
+            self.menu.block_pointer = True
+        return True
+
+    def key_pressed(self):
+        if self.placement.active:
+            return
+        pressed_keys = pygame.key.get_pressed()
+        for (k, v) in self.keys_state.items():
+            if pressed_keys[k]:
+                if v == 0:
+                    self.scroll(k)
+                self.keys_state[k] = (self.keys_state[k] + 1) % 4
+            else:
+                self.keys_state[k] = 0
+
+        if self.tools.regions.interacting():
+            return
+        if pressed_keys[pygame.K_SPACE]:
+            if self.key_space_state == 0:
+                self.show_obstacle = not self.show_obstacle
+                self.redraw_floor_obstacle_trigger = True
+            self.key_space_state += 1
+        else:
+            self.key_space_state = 0
+        if pressed_keys[pygame.K_b]:
+            if self.key_b_state == 0:
+                mouse_pos = self._MapBuilder__get_mouse_pos()
+                if mouse_pos is not None and mouse_pos != self.finish_at:
+                    self.menu.edit(lambda: setattr(self, "begin_at", mouse_pos))
+                self.redraw_floor_obstacle_trigger = True
+            self.key_b_state += 1
+        else:
+            self.key_b_state = 0
+        if pressed_keys[pygame.K_f]:
+            if self.key_f_state == 0:
+                mouse_pos = self._MapBuilder__get_mouse_pos()
+                if mouse_pos is not None and mouse_pos != self.begin_at:
+                    self.menu.edit(lambda: setattr(self, "finish_at", mouse_pos))
+                self.redraw_floor_obstacle_trigger = True
+            self.key_f_state += 1
+        else:
+            self.key_f_state = 0
+
+    def __get_mouse_pos(self):
+        mouse_pos = pygame.mouse.get_pos()
+        mouse_pos = [(mouse_pos[0] - MAP_AT[0]) // GAME_SQUARE, (mouse_pos[1] - MAP_AT[1]) // GAME_SQUARE]
+        # Restored from original bytecode: both viewport bounds must hold.
+        if not (0 <= mouse_pos[0] < MAP_GRID_X and 0 <= mouse_pos[1] < MAP_GRID_Y):
+            return
+        mouse_pos[0] += self.scroll_grid_at[0]
+        mouse_pos[1] += self.scroll_grid_at[1]
+        if mouse_pos[0] >= self.map_size[0] or mouse_pos[1] >= self.map_size[1]:
+            return
+        return mouse_pos
+
+    def mouse_pressed(self):
+        if self.placement.active or self.selection.start is not None or self.tools.tool != "paint" or self.tools.regions.interacting():
+            return
+        pressed_buttons = pygame.mouse.get_pressed()
+        pressed_keys = pygame.key.get_pressed()
+        mouse_pos = self._MapBuilder__get_mouse_pos()
+        if mouse_pos is None:
+            return
+        if not self.selection.group:
+            self._MapBuilder__color_hint(mouse_pos)
+        if pressed_buttons[2]:
+            if self.show_obstacle:
+                self.menu.edit(lambda: self.remove_elem(mouse_pos, "obstacle"))
+            else:
+                self.menu.edit(lambda: self.remove_elem(mouse_pos, "floor"))
+            self.mouse_button_1_state += 1
+        else:
+            self.mouse_button_1_state = 0
+
+    def mouse_scroll(self, button, pos):
+        delta_x = (pos[0] - MAP_AT[0] - MAP_W / 2) * 0.5
+        delta_y = -(pos[1] - MAP_AT[1] - MAP_H / 2)
+        add = delta_x + delta_y
+        minus = delta_x - delta_y
+        multi = add * minus
+        if button == 4:
+            self.scroll(pygame.K_LEFT) if multi > 0 else self.scroll(pygame.K_UP)
+        elif button == 5:
+            self.scroll(pygame.K_RIGHT) if multi > 0 else self.scroll(pygame.K_DOWN)
+
+    def __color_hint(self, mouse_pos):
+        self.blank_map_hint_area()
+        if self.current_elem["elem_type"] == "floor":
+            self.map_hint_area.fill((*COLOR_BLUE, *(64, )), (mouse_pos[0] * GAME_SQUARE, mouse_pos[1] * GAME_SQUARE, GAME_SQUARE, GAME_SQUARE))
+        elif self.current_elem["elem_type"] == "obstacle":
+            an_obstacle = obstacle.get_obstacle(self.current_elem["type"], self.current_elem["name"])
+            color = (*COLOR_RED, *(64, )) if (mouse_pos[0], mouse_pos[1]) in self.map_obstacles_dict.keys() else (*COLOR_GREEN, *(64, ))
+            self.map_hint_area.fill(color, (mouse_pos[0] * GAME_SQUARE, mouse_pos[1] * GAME_SQUARE, GAME_SQUARE, GAME_SQUARE))
+            for x in range(an_obstacle["WIDTH"]):
+                for y in range(an_obstacle["HEIGHT"]):
+                    if x == y == 0:
+                        continue
+                    else:
+                        color = (*COLOR_RED, *(64, )) if (
+                         mouse_pos[0] + x, mouse_pos[1] + y) in self.map_obstacles_dict.keys() else (*COLOR_GREEN, *(64, ))
+                        self.map_hint_area.fill(color, ((mouse_pos[0] + x) * GAME_SQUARE, (mouse_pos[1] + y) * GAME_SQUARE, GAME_SQUARE, GAME_SQUARE))
+
+    def add_elem(self, mouse_pos):
+        elem_type = self.current_elem["elem_type"]
+        if elem_type is None:
+            return
+        if elem_type == "obstacle":
+            if not self.show_obstacle:
+                return
+            obs = obstacle.get_obstacle(self.current_elem["type"], self.current_elem["name"])
+            if any((obs["WIDTH"] == obs["HEIGHT"] == 1 and
+                    (mouse_pos[0] + x, mouse_pos[1] + y) in self.map_obstacles_dict) or
+                   not (0 <= mouse_pos[0] + x < self.map_size[0] and 0 <= mouse_pos[1] + y < self.map_size[1])
+                   for x in range(obs["WIDTH"]) for y in range(obs["HEIGHT"])):
+                return
+        self.remove_elem(mouse_pos, elem_type)
+        if elem_type == "floor":
+            added = False
+            for elem in self.map_json[self.current_elem["elem_type"]]:
+                if elem["type"] == self.current_elem["type"]:
+                    if elem["name"] == self.current_elem["name"]:
+                        elem["points"].append({'x':mouse_pos[0],  'y':mouse_pos[1]})
+                        added = True
+                        break
+
+            if not added:
+                node = {'type':self.current_elem["type"], 
+                 'name':self.current_elem["name"],  'points':[]}
+                node["points"].append({'x':mouse_pos[0],  'y':mouse_pos[1]})
+                self.map_json[self.current_elem["elem_type"]].append(node)
+        elif elem_type == "obstacle":
+            if self.show_obstacle:
+                obs = obstacle.get_obstacle(self.current_elem["type"], self.current_elem["name"])
+                ObstacleInstance(mouse_pos[0], mouse_pos[1], self.map_obstacles_dict, obs)
+
+    def remove_elem(self, mouse_pos, elem_type):
+        if elem_type == "floor":
+            for elem in self.map_json[elem_type]:
+                for point in elem["points"]:
+                    if mouse_pos[0] == point["x"]:
+                        if mouse_pos[1] == point["y"]:
+                            elem["points"].remove(point)
+
+        elif elem_type == "obstacle":
+            mouse_pos = tuple(mouse_pos)
+            for key in list(self.map_obstacles_dict.keys()):
+                if mouse_pos == key:
+                    self.map_obstacles_dict[mouse_pos].uninstall()
+
+        self.redraw_floor_obstacle_trigger = True
+
+    def copy_elem(self, mouse_pos, elem_type):
+        if elem_type == "floor":
+            for elem in self.map_json[elem_type]:
+                for point in elem["points"]:
+                    if mouse_pos[0] == point["x"]:
+                        if mouse_pos[1] == point["y"]:
+                            pyperclip.copy(elem["type"] + "\\" + elem["name"] + ".png")
+
+        elif elem_type == "obstacle":
+            if (
+             mouse_pos[0], mouse_pos[1]) not in self.map_obstacles_dict.keys():
+                return
+            an_obstacle = self.map_obstacles_dict[(mouse_pos[0], mouse_pos[1])]
+            pyperclip.copy(an_obstacle.obstacle["TYPE"] + "\\" + an_obstacle.obstacle["NAME"] + "_.png")
+
+    def scroll(self, orientation):
+        if orientation in (pygame.K_UP, pygame.K_w):
+            self.scroll_grid_at[1] = max(self.scroll_grid_at[1] - 1, 0)
+        if orientation in (pygame.K_DOWN, pygame.K_s):
+            self.scroll_grid_at[1] = min(self.scroll_grid_at[1] + 1, max(0, self.map_size[1] - MAP_GRID_Y))
+        if orientation in (pygame.K_LEFT, pygame.K_a):
+            self.scroll_grid_at[0] = max(self.scroll_grid_at[0] - 1, 0)
+        if orientation in (pygame.K_RIGHT, pygame.K_d):
+            self.scroll_grid_at[0] = min(self.scroll_grid_at[0] + 1, max(0, self.map_size[0] - MAP_GRID_X))
+        self.redraw_floor_obstacle_trigger = True
+
+    def update_obstacles(self):
+        for an_obs in self.map_obstacles_dict.values():
+            an_obs.update()
+
+    def draw_coordinators(self):
+        for x in range(MAP_GRID_X):
+            x_pos = MAP_AT[0] + x * GAME_SQUARE + 10
+            self._MapBuilder__blit_text(self.screen, x + self.scroll_grid_at[0], (x_pos, MAP_AT[1] - HALF_GAME_SQUARE))
+
+        for y in range(MAP_GRID_Y):
+            y_pos = MAP_AT[1] + y * GAME_SQUARE + 10
+            self._MapBuilder__blit_text(self.screen, y + self.scroll_grid_at[1], (MAP_AT[0] - HALF_GAME_SQUARE, y_pos))
+
+    def draw_floors_and_obstacles(self):
+        if self.redraw_floor_obstacle_trigger:
+            self.redraw_floor_obstacle_trigger = False
+            self.blank_map_area()
+            self.draw_floors()
+            self.draw_obstacles()
+            self.draw_begin_finish_points()
+
+    def draw_floors(self):
+        floors = self.map_json["floor"]
+        for a_floor in floors:
+            type = a_floor["type"]
+            name = a_floor["name"]
+            for p in a_floor["points"]:
+                x_offset = int(p["x"]) - self.scroll_grid_at[0]
+                y_offset = int(p["y"]) - self.scroll_grid_at[1]
+                # The original jumps to the next point if either bound fails.
+                if not (0 <= x_offset < MAP_GRID_X and 0 <= y_offset < MAP_GRID_Y):
+                    continue
+                a_floor_instance = floor.get_floor(type, name)
+                self.map_area.blit(a_floor_instance, (int(p["x"]) * GAME_SQUARE, int(p["y"]) * GAME_SQUARE))
+
+    def draw_obstacles(self):
+        if not self.show_obstacle:
+            return
+        draw_seq = list(self.map_obstacles_dict.values())
+        draw_seq.sort(key=get_y)
+        for d in draw_seq:
+            d.draw(self.map_area)
+
+    def __blit_text(self, surf: pygame.Surface, text, pos, color=COLOR_WHITE):
+        text = self.text_font.render(str(text), False, color)
+        surf.blit(text, pos)
+
+    def draw_begin_finish_points(self):
+        self.map_area.blit(self.spawnPoint1_img, (self.begin_at[0] * GAME_SQUARE, self.begin_at[1] * GAME_SQUARE))
+        self.map_area.blit(self.spawnPoint2_img, (self.finish_at[0] * GAME_SQUARE, self.finish_at[1] * GAME_SQUARE))
+
+    def empty_current_elem(self):
+        self.current_elem = {'elem_type':None, 
+         'type':None,  'name':None}
+
+    def update_clip_board(self):
+        text = check_clipboard()
+        if self.selection.start is not None:
+            return
+        if self.selection.group:
+            if text == self.selection.clipboard_text:
+                if len(self.selection.group) == 1:
+                    node = self.selection.group[0]
+                    img = (floor.get_floor(node["type"], node["name"]) if node["layer"] == "floor" else
+                           obstacle.get_obstacle(node["type"], node["name"])["STAND"][0].image)
+                    scale = min(1, 160 / img.get_width(), 280 / img.get_height())
+                    if scale < 1:
+                        img = pygame.transform.smoothscale(img, (max(1, int(img.get_width() * scale)), max(1, int(img.get_height() * scale))))
+                    self.screen.blit(img, PREVIEW_AT)
+                    self._MapBuilder__blit_text(self.screen, node["type"], (PREVIEW_AT[0], PREVIEW_AT[1] - 40))
+                    self._MapBuilder__blit_text(self.screen, node["name"], (PREVIEW_AT[0], PREVIEW_AT[1] - 20))
+                    self._MapBuilder__blit_text(self.screen, "左键放置 / Esc取消", (PREVIEW_AT[0], PREVIEW_AT[1] + img.get_height() + 12))
+                    return
+                self._MapBuilder__blit_text(self.screen, "已复制 %d 个元素" % len(self.selection.group), PREVIEW_AT)
+                self._MapBuilder__blit_text(self.screen, "左键放置 / Esc取消", (PREVIEW_AT[0], PREVIEW_AT[1] + 24))
+                return
+            self.selection.cancel()
+        split_text = text.split("\\")
+        if len(split_text) < 2:
+            self.empty_current_elem()
+            return
+        type = split_text[-2]
+        fn = split_text[-1].split(".")[0]
+        try:
+            if fn.find("_") < 0:
+                self.current_elem["elem_type"] = "floor"
+                a_floor_instance = floor.get_floor(type, fn)
+                self.screen.blit(a_floor_instance, PREVIEW_AT)
+            else:
+                self.current_elem["elem_type"] = "obstacle"
+                fn = fn.split("_")[0]
+                an_obstacle_instance = obstacle.get_obstacle(type, fn)
+                self.screen.blit(an_obstacle_instance["STAND"][0].image, PREVIEW_AT)
+            self.current_elem["type"] = type
+            self.current_elem["name"] = fn
+            self._MapBuilder__blit_text(self.screen, type, (PREVIEW_AT[0], PREVIEW_AT[1] - 40))
+            self._MapBuilder__blit_text(self.screen, fn, (PREVIEW_AT[0], PREVIEW_AT[1] - 20))
+        except FileNotFoundError:
+            self.empty_current_elem()
+
+    def draw_map_area(self):
+        blit_area = (GAME_SQUARE * self.scroll_grid_at[0], GAME_SQUARE * self.scroll_grid_at[1], MAP_W, MAP_H)
+        self.screen.blit(self.map_area, MAP_AT, blit_area)
+        self.screen.blit(self.map_hint_area, MAP_AT, blit_area)
+        (text, color) = ("显示障碍", COLOR_GREEN) if self.show_obstacle else ("隐藏障碍", COLOR_RED)
+        self._MapBuilder__blit_text(self.screen, text, (20, MAP_AT[1]), color)
+        self._MapBuilder__blit_text(self.screen, "每30秒自动保存", (HINT_AT[0], HINT_AT[1] - 20))
+        self._MapBuilder__blit_text(self.screen, "WSAD或滚轮 移动", (HINT_AT[0], HINT_AT[1]))
+        self._MapBuilder__blit_text(self.screen, "左键放置 右键删除", (HINT_AT[0], HINT_AT[1] + 20))
+        self._MapBuilder__blit_text(self.screen, "B起始点 F结束点", (HINT_AT[0], HINT_AT[1] + 40))
+        self._MapBuilder__blit_text(self.screen, "空格 切换显示", (HINT_AT[0], HINT_AT[1] + 60))
+        self._MapBuilder__blit_text(self.screen, "Shift+左键拖动 框选", (HINT_AT[0], HINT_AT[1] + 80))
+        self._MapBuilder__blit_text(self.screen, "V 设置初始视野", (HINT_AT[0], HINT_AT[1] + 100))
+
+    def do_show_statement(self):
+        if self.key_space_state > 60 or self.mouse_button_0_state > 60 and self.mouse_button_1_state > 60:
+            self.screen.fill(COLOR_BLACK)
+            self._MapBuilder__blit_text((self.screen), "QQTPVE地图编辑器v1", (40, 60), color=COLOR_YELLOW)
+            self._MapBuilder__blit_text(self.screen, "垃圾小飞,盗我程序,连编辑器都盗,脸都不要了?小飞QQ群:924819359", (40, 100))
+            self._MapBuilder__blit_text(self.screen, "小飞QQ1:112111113  QQ2:1444404321 <--金钱能带给你的只有虚荣,知识与能力才是真本领", (40, 140))
+            self._MapBuilder__blit_text((self.screen), "QQTPVE原作者为:永恒  主页:space.bilibili.com/1260392652", (40, 180), color=COLOR_GREEN)
+            self._MapBuilder__blit_text((self.screen), "鸣谢[开发宣传]:影笺、悠闲、100の雨女、TesBot/Jhin、冥の归、兔兔、幻影、Null、幸运星、毁灭、根号十三、冰神等", (40, 220), color=COLOR_GREEN)
+            self._MapBuilder__blit_text((self.screen), "鸣谢[充电]:Anoxicc、奥柏轮、小獵犬七號、0悠闲人生0、-欢聚一堂、lint2、丶魂祭等", (40, 260), color=COLOR_GREEN)
+            self._MapBuilder__blit_text((self.screen), "QQTPVE开发已有一年,贡献者是一个团队。你小飞窃取的是我们团队的果实,将永远被钉在耻辱柱上!", (40, 300), color=COLOR_CYAN)
+
+    def update_timer(self):
+        current_time = pygame.time.get_ticks()
+        if current_time - self.timer > AUTO_SAVE_DURATION:
+            try:
+                self.save_map_json()
+            except Exception as error:
+                self.menu.notify("自动保存失败:" + str(error))
+            self.timer = current_time
+
+
+if __name__ == "__main__":
+    from datetime import datetime
+    import shutil
+
+    os.chdir(str(PROJECT_ROOT))
+    map_file = PROJECT_ROOT / MAP_JSON_FILE_NAME
+    if map_file.exists():
+        backup = PROJECT_ROOT / "recovered_map_editor" / "backups" / (datetime.now().strftime("%Y%m%d_%H%M%S_%f") + "_map.json")
+        backup.parent.mkdir(exist_ok=True)
+        shutil.copy2(str(map_file), str(backup))
+        print("Map backup:", backup)
+    map_builder = MapBuilder()

+ 227 - 0
recovered_map_editor/source/map_settings.py

@@ -0,0 +1,227 @@
+"""Map metadata inputs, music preview and independently stored initial camera."""
+from pathlib import Path
+import pygame
+from const.window import WINDOW_W, MAP_AT, MAP_W, MAP_H, GAME_SQUARE
+
+
+class MapSettings:
+    def __init__(self, app):
+        self.app = app
+        self.focus = None
+        self.select_all = False
+        self.muted = False
+        self.loaded_music = None
+        self.fields = [("width", "宽", pygame.Rect(WINDOW_W + 28, 37, 48, 28)),
+                       ("height", "高", pygame.Rect(WINDOW_W + 100, 37, 48, 28)),
+                       ("music", "音乐", pygame.Rect(WINDOW_W + 190, 37, 164, 28))]
+        self.confirm = pygame.Rect(WINDOW_W + 362, 37, 58, 28)
+        self.revert = pygame.Rect(WINDOW_W + 428, 37, 58, 28)
+        self.speaker = pygame.Rect(440, 2, 38, 28)
+        self.view_toggle = pygame.Rect(484, 2, 120, 28)
+        self.show_initial_view = True
+        self.sync()
+
+    def sync(self):
+        basic = self.app.map_json["basic"]
+        self.values = {k: str(basic.get(k, "")) for k in ("width", "height", "music")}
+        self.focus = None
+        self.cursor = 0
+        self.select_all = False
+        self.offsets = {key: 0 for key in self.values}
+        pygame.key.stop_text_input()
+        self.play_music()
+
+    def insert_text(self, text):
+        value = self.values[self.focus]
+        if self.select_all:
+            value, self.cursor = "", 0
+        text = text.replace("\r", "").replace("\n", "")[:max(0, 180 - len(value))]
+        self.values[self.focus] = value[:self.cursor] + text + value[self.cursor:]
+        self.cursor += len(text)
+        self.select_all = False
+
+    def play_music(self):
+        name = str(self.app.map_json["basic"].get("music", ""))
+        if name == self.loaded_music:
+            return
+        self.loaded_music = name
+        try:
+            if not pygame.mixer.get_init():
+                pygame.mixer.init()
+            pygame.mixer.music.stop()
+            if name and name.lower() != "none.ogg":
+                pygame.mixer.music.load(str(Path("res/music") / name))
+                pygame.mixer.music.set_volume(0 if self.muted else 0.5)
+                pygame.mixer.music.play(-1)
+        except (pygame.error, OSError) as error:
+            self.app.menu.notify("音乐播放失败 %s:%s" % (name, error))
+
+    def toggle_music(self):
+        self.muted = not self.muted
+        if pygame.mixer.get_init():
+            pygame.mixer.music.set_volume(0 if self.muted else 0.5)
+
+    def apply(self):
+        try:
+            width, height = int(self.values["width"]), int(self.values["height"])
+            if not (1 <= width <= 256 and 1 <= height <= 256 and width * height <= 10000):
+                raise ValueError("宽高须为 1~256,总格数不超过 10000")
+            music = self.values["music"].strip()
+            if music and music.lower() != "none.ogg" and not (Path("res/music") / music).is_file():
+                raise ValueError("找不到音乐:res/music/" + music)
+            data = self.app.document_snapshot()
+            data["basic"].update(width=width, height=height, music=music)
+            self.app.menu.finish_stroke()
+            self.app.menu.edit(lambda: self.app.restore_document(data))
+            self.focus = None
+            pygame.key.stop_text_input()
+            self.app.menu.notify("地图参数已修改;Ctrl+S 保存")
+        except (ValueError, OSError, pygame.error) as error:
+            self.app.menu.notify(str(error))
+
+    def handle_event(self, event):
+        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
+            if self.view_toggle.collidepoint(event.pos):
+                self.show_initial_view = not self.show_initial_view
+                self.app.menu.block_pointer = True
+                return True
+            if self.speaker.collidepoint(event.pos):
+                self.toggle_music()
+                self.app.menu.block_pointer = True
+                return True
+            if self.app.tools.visible:
+                for key, label, rect in self.fields:
+                    if rect.collidepoint(event.pos):
+                        if self.focus == key:
+                            target = event.pos[0] - rect.x - 4 + self.offsets[key]
+                            font = self.app.text_font
+                            self.cursor = min(range(len(self.values[key]) + 1), key=lambda n: abs(font.size(self.values[key][:n])[0] - target))
+                            self.select_all = False
+                        else:
+                            self.focus, self.select_all = key, True
+                            self.cursor = len(self.values[key])
+                        pygame.key.start_text_input()
+                        pygame.key.set_text_input_rect(rect)
+                        self.app.menu.block_pointer = True
+                        return True
+                if self.confirm.collidepoint(event.pos):
+                    self.apply()
+                    self.app.menu.block_pointer = True
+                    return True
+                if self.revert.collidepoint(event.pos):
+                    self.sync()
+                    self.app.menu.notify("已还原未确认的输入")
+                    self.app.menu.block_pointer = True
+                    return True
+            if self.focus is not None:
+                self.focus = None
+                pygame.key.stop_text_input()
+        if self.focus is None:
+            return False
+        if event.type == pygame.TEXTINPUT:
+            self.insert_text(event.text)
+            return True
+        if event.type == pygame.KEYDOWN:
+            if event.key == pygame.K_ESCAPE:
+                self.focus = None
+                pygame.key.stop_text_input()
+            elif event.key == pygame.K_RETURN:
+                self.apply()
+            elif event.key == pygame.K_TAB:
+                names = [k for k, label, rect in self.fields]
+                self.focus = names[(names.index(self.focus) + 1) % len(names)]
+                self.select_all = True
+                self.cursor = len(self.values[self.focus])
+            elif event.key == pygame.K_a and event.mod & pygame.KMOD_CTRL:
+                self.select_all = True
+                self.cursor = len(self.values[self.focus])
+            elif event.key == pygame.K_v and event.mod & pygame.KMOD_CTRL:
+                import pyperclip
+                self.insert_text(pyperclip.paste())
+            elif event.key in (pygame.K_LEFT, pygame.K_RIGHT, pygame.K_HOME, pygame.K_END):
+                length = len(self.values[self.focus])
+                if event.key == pygame.K_HOME or event.key == pygame.K_LEFT and self.select_all:
+                    self.cursor = 0
+                elif event.key == pygame.K_END or event.key == pygame.K_RIGHT and self.select_all:
+                    self.cursor = length
+                else:
+                    self.cursor = max(0, min(length, self.cursor + (-1 if event.key == pygame.K_LEFT else 1)))
+                self.select_all = False
+            elif event.key in (pygame.K_BACKSPACE, pygame.K_DELETE):
+                value = self.values[self.focus]
+                if self.select_all:
+                    self.values[self.focus], self.cursor = "", 0
+                elif event.key == pygame.K_BACKSPACE and self.cursor > 0:
+                    self.values[self.focus] = value[:self.cursor - 1] + value[self.cursor:]
+                    self.cursor -= 1
+                elif event.key == pygame.K_DELETE:
+                    self.values[self.focus] = value[:self.cursor] + value[self.cursor + 1:]
+                self.select_all = False
+            return True
+        return event.type == pygame.KEYUP
+
+    def set_scroll(self, cell):
+        self.app.menu.edit(lambda: self.app.map_json["basic"].update(scroll=list(cell)))
+        self.app.menu.notify("游戏初始视野:(%d, %d),20×13 格" % tuple(cell))
+
+    def draw_view(self):
+        if not self.show_initial_view:
+            return
+        x, y = self.app.map_json["basic"].get("scroll", [0, 0])
+        sx, sy = self.app.scroll_grid_at
+        overlay = pygame.Surface((MAP_W, MAP_H), pygame.SRCALPHA)
+        rect = pygame.Rect((x - sx) * GAME_SQUARE, (y - sy) * GAME_SQUARE, 20 * GAME_SQUARE, 13 * GAME_SQUARE)
+        pygame.draw.rect(overlay, (15, 20, 25, 230), rect.inflate(2, 2), 5)
+        pygame.draw.rect(overlay, (255, 235, 110, 255), rect, 2)
+        visible = rect.clip(overlay.get_rect())
+        if visible.width > 170 and visible.height > 24:
+            label = self.app.text_font.render("初始视野 20x13 (%s,%s)" % (x, y), True, (255, 235, 110))
+            overlay.blit(label, (visible.x + 6, visible.y + 6))
+        self.app.screen.blit(overlay, MAP_AT)
+
+    def draw_fields(self):
+        font, screen = self.app.text_font, self.app.screen
+        for key, label, rect in self.fields:
+            image = font.render(label, True, (235, 238, 243))
+            screen.blit(image, (rect.x - image.get_width() - 5, rect.y + 6))
+            pygame.draw.rect(screen, (20, 25, 32), rect)
+            pygame.draw.rect(screen, (240, 210, 100) if key == self.focus else (144, 155, 173), rect, 1)
+            if key == self.focus and self.select_all:
+                pygame.draw.rect(screen, (55, 78, 112), rect.inflate(-4, -4))
+            value = font.render(self.values[key], True, (235, 238, 243))
+            caret = font.size(self.values[key][:self.cursor])[0] if key == self.focus else 0
+            offset = self.offsets[key]
+            if key == self.focus:
+                offset = max(0, min(offset, caret))
+                offset = max(offset, caret - rect.width + 10)
+            self.offsets[key] = offset
+            old_clip = screen.get_clip()
+            screen.set_clip(rect.inflate(-6, -4))
+            screen.blit(value, (rect.x + 4 - offset, rect.y + 6))
+            if key == self.focus and not self.select_all and pygame.time.get_ticks() % 1000 < 650:
+                x = rect.x + 4 + caret - offset
+                pygame.draw.line(screen, (255, 235, 140), (x, rect.y + 5), (x, rect.bottom - 5))
+            screen.set_clip(old_clip)
+        for label, rect in [("确认", self.confirm), ("还原", self.revert)]:
+            pygame.draw.rect(screen, (53, 65, 81), rect)
+            pygame.draw.rect(screen, (144, 155, 173), rect, 1)
+            image = font.render(label, True, (235, 238, 243))
+            screen.blit(image, image.get_rect(center=rect.center))
+
+    def draw_speaker(self):
+        screen = self.app.screen
+        toggle = self.view_toggle
+        pygame.draw.rect(screen, (53, 61, 74) if self.show_initial_view else (22, 26, 33), toggle)
+        pygame.draw.rect(screen, (144, 155, 173), toggle, 1)
+        label = self.app.text_font.render("隐藏初始视野" if self.show_initial_view else "显示初始视野", True, (235, 240, 245))
+        screen.blit(label, label.get_rect(center=toggle.center))
+        rect = self.speaker
+        color = (125, 135, 148) if self.muted else (235, 240, 245)
+        pygame.draw.rect(screen, (22, 26, 33) if self.muted else (53, 61, 74), rect)
+        pygame.draw.rect(screen, (144, 155, 173), rect, 1)
+        x, y = rect.x + 8, rect.centery
+        pygame.draw.polygon(screen, color, [(x, y - 4), (x + 5, y - 4), (x + 12, y - 10), (x + 12, y + 10), (x + 5, y + 4), (x, y + 4)])
+        if self.muted:
+            pygame.draw.line(screen, (255, 120, 120), (rect.x + 5, rect.bottom - 5), (rect.right - 5, rect.y + 5), 2)
+        else:
+            pygame.draw.lines(screen, color, False, [(x + 17, y - 7), (x + 21, y), (x + 17, y + 7)], 2)

+ 61 - 0
recovered_map_editor/source/npc_preview.py

@@ -0,0 +1,61 @@
+"""Render game NPC standing frames without constructing gameplay NPC objects."""
+import pygame
+from const.window import GAME_SQUARE
+
+
+class NpcPreview:
+    def __init__(self, app):
+        self.app = app
+        self.cache = {}
+        self.errors = {}
+
+    def load(self, name):
+        if name in self.cache:
+            return self.cache[name]
+        if name in self.errors:
+            return None
+        try:
+            from client_local.file_loader.fileLoader import load_json
+            from client_local.frame.character import get_character, CHARACTER_COMPONENTS
+            config = load_json("game/npc/%s.json" % name) or load_json("game/npcs/%s.json" % name)
+            if not config:
+                raise ValueError("找不到 game/npc/%s.json" % name)
+            character_name = config["character"]
+            character = load_json("game/frame/character/%s.json" % character_name) or load_json("game/character/%s.json" % character_name)
+            if not character:
+                raise ValueError("找不到角色 " + character_name)
+            decorations = {}
+            for part, value in (config.get("decorations") or {}).items():
+                if value is not None:
+                    decorations[part.capitalize()] = load_json("game/frame/%s/%s.json" % (part.lower(), value))
+            frames = get_character(character, (255, 0, 0), decorations)
+            orient = next((o for o in ("STAND_D", "STAND_R", "STAND_L", "STAND_U", "D") if o in frames), None)
+            if orient is None:
+                raise ValueError("角色缺少可用站立帧")
+            value = (frames[orient], CHARACTER_COMPONENTS[orient[-1]], max(0, float(config.get("resent_dist", 0))))
+            self.cache[name] = value
+            return value
+        except Exception as error:
+            self.errors[name] = str(error)
+            self.app.menu.notify("模型加载失败 %s:%s" % (name, error))
+            return None
+
+    def draw(self, surface, npc, scroll, color, frame_index=None, show_vision=True):
+        model = self.load(npc.get("name", ""))
+        if model is None:
+            return False
+        frames, components, resent = model
+        x = (npc["x"] - scroll[0] + 0.5) * GAME_SQUARE
+        y = (npc["y"] - scroll[1] + 0.5) * GAME_SQUARE
+        radius = resent * GAME_SQUARE
+        if show_vision and radius > 0:
+            rect = pygame.Rect(round(x - radius), round(y - radius), round(radius * 2), round(radius * 2))
+            pygame.draw.rect(surface, (12, 16, 22, 240), rect.inflate(2, 2), 5)
+            pygame.draw.rect(surface, color + (255,), rect, 3)
+        tick = pygame.time.get_ticks() // 200 if frame_index is None else frame_index
+        for component in components:
+            sequence = frames.get(component)
+            if sequence:
+                frame = sequence[tick % len(sequence)]
+                surface.blit(frame.image, (round(x + frames["Cx"] + frame.cx), round(y + frames["Cy"] + frame.cy)))
+        return True

+ 104 - 0
recovered_map_editor/source/placement.py

@@ -0,0 +1,104 @@
+"""Rectangle brushes and continuous, replacing large-obstacle strokes."""
+import pygame
+from const.window import MAP_AT, MAP_SIZE, GAME_SQUARE
+from game.frame import obstacle
+
+
+class Placement:
+    def __init__(self, app):
+        self.app = app
+        self.active = False
+
+    def stamp(self, cell):
+        previous = self.app.current_elem
+        self.app.current_elem = self.brush
+        try:
+            self.app.add_elem(cell)
+        finally:
+            self.app.current_elem = previous
+
+    def move(self, cell):
+        if self.rectangle:
+            self.end = cell
+            return
+        dx, dy = cell[0] - self.end[0], cell[1] - self.end[1]
+        steps = max(abs(dx), abs(dy))
+        origin = self.end
+        for i in range(1, steps + 1):
+            self.stamp((origin[0] + round(dx * i / steps), origin[1] + round(dy * i / steps)))
+        self.end = cell
+
+    def finish(self, cancel=False):
+        if not self.active:
+            return
+        self.active = False
+        if cancel:
+            self.app.restore_document(self.before)
+        else:
+            if self.rectangle:
+                for x in range(min(self.start[0], self.end[0]), max(self.start[0], self.end[0]) + 1):
+                    for y in range(min(self.start[1], self.end[1]), max(self.start[1], self.end[1]) + 1):
+                        self.stamp((x, y))
+            self.app.menu.record(self.before)
+        self.app.menu.block_pointer = True
+
+    def handle_event(self, event):
+        app = self.app
+        if self.active:
+            if event.type == pygame.MOUSEMOTION:
+                self.move(app.selection.cell(event.pos, clamp=True))
+            elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
+                self.move(app.selection.cell(event.pos, clamp=True))
+                self.finish()
+            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
+                self.finish(cancel=True)
+            return True
+        if event.type != pygame.MOUSEBUTTONDOWN or event.button != 1:
+            return False
+        if (app.tools.tool != "paint" or app.tools.regions.interacting() or
+                app.settings.focus is not None or app.menu.blocks_editing() or
+                pygame.key.get_mods() & (pygame.KMOD_SHIFT | pygame.KMOD_CTRL) or
+                len(app.selection.group) > 1):
+            return False
+        cell = app.selection.cell(event.pos)
+        if cell is None:
+            return False
+        if app.selection.group:
+            node = app.selection.group[0]
+            brush = dict(elem_type=node["layer"], type=node["type"], name=node["name"])
+        else:
+            brush = dict(app.current_elem)
+        if not brush.get("elem_type"):
+            return False
+        if brush["elem_type"] == "obstacle" and not app.show_obstacle:
+            return True
+        obs = obstacle.get_obstacle(brush["type"], brush["name"]) if brush["elem_type"] == "obstacle" else None
+        self.rectangle = obs is None or obs["WIDTH"] == obs["HEIGHT"] == 1
+        app.menu.finish_stroke()
+        self.before = app.document_snapshot()
+        self.brush = brush
+        self.start = self.end = cell
+        self.active = True
+        app.blank_map_hint_area()
+        if not self.rectangle:
+            self.stamp(cell)
+        return True
+
+    def draw(self):
+        if not self.active or not self.rectangle:
+            return
+        app = self.app
+        x0, x1 = sorted((self.start[0], self.end[0]))
+        y0, y1 = sorted((self.start[1], self.end[1]))
+        old_clip = app.screen.get_clip()
+        app.screen.set_clip(pygame.Rect(MAP_AT, MAP_SIZE))
+        tile = pygame.Surface((GAME_SQUARE, GAME_SQUARE), pygame.SRCALPHA)
+        for x in range(x0, x1 + 1):
+            for y in range(y0, y1 + 1):
+                blocked = self.brush["elem_type"] == "obstacle" and (x, y) in app.map_obstacles_dict
+                tile.fill((230, 65, 65, 100) if blocked else (115, 160, 210, 100))
+                pos = (MAP_AT[0] + (x - app.scroll_grid_at[0]) * GAME_SQUARE,
+                       MAP_AT[1] + (y - app.scroll_grid_at[1]) * GAME_SQUARE)
+                app.screen.blit(tile, pos)
+                pygame.draw.rect(app.screen, (200, 215, 235), (*pos, GAME_SQUARE, GAME_SQUARE), 1)
+        app.screen.set_clip(old_clip)

+ 4 - 0
recovered_map_editor/source/runtime_paths.py

@@ -0,0 +1,4 @@
+import sys
+from pathlib import Path
+
+PROJECT_ROOT = Path(sys.executable).resolve().parent if getattr(sys, 'frozen', False) else Path(__file__).resolve().parents[2]

+ 146 - 0
recovered_map_editor/source/selection.py

@@ -0,0 +1,146 @@
+"""Rectangular copy and collision-checked group placement."""
+import pygame
+from const.window import MAP_AT, MAP_W, MAP_H, GAME_SQUARE
+from game.frame import obstacle
+from game.frame.obstacle_instance import ObstacleInstance
+
+
+class Selection:
+    def __init__(self, app, read_clipboard):
+        self.app = app
+        self.read_clipboard = read_clipboard
+        self.start = None
+        self.end = None
+        self.layer = None
+        self.group = []
+        self.clipboard_text = None
+
+    def cancel(self):
+        self.start = self.end = None
+        self.group = []
+        self.app.blank_map_hint_area()
+
+    def cell(self, pos, clamp=False):
+        x, y = pos[0] - MAP_AT[0], pos[1] - MAP_AT[1]
+        if not clamp and not (0 <= x < MAP_W and 0 <= y < MAP_H):
+            return None
+        x = max(0, min(MAP_W - 1, x)) // GAME_SQUARE + self.app.scroll_grid_at[0]
+        y = max(0, min(MAP_H - 1, y)) // GAME_SQUARE + self.app.scroll_grid_at[1]
+        if not clamp and (x >= self.app.map_size[0] or y >= self.app.map_size[1]):
+            return None
+        return (min(x, self.app.map_size[0] - 1), min(y, self.app.map_size[1] - 1))
+
+    def handle_event(self, event):
+        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
+            cell = self.cell(event.pos)
+            if cell is None:
+                return False
+            if pygame.key.get_mods() & pygame.KMOD_SHIFT:
+                self.start = self.end = cell
+                self.layer = "obstacle" if self.app.show_obstacle else "floor"
+                return True
+            if self.group:
+                self.app.menu.edit(lambda: self.place(cell))
+                self.app.menu.block_pointer = True
+                return True
+        if self.start is not None:
+            if event.type == pygame.MOUSEMOTION:
+                self.end = self.cell(event.pos, clamp=True)
+            elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
+                self.end = self.cell(event.pos, clamp=True)
+                self.copy_rectangle(self.start, self.end, self.layer)
+                self.start = self.end = None
+                self.app.menu.block_pointer = True
+            return True
+        return False
+
+    def copy_rectangle(self, start, end, layer):
+        x0, x1 = sorted((start[0], end[0]))
+        y0, y1 = sorted((start[1], end[1]))
+        nodes = []
+        if layer == "obstacle":
+            seen = set()
+            for (x, y), instance in self.app.map_obstacles_dict.items():
+                if x0 <= x <= x1 and y0 <= y <= y1 and id(instance) not in seen:
+                    seen.add(id(instance))
+                    nodes.append(dict(type=instance.obstacle["TYPE"], name=instance.obstacle["NAME"],
+                                      x=instance.x, y=instance.y, layer=layer))
+        else:
+            for node in self.app.map_json["floor"]:
+                for point in node["points"]:
+                    if x0 <= point["x"] <= x1 and y0 <= point["y"] <= y1:
+                        nodes.append(dict(type=node["type"], name=node["name"],
+                                          x=point["x"], y=point["y"], layer=layer))
+        self.group = nodes
+        self.clipboard_text = self.read_clipboard()
+        self.app.blank_map_hint_area()
+        if nodes:
+            anchor_x, anchor_y = min(n["x"] for n in nodes), min(n["y"] for n in nodes)
+            for node in nodes:
+                node["x"] -= anchor_x
+                node["y"] -= anchor_y
+        self.app.menu.notify("已复制 %d 个元素;左键放置,Esc 取消" % len(nodes))
+
+    def plan(self, position):
+        result, cells = [], set()
+        self.conflicts = set()
+        valid = bool(self.group)
+        moving = getattr(self.app.tools.extra, "sources", []) if self.app.tools.tool == "move" else []
+        for node in self.group:
+            x, y = position[0] + node["x"], position[1] + node["y"]
+            obs = obstacle.get_obstacle(node["type"], node["name"]) if node["layer"] == "obstacle" else None
+            width, height = (obs["WIDTH"], obs["HEIGHT"]) if obs else (1, 1)
+            if obs and not self.app.show_obstacle:
+                valid = False
+            for dx in range(width):
+                for dy in range(height):
+                    cell = (x + dx, y + dy)
+                    if (cell in cells or (obs is not None and cell in self.app.map_obstacles_dict and self.app.map_obstacles_dict[cell] not in moving) or
+                            not (0 <= cell[0] < self.app.map_size[0] and 0 <= cell[1] < self.app.map_size[1])):
+                        valid = False
+                        self.conflicts.add(cell)
+                    cells.add(cell)
+            result.append((node, x, y, obs))
+        return valid, result, cells
+
+    def place(self, position):
+        valid, nodes, cells = self.plan(position)
+        if not valid:
+            self.app.menu.notify("无法放置:有障碍物、超出地图或障碍物已隐藏")
+            return False
+        # The entire footprint is checked before making any change.
+        for node, x, y, obs in nodes:
+            if obs:
+                ObstacleInstance(x, y, self.app.map_obstacles_dict, obs)
+            else:
+                self.app.remove_elem((x, y), "floor")
+                target = next((n for n in self.app.map_json["floor"]
+                               if n["type"] == node["type"] and n["name"] == node["name"]), None)
+                if target is None:
+                    target = dict(type=node["type"], name=node["name"], points=[])
+                    self.app.map_json["floor"].append(target)
+                target["points"].append(dict(x=x, y=y))
+        self.app.redraw_floor_obstacle_trigger = True
+        return True
+
+    def draw(self):
+        overlay = pygame.Surface((MAP_W, MAP_H), pygame.SRCALPHA)
+        scroll_x, scroll_y = self.app.scroll_grid_at
+        if self.start is not None:
+            x0, x1 = sorted((self.start[0], self.end[0]))
+            y0, y1 = sorted((self.start[1], self.end[1]))
+            rect = pygame.Rect((x0 - scroll_x) * GAME_SQUARE, (y0 - scroll_y) * GAME_SQUARE,
+                               (x1 - x0 + 1) * GAME_SQUARE, (y1 - y0 + 1) * GAME_SQUARE)
+            pygame.draw.rect(overlay, (70, 155, 255, 55), rect)
+            pygame.draw.rect(overlay, (100, 195, 255, 240), rect, 2)
+        elif self.group and not self.app.menu.blocks_editing():
+            position = self.cell(pygame.mouse.get_pos())
+            if position is not None:
+                valid, nodes, cells = self.plan(position)
+                for x, y in cells:
+                    color = (255, 65, 65, 130) if (x, y) in self.conflicts else (170, 170, 170, 105)
+                    rect = pygame.Rect((x - scroll_x) * GAME_SQUARE, (y - scroll_y) * GAME_SQUARE,
+                                       GAME_SQUARE, GAME_SQUARE)
+                    pygame.draw.rect(overlay, color, rect)
+                    pygame.draw.rect(overlay, color[:3] + (220,), rect, 1)
+        self.app.screen.blit(overlay, MAP_AT)

+ 209 - 0
recovered_map_editor/source/tool_panel.py

@@ -0,0 +1,209 @@
+"""Optional right-hand tools and square layer-specific erasers."""
+import pygame
+from district_overlay import DistrictOverlay
+from extra_tools import ExtraTools
+from const.window import WINDOW_W, WINDOW_H, MENU_HEIGHT, MAP_AT, MAP_W, MAP_H, GAME_SQUARE, TOOL_PANEL_WIDTH
+
+
+class ToolPanel:
+    WIDTH = TOOL_PANEL_WIDTH
+
+    def __init__(self, app):
+        self.app = app
+        self.visible = True
+        self.tool = "paint"
+        self.size = 1
+        self.dragging = False
+        self.last = None
+        self.regions = DistrictOverlay(app)
+        self.extra = ExtraTools(app)
+
+    def toggle(self):
+        self.visible = not self.visible
+
+    def choose(self, tool):
+        if tool != "paint":
+            self.regions.finish_drag()
+            self.regions.enabled = False
+            self.regions.editing = self.regions.moving_npc = None
+            self.regions.create_mode = self.regions.create_start = self.regions.create_end = None
+        self.app.menu.finish_stroke()
+        self.dragging = False
+        self.last = None
+        self.tool = tool
+        self.extra.reset()
+        if tool != "spray":
+            self.app.selection.cancel()
+        if tool != "paint" and not self.visible:
+            self.toggle()
+        self.app.menu.notify({"paint": "放置工具", "floor": "地板橡皮擦", "obstacle": "障碍物橡皮擦", "move": "拖拽框选障碍物,再点击目标位置移动", "spray": "喷溅笔", "expand": "左 / 上方拓展", "export": "选择下方按钮导出图片"}[tool])
+
+    def buttons(self):
+        return [(name, label, pygame.Rect(WINDOW_W + 12 + i % 4 * 100, 72 + i // 4 * 72, 92, 64))
+                for i, (name, label) in enumerate([
+                    ("grid", "显示网格"), ("obstacles", "显示障碍"), ("regions", "显示区域"), ("models", "怪物渲染"),
+                    ("floor", "地板擦除"), ("obstacle", "障碍擦除"), ("paint", "放置工具"), ("origin", "回到原点"),
+                    ("move", "批量移动"), ("spray", "喷溅笔"), ("expand", "左/上拓展"), ("export", "图片导出")])]
+
+    def sizes(self):
+        if self.tool not in ("floor", "obstacle"):
+            return []
+        return [(n, pygame.Rect(WINDOW_W + 12 + (n - 1) % 3 * 64, 338 + (n - 1) // 3 * 36, 58, 30))
+                for n in range(1, 16)]
+
+    def erase_bounds(self, cell):
+        # Odd sizes center on the cursor; even sizes put it in the upper-left
+        # cell of the central 2x2. Clip without shifting the footprint inward.
+        offset = (self.size - 1) // 2
+        x0, y0 = cell[0] - offset, cell[1] - offset
+        x1, y1 = min(x0 + self.size, self.app.map_size[0]), min(y0 + self.size, self.app.map_size[1])
+        return max(0, x0), max(0, y0), x1, y1
+
+    def erase(self, cell):
+        x0, y0, x1, y1 = self.erase_bounds(cell)
+        if self.tool == "floor":
+            for node in self.app.map_json["floor"]:
+                node["points"] = [p for p in node["points"] if not (x0 <= p["x"] < x1 and y0 <= p["y"] < y1)]
+        elif self.tool == "obstacle":
+            objects = {self.app.map_obstacles_dict[(x, y)] for x in range(x0, x1) for y in range(y0, y1)
+                       if (x, y) in self.app.map_obstacles_dict}
+            for obj in objects:
+                obj.uninstall()
+        self.app.redraw_floor_obstacle_trigger = True
+
+    def erase_to(self, cell):
+        # Interpolate fast mouse motion, so a drag cannot skip cells.
+        start = self.last or cell
+        steps = max(abs(cell[0] - start[0]), abs(cell[1] - start[1]))
+        def action():
+            for i in range(steps + 1):
+                t = i / steps if steps else 0
+                self.erase((round(start[0] + (cell[0] - start[0]) * t),
+                            round(start[1] + (cell[1] - start[1]) * t)))
+        self.app.menu.edit(action)
+        self.last = cell
+
+    def handle_event(self, event):
+        if self.extra.handle_event(event):
+            return True
+        if self.visible and self.regions.handle_event(event):
+            self.app.menu.block_pointer = True
+            return True
+        if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
+            self.dragging = False
+            self.last = None
+        if self.visible and hasattr(event, "pos") and event.pos[0] >= WINDOW_W:
+            if event.type == pygame.MOUSEBUTTONDOWN:
+                self.app.menu.block_pointer = True
+                if event.button == 1:
+                    for name, label, rect in self.buttons():
+                        if rect.collidepoint(event.pos):
+                            actions = {"grid": self.app.menu.toggle_grid, "obstacles": self.app.menu.toggle_obstacles,
+                                       "origin": self.app.menu.go_origin, "regions": self.regions.toggle, "models": self.regions.toggle_models}
+                            self.app.menu.invoke(actions[name] if name in actions else lambda n=name: self.choose(n))
+                    for n, rect in self.sizes():
+                        if rect.collidepoint(event.pos):
+                            self.size = n
+            return True
+        if self.tool not in ("floor", "obstacle"):
+            return False
+        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
+            cell = self.app.selection.cell(event.pos)
+            if cell is not None:
+                self.dragging = True
+                self.last = None
+                self.erase_to(cell)
+                return True
+        if event.type == pygame.MOUSEMOTION and self.dragging:
+            cell = self.app.selection.cell(event.pos)
+            if cell is not None:
+                self.erase_to(cell)
+            else:
+                self.last = None
+            return True
+        return False
+
+    def draw_preview(self):
+        self.extra.draw_preview()
+        if self.tool not in ("floor", "obstacle") or self.app.menu.blocks_editing():
+            return
+        cell = self.app.selection.cell(pygame.mouse.get_pos())
+        if cell is None:
+            return
+        overlay = pygame.Surface((MAP_W, MAP_H), pygame.SRCALPHA)
+        x, y, x1, y1 = self.erase_bounds(cell)
+        sx, sy = self.app.scroll_grid_at
+        rect = pygame.Rect((x - sx) * GAME_SQUARE, (y - sy) * GAME_SQUARE,
+                           (x1 - x) * GAME_SQUARE, (y1 - y) * GAME_SQUARE)
+        color = (100, 180, 255) if self.tool == "floor" else (255, 160, 85)
+        pygame.draw.rect(overlay, color + (60,), rect)
+        pygame.draw.rect(overlay, color + (240,), rect, 2)
+        self.app.screen.blit(overlay, MAP_AT)
+
+    def draw(self):
+        if not self.visible:
+            return
+        screen, font = self.app.screen, self.app.text_font
+        pygame.draw.rect(screen, (35, 39, 46), (WINDOW_W, MENU_HEIGHT, self.WIDTH, WINDOW_H - MENU_HEIGHT))
+        pygame.draw.line(screen, (144, 155, 173), (WINDOW_W, MENU_HEIGHT), (WINDOW_W, WINDOW_H))
+        def text(label, center, color=(235, 238, 243)):
+            image = font.render(label, True, color)
+            screen.blit(image, image.get_rect(center=center))
+        self.app.settings.draw_fields()
+        mouse = pygame.mouse.get_pos()
+        for name, label, rect in self.buttons():
+            active = (name == self.tool or name == "grid" and self.app.menu.show_grid or
+                      name == "obstacles" and self.app.show_obstacle or name == "regions" and self.regions.enabled or name == "models" and self.regions.render_models)
+            bg = (22, 26, 33) if active else (72, 82, 98) if rect.collidepoint(mouse) else (53, 61, 74)
+            pygame.draw.rect(screen, bg, rect)
+            pygame.draw.rect(screen, (144, 155, 173), rect, 1)
+            cx, cy = rect.centerx, rect.y + 22
+            color = (235, 238, 243)
+            if name == "grid":
+                for d in (-12, 0, 12):
+                    pygame.draw.line(screen, color, (cx + d, cy - 12), (cx + d, cy + 12))
+                    pygame.draw.line(screen, color, (cx - 12, cy + d), (cx + 12, cy + d))
+            elif name == "models":
+                self.regions.monster_icon(screen, pygame.Rect(cx - 12, cy - 12, 24, 24), (255, 190, 85))
+            elif name == "regions":
+                pygame.draw.rect(screen, (100, 200, 255), (cx - 15, cy - 12, 22, 18), 2)
+                pygame.draw.rect(screen, (255, 190, 85), (cx - 5, cy - 3, 22, 18), 2)
+            elif name in ("floor", "obstacle"):
+                color = (100, 180, 255) if name == "floor" else (255, 160, 85)
+                pygame.draw.polygon(screen, color, [(cx - 13, cy + 3), (cx, cy - 10), (cx + 13, cy), (cx, cy + 13)], 2)
+                pygame.draw.line(screen, color, (cx - 7, cy - 3), (cx + 6, cy + 7), 2)
+            elif name == "obstacles":
+                pygame.draw.ellipse(screen, color, (cx - 15, cy - 9, 30, 18), 2)
+                pygame.draw.circle(screen, color, (cx, cy), 5)
+            elif name == "move":
+                pygame.draw.line(screen, color, (cx-15, cy), (cx+15, cy), 2)
+                pygame.draw.line(screen, color, (cx, cy-15), (cx, cy+15), 2)
+                for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
+                    pygame.draw.polygon(screen, color, [(cx+dx*16, cy+dy*16), (cx+dx*9-dy*4, cy+dy*9+dx*4), (cx+dx*9+dy*4, cy+dy*9-dx*4)])
+            elif name == "spray":
+                for dx, dy in ((0, 0), (-11, -7), (8, -10), (-6, 11), (12, 7), (1, -15)):
+                    pygame.draw.circle(screen, color, (cx+dx, cy+dy), 2)
+            elif name == "export":
+                pygame.draw.rect(screen, color, (cx-15, cy-12, 30, 24), 2)
+                pygame.draw.lines(screen, color, False, [(cx-12, cy+8), (cx-3, cy-2), (cx+4, cy+5), (cx+10, cy-3)], 2)
+            elif name == "expand":
+                pygame.draw.rect(screen, color, (cx-4, cy-2, 16, 14), 2)
+                pygame.draw.lines(screen, color, False, [(cx-15, cy+4), (cx-15, cy-13), (cx+5, cy-13)], 2)
+            elif name == "paint":
+                pygame.draw.line(screen, color, (cx - 9, cy + 9), (cx + 8, cy - 8), 5)
+                pygame.draw.polygon(screen, color, [(cx - 13, cy + 13), (cx - 10, cy + 5), (cx - 5, cy + 10)])
+            else:
+                pygame.draw.lines(screen, color, False, [(cx - 12, cy + 10), (cx - 12, cy - 10), (cx + 12, cy - 10)], 2)
+                pygame.draw.line(screen, color, (cx - 12, cy - 10), (cx + 7, cy + 8), 2)
+            text(label, (rect.centerx, rect.bottom - 12))
+        self.extra.draw()
+        self.regions.draw_panel()
+        if self.tool not in ("floor", "obstacle"):
+            return
+        text("橡皮擦大小", (WINDOW_W + 104, 310))
+        for n, rect in self.sizes():
+            pygame.draw.rect(screen, (22, 26, 33) if n == self.size else (53, 61, 74), rect)
+            pygame.draw.rect(screen, (144, 155, 173), rect, 1)
+            text("%dx%d" % (n, n), rect.center)
+        for i, label in enumerate(["左键拖动擦除", "触及多格障碍会整块删除", "Esc 返回放置工具"]):
+            text(label, (WINDOW_W + 104, 546 + i * 24), (175, 187, 203))

+ 148 - 0
recovered_map_editor/verify_authoring.py

@@ -0,0 +1,148 @@
+"""Exercise district/NPC creation, rename, focus isolation and real model rendering."""
+import copy
+import json
+import tempfile
+from pathlib import Path
+from verify_recovery import editor, pygame, ROOT, HERE
+
+
+def verify():
+    with tempfile.TemporaryDirectory(prefix="npc_authoring_") as tmp:
+        target = Path(tmp) / "map.json"
+        data = json.loads((ROOT / "CrimsonManorBT4.json").read_text())
+        data["basic"].setdefault("finish", [42, 22])
+        target.write_text(json.dumps(data))
+        editor.MAP_JSON_FILE_NAME = str(target)
+        update = editor.MapBuilder.update
+        editor.MapBuilder.update = lambda self: None
+        try:
+            app = editor.MapBuilder()
+        finally:
+            editor.MapBuilder.update = update
+        r = app.tools.regions
+        r.toggle()
+        app.scroll_grid_at = [0, 0]
+        def event(kind, x, y):
+            kwargs = dict(pos=(editor.MAP_AT[0] + x * 40 + 20, editor.MAP_AT[1] + y * 40 + 20))
+            if kind != pygame.MOUSEMOTION:
+                kwargs["button"] = 1
+            return pygame.event.Event(kind, **kwargs)
+        r.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=r.add_rect().center))
+        r.handle_map_event(event(pygame.MOUSEBUTTONDOWN, 8, 8))
+        r.handle_map_event(event(pygame.MOUSEMOTION, 4, 4))
+        r.handle_map_event(event(pygame.MOUSEBUTTONUP, 4, 4))
+        assert app.map_json["districts"][-1] == dict(square=dict(x1=4, y1=4, x2=8, y2=8), npcs=[])
+        app.menu.undo()
+        assert len(app.map_json["districts"]) == 2
+        app.menu.redo()
+        assert len(app.map_json["districts"]) == 3
+        app.menu.undo()
+        r.hidden = {1}
+        r.focus_region(0)
+        assert all(index == 0 for kind, index, value in r.list_entries())
+        assert r.list_rows()[1][3].x > r.list_rows()[0][3].x
+        r.focus_region(0)
+        assert not r.expanded and r.hidden == {1}
+        r.hidden.clear()
+        r.focus_region(1)
+        npc = app.map_json["districts"][1]["npcs"][0]
+        old = copy.deepcopy(npc)
+        app.menu.dialog = lambda *args, **kwargs: "CrimsonManorDTeddy"
+        r.rename_npc(1, 0)
+        assert npc["name"] == "CrimsonManorDTeddy" and npc["patrol"] == old["patrol"]
+        app.menu.undo()
+        assert app.map_json["districts"][1]["npcs"][0] == old
+        r.focus_region(1)
+        r.focus_region(0)
+        count = len(app.map_json["districts"][0]["npcs"])
+        r.start_add()
+        old_mouse = pygame.mouse.get_pos
+        pygame.mouse.get_pos = lambda: event(pygame.MOUSEMOTION, 5, 5).pos
+        app.screen.fill((0, 0, 0))
+        r.draw_map()
+        pixel = app.screen.get_at((editor.MAP_AT[0] + 5 * 40 + 10, editor.MAP_AT[1] + 5 * 40 + 20))
+        assert pixel.r > 200 and pixel.g > 170 and pixel.b < 100
+        pygame.mouse.get_pos = old_mouse
+        r.handle_map_event(event(pygame.MOUSEBUTTONDOWN, 5, 5))
+        assert len(app.map_json["districts"][0]["npcs"]) == count + 1
+        assert app.map_json["districts"][0]["npcs"][-1] == dict(name="CrimsonManorDTeddy", x=5, y=5)
+        app.menu.undo()
+        assert len(app.map_json["districts"][0]["npcs"]) == count
+        app.menu.dialog = lambda *args, **kwargs: None
+        r.start_add()
+        r.handle_map_event(event(pygame.MOUSEBUTTONDOWN, 5, 5))
+        assert len(app.map_json["districts"][0]["npcs"]) == count
+        r.focus_region(0)
+        r.start_add()
+        r.handle_map_event(event(pygame.MOUSEBUTTONDOWN, 2, 2))
+        r.handle_map_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_ESCAPE))
+        assert len(app.map_json["districts"]) == 2
+        r.focus_region(0)
+        r.toggle_models()
+        names = {npc["name"] for district in data["districts"] for npc in district["npcs"]}
+        for name in names:
+            assert r.models.load(name) is not None, (name, r.models.errors)
+        assert r.models.load("CrimsonManorDDancer")[2] == 3.8
+        assert r.models.load("__missing_npc_test__") is None
+        assert "__missing_npc_test__" in r.models.errors
+        assert len({r.npc_color(0, n) for n in range(20)}) == 20
+        # Delete buttons preserve the rest of the document and support undo/redo.
+        before_delete = app.document_snapshot()
+        npc_row = next(rect for kind, index, value, rect in r.list_rows() if kind == "npc" and value == 0)
+        r.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=r.delete_rect(npc_row).center))
+        assert len(app.map_json["districts"][0]["npcs"]) == len(before_delete["districts"][0]["npcs"]) - 1
+        app.menu.undo()
+        assert app.document_snapshot() == before_delete
+        app.menu.redo()
+        app.menu.undo()
+        region_row = r.rows()[0][2]
+        r.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=r.delete_rect(region_row).center))
+        assert app.map_json["districts"] == before_delete["districts"][1:]
+        assert not r.expanded and r.moving_npc is None and r.editing is None
+        app.menu.undo()
+        assert app.document_snapshot() == before_delete
+        app.menu.redo()
+        app.menu.undo()
+        r.focus_region(0)
+        app.menu.status_until = 0
+        assert app.screen.get_size() == (1776, 872)
+        npc_rows = [(value, rect) for kind, index, value, rect in r.list_rows() if kind == "npc"]
+        document_before_solo = app.document_snapshot()
+        n, row = npc_rows[0]
+        r.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=r.solo_rect(row).center))
+        assert r.solo_npc == (0, n)
+        render = r.models.draw
+        drawn = []
+        r.models.draw = lambda surface, npc, scroll, color: drawn.append(npc) or True
+        try:
+            r.draw_map()
+            assert len(drawn) == 1 and drawn[0] is app.map_json["districts"][0]["npcs"][n]
+            n2, row2 = npc_rows[1]
+            r.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=r.solo_rect(row2).center))
+            assert r.solo_npc == (0, n2)
+            r.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=r.solo_rect(row2).center))
+            drawn.clear()
+            r.draw_map()
+            assert len(drawn) == len(app.map_json["districts"][0]["npcs"])
+        finally:
+            r.models.draw = render
+        assert app.document_snapshot() == document_before_solo
+        r.toggle_solo(0, 0)
+        app.screen.fill((0, 0, 0))
+        app.update_obstacles()
+        app.draw_coordinators()
+        app.draw_floors_and_obstacles()
+        app.draw_map_area()
+        r.draw_map()
+        app.tools.draw()
+        app.menu.draw()
+        pygame.image.save(app.screen, str(HERE / "npc_models_preview.png"))
+        app.save_map_json()
+        assert json.loads(target.read_text())["districts"] == data["districts"]
+        pygame.quit()
+    print("PASS: region drag-create, NPC add/cancel/rename, metadata preservation, undo/redo, focus isolation,")
+    print("yellow placement cursor, real character loading/animation and resent_dist, save round trip")
+
+
+if __name__ == "__main__":
+    verify()

+ 118 - 0
recovered_map_editor/verify_districts.py

@@ -0,0 +1,118 @@
+"""Verify district rendering and single copied-element previews on a temporary map."""
+import copy
+import json
+import tempfile
+from pathlib import Path
+from verify_recovery import editor, pygame, ROOT, HERE
+
+
+def verify():
+    with tempfile.TemporaryDirectory(prefix="district_overlay_") as tmp:
+        target = Path(tmp) / "map.json"
+        target.write_bytes((ROOT / "map.json").read_bytes())
+        editor.MAP_JSON_FILE_NAME = str(target)
+        update = editor.MapBuilder.update
+        editor.MapBuilder.update = lambda self: None
+        try:
+            app = editor.MapBuilder()
+        finally:
+            editor.MapBuilder.update = update
+        regions = app.tools.regions
+        assert not regions.enabled
+        app.map_json["districts"] = []
+        assert regions.entries() == []
+        sample = json.loads((ROOT / "CrimsonManorBT4.json").read_text())
+        app.map_json["districts"] = copy.deepcopy(sample["districts"])
+        snapshot = copy.deepcopy(app.map_json["districts"])
+        assert regions.entries() == [(0, (2, 3, 19, 19)), (1, (22, 3, 40, 19))]
+        app.tools.choose("floor")
+        regions.toggle()
+        assert app.tools.tool == "paint"
+        app.scroll_grid_at = [0, 0]
+        app.screen.fill((0, 0, 0))
+        regions.draw_map()
+        point = (editor.MAP_AT[0] + 2 * 40, editor.MAP_AT[1] + 3 * 40)
+        assert app.screen.get_at(point).b > 0
+        row = regions.rows()[0][2]
+        app.tools.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=row.center))
+        app.screen.fill((0, 0, 0))
+        regions.draw_map()
+        assert app.screen.get_at(point)[:3] == (0, 0, 0)
+        assert 0 in regions.hidden and 1 not in regions.hidden
+        regions.hidden.clear()
+        app.map_json["districts"] = snapshot * 4
+        assert len(regions.rows()) == 6
+        regions.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=5, pos=row.center))
+        assert regions.offset == 1 and regions.rows()[0][0] == 1
+        track, thumb = regions.scrollbar()
+        regions.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=thumb.center))
+        regions.handle_map_event(pygame.event.Event(pygame.MOUSEMOTION, pos=(thumb.centerx, track.bottom)))
+        regions.handle_map_event(pygame.event.Event(pygame.MOUSEBUTTONUP, button=1, pos=(thumb.centerx, track.bottom)))
+        assert regions.offset == 2
+        app.map_json["districts"] = copy.deepcopy(snapshot)
+        regions.offset = 0
+
+        # Arm corner editing via its icon, then drag and undo/redo.
+        row = regions.rows()[0][2]
+        regions.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=(row.right - 50, row.centery)))
+        assert regions.editing == 0
+        corner = regions.corners(0)[0][2].center
+        regions.handle_map_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=corner))
+        destination = (corner[0] + 40, corner[1] + 40)
+        regions.handle_map_event(pygame.event.Event(pygame.MOUSEMOTION, pos=destination))
+        regions.handle_map_event(pygame.event.Event(pygame.MOUSEBUTTONUP, button=1, pos=destination))
+        assert app.map_json["districts"][0]["square"]["x1"] == 3
+        app.menu.undo()
+        assert app.map_json["districts"][0]["square"]["x1"] == 2
+        app.menu.redo()
+        assert app.map_json["districts"][0]["square"]["x1"] == 3
+        app.menu.undo()
+        regions.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=(row.right - 16, row.centery)))
+        assert 0 in regions.expanded
+        npc_row = next(rect for kind, index, value, rect in regions.list_rows() if kind == "npc" and value == 0)
+        regions.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=(npc_row.right - 16, npc_row.centery)))
+        assert regions.moving_npc == (0, 0)
+        before_npc = copy.deepcopy(app.map_json["districts"][0]["npcs"][0])
+        center = regions.npc_rect(0, 0).center
+        regions.handle_map_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=center))
+        destination = (center[0] + 40, center[1] + 40)
+        regions.handle_map_event(pygame.event.Event(pygame.MOUSEMOTION, pos=destination))
+        regions.handle_map_event(pygame.event.Event(pygame.MOUSEBUTTONUP, button=1, pos=destination))
+        assert app.map_json["districts"][0]["npcs"][0]["x"] == before_npc["x"] + 1
+        app.save_map_json()
+        assert json.loads(target.read_text())["districts"][0]["npcs"][0]["x"] == before_npc["x"] + 1
+        app.menu.undo()
+        assert app.map_json["districts"][0]["npcs"][0] == before_npc
+
+        old_clip = editor.check_clipboard
+        editor.check_clipboard = lambda: ""
+        try:
+            for layer in ("floor", "obstacle"):
+                node = app.map_json[layer][0]
+                app.selection.group = [dict(layer=layer, type=node["type"], name=node["name"], x=0, y=0)]
+                app.selection.clipboard_text = ""
+                app.screen.fill((0, 0, 0))
+                app.update_clip_board()
+                preview = app.screen.subsurface(pygame.Rect(editor.PREVIEW_AT, (160, 280)))
+                assert any(pygame.image.tobytes(preview, "RGB"))
+            app.screen.fill((0, 0, 0))
+            app.update_obstacles()
+            app.redraw_floor_obstacle_trigger = True
+            app.draw_coordinators()
+            app.draw_floors_and_obstacles()
+            app.draw_map_area()
+            app.update_clip_board()
+            regions.draw_map()
+            app.tools.draw()
+            app.menu.draw()
+            pygame.image.save(app.screen, str(HERE / "districts_preview.png"))
+        finally:
+            editor.check_clipboard = old_clip
+            pygame.quit()
+        assert app.map_json["districts"] == snapshot
+    print("PASS: CrimsonManorBT4 square bounds, per-region checkboxes, scrolling, no data mutation,")
+    print("single floor/obstacle previews, 416px toolbar")
+
+
+if __name__ == "__main__":
+    verify()

+ 149 - 0
recovered_map_editor/verify_extra_tools.py

@@ -0,0 +1,149 @@
+"""Temporary-map gesture regression checks."""
+import json
+import tempfile
+from pathlib import Path
+from verify_recovery import editor, pygame
+from game.frame import obstacle
+from game.frame.frame import Frame
+from game.frame.obstacle_instance import ObstacleInstance
+
+
+with tempfile.TemporaryDirectory() as tmp:
+    target = Path(tmp) / 'map.json'
+    target.write_text(json.dumps(dict(basic=dict(name='test', width=40, height=40,
+        scroll=[0, 0], begin=[0, 0], finish=[39, 39]), floor=[], obstacle=[], districts=[])))
+    editor.MAP_JSON_FILE_NAME = str(target)
+    editor.MapBuilder.update = lambda self: None
+    app = editor.MapBuilder()
+    for name, size in [('small', 1), ('large', 2)]:
+        obstacle.obstacles.setdefault('brush_test', {})[name] = dict(TYPE='brush_test', NAME=name,
+            WIDTH=size, HEIGHT=size, STAND=[Frame(pygame.Surface((size*40, size*40)), 0, 0)])
+
+    def event(kind, x, y):
+        return pygame.event.Event(kind, button=1, pos=(editor.MAP_AT[0]+x*40+5, editor.MAP_AT[1]+y*40+5))
+
+    def drag(start, end):
+        app.menu.begin_frame()
+        down = event(pygame.MOUSEBUTTONDOWN, *start)
+        app.menu.handle_event(down)
+        assert app.placement.handle_event(down)
+        app.placement.handle_event(event(pygame.MOUSEMOTION, *end))
+        app.placement.draw()
+        app.placement.handle_event(event(pygame.MOUSEBUTTONUP, *end))
+
+    extra = app.tools.extra
+    app.tools.choose('spray')
+    app.current_elem = dict(elem_type='obstacle', type='brush_test', name='small')
+    extra.values.update(radius='2', density='100')
+    extra.spray((5, 5))
+    assert len(app.map_obstacles_dict) == 13
+    before = app.document_snapshot()
+    extra.spray((5, 5))
+    assert app.document_snapshot() == before
+    app.current_elem = dict(elem_type='obstacle', type='brush_test', name='large')
+    try:
+        extra.spray((5, 5))
+        assert False
+    except ValueError:
+        pass
+    app.tools.choose('move')
+    extra.handle_event(event(pygame.MOUSEBUTTONDOWN, 3, 3))
+    extra.handle_event(event(pygame.MOUSEBUTTONUP, 7, 7))
+    assert len(extra.sources) == 13
+    before = app.document_snapshot()
+    assert not extra.move_to((39, 39))
+    assert app.document_snapshot() == before
+    assert extra.move_to((10, 10))
+    assert len(app.map_obstacles_dict) == 13 and (5, 5) not in app.map_obstacles_dict
+    app.menu.undo()
+    assert app.document_snapshot() == before
+    app.menu.redo()
+    app.map_json['districts'] = [dict(square=dict(x1=0, y1=1, x2=8, y2=9), npcs=[dict(name='test', x=2, y=3, custom={'a': [1]})])]
+    app.map_json['floor'] = [dict(type='test', name='tile', points=[dict(x=39, y=39)])]
+    before = app.document_snapshot()
+    extra.expand(3, 4)
+    assert app.map_size == (43, 44)
+    assert app.map_json['districts'][0]['npcs'][0]['x'] == 5
+    assert app.map_json['districts'][0]['square']['y2'] == 13
+    assert app.map_json['floor'][0]['points'][0] == dict(x=42, y=43)
+    assert app.map_json['basic']['scroll'] == [3, 4]
+    app.menu.undo()
+    assert app.document_snapshot() == before
+    regions = app.tools.regions
+    regions.enabled = True
+    regions.copy_npc(0, 0)
+    regions.handle_map_event(event(pygame.MOUSEBUTTONDOWN, 12, 12))
+    assert len(app.map_json['districts'][0]['npcs']) == 2
+    copied = app.map_json['districts'][0]['npcs'][1]
+    assert copied['name'] == 'test' and copied['x'] == 12 and copied['custom'] == {'a': [1]}
+    copied['custom']['a'].append(2)
+    assert app.map_json['districts'][0]['npcs'][0]['custom'] == {'a': [1]}
+    from game.frame import floor
+    original = floor.get_floor
+    floor.get_floor = lambda *args: pygame.Surface((40, 40), pygame.SRCALPHA)
+    tile = pygame.Surface((40, 40), pygame.SRCALPHA)
+    tile.fill((255, 0, 0, 255))
+    floor.get_floor = lambda *args: tile
+    try:
+        path = extra.export()
+        img = pygame.image.load(str(path))
+        assert img.get_size() == (1600, 1600)
+        assert img.get_at((1599, 1599)) == (255, 0, 0, 255)
+        assert img.get_at((0, 0)).a == 0
+        path.unlink()
+        before_export = app.document_snapshot()
+        app.map_json['districts'].append(dict(square=dict(x1=30, y1=30, x2=34, y2=34), npcs=[dict(name='other', x=31, y=31)]))
+        regions.hidden = {0, 1}
+        regions.expanded = {0}
+        regions.solo_npc = (0, 0)
+        calls = []
+        original_draw = regions.models.draw
+        def fake_draw(surface, npc, scroll, color, frame_index=None, show_vision=True):
+            calls.append((npc['name'], frame_index, show_vision, scroll))
+            surface.fill((0, 255, 0), (npc['x']*40+10, npc['y']*40+10, 5, 5))
+            return True
+        regions.models.draw = fake_draw
+        before_export = app.document_snapshot()
+        try:
+            path = extra.export(True)
+            img = pygame.image.load(str(path))
+            assert len(calls) == 3 and all(c[1:] == (0, False, (0, 0)) for c in calls)
+            assert img.get_at((31*40+10, 31*40+10))[:3] == (0, 255, 0)
+            assert img.get_at((30*40, 30*40))[:3] == regions.COLORS[1]
+            assert app.document_snapshot() == before_export
+            path.unlink()
+        finally:
+            regions.models.draw = original_draw
+        app.tools.choose('export')
+        app.tools.draw()
+    finally:
+        floor.get_floor = original
+    app.tools.choose('spray')
+    app.tools.draw()
+    app.tools.choose('expand')
+    app.tools.draw()
+    # Keypad events may carry no Unicode text on Windows.
+    extra.focus, extra.select_all, extra.cursor = 'left', True, 1
+    extra.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_KP1, unicode=''))
+    extra.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_KP2, unicode=''))
+    assert extra.values['left'] == '12'
+    extra.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_LEFT, unicode=''))
+    extra.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_KP0, unicode=''))
+    assert extra.values['left'] == '102'
+    extra.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_DELETE, unicode=''))
+    assert extra.values['left'] == '10'
+    extra.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_KP_ENTER, unicode=''))
+    assert extra.focus is None
+    before = app.document_snapshot()
+    app.scroll_grid_at = [5, 5]
+    down = pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=2, pos=(600, 400))
+    assert app.handle_pan(down)
+    app.handle_pan(pygame.event.Event(pygame.MOUSEMOTION, pos=(680, 440)))
+    assert app.scroll_grid_at == [3, 4]
+    app.handle_pan(pygame.event.Event(pygame.MOUSEMOTION, pos=(-2000, -2000)))
+    assert app.scroll_grid_at == [13, 20]
+    app.handle_pan(pygame.event.Event(pygame.MOUSEBUTTONUP, button=2, pos=(-2000, -2000)))
+    assert app.pan_anchor is None and app.document_snapshot() == before
+    assert not app.handle_pan(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=2, pos=(1500, 400)))
+    pygame.quit()
+print('PASS: spray density and size restriction, move undo, global expansion, NPC deep copy, full-map transparent export, tool drawing')

+ 63 - 0
recovered_map_editor/verify_library.py

@@ -0,0 +1,63 @@
+"""Temporary-map gesture regression checks."""
+import json
+import tempfile
+from pathlib import Path
+from verify_recovery import editor, pygame
+from game.frame import obstacle
+from game.frame.frame import Frame
+from game.frame.obstacle_instance import ObstacleInstance
+
+
+with tempfile.TemporaryDirectory() as tmp:
+    target = Path(tmp) / 'map.json'
+    target.write_text(json.dumps(dict(basic=dict(name='test', width=40, height=40,
+        scroll=[0, 0], begin=[0, 0], finish=[39, 39]), floor=[], obstacle=[], districts=[])))
+    editor.MAP_JSON_FILE_NAME = str(target)
+    editor.MapBuilder.update = lambda self: None
+    app = editor.MapBuilder()
+    import time
+    from asset_library import scan, decode
+    lib = app.library
+    def wait_until(predicate):
+        deadline = time.monotonic()+30
+        while not predicate():
+            lib.update()
+            if time.monotonic() > deadline:
+                raise AssertionError('background load timeout')
+            time.sleep(0.005)
+    try:
+        lib.toggle()
+        lib.choose_library('common')
+        lib.choose_library('crimson_manor')
+        wait_until(lambda: lib.scan_job is None and not lib.pending and not lib.jobs and bool(lib.entries))
+        assert all(e['type'] == 'crimson_manor' for e in lib.entries)
+        assert any(e['elem_type'] == 'floor' for e in lib.entries)
+        assert any(e['elem_type'] == 'obstacle' for e in lib.entries)
+        assert all(e['thumbnail'].get_size() == (112, 88) for e in lib.entries)
+        for kind in ('floor', 'obstacle'):
+            entry = next(e for e in lib.entries if e['elem_type'] == kind)
+            lib.selected_job = lib.pool.submit(decode, lib.root, entry, True)
+            wait_until(lambda: lib.selected_job is None)
+            assert app.current_elem['name'] == entry['name'] and len(app.selection.group) == 1
+            app.menu.block_pointer = False
+            pos = (editor.MAP_AT[0]+405, editor.MAP_AT[1]+405)
+            assert app.placement.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=pos))
+            app.placement.handle_event(pygame.event.Event(pygame.MOUSEBUTTONUP, button=1, pos=pos))
+        assert (10, 10) in app.map_obstacles_dict
+        app.menu.undo()
+        assert (10, 10) not in app.map_obstacles_dict
+        lib.draw()
+        app.menu.draw()
+        app.settings.draw_speaker()
+        lib.draw_button()
+        pygame.image.save(app.screen, 'recovered_map_editor/library_preview.png')
+        lib.dropdown = True
+        lib.scroll(10000)
+        lib.draw()
+        lib.choose_library('missing_test_directory')
+        wait_until(lambda: lib.scan_job is None)
+        assert not lib.entries
+        print('PASS: concurrent loading, stale job isolation, thumbnails, floor/obstacle selection and placement, undo, dropdown scrolling, invalid directory')
+    finally:
+        lib.close()
+        pygame.quit()

+ 140 - 0
recovered_map_editor/verify_menu.py

@@ -0,0 +1,140 @@
+"""Regression checks for menus, history, and save routing on temporary maps."""
+import copy
+import json
+import tempfile
+from pathlib import Path
+
+from verify_recovery import editor, pygame, ROOT, HERE
+
+
+def verify():
+    original = (ROOT / "map.json").read_bytes()
+    with tempfile.TemporaryDirectory(prefix="editor_menu_") as tmp:
+        target = Path(tmp) / "map.json"
+        target.write_bytes(original)
+        editor.MAP_JSON_FILE_NAME = str(target)
+        update = editor.MapBuilder.update
+        editor.MapBuilder.update = lambda self: None
+        try:
+            app = editor.MapBuilder()
+        finally:
+            editor.MapBuilder.update = update
+        menu = app.menu
+        initial = menu.snapshot()
+        node = app.map_json["floor"][0]
+        app.current_elem = dict(elem_type="floor", type=node["type"], name=node["name"])
+        down = pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=(editor.MAP_AT[0] + 60, editor.MAP_AT[1] + 60))
+        up = pygame.event.Event(pygame.MOUSEBUTTONUP, button=1, pos=down.pos)
+        menu.handle_event(down)
+        menu.edit(lambda: app.add_elem([1, 1]))
+        menu.edit(lambda: app.add_elem([2, 1]))
+        menu.handle_event(up)
+        drawn = menu.snapshot()
+        assert len(menu.undo_stack) == 1 and drawn != initial
+        menu.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_z, mod=pygame.KMOD_CTRL))
+        assert menu.snapshot() == initial
+        menu.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_z, mod=pygame.KMOD_CTRL | pygame.KMOD_SHIFT))
+        assert menu.snapshot() == drawn
+        menu.undo()
+        menu.edit(lambda: app.add_elem([3, 1]))
+        assert not menu.redo_stack
+        menu.undo()
+        assert menu.snapshot() == initial
+
+        if initial["obstacle"]:
+            node = initial["obstacle"][0]
+            app.current_elem = dict(elem_type="obstacle", type=node["type"], name=node["name"])
+            # Create a known empty area: the live map may have obstacles at (1, 1).
+            app.map_obstacles_dict.clear()
+            obstacle_before = menu.snapshot()
+            menu.edit(lambda: app.add_elem([1, 1]))
+            placed = menu.snapshot()
+            menu.undo()
+            assert menu.snapshot() == obstacle_before
+            menu.redo()
+            assert menu.snapshot() == placed
+            menu.edit(lambda: app.remove_elem([1, 1], "obstacle"))
+            menu.undo()
+            assert menu.snapshot() == placed
+        menu.edit(lambda: setattr(app, "begin_at", [3, 3]))
+        menu.undo()
+        assert app.begin_at == initial["basic"]["begin"]
+        menu.redo()
+        assert app.begin_at == [3, 3]
+
+        # Only text headings open dropdowns; arrows act immediately.
+        for name, rect in menu.buttons:
+            if name in ("undo", "redo"):
+                continue
+            menu.active = None
+            assert menu.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=rect.center))
+            assert menu.active == name and menu.blocks_editing()
+            assert menu.handle_event(down)
+            assert menu.active is None and menu.blocks_editing()
+            menu.handle_event(up)
+            menu.begin_frame()
+        arrow_rects = dict(menu.buttons)
+        def click_arrow(name):
+            menu.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=arrow_rects[name].center))
+            assert menu.active is None
+            menu.handle_event(up)
+            menu.begin_frame()
+        before_arrow = menu.snapshot()
+        click_arrow("undo")
+        assert menu.snapshot() != before_arrow
+        click_arrow("redo")
+        assert menu.snapshot() == before_arrow
+        menu.undo_stack.clear()
+        menu.redo_stack.clear()
+        for name in ("undo", "redo"):
+            assert not menu.button_enabled(name)
+            click_arrow(name)
+            assert menu.snapshot() == before_arrow
+        menu.active = "文件"
+        menu.handle_event(pygame.event.Event(pygame.MOUSEMOTION, pos=arrow_rects["undo"].center))
+        assert menu.active == "文件"
+        menu.active = "工具"
+        popup = menu.popup_rect()
+        menu.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=(popup.x + 16, popup.y + 16)))
+        assert menu.show_grid
+
+        state = menu.snapshot()
+        menu.save()
+        assert json.loads(target.read_text())["floor"] == state["floor"]
+        new_target = Path(tmp) / "saved_as.json"
+        menu.dialog = lambda *args, **kwargs: str(new_target)
+        menu.save_as()
+        assert app.map_path == str(new_target) and new_target.exists()
+        assert json.loads(new_target.read_text())["obstacle"] == state["obstacle"]
+        menu.dialog = lambda *args, **kwargs: ""
+        menu.save_as()
+        assert app.map_path == str(new_target)
+        menu.dialog = lambda *args, **kwargs: str(Path(tmp) / "missing" / "bad.json")
+        try:
+            menu.save_as()
+        except FileNotFoundError:
+            pass
+        else:
+            raise AssertionError("Expected save failure")
+        assert app.map_path == str(new_target)
+        assert menu.snapshot() == state
+
+        app.screen.fill((0, 0, 0))
+        app.update_obstacles()
+        app.draw_coordinators()
+        app.draw_floors_and_obstacles()
+        app.draw_map_area()
+        menu.draw_grid()
+        menu.active = "编辑"
+        menu.draw()
+        pygame.image.save(app.screen, str(HERE / "menu_preview.png"))
+        assert app.screen.get_size() == (1776, 872)
+        pygame.quit()
+    assert (ROOT / "map.json").read_bytes() == original
+    print("PASS: three dropdowns, direct undo/redo arrows, disabled clicks, click isolation, grouped history,")
+    print("obstacle and spawn history, grid toggle, save-as/cancel/failure, 27x20 viewport")
+    print("Original map unchanged")
+
+
+if __name__ == "__main__":
+    verify()

+ 72 - 0
recovered_map_editor/verify_open.py

@@ -0,0 +1,72 @@
+"""Temporary-map gesture regression checks."""
+import json
+import tempfile
+from pathlib import Path
+from verify_recovery import editor, pygame
+from game.frame import obstacle
+from game.frame.frame import Frame
+from game.frame.obstacle_instance import ObstacleInstance
+
+
+with tempfile.TemporaryDirectory() as tmp:
+    target = Path(tmp) / 'map.json'
+    target.write_text(json.dumps(dict(basic=dict(name='test', width=40, height=40,
+        scroll=[0, 0], begin=[0, 0], finish=[39, 39]), floor=[], obstacle=[], districts=[])))
+    editor.MAP_JSON_FILE_NAME = str(target)
+    editor.MapBuilder.update = lambda self: None
+    app = editor.MapBuilder()
+    menu = app.menu
+    original = target.read_bytes()
+    source = Path(tmp) / 'import.json'
+    data = json.loads(original)
+    data['basic'].update(width=45, height=30, scroll=[4, 5], name='imported')
+    source.write_text(json.dumps(data), encoding='utf-8')
+    source_original = source.read_bytes()
+    menu.dialog = lambda *args, **kwargs: str(source)
+    menu.open_map()
+    backups = list(Path(tmp).glob('map_*.json'))
+    assert len(backups) == 1 and backups[0].read_bytes() == original
+    assert not target.exists() and app.map_path == str(target.resolve())
+    assert app.map_size == (45, 30) and app.scroll_grid_at == [4, 5]
+    menu.save()
+    assert json.loads(target.read_text())['basic']['name'] == 'imported'
+    assert source.read_bytes() == source_original
+    menu.open_map()
+    assert len(list(Path(tmp).glob('map_*.json'))) == 1
+    before = app.document_snapshot()
+    menu.dialog = lambda *args, **kwargs: ''
+    menu.open_map()
+    assert app.document_snapshot() == before
+    bad = Path(tmp) / 'bad.json'
+    bad.write_text('{}')
+    menu.dialog = lambda *args, **kwargs: str(bad)
+    try:
+        menu.open_map()
+        assert False
+    except KeyError:
+        pass
+    assert app.document_snapshot() == before and target.exists()
+    # Legacy scenery can cross edges or have an anchor outside the canvas.
+    from game.frame import floor
+    original_floor = floor.get_floor
+    floor.get_floor = lambda *args: pygame.Surface((40, 40), pygame.SRCALPHA)
+    obstacle.obstacles.setdefault('open_test', {})['large'] = dict(
+        TYPE='open_test', NAME='large', WIDTH=2, HEIGHT=2,
+        STAND=[Frame(pygame.Surface((80, 80)), 0, 0)])
+    data['floor'] = [dict(type='test', name='tile', points=[dict(x=-1, y=2), dict(x=45, y=30)])]
+    data['obstacle'] = [dict(type='open_test', name='large', points=[dict(x=44, y=29), dict(x=-2, y=5)])]
+    source.write_text(json.dumps(data), encoding='utf-8')
+    menu.dialog = lambda *args, **kwargs: str(source)
+    try:
+        menu.open_map()
+        app.draw_floors_and_obstacles()
+        menu.save()
+        saved = json.loads(target.read_text())
+        assert saved['floor'] == data['floor']
+        assert saved['obstacle'] == data['obstacle']
+        assert app.map_size == (45, 30)
+        assert json.loads(source.read_text()) == data
+    finally:
+        floor.get_floor = original_floor
+    pygame.quit()
+print('PASS: open, first-open rename backup, default save, source untouched, repeated open, cancel, invalid input, out-of-bounds scenery preserved on open/render/save')

+ 73 - 0
recovered_map_editor/verify_placement.py

@@ -0,0 +1,73 @@
+"""Temporary-map gesture regression checks."""
+import json
+import tempfile
+from pathlib import Path
+from verify_recovery import editor, pygame
+from game.frame import obstacle
+from game.frame.frame import Frame
+from game.frame.obstacle_instance import ObstacleInstance
+
+
+with tempfile.TemporaryDirectory() as tmp:
+    target = Path(tmp) / 'map.json'
+    target.write_text(json.dumps(dict(basic=dict(name='test', width=40, height=40,
+        scroll=[0, 0], begin=[0, 0], finish=[39, 39]), floor=[], obstacle=[], districts=[])))
+    editor.MAP_JSON_FILE_NAME = str(target)
+    editor.MapBuilder.update = lambda self: None
+    app = editor.MapBuilder()
+    for name, size in [('small', 1), ('large', 2)]:
+        obstacle.obstacles.setdefault('brush_test', {})[name] = dict(TYPE='brush_test', NAME=name,
+            WIDTH=size, HEIGHT=size, STAND=[Frame(pygame.Surface((size*40, size*40)), 0, 0)])
+
+    def event(kind, x, y):
+        return pygame.event.Event(kind, button=1, pos=(editor.MAP_AT[0]+x*40+5, editor.MAP_AT[1]+y*40+5))
+
+    def drag(start, end):
+        app.menu.begin_frame()
+        down = event(pygame.MOUSEBUTTONDOWN, *start)
+        app.menu.handle_event(down)
+        assert app.placement.handle_event(down)
+        app.placement.handle_event(event(pygame.MOUSEMOTION, *end))
+        app.placement.draw()
+        app.placement.handle_event(event(pygame.MOUSEBUTTONUP, *end))
+
+    app.current_elem = dict(elem_type='floor', type='test', name='tile')
+    drag((4, 4), (2, 2))
+    assert len(app.map_json['floor'][0]['points']) == 9
+    assert len(app.menu.undo_stack) == 1
+    app.menu.undo()
+    assert not app.map_json['floor']
+    app.menu.redo()
+    app.selection.group = [dict(layer='obstacle', type='brush_test', name='small', x=0, y=0)]
+    drag((2, 2), (4, 4))
+    assert len(app.map_obstacles_dict) == 9
+    assert len(app.map_json['floor'][0]['points']) == 9
+    app.selection.cancel()
+    app.current_elem = dict(elem_type='obstacle', type='brush_test', name='large')
+    before = app.document_snapshot()
+    count = len(app.menu.undo_stack)
+    drag((1, 1), (5, 1))
+    assert len(app.menu.undo_stack) == count + 1
+    assert app.map_obstacles_dict[(5, 1)] is app.map_obstacles_dict[(6, 2)]
+    assert (2, 2) not in app.map_obstacles_dict
+    after = app.document_snapshot()
+    app.menu.undo()
+    assert app.document_snapshot() == before
+    app.menu.redo()
+    assert app.document_snapshot() == after
+    app.menu.begin_frame()
+    app.placement.handle_event(event(pygame.MOUSEBUTTONDOWN, 10, 10))
+    app.placement.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_ESCAPE))
+    assert app.document_snapshot() == after
+    app.scroll_grid_at = [13, 20]
+    drag((26, 19), (26, 19))  # Entire large footprint must fit the map.
+    assert app.document_snapshot() == after
+    app.scroll_grid_at = [0, 0]
+    pygame.key.set_mods(pygame.KMOD_SHIFT)
+    app.menu.begin_frame()
+    assert not app.placement.handle_event(event(pygame.MOUSEBUTTONDOWN, 2, 2))
+    pygame.key.set_mods(0)
+    app.save_map_json()
+    assert json.loads(target.read_text()) == app.document_snapshot()
+    pygame.quit()
+print('PASS: rectangle fill, copied single brush, replacing large strokes, one-step undo/redo, cancel, bounds, Shift, save')

+ 92 - 0
recovered_map_editor/verify_recovery.py

@@ -0,0 +1,92 @@
+"""Headless verification. All map writes go to a temporary directory."""
+from pathlib import Path
+import copy
+import hashlib
+import json
+import os
+import sys
+import tempfile
+
+HERE = Path(__file__).resolve().parent
+ROOT = HERE.parent
+os.environ["SDL_VIDEODRIVER"] = "dummy"
+os.environ["SDL_AUDIODRIVER"] = "dummy"
+sys.path.insert(0, str(ROOT / ".codex_build" / "map_editor_runtime"))
+sys.path.insert(0, str(HERE / "source"))
+os.chdir(str(ROOT))
+import main as editor
+import pygame
+
+def verify():
+    original = (ROOT / "map.json").read_bytes()
+    with tempfile.TemporaryDirectory(prefix="recovered_editor_") as tmp:
+        target = Path(tmp) / "map.json"
+        target.write_bytes(original)
+        editor.MAP_JSON_FILE_NAME = str(target)
+        update = editor.MapBuilder.update
+        editor.MapBuilder.update = lambda self: None
+        try:
+            app = editor.MapBuilder()
+        finally:
+            editor.MapBuilder.update = update
+        app.update_obstacles()
+        app.draw_coordinators()
+        app.draw_floors_and_obstacles()
+        app.draw_map_area()
+        app.menu.draw()
+        pygame.image.save(app.screen, str(HERE / "preview.png"))
+
+        # All four viewport edges must reject outside clicks.
+        mouse = pygame.mouse.get_pos
+        try:
+            left, top = editor.MAP_AT
+            for point in [(left - 1, top), (left, top - 1), (left + editor.MAP_W, top), (left, top + editor.MAP_H)]:
+                pygame.mouse.get_pos = lambda p=point: p
+                assert app._MapBuilder__get_mouse_pos() is None, point
+            pygame.mouse.get_pos = lambda: editor.MAP_AT
+            assert app._MapBuilder__get_mouse_pos() == app.scroll_grid_at
+        finally:
+            pygame.mouse.get_pos = mouse
+
+        before = copy.deepcopy(app.map_json)
+        floor_node = before["floor"][0]
+        app.current_elem = dict(elem_type="floor", type=floor_node["type"], name=floor_node["name"])
+        app.add_elem([1, 1])
+        assert any(p == {"x": 1, "y": 1} for e in app.map_json["floor"] for p in e["points"])
+        app.remove_elem([1, 1], "floor")
+        assert not any(p == {"x": 1, "y": 1} for e in app.map_json["floor"] for p in e["points"])
+        app.map_json = copy.deepcopy(before)
+        if before["obstacle"]:
+            node = before["obstacle"][0]
+            app.current_elem = dict(elem_type="obstacle", type=node["type"], name=node["name"])
+            app.add_elem([1, 1])
+            assert (1, 1) in app.map_obstacles_dict
+            app.remove_elem([1, 1], "obstacle")
+            assert (1, 1) not in app.map_obstacles_dict
+            app.map_obstacles_dict.clear()
+            app.load_map_json()
+        app.save_map_json()
+        saved = json.loads(target.read_text())
+        assert saved["floor"] == before["floor"]
+        assert saved["basic"] == before["basic"]
+        for key in before.keys() - {"basic", "floor", "obstacle"}:
+            assert saved[key] == before[key], key
+        def positions(nodes):
+            return {(n["type"], n["name"], p["x"], p["y"]) for n in nodes for p in n["points"]}
+        assert positions(saved["obstacle"]) == positions(before["obstacle"])
+        app.map_obstacles_dict.clear()
+        app.load_map_json()
+        app.redraw_floor_obstacle_trigger = True
+        app.draw_floors_and_obstacles()
+        # Exercise the real event-loop exit/save path.
+        pygame.event.post(pygame.event.Event(pygame.QUIT))
+        try:
+            app.update()
+        except SystemExit:
+            pass
+    assert (ROOT / "map.json").read_bytes() == original
+    print("PASS: initialize/render, viewport bounds, floor and obstacle edit, save/reload, quit/save")
+    print("Original map unchanged:", hashlib.sha256(original).hexdigest())
+
+if __name__ == "__main__":
+    verify()

+ 103 - 0
recovered_map_editor/verify_selection.py

@@ -0,0 +1,103 @@
+"""Group placement regression checks using an entirely temporary map."""
+import json
+import tempfile
+from pathlib import Path
+from verify_recovery import editor, pygame
+from game.frame import obstacle
+from game.frame.frame import Frame
+from game.frame.obstacle_instance import ObstacleInstance
+
+
+def verify():
+    with tempfile.TemporaryDirectory(prefix="editor_selection_") as tmp:
+        target = Path(tmp) / "map.json"
+        data = dict(basic=dict(name="test", width=40, height=40, scroll=[0, 0], begin=[0, 0], finish=[39, 39]),
+                    floor=[], obstacle=[], districts=[])
+        target.write_text(json.dumps(data))
+        editor.MAP_JSON_FILE_NAME = str(target)
+        update = editor.MapBuilder.update
+        editor.MapBuilder.update = lambda self: None
+        try:
+            app = editor.MapBuilder()
+        finally:
+            editor.MapBuilder.update = update
+        for name, width, height in [("large", 2, 2), ("small", 1, 1)]:
+            obstacle.obstacles.setdefault("selection_test", {})[name] = dict(
+                TYPE="selection_test", NAME=name, WIDTH=width, HEIGHT=height,
+                STAND=[Frame(pygame.Surface((width * 40, height * 40)), 0, 0)])
+        large = obstacle.get_obstacle("selection_test", "large")
+        small = obstacle.get_obstacle("selection_test", "small")
+        ObstacleInstance(2, 2, app.map_obstacles_dict, large)
+        ObstacleInstance(6, 2, app.map_obstacles_dict, large)
+        selection = app.selection
+        selection.copy_rectangle((7, 3), (3, 2), "obstacle")
+        assert len(selection.group) == 2  # Partial selection includes the full object, once.
+        before = app.document_snapshot()
+        ObstacleInstance(15, 11, app.map_obstacles_dict, small)
+        blocked = app.document_snapshot()
+        assert not selection.place((10, 10))  # Collision in the second object's far corner.
+        assert app.document_snapshot() == blocked and (10, 10) not in app.map_obstacles_dict
+        app.remove_elem((15, 11), "obstacle")
+        assert not selection.place((39, 39))
+        assert app.document_snapshot() == before
+        app.menu.edit(lambda: selection.place((10, 10)))
+        placed = app.document_snapshot()
+        assert (11, 11) in app.map_obstacles_dict and (15, 11) in app.map_obstacles_dict
+        app.menu.undo()
+        assert app.document_snapshot() == before
+        app.menu.redo()
+        assert app.document_snapshot() == placed
+        assert not selection.place((10, 10))  # Existing copies may not be replaced.
+        app.current_elem = dict(elem_type="obstacle", type="selection_test", name="large")
+        app.add_elem((9, 9))
+        assert app.map_obstacles_dict[(9, 9)] is app.map_obstacles_dict[(10, 10)]
+        assert (11, 11) not in app.map_obstacles_dict  # Overlapping object removed entirely.
+        app.restore_document(placed)
+
+        app.map_json["floor"] = [dict(type="test", name="tile", points=[dict(x=0, y=0), dict(x=1, y=0)])]
+        selection.copy_rectangle((0, 0), (1, 0), "floor")
+        floor_before = app.document_snapshot()
+        assert selection.place((1, 2))  # Floor placement ignores obstacles without modifying them.
+        assert app.document_snapshot()["obstacle"] == floor_before["obstacle"]
+        assert selection.plan((1, 2))[0] and not selection.conflicts
+        assert {"x": 2, "y": 2} in app.map_json["floor"][0]["points"]
+        app.current_elem = dict(elem_type="floor", type="test", name="tile")
+        app.add_elem((3, 3))
+        assert {"x": 3, "y": 3} in app.map_json["floor"][0]["points"]
+        assert app.document_snapshot()["obstacle"] == floor_before["obstacle"]
+        before_bounds = app.document_snapshot()
+        assert not selection.place((39, 39))
+        assert app.document_snapshot() == before_bounds
+        assert selection.place((20, 20))
+        selection.cancel()
+        assert not selection.group
+
+        # Exercise Shift-drag events, reverse direction, and release outside the viewport.
+        pygame.key.set_mods(pygame.KMOD_SHIFT)
+        def pos(x, y):
+            return (editor.MAP_AT[0] + x * 40 + 5, editor.MAP_AT[1] + y * 40 + 5)
+        app.show_obstacle = True
+        selection.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=pos(7, 3)))
+        selection.handle_event(pygame.event.Event(pygame.MOUSEMOTION, pos=pos(2, 2)))
+        selection.handle_event(pygame.event.Event(pygame.MOUSEBUTTONUP, button=1, pos=pos(2, 2)))
+        assert selection.start is None and len(selection.group) == 2
+        pygame.key.set_mods(0)
+        app.menu.begin_frame()
+        app.menu.undo_stack.clear()
+        app.menu.redo_stack.clear()
+        event = pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=pos(20, 10))
+        app.menu.handle_event(event)
+        assert selection.handle_event(event)
+        app.menu.handle_event(pygame.event.Event(pygame.MOUSEBUTTONUP, button=1, pos=event.pos))
+        assert len(app.menu.undo_stack) == 1 and (24, 10) in app.map_obstacles_dict
+        app.menu.undo()
+        assert (24, 10) not in app.map_obstacles_dict
+        app.save_map_json()
+        assert target.exists()
+        pygame.quit()
+    print("PASS: Shift-drag copy, full-object deduplication, full-footprint collision, atomic rejection,")
+    print("bounds, floors ignore obstacles, direct group placement, undo/redo, large-obstacle replacement")
+
+
+if __name__ == "__main__":
+    verify()

+ 101 - 0
recovered_map_editor/verify_settings.py

@@ -0,0 +1,101 @@
+"""Temporary-map checks for metadata, music, and independent game scroll."""
+import json
+import tempfile
+from pathlib import Path
+from verify_recovery import editor, pygame, ROOT, HERE
+
+
+def verify():
+    with tempfile.TemporaryDirectory(prefix="map_settings_") as tmp:
+        target = Path(tmp) / "map.json"
+        target.write_bytes((ROOT / "map.json").read_bytes())
+        editor.MAP_JSON_FILE_NAME = str(target)
+        update = editor.MapBuilder.update
+        editor.MapBuilder.update = lambda self: None
+        try:
+            app = editor.MapBuilder()
+        finally:
+            editor.MapBuilder.update = update
+        settings = app.settings
+        music_rect = settings.fields[2][2]
+        settings.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=music_rect.center))
+        settings.handle_event(pygame.event.Event(pygame.TEXTINPUT, text="abcd.ogg"))
+        def key(k):
+            settings.handle_event(pygame.event.Event(pygame.KEYDOWN, key=k, mod=0))
+        key(pygame.K_HOME)
+        key(pygame.K_RIGHT)
+        key(pygame.K_RIGHT)
+        settings.handle_event(pygame.event.Event(pygame.TEXTINPUT, text="X"))
+        assert settings.values["music"] == "abXcd.ogg"
+        key(pygame.K_DELETE)
+        assert settings.values["music"] == "abXd.ogg"
+        key(pygame.K_BACKSPACE)
+        assert settings.values["music"] == "abd.ogg" and settings.cursor == 2
+        key(pygame.K_LEFT)
+        key(pygame.K_BACKSPACE)
+        assert settings.values["music"] == "bd.ogg" and settings.cursor == 0
+        key(pygame.K_END)
+        assert settings.cursor == len(settings.values["music"])
+        before_revert = app.document_snapshot()
+        settings.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=settings.revert.center))
+        assert settings.values["music"] == str(app.map_json["basic"].get("music", ""))
+        assert app.document_snapshot() == before_revert and settings.focus is None
+        initial = app.document_snapshot()
+        app.scroll_grid_at = [7, 5]
+        app.save_map_json()
+        assert json.loads(target.read_text())["basic"]["scroll"] == initial["basic"]["scroll"]
+        settings.set_scroll((3, 4))
+        assert app.map_json["basic"]["scroll"] == [3, 4] and app.scroll_grid_at == [7, 5]
+        app.save_map_json()
+        assert json.loads(target.read_text())["basic"]["scroll"] == [3, 4]
+        app.menu.undo()
+        assert app.map_json["basic"]["scroll"] == initial["basic"]["scroll"]
+        app.menu.redo()
+        assert app.map_json["basic"]["scroll"] == [3, 4]
+
+        original_width = app.map_size[0]
+        rect = settings.fields[0][2]
+        assert settings.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=rect.center))
+        settings.handle_event(pygame.event.Event(pygame.TEXTINPUT, text=str(original_width + 2)))
+        assert settings.values["width"] == str(original_width + 2)
+        track = next(p for p in (ROOT / "res/music").glob("*.ogg") if p.name.lower() != "none.ogg")
+        settings.values["music"] = track.name
+        settings.apply()
+        assert app.map_size[0] == original_width + 2
+        assert app.map_json["basic"]["scroll"] == [3, 4]
+        assert pygame.mixer.music.get_busy()
+        settings.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=settings.speaker.center))
+        assert settings.muted and pygame.mixer.music.get_volume() == 0
+        settings.toggle_music()
+        assert pygame.mixer.music.get_volume() > 0
+        app.menu.undo()
+        assert app.map_size[0] == original_width
+        unchanged = app.document_snapshot()
+        settings.values["width"] = "invalid"
+        settings.apply()
+        assert app.document_snapshot() == unchanged
+        settings.sync()
+        settings.values["music"] = "__no_such_music__.ogg"
+        settings.apply()
+        assert app.document_snapshot() == unchanged
+        settings.sync()
+        app.scroll_grid_at = [0, 0]
+        app.screen.fill((0, 0, 0))
+        app.update_obstacles()
+        app.draw_coordinators()
+        app.draw_floors_and_obstacles()
+        app.draw_map_area()
+        settings.draw_view()
+        app.tools.draw()
+        app.menu.draw()
+        settings.draw_speaker()
+        pygame.image.save(app.screen, str(HERE / "settings_preview.png"))
+        app.save_map_json()
+        assert json.loads(target.read_text())["basic"]["scroll"] == [3, 4]
+        pygame.quit()
+    print("PASS: initial scroll independent of editor camera, set/undo/save, metadata text input/validation,")
+    print("resize undo, looping music load and mute/unmute on dummy audio driver")
+
+
+if __name__ == "__main__":
+    verify()

+ 129 - 0
recovered_map_editor/verify_tools.py

@@ -0,0 +1,129 @@
+"""Temporary-map checks for tool panel, erasers, and per-cell copy preview."""
+import copy
+import tempfile
+from pathlib import Path
+from verify_recovery import editor, pygame, ROOT, HERE
+from game.frame import obstacle
+from game.frame.frame import Frame
+from game.frame.obstacle_instance import ObstacleInstance
+
+
+def verify():
+    with tempfile.TemporaryDirectory(prefix="editor_tools_") as tmp:
+        target = Path(tmp) / "map.json"
+        target.write_bytes((ROOT / "map.json").read_bytes())
+        editor.MAP_JSON_FILE_NAME = str(target)
+        update = editor.MapBuilder.update
+        editor.MapBuilder.update = lambda self: None
+        try:
+            app = editor.MapBuilder()
+        finally:
+            editor.MapBuilder.update = update
+        original = app.document_snapshot()
+        tools = app.tools
+        assert tools.sizes() == []
+        assert tools.visible and app.screen.get_size() == (1776, 872)
+        tools.toggle()
+        assert not tools.visible and app.screen.get_size() == (1776, 872)
+        tools.choose("floor")
+        assert tools.visible
+        for n, rect in tools.sizes():
+            tools.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=rect.center))
+            assert tools.size == n
+        app.map_size = (40, 40)
+        app.map_json["basic"]["width"] = app.map_json["basic"]["height"] = 40
+        app.map_obstacles_dict.clear()
+        obs = dict(TYPE="tools_test", NAME="large", WIDTH=2, HEIGHT=2,
+                   STAND=[Frame(pygame.Surface((80, 80)), 0, 0)])
+        obstacle.obstacles["tools_test"] = {"large": obs}
+        ObstacleInstance(3, 3, app.map_obstacles_dict, obs)
+        for size in range(1, 16):
+            app.map_json["floor"] = [dict(type="test", name="tile", points=[dict(x=x, y=y) for x in range(20) for y in range(20)])]
+            tools.size = size
+            tools.erase((10, 10))
+            bounds = tools.erase_bounds((10, 10))
+            assert bounds == (10 - (size - 1) // 2, 10 - (size - 1) // 2,
+                              10 - (size - 1) // 2 + size, 10 - (size - 1) // 2 + size)
+            assert len(app.map_json["floor"][0]["points"]) == 400 - size * size
+            assert (3, 3) in app.map_obstacles_dict
+        tools.choose("obstacle")
+        tools.size = 1
+        before = app.document_snapshot()
+        app.menu.edit(lambda: tools.erase((4, 4)))
+        assert not app.map_obstacles_dict
+        assert app.map_json["floor"] == before["floor"]
+        app.menu.undo()
+        assert app.document_snapshot() == before
+        app.menu.redo()
+        assert not app.map_obstacles_dict
+        tools.choose("floor")
+        tools.size = 15
+        app.map_json["floor"] = [dict(type="test", name="tile", points=[dict(x=39, y=39), dict(x=38, y=39)])]
+        tools.erase((39, 39))
+        assert app.map_json["floor"][0]["points"] == []
+        assert tools.erase_bounds((39, 39)) == (32, 32, 40, 40)
+        assert tools.erase_bounds((0, 0)) == (0, 0, 8, 8)
+
+        # A rapid drag interpolates cells and remains one undo step.
+        app.map_json["floor"][0]["points"] = [dict(x=x, y=0) for x in range(8)]
+        tools.size = 1
+        app.scroll_grid_at = [0, 0]
+        app.menu.block_pointer = False
+        app.menu.undo_stack.clear()
+        def event(kind, x):
+            values = dict(pos=(editor.MAP_AT[0] + x * 40 + 4, editor.MAP_AT[1] + 4))
+            if kind != pygame.MOUSEMOTION:
+                values["button"] = 1
+            return pygame.event.Event(kind, **values)
+        down = event(pygame.MOUSEBUTTONDOWN, 0)
+        app.menu.handle_event(down)
+        tools.handle_event(down)
+        tools.handle_event(event(pygame.MOUSEMOTION, 7))
+        up = event(pygame.MOUSEBUTTONUP, 7)
+        app.menu.handle_event(up)
+        tools.handle_event(up)
+        assert not app.map_json["floor"][0]["points"] and len(app.menu.undo_stack) == 1
+        app.menu.undo()
+        assert len(app.map_json["floor"][0]["points"]) == 8
+
+        # Render conflicts red, other copied cells gray (not whole-group red).
+        tools.choose("paint")
+        assert tools.sizes() == []
+        old_size = tools.size
+        tools.handle_event(pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1,
+                                             pos=(editor.WINDOW_W + 30, 420)))
+        assert tools.size == old_size
+        app.selection.group = [dict(layer="obstacle", type="tools_test", name="large", x=0, y=0)]
+        ObstacleInstance(5, 5, app.map_obstacles_dict, obs)
+        valid, nodes, cells = app.selection.plan((4, 4))
+        assert not valid and app.selection.conflicts == {(5, 5)}
+        mouse = pygame.mouse.get_pos
+        try:
+            pygame.mouse.get_pos = lambda: (editor.MAP_AT[0] + 4 * 40 + 10, editor.MAP_AT[1] + 4 * 40 + 10)
+            app.menu.block_pointer = False
+            app.screen.fill((0, 0, 0))
+            app.selection.draw()
+            gray = app.screen.get_at(pygame.mouse.get_pos())
+            red = app.screen.get_at((editor.MAP_AT[0] + 5 * 40 + 10, editor.MAP_AT[1] + 5 * 40 + 10))
+            assert gray.r == gray.g == gray.b and red.r > red.g
+            app.restore_document(original)
+            tools.choose("floor")
+            tools.size = 3
+            app.screen.fill((0, 0, 0))
+            app.update_obstacles()
+            app.draw_coordinators()
+            app.draw_floors_and_obstacles()
+            app.draw_map_area()
+            tools.draw_preview()
+            tools.draw()
+            app.menu.draw()
+            pygame.image.save(app.screen, str(HERE / "tools_preview.png"))
+        finally:
+            pygame.mouse.get_pos = mouse
+            pygame.quit()
+    print("PASS: toolbar show/hide, all 15 sizes, floor/obstacle isolation, multi-cell removal,")
+    print("edge clipping, interpolated drag undo/redo, red conflict cells and gray free cells")
+
+
+if __name__ == "__main__":
+    verify()

+ 37 - 0
resource_tool/README.md

@@ -0,0 +1,37 @@
+# 动画抽帧工具
+
+可直接双击 `AnimationFrameTool.exe`,无需安装 Python 或 FFmpeg,可将 EXE 单独复制到其他 Windows 电脑使用。
+
+从源码运行时首次安装依赖:`python -m pip install -r requirements.txt`。
+
+双击 `启动工具.bat`,或在本目录执行 `python main.py`。需要带 Tkinter 的 Python 3.9 或更新版本;Windows 官方 Python 安装包默认包含 Tkinter。
+
+重新打包:先安装 PyInstaller(`python -m pip install pyinstaller`),再运行 `打包EXE.bat`。生成单文件无控制台窗口的 `AnimationFrameTool.exe`,包含 GIF、WebM 解码所需依赖。
+
+1. 选择 GIF 或 WebM,工具解析总帧数并自动播放采样结果,每 100ms 一帧循环播放。可暂停 / 继续,显示当前采样序号和原始帧号。
+2. 设置采样帧数和文件名前缀。按帧序号均匀抽取,包含首尾;只抽 1 帧时取首帧。采样数不能超过总帧数。不同帧停留时间不影响采样。
+3. 设置裁剪边界位置,百分比均相对于原图:左、上默认 0%,右、下默认 100%。例如左 25%、右 75%,表示保留横向中间一半。像素边界四舍五入。
+4. 可选择指定宽度或高度,另一边按裁剪后比例计算,取整至最近像素;默认不缩放。
+5. 选择输出目录,点击“导出 PNG”。命名为 `前缀_0.png`、`前缀_1.png`……;不会覆盖已有同名文件。
+
+修改采样帧数、裁剪、缩放会自动更新播放预览。预览使用与导出相同的抽帧和图像处理规则,使用 PNG 无损压缩缓存选中的帧。左侧设置区支持滚动条和鼠标滚轮,窗口缩小时仍可访问全部缩放设置。
+
+勾选“显示游戏网格”可查看固定 40×40 屏幕像素的背景网格,素材按最终导出像素尺寸 1:1 显示,只缩放素材,不缩放网格。超出预览区域可拖动滚动条查看;同时显示素材画布宽高占多少格。网格、边框仅用于预览,不写入导出的 PNG。关闭开关恢复适应窗口的透明棋盘格预览。
+
+网格预览中,金色高亮格子的中心为偏移原点。初始时图片左上角对准该中心,X、Y 均为 0。按住素材区域拖动可调整预览位置,实时显示图片左上角相对该中心的像素偏移,向右 / 向下为正;高亮参考格始终固定。动画播放、裁剪和缩放时保留当前位置。“位置归零”恢复对齐;载入新素材也会归零。拖动不改变导出 PNG 的尺寸、内容和透明背景;开启帧配置导出时,当前偏移会写入 JSON 的 Cx、Cy。
+
+开启网格时视野自动居中,兼顾素材和参考格。按住右键或中键拖动可平移视野,也可使用滚动条向四周移动(支持负坐标),网格始终保持 40×40 像素。“视野居中”重新找回素材及参考格;平移视野不会改变素材 X、Y 偏移,也不影响导出。左键仍用于拖动素材。
+
+## 同时导出游戏帧配置
+
+在左侧滚动到“游戏帧配置”,勾选“同时导出帧配置 JSON”。可填写 NAME(留空使用图片前缀),选择输入素材朝右(0)或朝左(1),INTERVAL 默认 200ms。
+
+“生成左右两套(镜像)”默认勾选:输出 `前缀.json`,以及 `前缀_0_idx.png`(右)、`前缀_1_idx.png`(左)两套图片,另一朝向通过水平镜像生成,每套均为所设采样帧数。
+
+不需要区分方向的怪物可以取消该选项:只导出一套 `前缀_0_idx.png`(固定保留中间的 0,不生成 `_1_` 图片),配置中八个动作方向均引用这套图片及同一个当前偏移,不计算镜像偏移,输入素材朝向选项也会禁用。保留八个方向入口是为了兼容游戏现有角色读取和切换方向的逻辑。
+
+未开启“同时导出帧配置 JSON”时仍只导出原始一套 `前缀_idx.png`,不受镜像选项影响。
+
+JSON 结构与 `Rogue59.json` 一致:`STAND_R/STAND_D/R/D` 引用右向图片,`STAND_U/STAND_L/U/L` 引用左向图片。各段 `Len` 为采样帧数。输入素材朝向的 `Cx/Cy` 使用点击导出时的预览偏移;另一朝向以参考格中心为镜像轴,`Cx = -原 Cx - 最终输出图片宽度`,`Cy` 不变。例如最终宽 160、原 Cx 为 -51,则镜像 Cx 为 -109;输入素材选择朝左时也按同样规则计算右向偏移。`Cloth.CX/CY` 为等长全零数组。`HEAD_POS` 按最终输出 PNG 的宽、高计算为 `[-max(0, 宽//2-15), -max(0, 高//4-15)]`,两个坐标均取负值,计算为 0 时保持 0。配置名与图片名冲突时拒绝覆盖,写入失败或取消会撤回本次生成的 PNG 和 JSON。
+
+GIF 透明区域会保留。WebM 由随依赖附带的 FFmpeg 解码,无需单独安装 FFmpeg;WebM 的 alpha 透明通道取决于解码器支持。长视频会先完整读取一次统计帧数,导出时再次顺序读取,避免将整段视频存入内存。取消或导出失败会删除本次生成的文件。

+ 246 - 0
resource_tool/core.py

@@ -0,0 +1,246 @@
+"""Streaming GIF / WebM extraction. No GUI dependency."""
+from dataclasses import dataclass
+from pathlib import Path
+import math
+import re
+import json
+from io import BytesIO
+from typing import Callable, Optional
+
+from PIL import Image, ImageOps
+
+
+class Cancelled(Exception):
+    pass
+
+
+@dataclass(frozen=True)
+class Options:
+    count: int = 16
+    prefix: str = "frame"
+    left: float = 0
+    right: float = 100
+    top: float = 0
+    bottom: float = 100
+    scale_axis: str = "none"
+    target: int = 256
+
+    def validate(self):
+        if self.count < 1:
+            raise ValueError("采样帧数必须大于 0。")
+        if (not self.prefix or self.prefix != self.prefix.strip()
+                or re.search(r'[<>:"/\\|?*\x00-\x1f]', self.prefix)
+                or self.prefix.endswith('.')):
+            raise ValueError("前缀不能为空,不能含路径或 Windows 文件名非法字符。")
+        if not all(math.isfinite(x) for x in (self.left, self.right, self.top, self.bottom)):
+            raise ValueError("裁剪位置必须是有效数字。")
+        if not (0 <= self.left < self.right <= 100 and 0 <= self.top < self.bottom <= 100):
+            raise ValueError("裁剪范围必须满足:0 ≤ 左 < 右 ≤ 100,0 ≤ 上 < 下 ≤ 100。")
+        if self.scale_axis not in ("none", "width", "height"):
+            raise ValueError("无效缩放方式。")
+        if self.scale_axis != "none" and self.target < 1:
+            raise ValueError("目标像素必须大于 0。")
+
+
+@dataclass(frozen=True)
+class MediaInfo:
+    count: int
+    size: tuple
+    first: Image.Image
+
+
+@dataclass(frozen=True)
+class FrameConfig:
+    name: str
+    cx: int = 0
+    cy: int = 0
+    source_direction: int = 0
+    interval: int = 200
+    mirror: bool = True
+
+    def validate(self, prefix):
+        if not self.name.strip():
+            raise ValueError('配置 NAME 不能为空。')
+        if self.source_direction not in (0, 1) or self.interval < 1:
+            raise ValueError('朝向须为 0 或 1,INTERVAL 须为正整数。')
+        if re.fullmatch(r'(?i:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?', prefix):
+            raise ValueError('配置文件前缀不能使用 Windows 保留名。')
+
+
+def build_frame_config(info, options, config):
+    config.validate(options.prefix)
+    _, (width, height) = geometry(info.size, options)
+    data = {'NAME': config.name, 'HEAD_POS': [-max(0, width // 2 - 15), -max(0, height // 4 - 15)]}
+    for action in ('STAND_R', 'STAND_U', 'STAND_L', 'STAND_D', 'R', 'U', 'L', 'D'):
+        direction = 0 if action.endswith(('R', 'D')) else 1
+        # Mirror [cx, cx + width) about the character anchor (x = 0).
+        cx = config.cx if not config.mirror or direction == config.source_direction else -config.cx - width
+        image_prefix = f'{options.prefix}_{direction if config.mirror else 0}'
+        data[action] = {'Len': options.count, 'Cx': cx, 'Cy': config.cy,
+                        'Cloth': {'IMG': [f'{image_prefix}_{i}.png' for i in range(options.count)],
+                                  'CX': [0] * options.count, 'CY': [0] * options.count}}
+    data['INTERVAL'] = config.interval
+    return data
+
+
+def frames(path: Path):
+    """Decode sequentially, allowing Pillow to composite GIF disposal frames."""
+    path = Path(path)
+    if path.suffix.lower() == '.gif':
+        with Image.open(path) as source:
+            for idx in range(source.n_frames):
+                source.seek(idx)
+                yield source.convert('RGBA')
+    elif path.suffix.lower() == '.webm':
+        import imageio_ffmpeg
+        reader = imageio_ffmpeg.read_frames(str(path), pix_fmt='rgba', bits_per_pixel=32)
+        try:
+            meta = next(reader)
+            for data in reader:
+                yield Image.frombytes('RGBA', meta['size'], data)
+        finally:
+            reader.close()
+    else:
+        raise ValueError("请选择 GIF 或 WebM 文件。")
+
+
+def inspect_media(path: Path, cancelled=lambda: False) -> MediaInfo:
+    first = None
+    count = 0
+    stream = frames(path)
+    try:
+        for frame in stream:
+            if cancelled():
+                raise Cancelled()
+            if first is None:
+                first = frame.copy()
+            count += 1
+    finally:
+        stream.close()
+    if first is None:
+        raise ValueError("文件中没有可读取的帧。")
+    return MediaInfo(count, first.size, first)
+
+
+def sample_indices(total: int, count: int):
+    if not 1 <= count <= total:
+        raise ValueError(f"采样帧数必须在 1 到 {total} 之间。")
+    if count == 1:
+        return [0]
+    # Include first and last frame. Integer arithmetic avoids float rounding drift.
+    return [(i * (total - 1) * 2 + count - 1) // (2 * (count - 1)) for i in range(count)]
+
+
+def geometry(size, options: Options):
+    options.validate()
+    width, height = size
+    box = (round(width * options.left / 100), round(height * options.top / 100),
+           round(width * options.right / 100), round(height * options.bottom / 100))
+    w, h = box[2] - box[0], box[3] - box[1]
+    if min(w, h) < 1:
+        raise ValueError("裁剪区域不足 1 像素,请扩大裁剪范围。")
+    if options.scale_axis == 'width':
+        output = (options.target, max(1, round(h * options.target / w)))
+    elif options.scale_axis == 'height':
+        output = (max(1, round(w * options.target / h)), options.target)
+    else:
+        output = (w, h)
+    return box, output
+
+
+def transform(frame: Image.Image, options: Options):
+    box, size = geometry(frame.size, options)
+    result = frame.crop(box)
+    if result.size != size:
+        result = result.resize(size, Image.Resampling.LANCZOS)
+    return result
+
+
+@dataclass(frozen=True)
+class PreviewFrame:
+    size: tuple
+    png: bytes
+
+    def copy(self):
+        with Image.open(BytesIO(self.png)) as image:
+            return image.convert('RGBA')
+
+
+def preview_samples(path, info, options, bounds=None, cancelled=lambda: False):
+    """Cache selected output frames losslessly, compressed instead of raw RGBA."""
+    indices = sample_indices(info.count, options.count)
+    geometry(info.size, options)
+    samples = []
+    stream = frames(path)
+    try:
+        for index, frame in enumerate(stream):
+            if cancelled():
+                raise Cancelled()
+            if index == indices[len(samples)]:
+                image = transform(frame, options)
+                buffer = BytesIO()
+                image.save(buffer, format='PNG')
+                samples.append(PreviewFrame(image.size, buffer.getvalue()))
+                if len(samples) == len(indices):
+                    return indices, samples
+        raise ValueError('源文件帧数发生变化,请重新选择文件。')
+    finally:
+        stream.close()
+
+
+def export_frames(path: Path, directory: Path, info: MediaInfo, options: Options,
+                  progress: Optional[Callable] = None, cancelled=lambda: False, config=None):
+    options.validate()
+    geometry(info.size, options)
+    indices = sample_indices(info.count, options.count)
+    directory = Path(directory)
+    directory.mkdir(parents=True, exist_ok=True)
+    outputs = [directory / f'{options.prefix}_{i}.png' for i in range(options.count)]
+    configuration = None
+    if config is not None:
+        configuration = build_frame_config(info, options, config)
+        output_directions = (0, 1) if config.mirror else (0,)
+        outputs = [directory / f'{options.prefix}_{d}_{i}.png' for d in output_directions for i in range(options.count)]
+    config_path = directory / f'{options.prefix}.json'
+    for output in outputs + ([config_path] if configuration is not None else []):
+        if output.exists():
+            raise ValueError(f"文件已存在,请更换前缀或输出目录:\n{output}")
+    created = []
+    stream = frames(path)
+    try:
+        selected = 0
+        for index, frame in enumerate(stream):
+            if cancelled():
+                raise Cancelled()
+            if index != indices[selected]:
+                continue
+            result = transform(frame, options)
+            directions = ((0, 1) if config.mirror else (0,)) if config is not None else (None,)
+            for direction in directions:
+                output = (directory / f'{options.prefix}_{direction}_{selected}.png' if direction is not None else outputs[selected])
+                image = ImageOps.mirror(result) if config is not None and config.mirror and direction != config.source_direction else result
+                with output.open('xb') as handle:
+                    created.append(output)
+                    image.save(handle, format='PNG')
+            selected += 1
+            if progress:
+                progress(selected, options.count)
+            if selected == options.count:
+                break
+        if selected != options.count:
+            raise ValueError("源文件帧数发生变化,请重新选择文件。")
+        if cancelled():
+            raise Cancelled()
+        if configuration is not None:
+            with config_path.open('x', encoding='utf-8') as handle:
+                created.append(config_path)
+                json.dump(configuration, handle, ensure_ascii=False, indent=4)
+                handle.write('\n')
+        return outputs
+    except Exception:
+        # Roll back only files created by this run; never remove existing files.
+        for output in created:
+            output.unlink(missing_ok=True)
+        raise
+    finally:
+        stream.close()

+ 33 - 0
resource_tool/deepseek_character/README.md

@@ -0,0 +1,33 @@
+# 蓝色大肥鱼 · DeepSeek 二创角色
+
+已经接入当前 QQTPVE 源码工程。双击工程根目录的 `试玩蓝色大肥鱼.bat`,会在当前配置所选关卡中使用新角色;方向键移动、空格放泡,沿用原游戏操作。试玩入口只在内存中选择角色,不修改 `config.json`。机器上现有的 Python 3.8 / pygame-ce 运行环境会被优先使用。
+
+源码菜单 `test_menu.py` 的角色列表也已加入“蓝色大肥鱼(DeepSeek)”。现有已编译的主菜单 EXE 不会随源码自动更新;无需等待菜单重新打包,可以直接使用上面的独立试玩入口。也可以自行将配置中的 `your_hero` 设置为 `DeepseekBlueWhale`。
+
+## 游戏文件
+
+- `game/hero/DeepseekBlueWhale.json`:角色注册,属性和现成道具技能沿用 Cola,普通 bomb1 糖泡;没有新增专属技能。
+- `game/frame/character/CharacterDeepseekBlueWhale.json`:右、上、左、下四方向的站立与行走配置。每方向 1 张站立图、6 张行走图。另有 LOSE 显示兜底,复用正面站立图,不是新制作的倒地动画。
+- `res/img/cloth/deepseek_bluewhale_stand_0_0.png` 至 `...stand_3_0.png`:4 张站立贴图。
+- `res/img/cloth/deepseek_bluewhale_walk_0_0.png` 至 `...walk_3_5.png`:24 张行走贴图。
+- `res/img/ui/game/icon_deepseek_bluewhale.png`:55×55 游戏头像。
+
+当前为 V2。方向编号 0 / 1 / 2 / 3 对应 R / U / L / D。贴图使用透明 128×112 画布,实际角色高度为 90 像素(V1 约 58 像素,约为原来的 1.55 倍);一格地板仍为 40 像素,碰撞格子没有放大。脚底基准为画布 y=100,游戏偏移为 `Cx=-64, Cy=-93`。六帧仅有 1 像素的受控起伏,并按头部中心定位,不因尾巴摆动改变角色横向位置。左右均为只露一只眼的正侧面,左向直接镜像右向的同一套姿态。角色整体放在 Cloth 图层,不使用染色蒙版,因此切换玩家颜色不会改变蓝白配色。行走间隔 100ms,站立为单帧。
+
+## 美术来源和预览
+
+使用内置 image_gen 图像生成工具制作。用户提供的蓝发女仆二创图用于角色外观参考;body10900、cloth10401 用于原游戏画风和体型参考。V2 重画正侧视及六帧连续步态,再进行切分、保持宽高比的尺寸统一、头部定位、受控起伏和 PNG 编码;左向镜像右向,没有用平移一张静图代替行走姿态。
+
+- `v2/source_views.png`:V2 站立、背面和正面原始图集。
+- `v2/source_side_walk.png`:V2 单独重画的正侧面六帧步态。
+- `v2/generation_prompt.txt`、`v2/side_animation_prompt.txt`:V2 两次内置图像生成的完整提示词。
+- `contact_sheet.png`:当前 28 帧对照图。
+- `walk_preview.gif`:当前四方向同时行走预览,按游戏原始像素尺寸显示。
+- `v2/size_comparison.png`:同为 40 像素地板网格的 V1 / V2 尺寸比较。
+- `source_sheet.png`、`generation_prompt.txt`:V1 原始美术及提示词,保留备查。
+- `v2/previous_version/`:替换前的游戏贴图、帧配置和预览备份。
+- `asset_manifest.json`:28 张游戏贴图的尺寸、路径、透明范围和 SHA256。
+- `in_game.png`:通过真实 Hero、Level 和渲染流程截取的关卡画面。
+- `runtime_verification.json`:游戏运行验证结果。
+
+`build_assets.py` 是 V1 整理脚本;`build_assets_v2.py` 先生成 V2 暂存贴图和预览,传入 `--install` 才安装,并先保留旧版本,不修改角色数值及道具技能。`verify_runtime.py` 使用游戏实际读取器和运行环境,验证图片引用、尺寸与透明边界、左右镜像、四方向动画、颜色保持、Hero/Level 初始化、关卡移动、放泡和死亡状态显示;以 SDL dummy 驱动执行,未修改默认角色配置。

+ 132 - 0
resource_tool/deepseek_character/build_assets.py

@@ -0,0 +1,132 @@
+"""Slice the generated sheet and register the independent DeepSeek character.
+
+Only packaging operations (crop, uniform resize and PNG encoding) are performed;
+the poses and animation artwork come from the image generation tool.
+"""
+import hashlib
+from copy import deepcopy
+import json
+from pathlib import Path
+
+import numpy as np
+from PIL import Image, ImageDraw
+
+ROOT = Path(__file__).resolve().parents[2]
+HERE = Path(__file__).resolve().parent
+PREFIX = 'deepseek_bluewhale'
+CHARACTER = 'CharacterDeepseekBlueWhale'
+HERO = 'DeepseekBlueWhale'
+DIRECTIONS = ('R', 'U', 'L', 'D')
+
+
+def write_json(path, value):
+    path.parent.mkdir(parents=True, exist_ok=True)
+    path.write_text(json.dumps(value, ensure_ascii=False, indent=4) + '\n', encoding='utf-8')
+
+
+def main():
+    sheet = Image.open(HERE / 'source_sheet.png').convert('RGBA')
+    alpha = np.asarray(sheet)[:, :, 3]
+    width, height = sheet.size
+    row_edges = [0]
+    for row in range(1, 4):
+        expected = round(height * row / 4)
+        low, high = max(0, expected - 18), min(height, expected + 18)
+        row_edges.append(low + int(np.argmin((alpha[low:high] > 64).sum(axis=1))))
+    row_edges.append(height)
+    cells = []
+    for row in range(4):
+        y0, y1 = row_edges[row:row + 2]
+        column_edges = [0]
+        for column in range(1, 7):
+            expected = round(width * column / 7)
+            low, high = max(0, expected - 18), min(width, expected + 18)
+            projection = (alpha[y0:y1, low:high] > 64).sum(axis=0)
+            column_edges.append(low + int(np.argmin(projection)))
+        column_edges.append(width)
+        poses = []
+        for col in range(7):
+            cell = sheet.crop((column_edges[col], y0, column_edges[col + 1], y1))
+            bounds = cell.getchannel('A').point(lambda value: 255 if value > 64 else 0).getbbox()
+            if bounds is None:
+                raise ValueError(f'Empty sprite at {row}, {col}')
+            poses.append(cell.crop(bounds))
+        cells.append(poses)
+    # One uniform scale for all 28 poses; do not independently stretch each pose.
+    scale = min(58 / max(im.height for row in cells for im in row),
+                60 / max(im.width for row in cells for im in row))
+    output = ROOT / 'res/img/cloth'
+    character_path = ROOT / f'game/frame/character/{CHARACTER}.json'
+    hero_path = ROOT / f'game/hero/{HERO}.json'
+    if character_path.exists() or hero_path.exists() or list(output.glob(PREFIX + '_*.png')):
+        raise FileExistsError('Character already exists; do not overwrite edited game assets.')
+    assets, textures = [], []
+    for row, direction in enumerate(DIRECTIONS):
+        poses = []
+        for col, image in enumerate(cells[row]):
+            resized = image.resize((round(image.width * scale), round(image.height * scale)), Image.Resampling.LANCZOS)
+            canvas = Image.new('RGBA', (64, 64))
+            canvas.alpha_composite(resized, ((64 - resized.width) // 2, 60 - resized.height))
+            motion, frame = ('stand', 0) if col == 0 else ('walk', col - 1)
+            filename = f'{PREFIX}_{motion}_{row}_{frame}.png'
+            canvas.save(output / filename)
+            assets.append({'path': str((output / filename).relative_to(ROOT)),
+                           'direction': direction, 'motion': motion, 'frame': frame,
+                           'size': [64, 64], 'visible_bounds': canvas.getbbox(),
+                           'sha256': hashlib.sha256((output / filename).read_bytes()).hexdigest()})
+            poses.append(canvas)
+        textures.append(poses)
+    data = {'NAME': CHARACTER, 'HEAD_POS': [-17, -1]}
+    for index, direction in enumerate(DIRECTIONS):
+        for standing in (True, False):
+            motion, count = ('stand', 1) if standing else ('walk', 6)
+            data[('STAND_' if standing else '') + direction] = {
+                'Len': count, 'Cx': -32, 'Cy': -53,
+                'Cloth': {'IMG': [f'{PREFIX}_{motion}_{index}_{frame}.png' for frame in range(count)],
+                          'CX': [0] * count, 'CY': [0] * count}}
+    # Reuse the front standing image as a safe defeat-state fallback.
+    data['LOSE'] = deepcopy(data['STAND_D'])
+    data['INTERVAL'] = 100
+    write_json(character_path, data)
+    hero = json.loads((ROOT / 'game/hero/Cola.json').read_text(encoding='utf-8-sig'))
+    hero.update(name=HERO, character=CHARACTER, icon_img='icon_deepseek_bluewhale')
+    hero['decorations']['bomb_skin'] = 'bomb1'
+    write_json(hero_path, hero)
+    icon = textures[3][0].crop(textures[3][0].getbbox())
+    icon.thumbnail((53, 53), Image.Resampling.LANCZOS)
+    icon_canvas = Image.new('RGBA', (55, 55))
+    icon_canvas.alpha_composite(icon, ((55 - icon.width) // 2, 55 - icon.height))
+    icon_canvas.save(ROOT / 'res/img/ui/game/icon_deepseek_bluewhale.png')
+    # Enlarged contact sheet and a 40 px grid animation for reviewing the result.
+    contact = Image.new('RGB', (7 * 168, 4 * 216), '#edf3f8')
+    draw = ImageDraw.Draw(contact)
+    for row in range(4):
+        for col in range(7):
+            x, y = col * 168, row * 216
+            contact.paste(textures[row][col].resize((160, 160), Image.Resampling.NEAREST),
+                          (x + 4, y + 24), textures[row][col].resize((160, 160), Image.Resampling.NEAREST))
+            draw.text((x + 8, y + 190), DIRECTIONS[row] + (' stand' if col == 0 else f' walk {col - 1}'), fill='#203349')
+    contact.save(HERE / 'contact_sheet.png')
+    sequence = []
+    for frame in range(6):
+        scene = Image.new('RGB', (400, 180), '#263447')
+        draw = ImageDraw.Draw(scene)
+        for gx in range(0, 401, 40):
+            draw.line((gx, 0, gx, 180), fill='#526174')
+        for gy in range(0, 181, 40):
+            draw.line((0, gy, 400, gy), fill='#526174')
+        for row in range(4):
+            sprite = textures[row][frame + 1]
+            scene.paste(sprite, (28 + row * 96, 47), sprite)
+            draw.text((44 + row * 96, 130), DIRECTIONS[row], fill='white')
+        sequence.append(scene.resize((800, 360), Image.Resampling.NEAREST))
+    sequence[0].save(HERE / 'walk_preview.gif', save_all=True, append_images=sequence[1:], duration=100, loop=0)
+    write_json(HERE / 'asset_manifest.json', {'hero': HERO, 'character': CHARACTER,
+               'source_sheet': 'source_sheet.png', 'source_size': list(sheet.size), 'row_edges': row_edges,
+               'uniform_scale': scale, 'canvas': [64, 64], 'foot_baseline': 60,
+               'character_offset': [-32, -53], 'assets': assets})
+    print(f'Created {len(assets)} frames, character JSON, hero JSON, icon and previews.')
+
+
+if __name__ == '__main__':
+    main()

+ 206 - 0
resource_tool/deepseek_character/build_assets_v2.py

@@ -0,0 +1,206 @@
+"""Package the redrawn V2 art; preserve V1 before installing this character only."""
+import argparse
+from copy import deepcopy
+import hashlib
+import json
+from pathlib import Path
+import shutil
+
+import numpy as np
+from PIL import Image, ImageDraw, ImageOps
+
+ROOT = Path(__file__).resolve().parents[2]
+HERE = Path(__file__).resolve().parent
+OUT = HERE / 'v2'
+PREFIX = 'deepseek_bluewhale'
+CANVAS = (128, 112)
+ART_HEIGHT = 90
+PIVOT = (64, 100)
+OFFSET = (-64, -93)
+DIRECTIONS = ('R', 'U', 'L', 'D')
+
+
+def dump(path, value):
+    path.parent.mkdir(parents=True, exist_ok=True)
+    path.write_text(json.dumps(value, ensure_ascii=False, indent=4) + '\n', encoding='utf-8')
+
+
+def split_sheet(path, columns, rows):
+    image = Image.open(path).convert('RGBA')
+    alpha = np.array(image.getchannel('A'))
+    width, height = image.size
+    row_edges = [0]
+    for row in range(1, rows):
+        middle = round(row * height / rows)
+        radius = round(height / rows * 0.12)
+        low, high = max(0, middle - radius), min(height, middle + radius)
+        values = (alpha[low:high] > 64).sum(axis=1)
+        candidates = np.flatnonzero(values == values.min())
+        edge = low + int(candidates[np.argmin(np.abs(candidates + low - middle))])
+        row_edges.append(edge)
+    row_edges.append(height)
+    result = []
+    for row in range(rows):
+        top, bottom = row_edges[row:row + 2]
+        edges = [0]
+        for column in range(1, columns):
+            middle = round(column * width / columns)
+            radius = round(width / columns * 0.12)
+            low, high = max(0, middle - radius), min(width, middle + radius)
+            values = (alpha[top:bottom, low:high] > 64).sum(axis=0)
+            candidates = np.flatnonzero(values == values.min())
+            edges.append(low + int(candidates[np.argmin(np.abs(candidates + low - middle))]))
+        edges.append(width)
+        cells = []
+        for column in range(columns):
+            cell = image.crop((edges[column], top, edges[column + 1], bottom))
+            bbox = cell.getchannel('A').point(lambda a: 255 if a > 64 else 0).getbbox()
+            if bbox is None:
+                raise ValueError(f'Empty frame: {path}, {row}, {column}')
+            cells.append(cell.crop(bbox))
+        result.append(cells)
+    return result
+
+
+def register(image, phase):
+    # Use the head, not the whole bounding-box center: a swinging tail must
+    # never push the character's face/feet from side to side.
+    alpha = np.asarray(image.getchannel('A')) > 64
+    top, bottom = round(image.height * .18), round(image.height * .52)
+    head = alpha[top:bottom]
+    weights = head.sum(axis=0)
+    head_x = float(np.dot(weights, np.arange(image.width)) / weights.sum())
+    factor = ART_HEIGHT / image.height
+    size = (round(image.width * factor), ART_HEIGHT)
+    image = image.resize(size, Image.Resampling.LANCZOS)
+    bob = 0 if phase is None else (0, -1, 0, 0, -1, 0)[phase]
+    x, y = round(PIVOT[0] - head_x * factor), PIVOT[1] - ART_HEIGHT + bob
+    if x < 1 or x + size[0] >= CANVAS[0] or y < 1 or y + size[1] >= CANVAS[1]:
+        raise ValueError(f'Clipped character: {x, y, size}')
+    result = Image.new('RGBA', CANVAS)
+    result.alpha_composite(image, (x, y))
+    return result
+
+
+def make_previews(textures):
+    contact = Image.new('RGB', (7 * 164, 4 * 166), '#edf3f8')
+    draw = ImageDraw.Draw(contact)
+    for row in range(4):
+        for column in range(7):
+            image = textures[row][column]
+            pos = (column * 164 + 18, row * 166 + 12)
+            contact.paste(image, pos, image)
+            draw.text((column * 164 + 18, row * 166 + 136),
+                      DIRECTIONS[row] + (' stand' if column == 0 else f' walk {column - 1}'), fill='#203349')
+    contact.save(OUT / 'contact_sheet.png')
+    sequence = []
+    for phase in range(6):
+        scene = Image.new('RGB', (640, 200), '#263447')
+        draw = ImageDraw.Draw(scene)
+        for x in range(0, 641, 40):
+            draw.line((x, 0, x, 200), fill='#526174')
+        for y in range(0, 201, 40):
+            draw.line((0, y, 640, y), fill='#526174')
+        for row in range(4):
+            image = textures[row][phase + 1]
+            scene.paste(image, (16 + row * 160, 27), image)
+            draw.text((72 + row * 160, 157), DIRECTIONS[row], fill='white')
+        draw.text((10, 181), 'V2 / 90px tall / 40px tiles / 100ms per frame', fill='#e1e9f2')
+        sequence.append(scene)
+    sequence[0].save(OUT / 'walk_preview.gif', save_all=True, append_images=sequence[1:], duration=100, loop=0)
+    old_path = OUT / 'previous_version/res/img/cloth/deepseek_bluewhale_stand_3_0.png'
+    if not old_path.exists():
+        old_path = ROOT / 'res/img/cloth/deepseek_bluewhale_stand_3_0.png'
+    old = Image.open(old_path).convert('RGBA')
+    compare = Image.new('RGB', (640, 220), '#263447')
+    draw = ImageDraw.Draw(compare)
+    for x in range(0, 641, 40):
+        draw.line((x, 0, x, 220), fill='#526174')
+    for y in range(0, 221, 40):
+        draw.line((0, y, 640, y), fill='#526174')
+    compare.paste(old, (160 - 32, 160 - 53), old)
+    compare.paste(textures[3][0], (480 + OFFSET[0], 160 + OFFSET[1]), textures[3][0])
+    draw.text((115, 190), 'V1 ~58 px', fill='white')
+    draw.text((435, 190), 'V2 90 px (1.55x)', fill='white')
+    compare.save(OUT / 'size_comparison.png')
+
+
+def build():
+    views = split_sheet(OUT / 'source_views.png', 7, 3)
+    side = sum(split_sheet(OUT / 'source_side_walk.png', 3, 2), [])
+    source_right = [views[0][0]] + side
+    right = [register(image, None if i == 0 else i - 1) for i, image in enumerate(source_right)]
+    back = [register(image, None if i == 0 else i - 1) for i, image in enumerate(views[1])]
+    front = [register(image, None if i == 0 else i - 1) for i, image in enumerate(views[2])]
+    left = [ImageOps.mirror(image) for image in right]
+    textures = [right, back, left, front]
+    assets = []
+    for row in range(4):
+        for column, image in enumerate(textures[row]):
+            motion, index = ('stand', 0) if column == 0 else ('walk', column - 1)
+            relative = Path('res/img/cloth') / f'{PREFIX}_{motion}_{row}_{index}.png'
+            path = OUT / 'assets' / relative
+            path.parent.mkdir(parents=True, exist_ok=True)
+            image.save(path)
+            assets.append({'path': relative.as_posix(), 'direction': DIRECTIONS[row],
+                           'motion': motion, 'frame': index, 'size': list(CANVAS),
+                           'visible_bounds': image.getbbox(), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()})
+    character_path = Path('game/frame/character/CharacterDeepseekBlueWhale.json')
+    data = json.loads((ROOT / character_path).read_text(encoding='utf-8'))
+    for row, direction in enumerate(DIRECTIONS):
+        for standing in (True, False):
+            state = ('STAND_' if standing else '') + direction
+            data[state]['Cx'], data[state]['Cy'] = OFFSET
+    data['HEAD_POS'] = [-max(0, CANVAS[0] // 2 - 15), -max(0, CANVAS[1] // 4 - 15)]
+    data['LOSE'] = deepcopy(data['STAND_D'])
+    dump(OUT / 'assets' / character_path, data)
+    icon = front[0].crop(front[0].getbbox())
+    icon.thumbnail((53, 53), Image.Resampling.LANCZOS)
+    icon_canvas = Image.new('RGBA', (55, 55))
+    icon_canvas.alpha_composite(icon, ((55 - icon.width) // 2, 55 - icon.height))
+    icon_path = OUT / 'assets/res/img/ui/game/icon_deepseek_bluewhale.png'
+    icon_path.parent.mkdir(parents=True, exist_ok=True)
+    icon_canvas.save(icon_path)
+    make_previews(textures)
+    manifest = {'version': 2, 'hero': 'DeepseekBlueWhale', 'character': 'CharacterDeepseekBlueWhale',
+                'canvas': list(CANVAS), 'art_height': ART_HEIGHT, 'foot_baseline': PIVOT[1],
+                'character_offset': list(OFFSET), 'head_registration': True,
+                'left_is_exact_mirror_of_right': True,
+                'source_sheet': 'v2/source_views.png', 'side_walk_source': 'v2/source_side_walk.png', 'assets': assets}
+    dump(OUT / 'asset_manifest.json', manifest)
+    return manifest
+
+
+def install(manifest):
+    # Only the explicitly redrawn character's files are replaced. Keep a
+    # recoverable V1 copy, including any edits made since the original build.
+    files = list((OUT / 'assets').rglob('*.png')) + list((OUT / 'assets').rglob('*.json'))
+    for source in files:
+        relative = source.relative_to(OUT / 'assets')
+        target = ROOT / relative
+        backup = OUT / 'previous_version' / relative
+        if target.exists() and not backup.exists():
+            backup.parent.mkdir(parents=True, exist_ok=True)
+            shutil.copy2(target, backup)
+    for name in ('asset_manifest.json', 'contact_sheet.png', 'walk_preview.gif', 'in_game.png', 'runtime_verification.json'):
+        previous = HERE / name
+        backup = OUT / 'previous_version/resource_tool/deepseek_character' / name
+        if previous.exists() and not backup.exists():
+            backup.parent.mkdir(parents=True, exist_ok=True)
+            shutil.copy2(previous, backup)
+    for source in files:
+        shutil.copy2(source, ROOT / source.relative_to(OUT / 'assets'))
+    for name in ('asset_manifest.json', 'contact_sheet.png', 'walk_preview.gif'):
+        shutil.copy2(OUT / name, HERE / name)
+    print('Installed V2: 28 character sprites, frame JSON and icon. Hero statistics unchanged.')
+
+
+if __name__ == '__main__':
+    parser = argparse.ArgumentParser()
+    parser.add_argument('--install', action='store_true')
+    args = parser.parse_args()
+    manifest = build()
+    if args.install:
+        install(manifest)
+    else:
+        print('Built staged V2 assets and previews; use --install after reviewing.')

+ 152 - 0
resource_tool/deepseek_character/verify_runtime.py

@@ -0,0 +1,152 @@
+"""Run with the game's Python, from the repository root."""
+import ast
+import hashlib
+import importlib.util
+import json
+import os
+from pathlib import Path
+
+os.environ.setdefault('SDL_VIDEODRIVER', 'dummy')
+os.environ.setdefault('SDL_AUDIODRIVER', 'dummy')
+ROOT = Path(__file__).resolve().parents[2]
+os.chdir(str(ROOT))
+import sys
+sys.path.insert(0, str(ROOT))
+
+import pygame
+from PIL import Image
+
+HERE = Path(__file__).resolve().parent
+checks = []
+
+
+def verify_assets():
+    manifest = json.loads((HERE / 'asset_manifest.json').read_text(encoding='utf-8'))
+    expected_size = tuple(manifest['canvas'])
+    baseline = manifest['foot_baseline']
+    hero = json.loads((ROOT / 'game/hero/DeepseekBlueWhale.json').read_text(encoding='utf-8'))
+    data = json.loads((ROOT / ('game/frame/character/' + hero['character'] + '.json')).read_text(encoding='utf-8'))
+    paths = []
+    for index, direction in enumerate(('R', 'U', 'L', 'D')):
+        for state, count in [('STAND_' + direction, 1), (direction, 6)]:
+            entry = data[state]
+            assert entry['Len'] == count
+            cloth = entry['Cloth']
+            assert len(cloth['IMG']) == len(cloth['CX']) == len(cloth['CY']) == count
+            hashes = []
+            for filename in cloth['IMG']:
+                path = ROOT / 'res/img/cloth' / filename
+                assert path.exists(), path
+                image = Image.open(path)
+                assert image.size == expected_size and image.mode == 'RGBA'
+                assert image.getchannel('A').getextrema() == (0, 255)
+                assert image.getbbox()[3] <= baseline
+                if manifest.get('version') == 2:
+                    assert image.getbbox()[3] - image.getbbox()[1] >= 87
+                    assert entry['Cx'] == -64 and entry['Cy'] == -93
+                hashes.append(hashlib.sha256(image.tobytes()).hexdigest())
+                paths.append(path)
+            assert len(set(hashes)) == count, ('Repeated walking image', state)
+    assert len(set(paths)) == 28
+    if manifest.get('version') == 2:
+        from PIL import ImageOps
+        for motion, count in [('stand', 1), ('walk', 6)]:
+            for i in range(count):
+                right = Image.open(ROOT / f'res/img/cloth/deepseek_bluewhale_{motion}_0_{i}.png')
+                left = Image.open(ROOT / f'res/img/cloth/deepseek_bluewhale_{motion}_2_{i}.png')
+                assert left.tobytes() == ImageOps.mirror(right).tobytes()
+        checks.append('V2 art >=87 px high, no clipping, exact side-view mirrors and updated anchor offsets')
+    assert (ROOT / 'res/img/ui/game' / (hero['icon_img'] + '.png')).exists()
+    menu = ast.parse((ROOT / 'test_menu.py').read_text(encoding='utf-8-sig'))
+    name_func = next(node for node in menu.body if isinstance(node, ast.FunctionDef) and node.name == 'show_hero_name')
+    namespace = {}
+    exec(compile(ast.Module(body=[name_func], type_ignores=[]), 'menu-name-check', 'exec'), namespace)
+    assert '蓝色大肥鱼' in namespace['show_hero_name']('DeepseekBlueWhale')
+    checks.append('28 distinct transparent sprites, 4 standing + 24 walking, hero/menu/icon registrations')
+
+
+def verify_real_game():
+    expected_size = tuple(json.loads((HERE / 'asset_manifest.json').read_text(encoding='utf-8'))['canvas'])
+    from client_local.const import color as C
+    from client_local.frame import character
+    from client_local.file_loader import fileLoader
+    # New unique asset names must work through the real archive-aware loader.
+    pygame.init()
+    pygame.display.set_mode((800, 600))
+    data = fileLoader.load_json('game/frame/character/CharacterDeepseekBlueWhale.json')
+    for color in (C.CHARACTER_RED, C.CHARACTER_SKYBLUE):
+        loaded = character.get_character(data, color, {})
+        assert len(loaded) == 9
+        assert len(loaded['LOSE']['Cloth']) == 1
+        for direction in ('R', 'U', 'L', 'D'):
+            assert len(loaded[direction]['Cloth']) == 6
+            assert len(loaded['STAND_' + direction]['Cloth']) == 1
+            for frame in loaded[direction]['Cloth']:
+                assert frame.image.get_size() == expected_size
+        # No recolor mask: navy/cyan identity is unaffected by player color.
+        original = pygame.image.load(str(ROOT / 'res/img/cloth/deepseek_bluewhale_walk_3_0.png')).convert_alpha()
+        assert pygame.image.tobytes(original, 'RGBA') == pygame.image.tobytes(loaded['D']['Cloth'][0].image, 'RGBA')
+    checks.append('Real frame loader, all 8 states, no missing-texture fallback, fixed palette across player colors')
+    spec = importlib.util.spec_from_file_location('deepseek_trial', str(ROOT / '试玩蓝色大肥鱼.py'))
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+
+    class SmokeControl(module.BlueWhaleControl):
+        def update(self):
+            assert self.me.hero_name == 'DeepseekBlueWhale'
+            assert self.current_level is not None
+            original = (ROOT / 'config.json').read_bytes()
+            # Exercise the engine's actual frame switching and Player.draw.
+            screen = pygame.Surface((800, 600))
+            for direction in ('R', 'U', 'L', 'D'):
+                self.me.orientation = direction
+                for walking in (False, True):
+                    self.me.walking = walking
+                    self.me.character_frame_trigger = True
+                    for index in range(6):
+                        self.me.update_frame(pygame.time.get_ticks() + 1000 + index * 120)
+                        self.me.draw(screen)
+            self.me.walking = False
+            self.me.orientation = 'D'
+            self.me.character_frame_trigger = True
+            self.current_level.update(self.screen)
+            self.me.rooted = 0
+            positions = []
+            for direction in ('R', 'U', 'L', 'D'):
+                self.me.set_motion(direction)
+                for index in range(8):
+                    pygame.time.delay(20)
+                    self.current_level.update(self.screen)
+                    positions.append((self.me.x_pos, self.me.y_pos))
+            assert len(set(positions)) > 1, 'Player did not move in the live Level update'
+            self.me.set_motion()
+            self.current_level.update(self.screen)
+            checks.append('Live Level.update movement with the new character')
+            bombs_before = len(self.current_level.bomb_instances)
+            remaining_before = self.me.remain_bombs
+            self.me.set_bomb()
+            assert len(self.current_level.bomb_instances) == bombs_before + 1
+            assert self.me.remain_bombs == remaining_before - 1
+            from client_local.sprite.player import PlayerState
+            self.me.state = PlayerState.LOSE
+            self.me.update_frame_dead(pygame.time.get_ticks() + 2000)
+            self.me.draw(screen)
+            self.me.state = PlayerState.NORMAL
+            self.me.character_frame_trigger = True
+            self.me.update_frame(pygame.time.get_ticks() + 2100)
+            checks.append('Live bomb placement and a valid LOSE-state sprite fallback')
+            pygame.image.save(pygame.display.get_surface(), str(HERE / 'in_game.png'))
+            assert (ROOT / 'config.json').read_bytes() == original
+            checks.append('Real Hero/Level initialization, standing/walking frame updates and draw in all four directions')
+    SmokeControl()
+    pygame.quit()
+
+
+if __name__ == '__main__':
+    before = hashlib.sha256((ROOT / 'config.json').read_bytes()).hexdigest()
+    verify_assets()
+    verify_real_game()
+    assert hashlib.sha256((ROOT / 'config.json').read_bytes()).hexdigest() == before
+    (HERE / 'runtime_verification.json').write_text(json.dumps({'ok': True, 'checks': checks,
+                            'config_sha256_unchanged': before}, indent=2, ensure_ascii=False), encoding='utf-8')
+    print(json.dumps({'ok': True, 'checks': checks}, ensure_ascii=False))

+ 602 - 0
resource_tool/main.py

@@ -0,0 +1,602 @@
+"""Run with python main.py or the adjacent Windows launcher."""
+from pathlib import Path
+import queue
+import threading
+import math
+import tkinter as tk
+from tkinter import filedialog, messagebox, ttk
+
+from PIL import Image, ImageTk
+from core import Cancelled, Options, FrameConfig, export_frames, geometry, inspect_media, preview_samples, transform
+
+
+class App(tk.Tk):
+    def __init__(self):
+        super().__init__()
+        self.title('动画抽帧工具 · GIF / WebM → PNG')
+        self.geometry('1040x760')
+        self.minsize(840, 560)
+        self.configure(bg='#f3f5f8')
+        self.info = None
+        self.loaded_path = None
+        self.busy = False
+        self.events = queue.Queue()
+        self.cancel = threading.Event()
+        self.preview_cancel = threading.Event()
+        self.preview_generation = 0
+        self.preview_job = None
+        self.play_job = None
+        self.samples = []
+        self.sample_sources = []
+        self.sample_position = 0
+        self.want_play = True
+        self.show_game_grid = tk.BooleanVar(value=False)
+        self.preview_offset = [0, 0]
+        self.reference_center = (100, 100)
+        self.drag_start = None
+        self.panning = False
+        self.center_pending = True
+        self.view_centered = True
+        self.grid_region = None
+        self.offset_status = tk.StringVar(value='偏移 X: 0 px    Y: 0 px(右 / 下为正)')
+        self.export_config = tk.BooleanVar(value=False)
+        self.mirror_directions = tk.BooleanVar(value=True)
+        self.config_name = tk.StringVar()
+        self.config_direction = tk.StringVar(value='0 · 朝右')
+        self.config_interval = tk.StringVar(value='200')
+        self.playback_status = tk.StringVar(value='100 ms / 帧 · 循环播放')
+        self.source = tk.StringVar()
+        self.output = tk.StringVar()
+        self.count = tk.StringVar(value='16')
+        self.prefix = tk.StringVar(value='frame')
+        self.axis = tk.StringVar(value='不缩放')
+        self.target = tk.StringVar(value='256')
+        self.crop = {name: tk.StringVar(value=default) for name, default in
+                     [('左', '0'), ('右', '100'), ('上', '0'), ('下', '100')]}
+        self.status = tk.StringVar(value='请选择一个 GIF 或 WebM 文件。')
+        self.metadata = tk.StringVar(value='尚未载入素材')
+        self.dimensions = tk.StringVar(value='')
+        self._build()
+        for variable in [self.count, *self.crop.values(), self.axis, self.target]:
+            variable.trace_add('write', self.settings_changed)
+        self.protocol('WM_DELETE_WINDOW', self.close)
+        self.poll_job = self.after(100, self.poll)
+
+    def _build(self):
+        style = ttk.Style(self)
+        style.theme_use('clam')
+        style.configure('TFrame', background='#f3f5f8')
+        style.configure('TLabel', background='#f3f5f8', font=('Microsoft YaHei UI', 10))
+        style.configure('TButton', font=('Microsoft YaHei UI', 10), padding=6)
+        style.configure('TLabelframe', background='#f3f5f8')
+        style.configure('TLabelframe.Label', background='#f3f5f8', font=('Microsoft YaHei UI', 10, 'bold'))
+        root = ttk.Frame(self, padding=20)
+        root.pack(fill='both', expand=True)
+        ttk.Label(root, text='动画抽帧', font=('Microsoft YaHei UI', 22, 'bold')).pack(anchor='w')
+        ttk.Label(root, text='均匀采样 · 百分比裁剪 · 等比缩放 · PNG 导出').pack(anchor='w', pady=(2, 16))
+        files = ttk.Frame(root)
+        files.pack(fill='x')
+        for row, (label, variable, command) in enumerate([
+                ('输入素材', self.source, self.choose_source), ('输出目录', self.output, self.choose_output)]):
+            ttk.Label(files, text=label).grid(row=row, column=0, padx=(0, 12), pady=5)
+            ttk.Entry(files, textvariable=variable, state='readonly' if row == 0 else 'normal').grid(row=row, column=1, sticky='ew', pady=5)
+            ttk.Button(files, text='选择…', command=command).grid(row=row, column=2, padx=(10, 0), pady=5)
+        files.columnconfigure(1, weight=1)
+        middle = ttk.Frame(root)
+        sidebar = ttk.Frame(middle, width=340)
+        sidebar.pack(side='left', fill='y', padx=(0, 14))
+        sidebar.pack_propagate(False)
+        self.settings_canvas = tk.Canvas(sidebar, bg='#f3f5f8', highlightthickness=0, width=320)
+        scrollbar = ttk.Scrollbar(sidebar, orient='vertical', command=self.settings_canvas.yview)
+        scrollbar.pack(side='right', fill='y')
+        self.settings_canvas.pack(side='left', fill='both', expand=True)
+        self.settings_canvas.configure(yscrollcommand=scrollbar.set)
+        controls = ttk.Frame(self.settings_canvas)
+        controls_window = self.settings_canvas.create_window((0, 0), window=controls, anchor='nw')
+        def update_scroll_region(_):
+            self.settings_canvas.configure(scrollregion=self.settings_canvas.bbox('all'))
+            sidebar.configure(width=controls.winfo_reqwidth() + scrollbar.winfo_reqwidth() + 4)
+        controls.bind('<Configure>', update_scroll_region)
+        self.settings_canvas.bind('<Configure>', lambda event: self.settings_canvas.itemconfigure(controls_window, width=event.width))
+        self.bind_all('<MouseWheel>', self.scroll_settings)
+        sampling = ttk.LabelFrame(controls, text='采样与命名', padding=12)
+        sampling.pack(fill='x', pady=(0, 12))
+        self.field(sampling, '采样帧数', self.count, 0)
+        self.field(sampling, '文件名前缀', self.prefix, 1)
+        ttk.Label(sampling, text='均匀按帧序号抽取,包含首尾帧。\n抽 1 帧时取首帧;编号从 0 开始。', foreground='#667085').grid(row=2, column=0, columnspan=2, sticky='w', pady=(8, 0))
+        crop = ttk.LabelFrame(controls, text='裁剪边界位置(原图百分比)', padding=12)
+        crop.pack(fill='x', pady=(0, 12))
+        for row, (label, variable) in enumerate(self.crop.items()):
+            self.field(crop, label + '边界 %', variable, row)
+        ttk.Label(crop, text='左 / 上从 0% 起;右 / 下到 100%。\n例如左 10%、右 90%:保留中间 80%。', foreground='#667085').grid(row=4, column=0, columnspan=2, sticky='w', pady=(8, 0))
+        scaling = ttk.LabelFrame(controls, text='裁剪后等比缩放', padding=12)
+        scaling.pack(fill='x')
+        ttk.Label(scaling, text='缩放方式').grid(row=0, column=0, sticky='w', pady=4)
+        ttk.Combobox(scaling, textvariable=self.axis, values=['不缩放', '指定宽度', '指定高度'], state='readonly', width=15).grid(row=0, column=1, padx=(12, 0))
+        self.target_entry = self.field(scaling, '目标像素', self.target, 1)
+        config_panel = ttk.LabelFrame(controls, text='游戏帧配置', padding=12)
+        config_panel.pack(fill='x', pady=(12, 0))
+        self.config_toggle = ttk.Checkbutton(config_panel, text='同时导出帧配置 JSON', variable=self.export_config)
+        self.config_toggle.grid(row=0, column=0, columnspan=2, sticky='w')
+        self.mirror_toggle = ttk.Checkbutton(config_panel, text='生成左右两套(镜像)', variable=self.mirror_directions,
+                                            command=self.update_direction_controls)
+        self.mirror_toggle.grid(row=1, column=0, columnspan=2, sticky='w', pady=4)
+        self.field(config_panel, 'NAME(可留空)', self.config_name, 2)
+        ttk.Label(config_panel, text='输入素材朝向').grid(row=3, column=0, sticky='w', pady=4)
+        self.direction_select = ttk.Combobox(config_panel, textvariable=self.config_direction, values=['0 · 朝右', '1 · 朝左'],
+                                             state='readonly', width=15)
+        self.direction_select.grid(row=3, column=1, padx=(12, 0))
+        self.field(config_panel, 'INTERVAL (ms)', self.config_interval, 4)
+        ttk.Label(config_panel, text='配置名:前缀.json;NAME 留空用前缀。\n勾选:左右两套;镜像 Cx = -Cx - 宽。\n不勾选:前缀_0_idx.png,各方向共用\n同一套图片及当前偏移,不做翻转。', foreground='#667085').grid(row=5, column=0, columnspan=2, sticky='w', pady=(8, 0))
+        preview = ttk.LabelFrame(middle, text='采样结果预览', padding=12)
+        preview.pack(side='left', fill='both', expand=True)
+        ttk.Label(preview, textvariable=self.metadata).pack(anchor='w')
+        self.grid_toggle = ttk.Checkbutton(preview, text='显示游戏网格(固定 40×40 像素,素材按导出尺寸 1:1 显示)',
+                                           variable=self.show_game_grid, command=self.toggle_grid)
+        self.grid_toggle.pack(anchor='w', pady=(6, 0))
+        placement = ttk.Frame(preview)
+        placement.pack(fill='x', pady=(4, 0))
+        self.reset_position_button = ttk.Button(placement, text='位置归零', command=self.reset_preview_position)
+        self.reset_position_button.pack(side='right')
+        self.center_view_button = ttk.Button(placement, text='视野居中', command=self.center_view)
+        self.center_view_button.pack(side='right', padx=6)
+        ttk.Label(placement, textvariable=self.offset_status, wraplength=350).pack(side='left', fill='x', expand=True)
+        ttk.Label(preview, text='左键拖素材 · 右键 / 中键拖视野 · 滚动条移动视野', foreground='#667085').pack(anchor='w', pady=(4, 0))
+        playback = ttk.Frame(preview)
+        playback.pack(side='bottom', fill='x', pady=(8, 0))
+        self.play_button = ttk.Button(playback, text='暂停播放', command=self.toggle_play, state='disabled')
+        self.play_button.pack(side='left')
+        ttk.Label(playback, textvariable=self.playback_status).pack(side='left', padx=10)
+        ttk.Label(preview, textvariable=self.dimensions, wraplength=420).pack(side='bottom', anchor='w')
+        viewport = ttk.Frame(preview)
+        viewport.pack(fill='both', expand=True, pady=10)
+        viewport.rowconfigure(0, weight=1)
+        viewport.columnconfigure(0, weight=1)
+        self.canvas = tk.Canvas(viewport, bg='#222936', highlightthickness=0, width=100, height=100)
+        self.canvas.grid(row=0, column=0, sticky='nsew')
+        xbar = ttk.Scrollbar(viewport, orient='horizontal', command=lambda *args: self.scroll_preview('x', *args))
+        ybar = ttk.Scrollbar(viewport, orient='vertical', command=lambda *args: self.scroll_preview('y', *args))
+        xbar.grid(row=1, column=0, sticky='ew')
+        ybar.grid(row=0, column=1, sticky='ns')
+        self.canvas.configure(xscrollcommand=xbar.set, yscrollcommand=ybar.set)
+        self.canvas.bind('<Configure>', self.resize_preview)
+        self.canvas.bind('<ButtonPress-1>', self.start_drag)
+        self.canvas.bind('<B1-Motion>', self.drag_sprite)
+        self.canvas.bind('<ButtonRelease-1>', self.end_drag)
+        for button in (2, 3):
+            self.canvas.bind(f'<ButtonPress-{button}>', self.start_pan)
+            self.canvas.bind(f'<B{button}-Motion>', self.pan_view)
+            self.canvas.bind(f'<ButtonRelease-{button}>', self.end_pan)
+        bottom = ttk.Frame(root)
+        bottom.pack(fill='x', side='bottom')
+        self.start_button = ttk.Button(bottom, text='导出 PNG', command=self.export)
+        self.start_button.pack(side='right')
+        self.cancel_button = ttk.Button(bottom, text='取消处理', command=self.cancel.set, state='disabled')
+        self.cancel_button.pack(side='right', padx=10)
+        self.progress = ttk.Progressbar(bottom, mode='determinate')
+        self.progress.pack(side='left', fill='x', expand=True, padx=(0, 12))
+        ttk.Label(root, textvariable=self.status, wraplength=920).pack(anchor='w', side='bottom', pady=(10, 8))
+        middle.pack(fill='both', expand=True, pady=16)
+
+    @staticmethod
+    def field(parent, label, variable, row):
+        ttk.Label(parent, text=label).grid(row=row, column=0, sticky='w', pady=4)
+        entry = ttk.Entry(parent, textvariable=variable, width=17)
+        entry.grid(row=row, column=1, padx=(12, 0), pady=4)
+        return entry
+
+    def scroll_settings(self, event):
+        widget = self.winfo_containing(event.x_root, event.y_root)
+        while widget is not None:
+            if widget == self.settings_canvas:
+                self.settings_canvas.yview_scroll(-int(event.delta / 120), 'units')
+                return 'break'
+            widget = getattr(widget, 'master', None)
+
+    def update_direction_controls(self):
+        self.direction_select.configure(state='readonly' if self.mirror_directions.get() else 'disabled')
+
+    def options(self):
+        try:
+            options = Options(count=int(self.count.get()), prefix=self.prefix.get(),
+                              left=float(self.crop['左'].get()), right=float(self.crop['右'].get()),
+                              top=float(self.crop['上'].get()), bottom=float(self.crop['下'].get()),
+                              scale_axis={'不缩放': 'none', '指定宽度': 'width', '指定高度': 'height'}[self.axis.get()],
+                              target=int(self.target.get()) if self.axis.get() != '不缩放' else 1)
+        except (ValueError, KeyError):
+            raise ValueError('帧数、目标像素须为整数;裁剪位置须为数字。') from None
+        options.validate()
+        return options
+
+    def choose_source(self):
+        if self.busy:
+            return
+        filename = filedialog.askopenfilename(title='选择动画素材', filetypes=[('GIF / WebM', '*.gif *.webm'), ('所有文件', '*.*')])
+        if not filename:
+            return
+        path = Path(filename)
+        self.invalidate_preview()
+        self.source.set(str(path))
+        self.output.set(str(path.parent / (path.stem + '_frames')))
+        self.prefix.set(path.stem)
+        self.info = None
+        self.loaded_path = None
+        self.center_pending = True
+        self.grid_region = None
+        self.reset_preview_position()
+        self.canvas.delete('all')
+        self.metadata.set('正在解析素材…')
+        self.dimensions.set('')
+        self.set_busy(True, '正在统计帧数,较长的 WebM 需要一些时间…')
+        self.progress.configure(mode='indeterminate')
+        self.progress.start()
+        self.run_worker(lambda: ('loaded', path, inspect_media(path, self.cancel.is_set)))
+
+    def choose_output(self):
+        if not self.busy:
+            folder = filedialog.askdirectory(title='选择 PNG 输出目录')
+            if folder:
+                self.output.set(folder)
+
+    def set_busy(self, value, text):
+        self.busy = value
+        self.status.set(text)
+        self.start_button.configure(state='disabled' if value else 'normal')
+        self.cancel_button.configure(state='normal' if value else 'disabled')
+        if value:
+            self.cancel.clear()
+
+    def run_worker(self, action):
+        def run():
+            try:
+                self.events.put(action())
+            except Cancelled:
+                self.events.put(('cancelled',))
+            except Exception as error:
+                self.events.put(('error', str(error)))
+        threading.Thread(target=run, daemon=True).start()
+
+    def invalidate_preview(self):
+        self.preview_generation += 1
+        self.preview_cancel.set()
+        for name in ('preview_job', 'play_job'):
+            job = getattr(self, name)
+            if job is not None:
+                self.after_cancel(job)
+                setattr(self, name, None)
+        self.samples = []
+        self.sample_sources = []
+        self.sample_position = 0
+        self.play_button.configure(state='disabled')
+
+    def settings_changed(self, *_):
+        self.invalidate_preview()
+        self.preview()
+        if self.info is not None:
+            self.playback_status.set('正在更新采样预览…')
+            self.preview_job = self.after(350, self.prepare_preview)
+
+    def prepare_preview(self):
+        self.preview_job = None
+        if self.info is None:
+            return
+        try:
+            options = self.options()
+            geometry(self.info.size, options)
+            if not 1 <= options.count <= self.info.count:
+                raise ValueError(f'采样数须在 1 到 {self.info.count} 之间。')
+        except ValueError as error:
+            self.playback_status.set(str(error))
+            return
+        generation = self.preview_generation
+        cancel = self.preview_cancel = threading.Event()
+        path, info = self.loaded_path, self.info
+        bounds = (max(1, self.canvas.winfo_width() - 20), max(1, self.canvas.winfo_height() - 20))
+        def build():
+            try:
+                indices, samples = preview_samples(path, info, options, bounds, cancel.is_set)
+                self.events.put(('preview_ready', generation, indices, samples))
+            except Cancelled:
+                pass
+            except Exception as error:
+                self.events.put(('preview_error', generation, str(error)))
+        threading.Thread(target=build, daemon=True).start()
+
+    def toggle_play(self):
+        self.want_play = not self.want_play
+        self.play_button.configure(text='暂停播放' if self.want_play else '播放预览')
+        if self.play_job is not None:
+            self.after_cancel(self.play_job)
+            self.play_job = None
+        if self.want_play and self.samples:
+            self.play_job = self.after(100, self.advance_frame)
+
+    def advance_frame(self):
+        self.play_job = None
+        if self.samples and self.want_play:
+            self.sample_position = (self.sample_position + 1) % len(self.samples)
+            self.draw_current()
+            self.play_job = self.after(100, self.advance_frame)
+
+    def draw_current(self):
+        self.preview()
+
+    def scroll_preview(self, axis, *args):
+        self.view_centered = False
+        (self.canvas.xview if axis == 'x' else self.canvas.yview)(*args)
+        self.draw_current()
+
+    def resize_preview(self, _):
+        if self.view_centered and self.show_game_grid.get():
+            self.center_pending = True
+        self.draw_current()
+
+    def reset_preview_position(self):
+        self.preview_offset = [0, 0]
+        self.drag_start = None
+        self.canvas.configure(cursor='')
+        self.update_offset_label()
+        self.draw_current()
+
+    def toggle_grid(self):
+        self.drag_start = None
+        self.panning = False
+        if self.show_game_grid.get():
+            self.center_pending = True
+            self.view_centered = True
+        self.draw_current()
+
+    def center_view(self):
+        self.center_pending = True
+        self.view_centered = True
+        self.draw_current()
+
+    def start_pan(self, event):
+        if not self.show_game_grid.get() or self.info is None:
+            return
+        self.drag_start = None
+        self.panning = True
+        self.view_centered = False
+        self.canvas.scan_mark(event.x, event.y)
+        self.canvas.configure(cursor='hand2')
+
+    def pan_view(self, event):
+        if self.panning:
+            self.canvas.scan_dragto(event.x, event.y, gain=1)
+            self.draw_current()
+
+    def end_pan(self, event):
+        if self.panning:
+            self.pan_view(event)
+            self.panning = False
+            self.canvas.configure(cursor='')
+
+    def update_offset_label(self):
+        x, y = self.preview_offset
+        self.offset_status.set(f'偏移 X: {x:+d} px    Y: {y:+d} px(右 / 下为正)')
+
+    def start_drag(self, event):
+        if not self.show_game_grid.get() or self.info is None or self.panning:
+            return
+        bounds = self.canvas.find_withtag('sprite_bounds')
+        if not bounds:
+            return
+        x, y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
+        left, top, right, bottom = self.canvas.coords(bounds[0])
+        if left <= x <= right and top <= y <= bottom:
+            self.view_centered = False
+            self.drag_start = (x, y, *self.preview_offset)
+            self.canvas.configure(cursor='fleur')
+
+    def drag_sprite(self, event):
+        if self.drag_start is None:
+            return
+        x, y, offset_x, offset_y = self.drag_start
+        self.preview_offset = [offset_x + round(self.canvas.canvasx(event.x) - x),
+                               offset_y + round(self.canvas.canvasy(event.y) - y)]
+        self.update_offset_label()
+        self.draw_current()
+
+    def end_drag(self, event):
+        if self.drag_start is not None:
+            self.drag_sprite(event)
+            self.drag_start = None
+            self.canvas.configure(cursor='')
+            self.draw_current()
+
+    def preview(self):
+        if self.info is None:
+            return
+        try:
+            options = self.options()
+            box, size = geometry(self.info.size, options)
+            if self.show_game_grid.get():
+                frame = (self.samples[self.sample_position].copy() if self.samples else transform(self.info.first, options))
+                self.draw_game_grid(frame)
+                self.dimensions.set(f'输出:{size[0]} × {size[1]} px · {size[0] / 40:g} × {size[1] / 40:g} 格\n1:1 显示 · 每格固定 40×40 px · 网格仅用于预览')
+                if self.samples:
+                    self.update_frame_label()
+                return
+            frame = (self.samples[self.sample_position].copy() if self.samples else self.info.first.crop(box))
+            self.drag_start = None
+            self.canvas.configure(cursor='')
+            frame.thumbnail((max(1, self.canvas.winfo_width() - 20), max(1, self.canvas.winfo_height() - 20)), Image.Resampling.LANCZOS)
+            backdrop = Image.new('RGBA', frame.size)
+            from PIL import ImageDraw
+            draw = ImageDraw.Draw(backdrop)
+            for y in range(0, frame.height, 12):
+                for x in range(0, frame.width, 12):
+                    draw.rectangle((x, y, x + 11, y + 11), fill='#d8dde5' if (x // 12 + y // 12) % 2 else '#f4f5f7')
+            backdrop.alpha_composite(frame)
+            self.photo = ImageTk.PhotoImage(backdrop)
+            self.canvas.delete('all')
+            self.canvas.configure(scrollregion=(0, 0, self.canvas.winfo_width(), self.canvas.winfo_height()))
+            self.canvas.xview_moveto(0)
+            self.canvas.yview_moveto(0)
+            self.canvas.create_image(self.canvas.winfo_width() // 2, self.canvas.winfo_height() // 2, image=self.photo)
+            self.dimensions.set(f'裁剪:{box[2] - box[0]} × {box[3] - box[1]} px    →    输出:{size[0]} × {size[1]} px')
+            if self.samples:
+                self.update_frame_label()
+        except ValueError as error:
+            self.canvas.delete('all')
+            self.dimensions.set(str(error))
+
+    def update_frame_label(self):
+        self.playback_status.set(f'{self.sample_position + 1} / {len(self.samples)} 帧 · 原帧 {self.sample_sources[self.sample_position]} · 100 ms')
+
+    def draw_game_grid(self, frame):
+        width, height = self.canvas.winfo_width(), self.canvas.winfo_height()
+        cx, cy = self.reference_center
+        x, y = cx + self.preview_offset[0], cy + self.preview_offset[1]
+        if self.drag_start is None:
+            left, top = self.canvas.canvasx(0), self.canvas.canvasy(0)
+            if self.center_pending:
+                left = round((min(cx - 20, x) + max(cx + 20, x + frame.width) - width) / 2)
+                top = round((min(cy - 20, y) + max(cy + 20, y + frame.height) - height) / 2)
+                self.center_pending = False
+            # Keep generous space on all sides, including negative coordinates.
+            # Never shrink it during playback or sprite dragging.
+            previous = self.grid_region or (cx - 2000, cy - 2000, cx + 2000, cy + 2000)
+            region = (min(previous[0], left - width * 2, x - 80, cx - 80),
+                      min(previous[1], top - height * 2, y - 80, cy - 80),
+                      max(previous[2], left + width * 3, x + frame.width + 80, cx + 80),
+                      max(previous[3], top + height * 3, y + frame.height + 80, cy + 80))
+            self.grid_region = region
+            self.canvas.configure(scrollregion=region)
+            self.canvas.xview_moveto((left - region[0]) / (region[2] - region[0]))
+            self.canvas.yview_moveto((top - region[1]) / (region[3] - region[1]))
+        self.canvas.delete('all')
+        left, top = self.canvas.canvasx(0), self.canvas.canvasy(0)
+        right, bottom = left + width, top + height
+        # Draw only visible lines; scrolling never changes the 40 px spacing.
+        for gx in range(cx - 20 + math.floor((left - cx + 20) / 40) * 40, math.ceil(right), 40):
+            self.canvas.create_line(gx, top, gx, bottom, fill='#526174', tags='game_grid')
+        for gy in range(cy - 20 + math.floor((top - cy + 20) / 40) * 40, math.ceil(bottom), 40):
+            self.canvas.create_line(left, gy, right, gy, fill='#526174', tags='game_grid')
+        self.canvas.create_rectangle(cx - 20, cy - 20, cx + 20, cy + 20,
+                                     fill='#6d5934', outline='', tags='reference_fill')
+        self.photo = ImageTk.PhotoImage(frame)
+        self.canvas.create_image(x, y, anchor='nw', image=self.photo, tags='sprite')
+        self.canvas.create_rectangle(x, y, x + frame.width, y + frame.height,
+                                     outline='#8fc9db', dash=(4, 4), tags='sprite_bounds')
+        self.canvas.create_rectangle(cx - 20, cy - 20, cx + 20, cy + 20,
+                                     outline='#ffc857', width=2, tags='reference_cell')
+        self.canvas.create_line(cx - 5, cy, cx + 5, cy, fill='#ffc857', tags='reference_center')
+        self.canvas.create_line(cx, cy - 5, cx, cy + 5, fill='#ffc857', tags='reference_center')
+
+    def export(self):
+        if self.busy:
+            return
+        try:
+            if self.info is None:
+                raise ValueError('请先选择并载入素材。')
+            options = self.options()
+            geometry(self.info.size, options)
+            if options.count > self.info.count:
+                raise ValueError(f'素材共有 {self.info.count} 帧,采样数不能超过总帧数。')
+            if not self.output.get().strip():
+                raise ValueError('请选择输出目录。')
+            directory = Path(self.output.get())
+            config = None
+            if self.export_config.get():
+                try:
+                    interval = int(self.config_interval.get())
+                except ValueError:
+                    raise ValueError('INTERVAL 须为正整数。') from None
+                config = FrameConfig(name=self.config_name.get().strip() or options.prefix,
+                                     cx=self.preview_offset[0], cy=self.preview_offset[1],
+                                     source_direction=0 if self.config_direction.get() == '0 · 朝右' else 1,
+                                     interval=interval, mirror=self.mirror_directions.get())
+                config.validate(options.prefix)
+        except ValueError as error:
+            messagebox.showerror('请检查设置', str(error), parent=self)
+            return
+        # Capture all settings before starting: edits cannot affect an active run.
+        path, info = self.loaded_path, self.info
+        self.set_busy(True, '正在导出 PNG…')
+        self.progress.configure(mode='determinate', maximum=options.count, value=0)
+        self.run_worker(lambda: ('exported', export_frames(path, directory, info, options,
+                        lambda done, total: self.events.put(('progress', done, total)), self.cancel.is_set, config),
+                        directory / f'{options.prefix}.json' if config else None))
+
+    def poll(self):
+        if getattr(self, 'poll_job', None) is not None:
+            self.after_cancel(self.poll_job)
+            self.poll_job = None
+        try:
+            while True:
+                event = self.events.get_nowait()
+                kind = event[0]
+                if kind in ('preview_ready', 'preview_error'):
+                    if event[1] != self.preview_generation:
+                        continue
+                    if kind == 'preview_error':
+                        self.playback_status.set(event[2])
+                    else:
+                        self.sample_sources, self.samples = event[2:]
+                        self.sample_position = 0
+                        self.play_button.configure(state='normal', text='暂停播放' if self.want_play else '播放预览')
+                        self.draw_current()
+                        if self.want_play:
+                            self.play_job = self.after(100, self.advance_frame)
+                    continue
+                if kind == 'progress':
+                    self.progress['value'] = event[1]
+                    self.status.set(f'正在导出 {event[1]} / {event[2]} 帧…')
+                    continue
+                self.progress.stop()
+                self.progress.configure(mode='determinate')
+                if kind == 'loaded':
+                    self.loaded_path, self.info = event[1:]
+                    self.metadata.set(f'{self.info.size[0]} × {self.info.size[1]} px  ·  共 {self.info.count} 帧')
+                    self.count.set(str(min(16, self.info.count)))
+                    self.set_busy(False, '素材已载入。调整设置后即可导出。')
+                    self.preview()
+                    self.settings_changed()
+                elif kind == 'exported':
+                    self.progress['value'] = self.progress['maximum']
+                    suffix = ' 和 1 个帧配置 JSON' if len(event) > 2 and event[2] else ''
+                    self.set_busy(False, f'已导出 {len(event[1])} 张 PNG{suffix} 至:{event[1][0].parent}')
+                    messagebox.showinfo('导出完成', f'已保存 {len(event[1])} 张 PNG{suffix}。\n{event[1][0].parent}', parent=self)
+                elif kind == 'cancelled':
+                    self.set_busy(False, '处理已取消,本次已导出的文件已撤回。')
+                    if self.info is None:
+                        self.metadata.set('载入已取消')
+                elif kind == 'error':
+                    self.set_busy(False, '处理失败,请检查文件和设置。')
+                    if self.info is None:
+                        self.metadata.set('载入失败')
+                    messagebox.showerror('处理失败', event[1], parent=self)
+        except queue.Empty:
+            pass
+        self.poll_job = self.after(100, self.poll)
+
+    def destroy(self):
+        self.invalidate_preview()
+        if getattr(self, 'poll_job', None) is not None:
+            self.after_cancel(self.poll_job)
+        self.unbind_all('<MouseWheel>')
+        super().destroy()
+
+    def close(self):
+        if self.busy:
+            self.cancel.set()
+            self.status.set('正在取消处理,清理完成后自动关闭…')
+            self.after(100, self._close_when_idle)
+        else:
+            self.destroy()
+
+    def _close_when_idle(self):
+        if self.busy:
+            self.after(100, self._close_when_idle)
+        else:
+            self.destroy()
+
+
+if __name__ == '__main__':
+    import sys
+    if len(sys.argv) == 3 and sys.argv[1] == '--self-test':
+        from smoke_test import run_self_test
+        sys.exit(run_self_test(Path(sys.argv[2]), App))
+    else:
+        App().mainloop()

+ 2 - 0
resource_tool/requirements.txt

@@ -0,0 +1,2 @@
+Pillow>=10.0
+imageio-ffmpeg>=0.6.0

+ 70 - 0
resource_tool/smoke_test.py

@@ -0,0 +1,70 @@
+"""Verify the packaged runtime, including its bundled FFmpeg, from any cwd."""
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import traceback
+
+from PIL import Image
+import imageio_ffmpeg
+
+from core import FrameConfig, Options, export_frames, inspect_media
+
+
+def run_self_test(report_path, app_class):
+    checks = []
+    app = None
+    try:
+        with tempfile.TemporaryDirectory(prefix='animation_tool_') as temp:
+            root = Path(temp)
+            images = [Image.new('RGBA', (160, 80), (i * 70, 100, 150, 255)) for i in range(3)]
+            for image in images:
+                image.putpixel((0, 0), (0, 0, 0, 0))
+            gif = root / '测试动画.gif'
+            images[0].save(gif, save_all=True, append_images=images[1:], duration=100, disposal=2)
+            info = inspect_media(gif)
+            if info.count != 3:
+                raise RuntimeError('GIF frame count mismatch')
+            options = Options(count=2, prefix='role')
+            files = export_frames(gif, root / 'gif', info, options,
+                                  config=FrameConfig('Role', -51, -85))
+            data = json.loads((root / 'gif/role.json').read_text(encoding='utf-8'))
+            if len(files) != 4 or data['HEAD_POS'] != [-65, -5] or data['L']['Cx'] != -109:
+                raise RuntimeError('Mirrored config or negative HEAD_POS mismatch')
+            with Image.open(files[0]) as image:
+                if image.getpixel((0, 0))[3] != 0:
+                    raise RuntimeError('GIF transparency mismatch')
+            checks.append('GIF, transparency, mirrored offsets and negative HEAD_POS')
+            files = export_frames(gif, root / 'single', info, options,
+                                  config=FrameConfig('Role', -51, -85, mirror=False))
+            if [p.name for p in files] != ['role_0_0.png', 'role_0_1.png']:
+                raise RuntimeError('Single-direction naming mismatch')
+            checks.append('Single-direction PNG and JSON export')
+            webm = root / '测试视频.webm'
+            subprocess.run([imageio_ffmpeg.get_ffmpeg_exe(), '-v', 'error', '-f', 'rawvideo',
+                            '-pix_fmt', 'rgb24', '-s', '160x80', '-r', '10', '-i', 'pipe:0',
+                            '-c:v', 'libvpx-vp9', '-lossless', '1', str(webm)],
+                           input=b''.join(im.convert('RGB').tobytes() for im in images),
+                           check=True, capture_output=True,
+                           creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
+            video_info = inspect_media(webm)
+            files = export_frames(webm, root / 'webm', video_info, options)
+            if video_info.count != 3 or len(files) != 2:
+                raise RuntimeError('Bundled FFmpeg WebM decode mismatch')
+            checks.append('Bundled FFmpeg WebM encode, decode and PNG export')
+            app = app_class()
+            app.withdraw()
+            app.update()
+            if not app.mirror_directions.get():
+                raise RuntimeError('Default mirror setting mismatch')
+            app.destroy()
+            app = None
+            checks.append('Packaged Tk GUI initialization')
+        result = {'ok': True, 'checks': checks}
+    except Exception:
+        result = {'ok': False, 'checks': checks, 'error': traceback.format_exc()}
+    finally:
+        if app is not None:
+            app.destroy()
+    Path(report_path).write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
+    return 0 if result['ok'] else 1

+ 430 - 0
resource_tool/test_tool.py

@@ -0,0 +1,430 @@
+import subprocess
+import json
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+import imageio_ffmpeg
+from PIL import Image, ImageOps
+
+from core import Cancelled, Options, FrameConfig, export_frames, geometry, inspect_media, sample_indices, preview_samples
+
+
+class ExtractionTests(unittest.TestCase):
+    def setUp(self):
+        self.temp = tempfile.TemporaryDirectory()
+        self.root = Path(self.temp.name)
+        self.gif = self.root / '中文 动画.gif'
+        images = []
+        for i in range(7):
+            image = Image.new('RGBA', (40, 20), (0, 0, 0, 0))
+            for x in range(10, 30):
+                for y in range(5, 15):
+                    image.putpixel((x, y), (i * 35, 240 - i * 30, 50, 255))
+            images.append(image)
+            image.putpixel((10, 5), (255, 255, 255, 255))
+        images[0].save(self.gif, save_all=True, append_images=images[1:],
+                       duration=100, disposal=2, loop=0)
+
+    def tearDown(self):
+        self.temp.cleanup()
+
+    def test_sampling_and_gif_transparency(self):
+        info = inspect_media(self.gif)
+        self.assertEqual(info.count, 7)
+        self.assertEqual(sample_indices(7, 4), [0, 2, 4, 6])
+        self.assertEqual(sample_indices(7, 1), [0])
+        for total in range(1, 40):
+            for count in range(1, total + 1):
+                indices = sample_indices(total, count)
+                self.assertEqual(len(set(indices)), count)
+                self.assertEqual(indices, sorted(indices))
+        files = export_frames(self.gif, self.root / '输出', info, Options(count=4, prefix='角色'))
+        self.assertEqual([f.name for f in files], [f'角色_{i}.png' for i in range(4)])
+        for path, source_idx in zip(files, [0, 2, 4, 6]):
+            with Image.open(path) as result:
+                self.assertEqual(result.getpixel((20, 10)), (source_idx * 35, 240 - source_idx * 30, 50, 255))
+                self.assertEqual(result.getpixel((0, 0))[3], 0)
+
+    def test_crop_resize_and_no_overwrite(self):
+        info = inspect_media(self.gif)
+        options = Options(count=3, left=25, right=75, top=25, bottom=75,
+                          scale_axis='width', target=80)
+        files = export_frames(self.gif, self.root / 'sized', info, options)
+        with Image.open(files[0]) as result:
+            self.assertEqual(result.size, (80, 40))
+            self.assertEqual(result.getpixel((40, 20)), (0, 240, 50, 255))
+        before = files[0].read_bytes()
+        with self.assertRaises(ValueError):
+            export_frames(self.gif, files[0].parent, info, options)
+        self.assertEqual(before, files[0].read_bytes())
+        self.assertEqual(geometry(info.size, Options(scale_axis='height', target=33))[1], (66, 33))
+
+    def test_invalid_settings_and_cancel_rollback(self):
+        for options in [Options(left=80, right=20), Options(top=float('nan')),
+                        Options(prefix='../bad'), Options(count=0)]:
+            with self.assertRaises(ValueError):
+                options.validate()
+        info = inspect_media(self.gif)
+        with self.assertRaises(ValueError):
+            export_frames(self.gif, self.root / 'bad', info, Options(count=8))
+        stopped = [False]
+        with self.assertRaises(Cancelled):
+            export_frames(self.gif, self.root / 'cancel', info, Options(count=7),
+                          lambda *_: stopped.__setitem__(0, True), lambda: stopped[0])
+        self.assertEqual(list((self.root / 'cancel').iterdir()), [])
+
+    def test_real_webm(self):
+        video = self.root / '视频.webm'
+        pixels = b''.join(Image.new('RGB', (40, 20), (i * 30, 100, 150)).tobytes() for i in range(6))
+        subprocess.run([imageio_ffmpeg.get_ffmpeg_exe(), '-v', 'error', '-f', 'rawvideo',
+                        '-pix_fmt', 'rgb24', '-s', '40x20', '-r', '10', '-i', 'pipe:0',
+                        '-c:v', 'libvpx-vp9', '-lossless', '1', str(video)], input=pixels, check=True)
+        info = inspect_media(video)
+        self.assertEqual((info.count, info.size), (6, (40, 20)))
+        files = export_frames(video, self.root / 'webm', info, Options(count=3, scale_axis='height', target=10))
+        for path, source_idx in zip(files, [0, 3, 5]):
+            with Image.open(path) as result:
+                self.assertEqual(result.size, (20, 10))
+                self.assertLessEqual(abs(result.getpixel((10, 5))[0] - source_idx * 30), 4)
+
+    def test_frame_config_and_mirrored_images(self):
+        info = inspect_media(self.gif)
+        options = Options(count=3, prefix='角色', left=25, right=75, top=25, bottom=75,
+                          scale_axis='width', target=160)
+        config = FrameConfig('RogueTest', -51, -85, source_direction=1)
+        output = self.root / 'config'
+        files = export_frames(self.gif, output, info, options, config=config)
+        self.assertEqual(len(files), 6)
+        data = json.loads((output / '角色.json').read_text(encoding='utf-8'))
+        template = json.loads((Path(__file__).parent.parent / 'game/frame/character/Rogue59.json').read_text(encoding='utf-8'))
+        self.assertEqual(list(data), list(template))
+        self.assertEqual(data['HEAD_POS'], [-65, -5])
+        self.assertEqual(data['NAME'], 'RogueTest')
+        self.assertEqual(data['INTERVAL'], 200)
+        for action in ('STAND_R', 'STAND_U', 'STAND_L', 'STAND_D', 'R', 'U', 'L', 'D'):
+            item = data[action]
+            direction = 0 if action.endswith(('R', 'D')) else 1
+            self.assertEqual((item['Len'], item['Cx'], item['Cy']), (3, -51 if direction == 1 else -109, -85))
+            self.assertEqual(item['Cloth']['CX'], [0] * 3)
+            self.assertEqual(item['Cloth']['CY'], [0] * 3)
+            self.assertEqual(item['Cloth']['IMG'], [f'角色_{direction}_{i}.png' for i in range(3)])
+            self.assertTrue(all((output / name).is_file() for name in item['Cloth']['IMG']))
+        from core import transform
+        with Image.open(output / '角色_1_0.png') as left, Image.open(output / '角色_0_0.png') as right:
+            expected = transform(info.first, options)
+            self.assertEqual(left.tobytes(), expected.tobytes())
+            self.assertEqual(right.tobytes(), ImageOps.mirror(expected).tobytes())
+
+    def test_mirrored_offset_preserves_world_anchor(self):
+        info = inspect_media(self.gif)
+        for direction in (0, 1):
+            for width, cx in ((160, -51), (161, 13), (160, -80)):
+                with self.subTest(direction=direction, width=width, cx=cx):
+                    options = Options(count=1, scale_axis='width', target=width)
+                    folder = self.root / f'anchor_{direction}_{width}_{cx}'
+                    export_frames(self.gif, folder, info, options,
+                                  config=FrameConfig('Anchor', cx, -85, direction))
+                    data = json.loads((folder / 'frame.json').read_text())
+                    original_key, mirror_key = ('R', 'L') if direction == 0 else ('L', 'R')
+                    original, mirrored = data[original_key], data[mirror_key]
+                    self.assertEqual(original['Cx'], cx)
+                    self.assertEqual(mirrored['Cx'], -cx - width)
+                    self.assertEqual(original['Cy'], mirrored['Cy'])
+                    scenes = []
+                    for item in (original, mirrored):
+                        scene = Image.new('RGBA', (600, 300))
+                        with Image.open(folder / item['Cloth']['IMG'][0]) as sprite:
+                            scene.alpha_composite(sprite, (300 + item['Cx'], 150 + item['Cy']))
+                        scenes.append(scene)
+                    # Check actual rendered pixels about the same world anchor,
+                    # including positive offsets and odd output widths.
+                    self.assertEqual(ImageOps.mirror(scenes[0]).tobytes(), scenes[1].tobytes())
+
+    def test_config_collision_and_failure_rollback(self):
+        info = inspect_media(self.gif)
+        options = Options(count=2)
+        config = FrameConfig('Test')
+        output = self.root / 'collision'
+        output.mkdir()
+        (output / 'frame.json').write_text('existing', encoding='utf-8')
+        with self.assertRaises(ValueError):
+            export_frames(self.gif, output, info, options, config=config)
+        self.assertEqual(list(output.iterdir()), [output / 'frame.json'])
+        self.assertEqual((output / 'frame.json').read_text(), 'existing')
+        with patch('core.json.dump', side_effect=OSError('disk full')):
+            with self.assertRaises(OSError):
+                export_frames(self.gif, self.root / 'rollback', info, options, config=config)
+        self.assertEqual(list((self.root / 'rollback').iterdir()), [])
+
+    def test_single_direction_config_without_mirror(self):
+        info = inspect_media(self.gif)
+        for direction in (0, 1):
+            with self.subTest(source_direction=direction):
+                folder = self.root / f'single_{direction}'
+                options = Options(count=3, prefix='static', scale_axis='width', target=100)
+                config = FrameConfig('StaticMonster', -31, -63, direction, mirror=False)
+                files = export_frames(self.gif, folder, info, options, config=config)
+                self.assertEqual([p.name for p in files], [f'static_0_{i}.png' for i in range(3)])
+                self.assertEqual(len(list(folder.glob('*.png'))), 3)
+                data = json.loads((folder / 'static.json').read_text())
+                self.assertEqual(data['HEAD_POS'], [-35, 0])
+                for key in ('STAND_R', 'STAND_U', 'STAND_L', 'STAND_D', 'R', 'U', 'L', 'D'):
+                    self.assertEqual((data[key]['Len'], data[key]['Cx'], data[key]['Cy']), (3, -31, -63))
+                    self.assertEqual(data[key]['Cloth']['IMG'], [p.name for p in files])
+                    self.assertEqual(data[key]['Cloth']['CX'], [0] * 3)
+                    self.assertEqual(data[key]['Cloth']['CY'], [0] * 3)
+                from core import transform
+                with Image.open(files[0]) as image:
+                    self.assertEqual(image.tobytes(), transform(info.first, options).tobytes())
+
+    def test_gui_config_export_snapshot(self):
+        import time
+        from main import App
+        app = App()
+        try:
+            app.update()
+            app.events.put(('loaded', self.gif, inspect_media(self.gif)))
+            app.poll()
+            app.output.set(str(self.root / 'gui_config'))
+            app.count.set('2')
+            app.prefix.set('test')
+            app.preview_offset = [-24, -72]
+            app.config_toggle.invoke()
+            with patch('main.messagebox.showinfo'), patch('main.messagebox.showerror') as error:
+                app.start_button.invoke()
+                app.preview_offset = [999, 999]
+                deadline = time.monotonic() + 5
+                while app.busy and time.monotonic() < deadline:
+                    app.update()
+                    time.sleep(0.01)
+                self.assertFalse(app.busy)
+                error.assert_not_called()
+            data = json.loads((self.root / 'gui_config/test.json').read_text(encoding='utf-8'))
+            self.assertEqual(data['NAME'], 'test')
+            self.assertEqual((data['R']['Cx'], data['R']['Cy']), (-24, -72))
+            self.assertEqual(data['HEAD_POS'], [-5, 0])
+            self.assertEqual(len(list((self.root / 'gui_config').glob('*.png'))), 4)
+            self.assertTrue(app.mirror_directions.get())
+            app.mirror_toggle.invoke()
+            self.assertEqual(str(app.direction_select.cget('state')), 'disabled')
+            app.output.set(str(self.root / 'gui_single'))
+            app.preview_offset = [-24, -72]
+            with patch('main.messagebox.showinfo'), patch('main.messagebox.showerror') as error:
+                app.start_button.invoke()
+                deadline = time.monotonic() + 5
+                while app.busy and time.monotonic() < deadline:
+                    app.update()
+                    time.sleep(0.01)
+                self.assertFalse(app.busy)
+                error.assert_not_called()
+            single = json.loads((self.root / 'gui_single/test.json').read_text())
+            self.assertEqual(single['R'], single['L'])
+            self.assertEqual(single['L']['Cloth']['IMG'], ['test_0_0.png', 'test_0_1.png'])
+            self.assertEqual(len(list((self.root / 'gui_single').glob('*.png'))), 2)
+            app.mirror_toggle.invoke()
+            self.assertEqual(str(app.direction_select.cget('state')), 'readonly')
+        finally:
+            app.destroy()
+
+    def test_gui_preview_and_export_button(self):
+        import time
+        from main import App
+        app = App()
+        try:
+            app.update()
+            self.assertTrue(app.start_button.winfo_ismapped())
+            self.assertLess(app.start_button.winfo_rooty() - app.winfo_rooty(), app.winfo_height())
+            app.events.put(('loaded', self.gif, inspect_media(self.gif)))
+            app.poll()
+            app.output.set(str(self.root / 'gui'))
+            app.prefix.set('界面')
+            app.count.set('3')
+            app.crop['左'].set('25')
+            app.crop['右'].set('75')
+            app.axis.set('指定宽度')
+            app.target.set('60')
+            app.update()
+            self.assertIn('60 × 60', app.dimensions.get())
+            app.grid_toggle.invoke()
+            self.assertEqual((app.photo.width(), app.photo.height()), (60, 60))
+            self.assertIn('1.5 × 1.5 格', app.dimensions.get())
+            def check_grid_spacing():
+                lines = [app.canvas.coords(item) for item in app.canvas.find_withtag('game_grid')]
+                vertical = [line[0] for line in lines if line[0] == line[2]]
+                self.assertGreater(len(vertical), 1)
+                self.assertTrue(all(b - a == 40 for a, b in zip(vertical, vertical[1:])))
+            check_grid_spacing()
+            app.target.set('800')
+            app.update()
+            self.assertEqual((app.photo.width(), app.photo.height()), (800, 800))
+            check_grid_spacing()
+            self.assertLess(app.canvas.xview()[1], 1)
+            app.scroll_preview('x', 'moveto', 1)
+            check_grid_spacing()
+            app.target.set('60')
+            app.update()
+            def drag_world(start, end):
+                left, top = app.canvas.canvasx(0), app.canvas.canvasy(0)
+                sx, sy = round(start[0] - left), round(start[1] - top)
+                ex, ey = round(end[0] - left), round(end[1] - top)
+                app.canvas.event_generate('<ButtonPress-1>', x=sx, y=sy)
+                app.canvas.event_generate('<B1-Motion>', x=ex, y=ey)
+                app.canvas.event_generate('<ButtonRelease-1>', x=ex, y=ey)
+            app.center_view_button.invoke()
+            reference = app.canvas.coords(app.canvas.find_withtag('reference_cell')[0])
+            self.assertEqual(reference, [80, 80, 120, 120])
+            bounds = app.canvas.coords(app.canvas.find_withtag('sprite_bounds')[0])
+            self.assertEqual(bounds[:2], [100, 100])
+            drag_world((110, 110), (73, 180))
+            self.assertEqual(app.preview_offset, [-37, 70])
+            self.assertIn('X: -37 px', app.offset_status.get())
+            self.assertIn('Y: +70 px', app.offset_status.get())
+            self.assertEqual(app.canvas.coords(app.canvas.find_withtag('reference_cell')[0]), reference)
+            self.assertEqual(app.canvas.coords(app.canvas.find_withtag('sprite_bounds')[0])[:2], [63, 170])
+            # A redraw or a settings change must not move the reference or reset placement.
+            app.draw_current()
+            app.target.set('80')
+            app.update()
+            self.assertEqual(app.preview_offset, [-37, 70])
+            app.reset_position_button.invoke()
+            self.assertEqual(app.preview_offset, [0, 0])
+            app.target.set('60')
+            app.update()
+            # Leave a nonzero placement active while exporting.
+            drag_world((110, 110), (140, 150))
+            self.assertEqual(app.preview_offset, [30, 40])
+            with patch('main.messagebox.showinfo'), patch('main.messagebox.showerror') as error:
+                app.start_button.invoke()
+                deadline = time.monotonic() + 15
+                while app.busy and time.monotonic() < deadline:
+                    app.update()
+                    time.sleep(0.02)
+                self.assertFalse(app.busy)
+                error.assert_not_called()
+            self.assertEqual(len(list((self.root / 'gui').glob('界面_*.png'))), 3)
+            with Image.open(self.root / 'gui' / '界面_0.png') as result:
+                self.assertEqual(result.size, (60, 60))
+                self.assertEqual(result.getpixel((0, 0))[3], 0)
+                # Grid enabled in the UI must not change any exported pixel.
+                from core import transform
+                expected = transform(app.info.first, app.options())
+                self.assertEqual(result.tobytes(), expected.tobytes())
+        finally:
+            app.destroy()
+
+    def test_center_and_pan_view_without_moving_sprite(self):
+        from main import App
+        app = App()
+        try:
+            app.update()
+            app.events.put(('loaded', self.gif, inspect_media(self.gif)))
+            app.poll()
+            app.axis.set('指定宽度')
+            app.target.set('144')
+            app.preview_offset = [-61, -117]
+            app.grid_toggle.invoke()
+            app.update()
+            width, height = app.canvas.winfo_width(), app.canvas.winfo_height()
+            left, top = app.canvas.canvasx(0), app.canvas.canvasy(0)
+            # Center both the sprite and reference cell, including negative placement.
+            self.assertAlmostEqual(left + width / 2, (39 + 183) / 2, delta=1)
+            self.assertAlmostEqual(top + height / 2, (-17 + 120) / 2, delta=1)
+            before_sprite = app.canvas.coords(app.canvas.find_withtag('sprite_bounds')[0])
+            before_offset = app.preview_offset.copy()
+            before_label = app.offset_status.get()
+            for button, dx, dy in [(3, 140, 70), (2, -90, -45)]:
+                old_left, old_top = app.canvas.canvasx(0), app.canvas.canvasy(0)
+                app.canvas.event_generate(f'<ButtonPress-{button}>', x=150, y=100)
+                app.canvas.event_generate(f'<B{button}-Motion>', x=150 + dx, y=100 + dy)
+                app.canvas.event_generate(f'<ButtonRelease-{button}>', x=150 + dx, y=100 + dy)
+                self.assertAlmostEqual(app.canvas.canvasx(0), old_left - dx, delta=1)
+                self.assertAlmostEqual(app.canvas.canvasy(0), old_top - dy, delta=1)
+                self.assertEqual(app.preview_offset, before_offset)
+                self.assertEqual(app.offset_status.get(), before_label)
+                self.assertEqual(app.canvas.coords(app.canvas.find_withtag('sprite_bounds')[0]), before_sprite)
+            held_view = (app.canvas.canvasx(0), app.canvas.canvasy(0))
+            for _ in range(4):
+                app.draw_current()
+            self.assertEqual(held_view, (app.canvas.canvasx(0), app.canvas.canvasy(0)))
+            app.scroll_preview('x', 'scroll', -1, 'pages')
+            self.assertLess(app.canvas.canvasx(0), held_view[0])
+            self.assertEqual(app.preview_offset, before_offset)
+            app.center_view_button.invoke()
+            self.assertAlmostEqual(app.canvas.canvasx(0), left, delta=1)
+            self.assertAlmostEqual(app.canvas.canvasy(0), top, delta=1)
+            self.assertEqual(app.preview_offset, before_offset)
+        finally:
+            app.destroy()
+
+    def test_scrollable_settings_and_animation(self):
+        import time
+        from main import App
+        app = App()
+        def pump_until(predicate, timeout=5):
+            deadline = time.monotonic() + timeout
+            while not predicate() and time.monotonic() < deadline:
+                app.update()
+                time.sleep(0.005)
+            self.assertTrue(predicate())
+        try:
+            # Reproduce a shorter window with larger system text.
+            app.tk.call('tk', 'scaling', 1.75)
+            app.geometry('1000x600')
+            app.update()
+            app.settings_canvas.yview_moveto(1)
+            app.update()
+            canvas = app.settings_canvas
+            entry = app.target_entry
+            # Scaling is no longer the final section; scroll it into view explicitly.
+            region = [float(value) for value in canvas.cget('scrollregion').split()]
+            canvas.yview_moveto((canvas.canvasy(entry.winfo_rooty() - canvas.winfo_rooty()) - 20) / region[3])
+            app.update()
+            self.assertGreaterEqual(entry.winfo_rooty(), canvas.winfo_rooty())
+            self.assertLessEqual(entry.winfo_rooty() + entry.winfo_height(), canvas.winfo_rooty() + canvas.winfo_height())
+            self.assertLessEqual(entry.winfo_rootx() + entry.winfo_width(), canvas.winfo_rootx() + canvas.winfo_width())
+            self.assertTrue(app.start_button.winfo_ismapped())
+            app.events.put(('loaded', self.gif, inspect_media(self.gif)))
+            app.poll()
+            app.count.set('3')
+            pump_until(lambda: len(app.samples) == 3)
+            self.assertEqual(app.sample_sources, [0, 3, 6])
+            # Confirm scheduled playback advances and wraps at the requested cadence.
+            positions = []
+            last = app.sample_position
+            started = time.monotonic()
+            while len(positions) < 4 and time.monotonic() - started < 2:
+                app.update()
+                if last != app.sample_position:
+                    positions.append((app.sample_position, time.monotonic()))
+                    last = app.sample_position
+                time.sleep(0.003)
+            self.assertEqual([p[0] for p in positions], [1, 2, 0, 1])
+            for before, after in zip(positions, positions[1:]):
+                self.assertGreaterEqual(after[1] - before[1], 0.09)
+                self.assertLess(after[1] - before[1], 0.25)
+            app.play_button.invoke()
+            paused = app.sample_position
+            until = time.monotonic() + 0.25
+            while time.monotonic() < until:
+                app.update()
+                time.sleep(0.005)
+            self.assertEqual(app.sample_position, paused)
+            app.count.set('2')
+            app.crop['左'].set('25')
+            app.crop['右'].set('75')
+            app.axis.set('指定宽度')
+            app.target.set('60')
+            pump_until(lambda: len(app.samples) == 2)
+            self.assertEqual(app.sample_sources, [0, 6])
+            self.assertEqual(app.samples[0].size, (60, 60))
+            self.assertFalse(app.want_play)
+            app.play_button.invoke()
+            pump_until(lambda: app.sample_position == 1)
+        finally:
+            app.destroy()
+
+
+if __name__ == '__main__':
+    unittest.main()

+ 2 - 1
test_menu.py

@@ -1036,6 +1036,7 @@ def show_hero_name(hero):
     if hero == "mxfc": return "梦小繁(残冰制)"
     if hero == "Flandre": return "芙兰朵露(雨制)"
     if hero == "Remilia": return "蕾米莉亚(雨制)"
+    if hero == "DeepseekBlueWhale": return "蓝色大肥鱼(DeepSeek)"
 
     if hero == "Red": return "红色"
     if hero == "Blue": return "蓝色"
@@ -1140,7 +1141,7 @@ def draw_game_settings():
          "choices": [
              "Maomao", "Asha", "Monkey", "Titan", "Fox", "FoxPlus", "Maria", "CaiBaozi", "Xiami", "Chunli", "Boboli",
              "XingZai", "SeaPrince_old", "Naruto_old", "Cola", "SeaPrince", "Naruto", "Nezha", "Chris",
-             "mxfc", "Flandre", "Remilia"
+             "mxfc", "Flandre", "Remilia", "DeepseekBlueWhale"
          ]},
         {"name": "your_character_color", "label": "角色颜色:",
          "choices": [

+ 217 - 0
tests/test_bomb_index_and_boss_cache.py

@@ -0,0 +1,217 @@
+"""Second-batch regression checks without starting the game or writing saves."""
+import math
+import random
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock
+
+from test_render_optimizations import load_definitions, pixels, CountingSurface, ROOT
+import pygame
+
+
+class BombIndexTest(unittest.TestCase):
+    def setUp(self):
+        ns = load_definitions("client_local/level/level.py", {}, classes={"Level": {"get_bomb_instance"}})
+        self.cl = ns["Level"]()
+        self.cl.bomb_instances = []
+        self.cl._bomb_position_index = {}
+        self.cl._bomb_index_dirty = True
+        self.cl.map_x = self.cl.map_y = 20
+        self.cl.map_x_pos = self.cl.map_y_pos = 800
+        self.cl.obstacle_instances = {}
+        self.level_module = SimpleNamespace(current_level=self.cl)
+        self.ticks = 0
+        ns = {"level": self.level_module, "pygame": SimpleNamespace(time=SimpleNamespace(get_ticks=lambda: self.ticks)),
+              "G": SimpleNamespace(GAME_SQUARE=40, HALF_GAME_SQUARE=20), "math": math,
+              "updatable": SimpleNamespace(current_grid=lambda x, y: (int(x//40), int(y//40))),
+              "bomb_direction": {"R": 1}}
+        load_definitions("client_local/sprite/bomb_instance.py", ns, classes={"BombInstance": {
+            "x", "y", "throwing", "_set_indexed_value", "setup", "uninstall", "set_restoration", "update_pos"}})
+        load_definitions("client_local/sprite/throwable.py", ns, functions={"cal_y"},
+                         classes={"Throwable": {"throw_to", "throw", "get_points"}})
+        self.Bomb = ns["BombInstance"]
+        for name in ("throw_to", "throw", "get_points"):
+            setattr(self.Bomb, name, getattr(ns["Throwable"], name))
+
+    def bomb(self, x, y):
+        b = self.Bomb()
+        b.x, b.y, b.throwing = x, y, False
+        b.x_pos, b.y_pos = x*40+20, y*40+20
+        b.bomb_instances_list = self.cl.bomb_instances
+        b.player = SimpleNamespace(restore_a_bomb=Mock())
+        b.current_point = 0
+        b.update_time_old = 0
+        b.setup()
+        return b
+
+    def assert_index_matches_scan(self):
+        for x in range(6):
+            for y in range(6):
+                expected = [b for b in self.cl.bomb_instances if b.x == x and b.y == y and not b.throwing]
+                self.assertEqual(self.cl.get_bomb_instance(x, y), expected)
+
+    def test_stacked_bombs_order_snapshot_and_chain_removal(self):
+        a, b, c = [self.bomb(1, 2) for _ in range(3)]
+        snapshot = self.cl.get_bomb_instance(1, 2)
+        self.assertEqual(snapshot, [a, b, c])
+        self.cl.get_bomb_instance(1, 2).clear()
+        self.assertEqual(self.cl.get_bomb_instance(1, 2), snapshot)
+        for bomb in snapshot:
+            bomb.uninstall()
+            self.assertNotIn(bomb, self.cl.get_bomb_instance(1, 2))
+            bomb.player.restore_a_bomb.assert_called_once_with()
+        self.assertEqual(self.cl.get_bomb_instance(1, 2), [])
+
+    def test_throw_start_destination_and_landing_invalidate_immediately(self):
+        for target in (3, 22):  # Includes wrapped landing coordinates.
+            bomb = self.bomb(1, 2)
+            self.assertEqual(self.cl.get_bomb_instance(1, 2), [bomb])
+            bomb.throw_to(target, 2, "R", True)
+            self.assertEqual(self.cl.get_bomb_instance(1, 2), [])
+            self.assertEqual(self.cl.get_bomb_instance(target % 20, 2), [])
+            self.ticks += 100000
+            bomb.throw()
+            bomb.throw()
+            self.assertFalse(bomb.throwing)
+            self.assertEqual(self.cl.get_bomb_instance(target % 20, 2), [bomb])
+            bomb.uninstall()
+
+    def test_conveyor_and_floating_cross_grid_boundaries(self):
+        for conveyor in (True, False):
+            bomb = self.bomb(1, 2)
+            self.cl.get_bomb_instance(1, 2)
+            self.cl.block = object()
+            self.cl.slide_orientation = {(1, 2): (1, 5)} if conveyor else {}
+            bomb.floating = not conveyor
+            bomb.floating_direction = "R"
+            bomb.floating_speed = 5
+            bomb.get_ruld_block = lambda: (0,) * 8
+            def slide(*args):
+                bomb.x_pos, bomb.y_pos = 201, 201
+            bomb.slide = slide
+            bomb.update_pos(100)
+            self.assertEqual(self.cl.get_bomb_instance(1, 2), [])
+            self.assertEqual(self.cl.get_bomb_instance(5, 5), [bomb])
+            bomb.uninstall()
+
+    def test_random_mutations_match_linear_reference(self):
+        rng = random.Random(13)
+        for _ in range(300):
+            live = self.cl.bomb_instances
+            action = rng.randrange(5)
+            if not live or action == 0:
+                self.bomb(rng.randrange(6), rng.randrange(6))
+            else:
+                b = rng.choice(live)
+                if action == 1:
+                    b.x, b.y = rng.randrange(6), rng.randrange(6)
+                elif action == 2:
+                    b.throwing = not b.throwing
+                elif action == 3:
+                    b.uninstall()
+                else:
+                    b.x, b.y = b.x, b.y
+            self.assert_index_matches_scan()
+
+    def test_unchanged_queries_reuse_index_and_old_level_stays_isolated(self):
+        bomb = self.bomb(1, 2)
+        self.cl.get_bomb_instance(1, 2)
+        index = self.cl._bomb_position_index
+        bomb.x, bomb.y, bomb.throwing = 1, 2, False
+        self.assertFalse(self.cl._bomb_index_dirty)
+        for _ in range(20):
+            self.cl.get_bomb_instance(3, 4)
+            self.assertIs(self.cl._bomb_position_index, index)
+        new_level = SimpleNamespace(_bomb_index_dirty=False)
+        self.level_module.current_level = new_level
+        bomb.x = 5
+        self.assertTrue(self.cl._bomb_index_dirty)
+        self.assertFalse(new_level._bomb_index_dirty)
+
+
+class BossBarCacheTest(unittest.TestCase):
+    def setUp(self):
+        self.ticks = 0
+        pg = SimpleNamespace(Surface=pygame.Surface, SRCALPHA=pygame.SRCALPHA,
+                             time=SimpleNamespace(get_ticks=lambda: self.ticks))
+        self.ns = load_definitions("client_local/ui/game/blood_bar.py", {"pygame": pg, "math": math},
+            functions={"_render_boss_blood_sheet"}, classes={
+                "BossBloodBar": {"update", "set_blood", "set_max_blood"},
+                "BossLongBloodBar": {"update", "set_blood", "set_max_blood"}})
+        self.image = pygame.image.load(str(ROOT / "res/img/ui/game/img_bossLife2.png"))
+
+    def bar(self, long=True):
+        bar = self.ns["BossLongBloodBar" if long else "BossBloodBar"]()
+        bar.rect = pygame.Rect(0, 0, 562 if long else 162, 20)
+        bar.sheet = CountingSurface(bar.rect.size)
+        bar.blood_slice_img = self.image
+        bar.blood_slice_idx = 554 if long else 154
+        bar.max_blood = 1000
+        bar.blood_slice_last_update_time = 0
+        bar.user = SimpleNamespace(remain_blood=1000, fake_blood=0)
+        return bar
+
+    def reference(self, bar, length):
+        sheet = pygame.Surface(bar.rect.size, pygame.SRCALPHA, 32)
+        for i in range(length):
+            sheet.blit(bar.blood_slice_img, (i+2, 4))
+        return sheet
+
+    def test_every_visible_length_matches_original_overlapping_pixels(self):
+        for long in (False, True):
+            bar = self.bar(long)
+            for length in range(-1, bar.rect.width + 4):
+                bar.blood_slice_idx = length
+                bar.set_blood(1000)
+                self.assertEqual(pixels(bar.sheet), pixels(self.reference(bar, length)), (long, length))
+
+    def test_animation_timing_healing_damage_and_fake_blood_unchanged(self):
+        for long in (False, True):
+            bar = self.bar(long)
+            bar.set_blood(1000)
+            last_time, length = 0, bar.blood_slice_idx
+            expected = pixels(self.reference(bar, length))
+            for tick in range(0, 30000, 25):
+                self.ticks = tick
+                bar.user.remain_blood = 200 if tick < 10000 else 900
+                bar.user.fake_blood = 100 if tick > 20000 else 0
+                if tick - last_time > (50 if long else 100):
+                    last_time = tick
+                    expected = pixels(self.reference(bar, length))
+                    target = math.ceil((bar.user.remain_blood - bar.user.fake_blood) * (554 if long else 154) / bar.max_blood)
+                    if target != length:
+                        delta = max(1, int(abs(length-target)/5)) if long else 1
+                        length += delta if target > length else -delta
+                bar.update()
+                self.assertEqual(bar.blood_slice_idx, length)
+                self.assertEqual(pixels(bar.sheet), expected)
+                self.assertTrue(bar.redraw_trigger)
+
+    def test_stable_bar_does_not_allocate_or_clear_sheet(self):
+        bar = self.bar()
+        bar.set_blood(1000)
+        sheet, strip = bar.sheet, bar._boss_strip
+        fills = sheet.fills
+        for tick in range(101, 3001, 101):
+            self.ticks = tick
+            bar.update()
+        self.assertIs(bar.sheet, sheet)
+        self.assertIs(bar._boss_strip, strip)
+        self.assertEqual(sheet.fills, fills)
+
+    def test_short_translucent_tail_and_replaced_sheet_or_texture(self):
+        bar = self.bar()
+        texture = pygame.Surface((5, 12), pygame.SRCALPHA)
+        texture.fill((81, 160, 223, 91))
+        bar.blood_slice_img = texture
+        for length in (0, 1, 2, 3, 4, 5, 100):
+            bar.blood_slice_idx = length
+            bar.set_blood(1000)
+            self.assertEqual(pixels(bar.sheet), pixels(self.reference(bar, length)))
+        bar.sheet = pygame.Surface(bar.rect.size, pygame.SRCALPHA)
+        bar.set_blood(1000)
+        self.assertEqual(pixels(bar.sheet), pixels(self.reference(bar, 100)))
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 368 - 0
tests/test_render_optimizations.py

@@ -0,0 +1,368 @@
+"""Headless regression tests; do not construct Control or touch game saves.
+
+Load selected production definitions via AST to avoid the client's circular
+imports and asset-loading startup. Pixel comparisons use real pygame Surfaces.
+"""
+import ast
+import os
+from pathlib import Path
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock
+
+os.environ.setdefault("SDL_VIDEODRIVER", "dummy")
+os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
+os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1")
+
+import numpy as np
+import pygame
+
+from client_local.algo import blender
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def load_definitions(path, namespace, functions=(), classes=None):
+    tree = ast.parse((ROOT / path).read_text(encoding="utf-8-sig"))
+    nodes = []
+    for node in tree.body:
+        if isinstance(node, ast.FunctionDef) and node.name in functions:
+            nodes.append(node)
+        elif isinstance(node, ast.ClassDef) and node.name in (classes or {}):
+            methods = classes[node.name]
+            if methods is not None:
+                node.body = [n for n in node.body if isinstance(n, ast.FunctionDef) and n.name in methods]
+                node.bases = []
+            nodes.append(node)
+    exec(compile(ast.Module(body=nodes, type_ignores=[]), str(ROOT / path), "exec"), namespace)
+    return namespace
+
+
+def pixels(surface):
+    return pygame.image.tobytes(surface, "RGBA")
+
+
+class CountingSurface(pygame.Surface):
+    def __init__(self, size):
+        super().__init__(size, pygame.SRCALPHA)
+        self.fills = 0
+
+    def fill(self, *args, **kwargs):
+        self.fills += 1
+        return super().fill(*args, **kwargs)
+
+
+class NameCacheTest(unittest.TestCase):
+    def setUp(self):
+        pygame.font.init()
+        self.flags = SimpleNamespace(DISPLAY_NPC_NAME_CARD=True, DISPLAY_NPC_BLOOD=False)
+        ns = load_definitions(
+            "client_local/sprite/npc.py", {"G": self.flags},
+            classes={"Npc": {"update_npc_blood_display"}},
+        )
+        self.npc = ns["Npc"]()
+        self.npc.chs_name = "Boss"
+        self.npc.remain_blood = 100
+        self.npc.fake_blood = 2
+        self.npc.chs_name_font = Mock(wraps=pygame.font.Font(None, 13))
+        self.npc._name_display_cache_key = None
+
+    def test_unchanged_name_reuses_both_images_and_alpha(self):
+        npc = self.npc
+        npc.update_npc_blood_display(0)
+        images = (npc.chs_name_text, npc.chs_name_text_shadow)
+        npc.chs_name_text.set_alpha(123)
+        for t in range(100):
+            npc.update_npc_blood_display(t)
+        self.assertEqual(npc.chs_name_font.render.call_count, 2)
+        self.assertIs(npc.chs_name_text, images[0])
+        self.assertIs(npc.chs_name_text_shadow, images[1])
+        self.assertEqual(npc.chs_name_text.get_alpha(), 123)
+
+    def test_name_blood_font_and_visibility_changes(self):
+        npc = self.npc
+        npc.update_npc_blood_display(0)
+        npc.chs_name = "New boss"
+        npc.update_npc_blood_display(0)
+        self.assertEqual(npc.chs_name_font.render.call_count, 4)
+        self.flags.DISPLAY_NPC_BLOOD = True
+        npc.update_npc_blood_display(0)
+        self.assertEqual(npc._name_display_cache_key[1], "98")
+        npc.remain_blood -= 1
+        npc.update_npc_blood_display(0)
+        self.assertEqual(npc.chs_name_font.render.call_count, 8)
+        self.flags.DISPLAY_NPC_NAME_CARD = False
+        npc.remain_blood = 10
+        npc.update_npc_blood_display(0)
+        self.assertEqual(npc.chs_name_font.render.call_count, 8)
+        self.flags.DISPLAY_NPC_NAME_CARD = True
+        npc.update_npc_blood_display(0)
+        self.assertEqual(npc._name_display_cache_key[1], "8")
+        npc.chs_name_font = Mock(wraps=pygame.font.Font(None, 15))
+        npc.update_npc_blood_display(0)
+        self.assertEqual(npc.chs_name_font.render.call_count, 2)
+        self.flags.DISPLAY_NPC_BLOOD = False
+        npc.update_npc_blood_display(0)
+        self.assertEqual(npc._name_display_cache_key[1], "New boss")
+
+
+class BlendClipTest(unittest.TestCase):
+    def test_all_modes_match_full_blend_inside_clip(self):
+        rng = np.random.RandomState(42)
+        source = pygame.surfarray.make_surface(rng.randint(0, 256, (31, 27, 3), dtype=np.uint8))
+        alpha = rng.randint(0, 256, (31, 27), dtype=np.uint8)
+        for mode in (blender.BLEND_SCREEN, blender.BLEND_MULTIPLY, blender.BLEND_OVERLAY):
+            # Existing overlay uses 2D byte alpha; screen/multiply use expanded alpha.
+            a = alpha if mode == blender.BLEND_OVERLAY else blender.broaden_alpha(alpha)
+            for pos in ((-7, -4), (8, 9), (43, 37), (0, -50), (90, 0)):
+                for clip in (pygame.Rect(7, 6, 25, 23), pygame.Rect(0, 0, 60, 50), pygame.Rect(0, 0, 0, 0)):
+                    with self.subTest(mode=mode, pos=pos, clip=clip):
+                        base = pygame.surfarray.make_surface(rng.randint(0, 256, (60, 50, 3), dtype=np.uint8))
+                        full = base.copy()
+                        blender.blit(source, a, full, pos, mode)
+                        expected = base.copy()
+                        expected.blit(full, clip, clip)
+                        actual = base.copy()
+                        actual.set_clip(clip)
+                        blender.blit(source, a, actual, pos, mode)
+                        self.assertEqual(pixels(expected), pixels(actual))
+                        self.assertFalse(actual.get_locked())
+                        self.assertFalse(source.get_locked())
+
+    def test_offscreen_blend_does_not_read_pixels(self):
+        surface = pygame.Surface((50, 50))
+        surface.set_clip((10, 10, 10, 10))
+        # Invalid pixel sources would fail if the fast rejection didn't happen.
+        blender.blit(pygame.Surface((5, 5)), None, surface, (30, 30), blender.BLEND_SCREEN)
+
+
+def light(x, y, strength, hidden=False):
+    return SimpleNamespace(x_pos=x, y_pos=y, light=strength, is_hide_sight=lambda: hidden)
+
+
+class WorldRenderTest(unittest.TestCase):
+    def setUp(self):
+        self.flags = SimpleNamespace(MAIN_AREA_X_POS=80, MAIN_AREA_Y_POS=52)
+        masks = {}
+        for i in range(1, 10):
+            radius = i * 20
+            surface = pygame.Surface((radius * 2, radius * 2), pygame.SRCALPHA)
+            for r in range(radius):
+                distance = radius - r
+                value = 255 - int(255 / radius * distance)
+                pygame.draw.circle(surface, (value,) * 4, (radius, radius), distance)
+            masks[i] = surface
+        self.ns = load_definitions(
+            "client_local/level/level.py",
+            {"pygame": pygame, "G": self.flags, "Y_SCALE_FACTOR": 1, "circleMasks": masks,
+             "MASK_STEP": 20, "_last_light_states": None, "_last_colour_light_states": None},
+            functions={"_render_light_mask", "get_player_mask", "special_colour_mask"},
+            classes={"MainArea": None, "Level": {"get_render_view_rect", "apply_light_masks", "update"}},
+        )
+        self.level = self.ns["Level"]()
+        self.ns["current_level"] = self.level
+        self.level.scroll_x_pos = 30
+        self.level.scroll_y_pos = 40
+        self.level.main_area = self.ns["MainArea"]((180, 160))
+        self.level.mask_surface = CountingSurface((80, 52))
+        self.level.colour_mask_surface = CountingSurface((81, 52))
+        self.level.bg_light = 47
+        self.level.rgb_light = [120, 60, 30]
+        self.level.special_rgb = True
+        self.level.haunt_Mode = True
+        self.level.me = light(63.5, 81.2, 1)
+        self.level.npcs = [light(142, 125, 2), light(0.5, 1.5, 3, True)]
+        obstacle = light(20, 40, 2)
+        self.level.obstacle_instances = {(0, 0): obstacle, (0, 1): obstacle}
+
+    def legacy_blit(self, dest, source, pos, area=None, flags=0):
+        x, y = pos
+        bias = (y - self.level.scroll_y_pos - 26) * (1 - self.ns["Y_SCALE_FACTOR"])
+        dest.blit(source, (x, int(y - bias)), area, flags)
+
+    def legacy_lighting(self, dest):
+        cl = self.level
+        if cl.special_rgb:
+            mask = pygame.Surface(dest.get_size(), pygame.SRCALPHA)
+            mask.fill((*[max(0, min(v, 255)) for v in cl.rgb_light], 0))
+            for p in [cl.me] + cl.npcs + list(cl.obstacle_instances.values()):
+                if p.light:
+                    r = p.light * 20
+                    mask.blit(self.ns["circleMasks"][p.light], (p.x_pos-r, p.y_pos-r-15), special_flags=pygame.BLEND_RGBA_ADD)
+            self.legacy_blit(dest, mask, (0, 0), flags=pygame.BLEND_RGBA_MULT)
+        if cl.haunt_Mode:
+            mask = pygame.Surface(dest.get_size(), pygame.SRCALPHA)
+            bgl = max(0, min(cl.bg_light, 255))
+            mask.fill((bgl, bgl, bgl, 0))
+            players = [p for p in [cl.me] + cl.npcs if not p.is_hide_sight()]
+            view = pygame.Rect(cl.scroll_x_pos, cl.scroll_y_pos, 80, 52)
+            for p in players + list(cl.obstacle_instances.values()):
+                if p.light:
+                    r = p.light * 20
+                    if view.inflate(2*r, 2*(r+15)).collidepoint(p.x_pos, p.y_pos):
+                        mask.blit(self.ns["circleMasks"][p.light], (p.x_pos-cl.scroll_x_pos-r, p.y_pos-cl.scroll_y_pos-r-15), special_flags=pygame.BLEND_RGBA_ADD)
+            view = view.clip(dest.get_rect())
+            if view.w and view.h:
+                self.legacy_blit(dest.subsurface(view), mask, (0, 0), flags=pygame.BLEND_RGBA_MULT)
+
+    def test_clipped_world_matches_full_render_including_large_sprites_and_quake(self):
+        cl = self.level
+        small = pygame.Surface((17, 23), pygame.SRCALPHA)
+        small.fill((190, 50, 70, 150))
+        large = pygame.Surface((130, 100), pygame.SRCALPHA)
+        large.fill((20, 100, 230, 90))
+        for factor in (1, 0.7, 1.2):
+            self.ns["Y_SCALE_FACTOR"] = factor
+            for scroll in ((0, 0), (30.7, 40.3), (100, 108)):
+                cl.scroll_x_pos, cl.scroll_y_pos = scroll
+                expected = pygame.Surface((180, 160))
+                expected.fill((21, 43, 65))
+                actual = cl.main_area
+                actual.set_clip(None)
+                actual.fill((21, 43, 65))
+                actual.set_clip(cl.get_render_view_rect())
+                for image, pos in ((small, (-10.7, -5.2)), (large, (-40, -20)), (small, (80, 65)), (large, (100, 110)), (small, (150, 10))):
+                    self.legacy_blit(expected, image, pos)
+                    actual.blit(image, pos)
+                rect = cl.get_render_view_rect()
+                self.assertEqual(pixels(expected.subsurface(rect)), pixels(actual.subsurface(rect)))
+
+    def test_masks_match_legacy_pixels_at_scroll_edges_and_during_quake(self):
+        cl = self.level
+        for size in ((180, 160), (40, 30)):
+            cl.main_area = self.ns["MainArea"](size)
+            scrolls = ((0, 0),) if size == (40, 30) else ((0, 0), (30.7, 40.3), (100, 108))
+            for factor in (1, 0.8, 1.2):
+                self.ns["Y_SCALE_FACTOR"] = factor
+                for scroll in scrolls:
+                    cl.scroll_x_pos, cl.scroll_y_pos = scroll
+                    for colour, haunt in ((True, False), (False, True), (True, True)):
+                        with self.subTest(size=size, factor=factor, scroll=scroll, colour=colour, haunt=haunt):
+                            cl.special_rgb, cl.haunt_Mode = colour, haunt
+                            for _ in range(2):  # Repeat also checks simultaneous-mode cache isolation.
+                                expected = pygame.Surface(size)
+                                expected.fill((200, 180, 130))
+                                self.legacy_lighting(expected)
+                                cl.main_area.set_clip(None)
+                                cl.main_area.fill((200, 180, 130))
+                                cl.main_area.set_clip(cl.get_render_view_rect())
+                                cl.apply_light_masks()
+                                rect = cl.get_render_view_rect()
+                                self.assertEqual(pixels(expected.subsurface(rect)), pixels(cl.main_area.subsurface(rect)))
+
+    def test_mask_cache_reuses_unchanged_pixels_and_invalidates_when_needed(self):
+        cl = self.level
+        cl.main_area.set_clip(cl.get_render_view_rect())
+        cl.apply_light_masks()
+        for _ in range(10):
+            cl.apply_light_masks()
+        self.assertEqual(cl.mask_surface.fills, 1)
+        self.assertEqual(cl.colour_mask_surface.fills, 1)
+        cl.npcs.append(light(10000, 10000, 1))
+        cl.apply_light_masks()
+        self.assertEqual(cl.mask_surface.fills, 1)
+        cl.me.x_pos += 3
+        cl.apply_light_masks()
+        self.assertEqual(cl.mask_surface.fills, 2)
+        cl.bg_light = 55
+        cl.rgb_light[0] = 90
+        cl.apply_light_masks()
+        self.assertEqual(cl.mask_surface.fills, 3)
+        self.assertEqual(cl.colour_mask_surface.fills, 3)
+
+    def test_level_update_keeps_offscreen_logic_and_restores_clip_before_ui(self):
+        cl = self.level
+        self.ns["BombInstance"] = SimpleNamespace(sound_played=True)
+        cl.score_board = cl.time_board = None
+        cl.intro_chat_started = cl.intro_chat_active = True
+        cl.grid_damage_frame = 0
+        cl.wanderers = []
+        cl.teammates = []
+        cl.pets = []
+        cl.ghosts = []
+        cl.bomb_instances = []
+        cl.flame_instances = []
+        cl.item_instances = {}
+        cl.obstacle_instances_need_to_update = False
+        cl.obstacle_instances_update = []
+        cl.transport_obstacle = []
+        cl._cached_item_count = 0
+        cl._static_dirty = False
+        cl._static_sorted = []
+        cl.grid_damage_orientations = set()
+        cl.floor_image = pygame.Surface(cl.main_area.get_size())
+        cl.floor_image.fill((50, 80, 120))
+        cl.left_black = pygame.Surface((1, 1))
+        for name in ("run_earth_quake_effect", "display_frame_rate", "start_ending_sequence_if_needed",
+                     "pass_map", "portal_map", "draw_background_png", "update_particles"):
+            setattr(cl, name, Mock())
+        cl.skill_instances = [SimpleNamespace(update=Mock())]
+        image = pygame.Surface((10, 10), pygame.SRCALPHA)
+        image.fill((220, 110, 20, 128))
+
+        def make_actor(x, y):
+            actor = light(x, y, 0)
+            actor.remain_blood = 10
+            actor.update = Mock()
+            actor.get_y = lambda: y
+            def draw(surface):
+                self.assertEqual(surface.get_clip(), cl.get_render_view_rect())
+                surface.blit(image, (x, y))
+            actor.draw = Mock(side_effect=draw)
+            return actor
+
+        cl.me = make_actor(60, 70)
+        offscreen = make_actor(150, 145)
+        cl.npcs = [offscreen]
+        cl.effects_behind = [make_actor(500, 500)]
+        cl.effects_front = [make_actor(70, 50)]
+        cl.effects_screen = []
+        cl.draw_dynamic_object = lambda obj: obj.draw(cl.main_area)
+        original_clip = cl.main_area.get_clip()
+
+        def draw_ui(screen):
+            self.assertEqual(cl.main_area.get_clip(), original_clip)
+
+        cl.ui_instances_top = [SimpleNamespace(update=Mock(), draw=Mock(side_effect=draw_ui))]
+        cl.ui_instances_bot = [SimpleNamespace(update=Mock(), draw=Mock(side_effect=draw_ui))]
+        screen = pygame.Surface((120, 100))
+        for scroll in (30, 35, 40):
+            cl.scroll_x_pos = scroll
+            cl.update(screen)
+            self.assertEqual(cl.main_area.get_clip(), original_clip)
+        self.assertEqual(offscreen.update.call_count, 3)
+        self.assertEqual(offscreen.draw.call_count, 3)
+        self.assertEqual(cl.skill_instances[0].update.call_count, 3)
+        self.assertEqual(cl.effects_behind[0].update.call_count, 3)
+
+
+class ClockLifetimeTest(unittest.TestCase):
+    def test_clock_created_once_for_multiple_frames(self):
+        class Finished(Exception):
+            pass
+
+        clock = Mock()
+        clock.tick.side_effect = [None, None, Finished()]
+        fake_pygame = SimpleNamespace(
+            time=SimpleNamespace(Clock=Mock(return_value=clock)),
+            event=SimpleNamespace(get=lambda: []),
+            display=SimpleNamespace(flip=Mock()),
+        )
+        ns = load_definitions("client_local/control.py", {"pygame": fake_pygame}, classes={"Control": {"update"}})
+        control = ns["Control"]()
+        control.current_level = SimpleNamespace(finish_flag=False, custom_finish_flag=False, update=Mock())
+        control.screen = object()
+        control.description_shown = False
+        control.frame_rate = 60
+        control.key_pressed = Mock()
+        with self.assertRaises(Finished):
+            control.update()
+        fake_pygame.time.Clock.assert_called_once_with()
+        self.assertEqual(clock.tick.call_count, 3)
+        self.assertEqual(control.current_level.update.call_count, 3)
+        self.assertEqual(fake_pygame.display.flip.call_count, 3)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 199 - 0
tests/test_skill_combo.py

@@ -0,0 +1,199 @@
+import unittest
+
+from client_local.skill.skill_combo import (
+    SkillComboDefinition,
+    SkillComboError,
+    SkillComboRunner,
+)
+
+
+class SkillComboDefinitionTest(unittest.TestCase):
+    def test_sample_features_expand_to_normal_skills(self):
+        combo = SkillComboDefinition(
+            "TestSprayFireball",
+            {
+                "params": ["combo_angle", "combo_damage", "combo_init", "combo_interval"],
+                "inner_variables": [
+                    {"name": "x", "value_type": "list", "values": [0, 60, 120]},
+                    {
+                        "name": "i",
+                        "value_type": "range",
+                        "values": {"start": 0, "end": 2, "delta": 1},
+                    },
+                    {
+                        "name": "z",
+                        "value_type": "computed_list",
+                        "values": [60, "*", "i", "+", "combo_angle"],
+                    },
+                    {
+                        "name": "fire_ball_init",
+                        "value_type": "computed_scalar",
+                        "values": ["(", "combo_init", "+", 400, ")", "/", 2],
+                    },
+                ],
+                "skills": [
+                    {
+                        "skill_type": "single",
+                        "name": "Skill21018",
+                        "init": "combo_init",
+                        "interval": "combo_interval",
+                        "max": 1,
+                    },
+                    {
+                        "skill_type": "one_loop",
+                        "name": "Fireball",
+                        "init": "fire_ball_init",
+                        "interval": "combo_interval",
+                        "params": ["combo_damage", "x", "z"],
+                        "max": 1,
+                    },
+                ],
+            },
+        )
+
+        result = combo.expand(
+            {
+                "combo_angle": 30,
+                "combo_damage": 50,
+                "combo_init": 600,
+                "combo_interval": 3000,
+            }
+        )
+
+        self.assertEqual(4, len(result))
+        self.assertEqual(600, result[0]["init"])
+        self.assertEqual([50, 0, 30], result[1]["params"])
+        self.assertEqual([50, 60, 90], result[2]["params"])
+        self.assertEqual(500, result[3]["init"])
+        self.assertNotIn("skill_type", result[3])
+
+    def test_outer_product(self):
+        combo = SkillComboDefinition(
+            "Grid",
+            {
+                "inner_variables": [
+                    {"name": "x", "value_type": "list", "values": [1, 2]},
+                    {"name": "y", "value_type": "list", "values": [10, 20, 30]},
+                ],
+                "skills": [
+                    {
+                        "skill_type": "outer_product",
+                        "name": "PointSkill",
+                        "init": 0,
+                        "interval": 1000,
+                        "params": ["x", "y"],
+                        "max": 1,
+                    }
+                ],
+            },
+        )
+
+        result = combo.expand({})
+
+        self.assertEqual(
+            [[1, 10], [1, 20], [1, 30], [2, 10], [2, 20], [2, 30]],
+            [skill["params"] for skill in result],
+        )
+
+    def test_one_loop_requires_equal_lengths(self):
+        combo = SkillComboDefinition(
+            "BadLoop",
+            {
+                "inner_variables": [
+                    {"name": "x", "value_type": "list", "values": [1]},
+                    {"name": "y", "value_type": "list", "values": [1, 2]},
+                ],
+                "skills": [
+                    {
+                        "skill_type": "one_loop",
+                        "name": "PointSkill",
+                        "init": 0,
+                        "interval": 1000,
+                        "params": ["x", "y"],
+                        "max": 1,
+                    }
+                ],
+            },
+        )
+
+        with self.assertRaisesRegex(SkillComboError, "长度不一致"):
+            combo.expand({})
+
+    def test_computed_scalar_rejects_list(self):
+        combo = SkillComboDefinition(
+            "BadScalar",
+            {
+                "inner_variables": [
+                    {"name": "x", "value_type": "list", "values": [1, 2]},
+                    {"name": "y", "value_type": "computed_scalar", "values": ["x", "+", 1]},
+                ],
+                "skills": [
+                    {"skill_type": "single", "name": "Skill", "init": 0, "interval": 1, "max": 1}
+                ],
+            },
+        )
+
+        with self.assertRaisesRegex(SkillComboError, "不能引用列表变量"):
+            combo.expand({})
+
+    def test_inner_init_starts_when_outer_combo_is_called(self):
+        combo = SkillComboDefinition(
+            "Reusable",
+            {
+                "params": ["damage", "delay"],
+                "skills": [
+                    {
+                        "skill_type": "single",
+                        "name": "ImmediateSkill",
+                        "init": 0,
+                        "interval": 1000,
+                        "params": ["damage"],
+                        "max": 1,
+                    },
+                    {
+                        "skill_type": "single",
+                        "name": "DelayedSkill",
+                        "init": "delay",
+                        "interval": 1000,
+                        "params": ["damage"],
+                        "max": 1,
+                    }
+                ],
+            },
+        )
+        current_time = [5000]
+        user = _FakeNpc()
+
+        runner = SkillComboRunner(
+            user,
+            combo,
+            {"damage": 88, "delay": 400},
+            user.skill_instances,
+            time_provider=lambda: current_time[0],
+        )
+
+        self.assertEqual([("ImmediateSkill", [88])], user.calls)
+        current_time[0] = 5399
+        runner.update()
+        self.assertEqual(1, len(user.calls))
+        current_time[0] = 5400
+        runner.update()
+        self.assertEqual(
+            [("ImmediateSkill", [88]), ("DelayedSkill", [88])],
+            user.calls,
+        )
+        self.assertNotIn(runner, user.skill_instances)
+
+
+class _FakeNpc:
+    def __init__(self):
+        self.remain_blood = 100
+        self.skill_instances = []
+        self.calls = []
+
+    def using_skill_map(self, name, params, spawn_order, skill_spawns=None, combo_stack=None):
+        self.calls.append((name, params))
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 18 - 0
试玩蓝色大肥鱼.py

@@ -0,0 +1,18 @@
+"""Play the new character on the currently selected map without editing config.json."""
+import os
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent
+os.chdir(str(ROOT))
+
+from client_local.control import Control
+
+
+class BlueWhaleControl(Control):
+    def init_game(self):
+        super().init_game()
+        self.cfg_json['your_hero'] = 'DeepseekBlueWhale'
+
+
+if __name__ == '__main__':
+    BlueWhaleControl()