"""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))