npc_preview.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """Render game NPC standing frames without constructing gameplay NPC objects."""
  2. import pygame
  3. from const.window import GAME_SQUARE
  4. class NpcPreview:
  5. def __init__(self, app):
  6. self.app = app
  7. self.cache = {}
  8. self.errors = {}
  9. def load(self, name):
  10. if name in self.cache:
  11. return self.cache[name]
  12. if name in self.errors:
  13. return None
  14. try:
  15. from client_local.file_loader.fileLoader import load_json
  16. from client_local.frame.character import get_character, CHARACTER_COMPONENTS
  17. config = load_json("game/npc/%s.json" % name) or load_json("game/npcs/%s.json" % name)
  18. if not config:
  19. raise ValueError("找不到 game/npc/%s.json" % name)
  20. character_name = config["character"]
  21. character = load_json("game/frame/character/%s.json" % character_name) or load_json("game/character/%s.json" % character_name)
  22. if not character:
  23. raise ValueError("找不到角色 " + character_name)
  24. decorations = {}
  25. for part, value in (config.get("decorations") or {}).items():
  26. if value is not None:
  27. decorations[part.capitalize()] = load_json("game/frame/%s/%s.json" % (part.lower(), value))
  28. frames = get_character(character, (255, 0, 0), decorations)
  29. orient = next((o for o in ("STAND_D", "STAND_R", "STAND_L", "STAND_U", "D") if o in frames), None)
  30. if orient is None:
  31. raise ValueError("角色缺少可用站立帧")
  32. value = (frames[orient], CHARACTER_COMPONENTS[orient[-1]], max(0, float(config.get("resent_dist", 0))))
  33. self.cache[name] = value
  34. return value
  35. except Exception as error:
  36. self.errors[name] = str(error)
  37. self.app.menu.notify("模型加载失败 %s:%s" % (name, error))
  38. return None
  39. def draw(self, surface, npc, scroll, color, frame_index=None, show_vision=True):
  40. model = self.load(npc.get("name", ""))
  41. if model is None:
  42. return False
  43. frames, components, resent = model
  44. x = (npc["x"] - scroll[0] + 0.5) * GAME_SQUARE
  45. y = (npc["y"] - scroll[1] + 0.5) * GAME_SQUARE
  46. radius = resent * GAME_SQUARE
  47. if show_vision and radius > 0:
  48. rect = pygame.Rect(round(x - radius), round(y - radius), round(radius * 2), round(radius * 2))
  49. pygame.draw.rect(surface, (12, 16, 22, 240), rect.inflate(2, 2), 5)
  50. pygame.draw.rect(surface, color + (255,), rect, 3)
  51. tick = pygame.time.get_ticks() // 200 if frame_index is None else frame_index
  52. for component in components:
  53. sequence = frames.get(component)
  54. if sequence:
  55. frame = sequence[tick % len(sequence)]
  56. surface.blit(frame.image, (round(x + frames["Cx"] + frame.cx), round(y + frames["Cy"] + frame.cy)))
  57. return True