extra_tools.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. """Move, spray, directional expansion and clean map export."""
  2. import random
  3. from datetime import datetime
  4. from pathlib import Path
  5. from runtime_paths import PROJECT_ROOT
  6. import pygame
  7. from const.window import WINDOW_W, MAP_AT, GAME_SQUARE
  8. from game.frame import floor, obstacle
  9. class ExtraTools:
  10. def __init__(self, app):
  11. self.app = app
  12. self.values = dict(radius='3', density='30', left='0', top='0')
  13. self.reset()
  14. def reset(self):
  15. self.focus = None
  16. self.start = self.end = None
  17. self.sources = []
  18. def fields(self):
  19. names = [('radius', '半径(格)'), ('density', '密度(%)')] if self.app.tools.tool == 'spray' else [('left', '向左拓展'), ('top', '向上拓展')]
  20. return [(key, label, pygame.Rect(WINDOW_W + 130, 308 + i*44, 100, 32)) for i, (key, label) in enumerate(names)]
  21. def expand(self, left, top):
  22. if left < 0 or top < 0:
  23. raise ValueError('拓展格数不能为负数')
  24. data = self.app.document_snapshot()
  25. basic = data['basic']
  26. width, height = basic['width'] + left, basic['height'] + top
  27. if width > 256 or height > 256 or width*height > 10000:
  28. raise ValueError('地图最多 256×256,且总格数不超过 10000')
  29. basic.update(width=width, height=height)
  30. for key in ('begin', 'finish', 'scroll'):
  31. if key in basic:
  32. basic[key] = [basic[key][0]+left, basic[key][1]+top]
  33. for layer in ('floor', 'obstacle'):
  34. for node in data[layer]:
  35. for point in node['points']:
  36. point['x'] += left
  37. point['y'] += top
  38. for region in data.get('districts', []):
  39. square = region['square']
  40. for key in ('x1', 'x2'):
  41. square[key] += left
  42. for key in ('y1', 'y2'):
  43. square[key] += top
  44. for npc in region.get('npcs', []):
  45. npc['x'] += left
  46. npc['y'] += top
  47. self.app.menu.edit(lambda: self.app.restore_document(data))
  48. self.app.selection.cancel()
  49. self.app.menu.notify('地图已拓展,所有元素和初始视野已平移;Ctrl+Z 撤销')
  50. def spray(self, cell):
  51. app = self.app
  52. brush = app.current_elem
  53. if len(app.selection.group) == 1:
  54. node = app.selection.group[0]
  55. brush = dict(elem_type=node['layer'], type=node['type'], name=node['name'])
  56. if len(app.selection.group) > 1 or not brush.get('elem_type'):
  57. raise ValueError('请选择单个 1×1 障碍物或地板')
  58. if brush['elem_type'] == 'obstacle':
  59. obs = obstacle.get_obstacle(brush['type'], brush['name'])
  60. if obs['WIDTH'] != 1 or obs['HEIGHT'] != 1:
  61. raise ValueError('喷溅笔只支持 1×1 障碍物')
  62. radius, density = int(self.values['radius']), int(self.values['density'])
  63. if not 1 <= radius <= 50 or not 0 <= density <= 100:
  64. raise ValueError('半径须为 1–50 格,密度须为 0–100%')
  65. candidates = [(x, y) for x in range(max(0, cell[0]-radius), min(app.map_size[0], cell[0]+radius+1))
  66. for y in range(max(0, cell[1]-radius), min(app.map_size[1], cell[1]+radius+1))
  67. if (x-cell[0])**2+(y-cell[1])**2 <= radius**2 and
  68. (brush['elem_type'] == 'floor' or (x, y) not in app.map_obstacles_dict)]
  69. points = random.sample(candidates, round(len(candidates)*density/100))
  70. previous = app.current_elem
  71. def action():
  72. app.current_elem = brush
  73. try:
  74. for point in points:
  75. app.add_elem(point)
  76. finally:
  77. app.current_elem = previous
  78. app.menu.edit(action)
  79. def move_to(self, cell):
  80. app = self.app
  81. app.menu.finish_stroke()
  82. before = app.document_snapshot()
  83. sources = {app.map_obstacles_dict.get(pos) for pos in self.source_positions}
  84. if None in sources:
  85. self.sources = []
  86. app.selection.cancel()
  87. app.menu.notify('原选区已改变,请重新框选')
  88. return False
  89. for obj in sources:
  90. obj.uninstall()
  91. if not app.selection.place(cell):
  92. app.restore_document(before)
  93. self.sources = [app.map_obstacles_dict[pos] for pos in self.source_positions]
  94. return False
  95. app.menu.record(before)
  96. self.sources = []
  97. app.selection.cancel()
  98. return True
  99. def export_buttons(self):
  100. return [(False, '只导出地图', pygame.Rect(WINDOW_W+12, 308, 180, 38)),
  101. (True, '包含区域和怪物', pygame.Rect(WINDOW_W+204, 308, 230, 38))]
  102. def export(self, include_regions=False):
  103. app = self.app
  104. surface = pygame.Surface((app.map_size[0]*GAME_SQUARE, app.map_size[1]*GAME_SQUARE), pygame.SRCALPHA)
  105. for node in app.map_json['floor']:
  106. tile = floor.get_floor(node['type'], node['name'])
  107. for point in node['points']:
  108. surface.blit(tile, (point['x']*GAME_SQUARE, point['y']*GAME_SQUARE))
  109. for obj in sorted(set(app.map_obstacles_dict.values()), key=lambda obj: obj.get_y()):
  110. obj.draw(surface)
  111. missing = set()
  112. if include_regions:
  113. regions = app.tools.regions
  114. npcs = []
  115. for index, region in enumerate(app.map_json.get('districts', [])):
  116. square = region['square']
  117. x1, x2 = sorted((square['x1'], square['x2']))
  118. y1, y2 = sorted((square['y1'], square['y2']))
  119. rect = pygame.Rect(x1*GAME_SQUARE, y1*GAME_SQUARE,
  120. (x2-x1+1)*GAME_SQUARE, (y2-y1+1)*GAME_SQUARE)
  121. color = regions.COLORS[index % len(regions.COLORS)]
  122. pygame.draw.rect(surface, (12, 16, 22), rect, 7)
  123. pygame.draw.rect(surface, color, rect, 3)
  124. surface.blit(app.text_font.render('区域 %d' % (index+1), True, color), (rect.x+6, rect.y+6))
  125. npcs.extend((npc, regions.npc_color(index, n)) for n, npc in enumerate(region.get('npcs', [])))
  126. for npc, color in sorted(npcs, key=lambda item: item[0].get('y', 0)):
  127. if not regions.models.draw(surface, npc, (0, 0), color, frame_index=0, show_vision=False):
  128. missing.add(npc.get('name', ''))
  129. regions.monster_icon(surface, pygame.Rect(npc['x']*GAME_SQUARE+8, npc['y']*GAME_SQUARE+8, 24, 24), color)
  130. directory = PROJECT_ROOT / 'map_editor_eport'
  131. directory.mkdir(exist_ok=True)
  132. path = directory / ('map_%s_%dx%d.png' % (datetime.now().strftime('%Y%m%d_%H%M%S_%f'), *app.map_size))
  133. pygame.image.save(surface, str(path))
  134. app.menu.notify('已导出:' + path.name + (';%d 种怪物模型缺失,已用图标代替' % len(missing) if missing else ''))
  135. return path
  136. def handle_event(self, event):
  137. app = self.app
  138. tool = app.tools.tool
  139. if tool not in ('move', 'spray', 'expand', 'export'):
  140. return False
  141. if tool == 'export':
  142. if app.tools.visible and event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
  143. for include_regions, label, rect in self.export_buttons():
  144. if rect.collidepoint(event.pos):
  145. app.menu.invoke(lambda: self.export(include_regions))
  146. app.menu.block_pointer = True
  147. return True
  148. return False
  149. if self.focus is not None and event.type == pygame.KEYDOWN:
  150. value = self.values[self.focus]
  151. keypad = {getattr(pygame, 'K_KP%d' % n): str(n) for n in range(10)}
  152. digit = keypad.get(event.key, getattr(event, 'unicode', ''))
  153. if event.key in (pygame.K_RETURN, pygame.K_KP_ENTER, pygame.K_ESCAPE):
  154. self.focus = None
  155. elif event.key in (pygame.K_LEFT, pygame.K_RIGHT, pygame.K_HOME, pygame.K_END):
  156. if event.key == pygame.K_HOME:
  157. self.cursor = 0
  158. elif event.key == pygame.K_END:
  159. self.cursor = len(value)
  160. else:
  161. self.cursor = max(0, min(len(value), self.cursor + (-1 if event.key == pygame.K_LEFT else 1)))
  162. self.select_all = False
  163. elif event.key in (pygame.K_BACKSPACE, pygame.K_DELETE):
  164. if self.select_all:
  165. self.values[self.focus], self.cursor = '', 0
  166. elif event.key == pygame.K_BACKSPACE and self.cursor:
  167. self.values[self.focus] = value[:self.cursor-1]+value[self.cursor:]
  168. self.cursor -= 1
  169. elif event.key == pygame.K_DELETE:
  170. self.values[self.focus] = value[:self.cursor]+value[self.cursor+1:]
  171. self.select_all = False
  172. elif digit.isdigit():
  173. if self.select_all:
  174. value, self.cursor = '', 0
  175. self.values[self.focus] = value[:self.cursor]+digit+value[self.cursor:]
  176. self.cursor += len(digit)
  177. self.select_all = False
  178. return True
  179. if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
  180. self.focus = None
  181. if app.tools.visible and tool in ('spray', 'expand'):
  182. for key, label, rect in self.fields():
  183. if rect.collidepoint(event.pos):
  184. self.focus, self.select_all = key, True
  185. self.cursor = len(self.values[key])
  186. return True
  187. if tool == 'expand' and pygame.Rect(WINDOW_W+245, 352, 110, 32).collidepoint(event.pos):
  188. app.menu.invoke(lambda: self.expand(int(self.values['left']), int(self.values['top'])))
  189. return True
  190. cell = app.selection.cell(event.pos)
  191. if cell is None:
  192. return False
  193. if tool == 'spray':
  194. app.menu.finish_stroke()
  195. app.menu.invoke(lambda: self.spray(cell))
  196. elif tool == 'move':
  197. app.menu.finish_stroke()
  198. if self.sources:
  199. self.move_to(cell)
  200. else:
  201. self.start = self.end = cell
  202. return True
  203. if tool == 'move' and self.start is not None:
  204. if event.type in (pygame.MOUSEMOTION, pygame.MOUSEBUTTONUP):
  205. self.end = app.selection.cell(event.pos, clamp=True)
  206. if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
  207. app.selection.copy_rectangle(self.start, self.end, 'obstacle')
  208. x0, x1 = sorted((self.start[0], self.end[0]))
  209. y0, y1 = sorted((self.start[1], self.end[1]))
  210. self.sources = list({obj for (x, y), obj in app.map_obstacles_dict.items() if x0 <= x <= x1 and y0 <= y <= y1})
  211. self.source_positions = [(obj.x, obj.y) for obj in self.sources]
  212. self.start = self.end = None
  213. return True
  214. return False
  215. def draw(self):
  216. if self.app.tools.tool == 'export':
  217. for include_regions, label, rect in self.export_buttons():
  218. pygame.draw.rect(self.app.screen, (53, 61, 74), rect)
  219. pygame.draw.rect(self.app.screen, (145, 155, 170), rect, 1)
  220. text = self.app.text_font.render(label, True, (235, 235, 235))
  221. self.app.screen.blit(text, text.get_rect(center=rect.center))
  222. return
  223. if self.app.tools.tool not in ('spray', 'expand'):
  224. return
  225. for key, label, rect in self.fields():
  226. self.app.screen.blit(self.app.text_font.render(label, True, (230, 230, 235)), (WINDOW_W+12, rect.y+6))
  227. pygame.draw.rect(self.app.screen, (24, 28, 34), rect)
  228. pygame.draw.rect(self.app.screen, (240, 195, 80) if self.focus == key else (145, 155, 170), rect, 1)
  229. value = self.values[key]
  230. if self.focus == key:
  231. value = value[:self.cursor] + '|' + value[self.cursor:]
  232. self.app.screen.blit(self.app.text_font.render(value, True, (235, 235, 235)), (rect.x+8, rect.y+6))
  233. if self.app.tools.tool == 'expand':
  234. rect = pygame.Rect(WINDOW_W+245, 352, 110, 32)
  235. pygame.draw.rect(self.app.screen, (145, 155, 170), rect, 1)
  236. text = self.app.text_font.render('确认拓展', True, (235, 235, 235))
  237. self.app.screen.blit(text, text.get_rect(center=rect.center))
  238. def draw_preview(self):
  239. if self.app.tools.tool == 'spray':
  240. cell = self.app.selection.cell(pygame.mouse.get_pos())
  241. if cell is not None:
  242. try:
  243. radius = max(1, min(50, int(self.values['radius'])))
  244. except ValueError:
  245. radius = 1
  246. clip = self.app.screen.get_clip()
  247. from const.window import MAP_W, MAP_H
  248. self.app.screen.set_clip(pygame.Rect(MAP_AT, (MAP_W, MAP_H)))
  249. pygame.draw.circle(self.app.screen, (255, 205, 70),
  250. (MAP_AT[0]+(cell[0]-self.app.scroll_grid_at[0])*GAME_SQUARE+GAME_SQUARE//2,
  251. MAP_AT[1]+(cell[1]-self.app.scroll_grid_at[1])*GAME_SQUARE+GAME_SQUARE//2), radius*GAME_SQUARE, 2)
  252. self.app.screen.set_clip(clip)
  253. if self.start is not None:
  254. x0, x1 = sorted((self.start[0], self.end[0]))
  255. y0, y1 = sorted((self.start[1], self.end[1]))
  256. pygame.draw.rect(self.app.screen, (255, 205, 70), (MAP_AT[0]+(x0-self.app.scroll_grid_at[0])*GAME_SQUARE,
  257. MAP_AT[1]+(y0-self.app.scroll_grid_at[1])*GAME_SQUARE, (x1-x0+1)*GAME_SQUARE, (y1-y0+1)*GAME_SQUARE), 3)