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