npc.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. import json
  2. import random
  3. import os
  4. import pygame
  5. from math import inf
  6. from client_local.skill.skill_map import skill_map
  7. from client_local.skill.skill_combo import SkillComboError, SkillComboRunner, get_skill_combo
  8. from client_local.algo import aStar
  9. from client_local.const import color as C
  10. from client_local.const import game as G
  11. from client_local.frame import bomb, item
  12. from client_local.level import level
  13. from client_local.skill.skill import *
  14. from client_local.sound import sound_player
  15. from client_local.sprite.bomb_instance import BombInstance
  16. from client_local.sprite.ghost import Ghost
  17. from client_local.sprite.hero import Hero, DECORATION_CATEGORIES
  18. from client_local.sprite.item_instance import ItemInstance
  19. from client_local.sprite.player import Player, PlayerState
  20. from client_local.sprite.throwable import Throwable
  21. from client_local.ui.game.blood_bar import BossBloodBar, BossLongBloodBar, BossHead
  22. from client_local.file_loader.fileLoader import load_json, load_png
  23. user_documents_folder = os.path.expanduser("~\\Documents") # 获取用户的"文档"文件夹路径
  24. qqtpve_folder = os.path.join(user_documents_folder, "QQTPVE") # 构建QQTPVE文件夹路径
  25. os.makedirs(qqtpve_folder, exist_ok=True) # 确保QQTPVE文件夹存在,如果不存在则创建
  26. monster_stats_file_path = os.path.join(qqtpve_folder, "monster_stats.json") # 构建json文件路径
  27. name_card_img_dict = dict()
  28. def _create_undead_icon():
  29. icon = pygame.Surface((23, 25), pygame.SRCALPHA)
  30. outline = (28, 14, 39)
  31. edge = (148, 92, 181)
  32. face = (90, 49, 116)
  33. sockets = (23, 12, 34)
  34. pygame.draw.polygon(icon, edge, ((7, 0), (15, 0), (20, 3), (22, 7), (22, 14),
  35. (19, 17), (17, 18), (17, 22), (15, 24), (7, 24),
  36. (5, 22), (5, 18), (3, 17), (0, 14), (0, 7), (2, 4)))
  37. pygame.draw.polygon(icon, outline, ((7, 1), (15, 1), (19, 4), (21, 7), (21, 14),
  38. (18, 16), (16, 17), (16, 22), (15, 23), (7, 23),
  39. (6, 22), (6, 17), (4, 16), (1, 14), (1, 7), (3, 4)))
  40. pygame.draw.polygon(icon, face, ((7, 3), (15, 3), (19, 7), (19, 13), (16, 15),
  41. (14, 18), (14, 21), (8, 21), (8, 18), (6, 15), (3, 13), (3, 7)))
  42. pygame.draw.lines(icon, (121, 72, 151), False, ((4, 7), (7, 4), (13, 4)))
  43. pygame.draw.polygon(icon, sockets, ((4, 9), (9, 10), (9, 13), (7, 14), (4, 12)))
  44. pygame.draw.polygon(icon, sockets, ((18, 9), (13, 10), (13, 13), (15, 14), (18, 12)))
  45. pygame.draw.polygon(icon, sockets, ((11, 13), (9, 16), (13, 16)))
  46. for x in (9, 12):
  47. pygame.draw.line(icon, outline, (x, 19), (x, 22))
  48. return pygame.transform.smoothscale(icon, (21, 23))
  49. def init_name_card_img_dict():
  50. global name_card_img_dict
  51. if name_card_img_dict != dict():
  52. return
  53. name_card_img_dict = {
  54. "blue": load_png("res/img/ui/game/misc171.png").convert_alpha(),
  55. "red": load_png("res/img/ui/game/misc169.png").convert_alpha(),
  56. "purple": load_png("res/img/ui/game/misc170.png").convert_alpha(),
  57. "green": load_png("res/img/ui/game/misc172.png").convert_alpha(),
  58. "blue_long": load_png("res/img/ui/game/misc171_long.png").convert_alpha(),
  59. "red_long": load_png("res/img/ui/game/misc169_long.png").convert_alpha(),
  60. "purple_long": load_png("res/img/ui/game/misc170_long.png").convert_alpha(),
  61. "green_long": load_png("res/img/ui/game/misc172_long.png").convert_alpha(),
  62. "undead": _create_undead_icon(),
  63. }
  64. def get_name_card_img(colour: str, length: int):
  65. if length >= 88:
  66. return name_card_img_dict[f"{colour}_long"]
  67. return name_card_img_dict[colour]
  68. def caesar_encrypt(text, k=3):
  69. encrypted_text = ""
  70. for char in text:
  71. if char.isalpha():
  72. # 处理字母
  73. if char.isupper():
  74. encrypted_char = chr((ord(char) - ord('A') + k) % 26 + ord('A'))
  75. else:
  76. encrypted_char = chr((ord(char) - ord('a') + k) % 26 + ord('a'))
  77. elif char.isdigit():
  78. # 处理数字
  79. encrypted_char = str((int(char) + k) % 10)
  80. else:
  81. # 其他字符保持不变
  82. encrypted_char = char
  83. encrypted_text += encrypted_char
  84. return encrypted_text
  85. def render_digit(screen, number, x_pos, y_pos, alpha, offset=0):
  86. num_img = G.NUMBER_IMG[int(max(min(number, 9), 0))] # 获取对应的数字图片
  87. num_img.set_alpha(alpha) # 设置透明度
  88. screen.blit(num_img, (x_pos + offset, y_pos - 110)) # 渲染到屏幕
  89. class Npc(Player, Throwable):
  90. def __init__(self, npc_name, xy, color=C.CHARACTER_RED, patrol_path=None):
  91. super(Npc, self).__init__(npc_name, xy, color)
  92. self.npc_json = None
  93. self.chs_name = None # Npc中文名
  94. self.stats_name = npc_name
  95. self.idx_motion = {0: "R", 1: "U", 2: "L", 3: "D"}
  96. self.contact = 0 # Npc接触伤害
  97. self.resent_dist = None # Npc仇恨范围(几格以内)
  98. self.resentful = False # Npc玩家仇恨
  99. self.mocking = False # Npc受到嘲笑药水的作用暂时仇恨
  100. self.friendly = False # Npc受到玫瑰药水的作用暂时解除仇恨
  101. self.boss_mode = False # Boss模式
  102. self.refresh = 0
  103. self.original_speed = 0
  104. self.has_patrol = False
  105. self.patrol_path = patrol_path
  106. if self.patrol_path is not None:
  107. self.has_patrol = True
  108. self.patrol_nodes_num = len(self.patrol_path)
  109. self.current_patrol_node = 0
  110. self.patrol_last_wait_time = 0
  111. self.is_patrol_switch = True
  112. self.protect_resource = False
  113. self.is_dead = False
  114. self.is_ghost = False # 幽灵模式
  115. self.fake_blood = 0
  116. self.energy_amount = 0 # 充能格数
  117. self.max_energy_amount = 0
  118. self.show_light_energy = False # 电量变为光盾数
  119. self.has_energy = False
  120. self.wall_walking = False # 穿墙
  121. self.flying = False # 飞行(免疫墙体减速)
  122. self.sliding = False # 踩技能滑行中
  123. self.sliding_direction = None # 踩技能后滑的方向
  124. self.witch_protected_remove = False # 巫师无防护状态
  125. self.fire_load_time = 0
  126. self.slime = False
  127. self.last_in_water = 0
  128. self.slime_time = 0
  129. self.free_chasing = False
  130. self.chasing_monster = False
  131. self.chasing_monster_target = None
  132. self.recal_chasing_monster = False
  133. self.chasing_point = (1, 1)
  134. self.imitating = False
  135. self.combo_num = 1
  136. self.is_combo_target = False
  137. self.bomb_shield_num = 0 # 防糖泡电磁护盾
  138. self.bomb_shield_protect = False
  139. self.is_target = True
  140. self.light = 0 # 鬼屋模式发光大小 0不发光,1发光20像素,2发光40像素 最大9
  141. self.sharing_damage = False
  142. self.last_get_damage_multiple = 0
  143. self.total_damage_bound = inf
  144. self.has_light_shield = False
  145. self.obstacle_can_push = False
  146. self.npc_time_init = None # Npc初始化时刻
  147. self.wander_random = 10 # Npc在无仇恨时的闲逛时间
  148. self.district_locked = True
  149. self.chase_path = None # Npc追踪路径
  150. self.npc_skill_time = pygame.time.get_ticks() # npc施放技能时的时刻 设为成员变量是为了统一多个技能的时间
  151. self.is_skill_init = False
  152. init_name_card_img_dict()
  153. self.chs_name_bg = name_card_img_dict["blue"] # Npc姓名牌背景
  154. self.name_bg_x_offset = 40
  155. # self.chs_name_bg = pygame.image.load("res/img/ui/game/misc171.png").convert_alpha() # Npc姓名牌背景
  156. self.blood_bar = None
  157. self.blood_bar_pos = 0
  158. self.long_blood_bar = False
  159. self.long_blood_y = 0
  160. self.profile = None
  161. # self.head_cx = -100000
  162. # self.head_cy = -100000
  163. self.chs_name_font = pygame.font.Font("res/font/simsun.ttc", 13) # Npc姓名牌字体
  164. self.chs_name_text = None # Npc姓名牌前景文字
  165. self.chs_name_text_shadow = None # Npc姓名牌背景文字
  166. self.chs_name_text_half_width = None # Npc姓名牌文字的半宽 用于居中显示文字
  167. self.chs_name_show = True # 是否显示名牌
  168. self.bomb_skin = bomb.get_bomb("bomb1")
  169. self.gifts = None # 爆装备
  170. self.death = None # 死亡状态
  171. self.last_motion = 0
  172. self.last_random = 10
  173. self.energy_num = None
  174. self.load_npc(npc_name, color)
  175. def load_decorations(self):
  176. decorations = {}
  177. decoration_config = self.npc_json.get("decorations") or {}
  178. for component in DECORATION_CATEGORIES:
  179. decoration_name = decoration_config.get(component)
  180. if decoration_name is None:
  181. continue
  182. if component == "footprint":
  183. self.allow_footprint = True
  184. decorations[component.capitalize()] = load_json(
  185. f"game/frame/{component}/{decoration_name}.json"
  186. )
  187. return decorations
  188. def load_npc(self, npc_name, color):
  189. # 加载npc的json文件
  190. # try:
  191. # self.npc_json = load_json(f"game/npc/{npc_name}.json")
  192. # self.chs_name = self.npc_json["chs_name"]
  193. # except Exception as e:
  194. # print(e)
  195. # print(f"{npc_name} not exist")
  196. # return
  197. self.npc_json = load_json(f"game/npc/{npc_name}.json")
  198. self.chs_name = self.npc_json["chs_name"]
  199. self.chs_name_bg = get_name_card_img("blue", self.chs_name_font.size(self.chs_name)[0])
  200. if self.chs_name_font.size(self.chs_name)[0] >= 88:
  201. self.name_bg_x_offset = 61
  202. self.blood = self.npc_json["blood"]
  203. self.light = self.npc_json.get("light", self.light)
  204. if "self_damage_blood" in self.npc_json.keys():
  205. self.self_damage_blood = self.npc_json["self_damage_blood"]
  206. self.speed = (self.npc_json["speed"] * G.GAME_SQUARE) / 1000
  207. self.original_speed = self.speed
  208. self.contact = self.npc_json["contact"]
  209. self.defense = self.npc_json["defense"]
  210. if "boss_mode" in self.npc_json.keys():
  211. self.boss_mode = bool(self.npc_json["boss_mode"])
  212. if "elite" in self.npc_json.keys():
  213. if self.npc_json["elite"]:
  214. try:
  215. self.chs_name_bg = get_name_card_img("purple", self.chs_name_font.size(self.chs_name)[0])
  216. # self.chs_name_bg = pygame.image.load("res/img/ui/game/misc170.png").convert_alpha() # Npc姓名牌背景
  217. except:
  218. pass
  219. if "boss" in self.npc_json.keys():
  220. if self.npc_json["boss"]:
  221. self.boss_mode = True
  222. try:
  223. self.chs_name_bg = get_name_card_img("red", self.chs_name_font.size(self.chs_name)[0])
  224. # self.chs_name_bg = pygame.image.load("res/img/ui/game/misc169.png").convert_alpha() # Npc姓名牌背景
  225. except:
  226. pass
  227. if "ally" in self.npc_json.keys():
  228. if self.npc_json["ally"]:
  229. try:
  230. self.chs_name_bg = get_name_card_img("green", self.chs_name_font.size(self.chs_name)[0])
  231. # self.chs_name_bg = pygame.image.load("res/img/ui/game/misc172.png").convert_alpha() # Npc姓名牌背景
  232. except:
  233. pass
  234. if "max_energy_amount" in self.npc_json.keys():
  235. if self.npc_json["max_energy_amount"] > 0:
  236. self.has_energy = True
  237. self.max_energy_amount = self.npc_json["max_energy_amount"]
  238. self.energy_amount = self.npc_json["max_energy_amount"]
  239. self.flying = self.npc_json.get("flying", False)
  240. self.slime = self.npc_json.get("slime", False)
  241. self.gifts = self.npc_json.get("gifts", None)
  242. self.death = self.npc_json.get("death", None)
  243. self.chs_name_show = self.npc_json.get("show_name", True)
  244. self.is_target = self.npc_json.get("is_target", True)
  245. self.protect_resource = self.npc_json.get("protect_resource", False)
  246. self.resent_dist = self.npc_json["resent_dist"] * G.GAME_SQUARE # 仇恨距离(像素)
  247. self.load_npc_skills(self.npc_json["skills"])
  248. self.remain_blood = self.blood
  249. self.chase_path = dict()
  250. self.chs_name_text = self.chs_name_font.render(self.chs_name, True, (255, 255, 0))
  251. self.chs_name_text_shadow = self.chs_name_font.render(self.chs_name, True, (0, 0, 0))
  252. self.chs_name_text_half_width = self.chs_name_text.get_width() // 2
  253. self._name_display_cache_key = (self.chs_name_font, self.chs_name)
  254. self.color = C.resolve_character_colour(self.npc_json.get("colour"), color)
  255. self.character = self.load_character(
  256. self.npc_json["character"], self.color, self.load_decorations()
  257. )
  258. self.npc_time_init = pygame.time.get_ticks()
  259. if "head_pos" in self.npc_json.keys():
  260. self.head_cx, self.head_cy = self.npc_json["head_pos"][0], self.npc_json["head_pos"][1]
  261. if self.npc_json.get("blood_bar", False) or self.boss_mode:
  262. if self.npc_json.get("long_blood_bar", False):
  263. for bar_y in [0, 1]:
  264. bar_pos = 1 + bar_y * 3
  265. if sum([level.current_level.boss_blood_bar_dic[i] for i in range(bar_pos, bar_pos+3)]) == 0:
  266. for i in range(bar_pos, bar_pos+3):
  267. level.current_level.boss_blood_bar_dic[i] = 1
  268. self.long_blood_bar = True
  269. self.long_blood_y = bar_y
  270. self.blood_bar_pos = bar_pos
  271. self.blood_bar = BossLongBloodBar(self, bar_y)
  272. level.current_level.ui_instances_top.append(self.blood_bar)
  273. self.profile = BossHead(self, bar_pos)
  274. level.current_level.ui_instances_top.append(self.profile)
  275. break
  276. else:
  277. for bar_pos in range(1, 7):
  278. if level.current_level.boss_blood_bar_dic[bar_pos] == 0:
  279. level.current_level.boss_blood_bar_dic[bar_pos] = 1
  280. self.blood_bar_pos = bar_pos
  281. self.blood_bar = BossBloodBar(self, bar_pos)
  282. level.current_level.ui_instances_top.append(self.blood_bar)
  283. self.profile = BossHead(self, bar_pos)
  284. level.current_level.ui_instances_top.append(self.profile)
  285. break
  286. def update(self):
  287. super().update()
  288. if not self.is_dead:
  289. current_time = pygame.time.get_ticks()
  290. self.update_npc_blood_display(current_time)
  291. self.wander_and_detect(current_time)
  292. self.chase_hero()
  293. self.contact_damage()
  294. self.try_using_skills()
  295. self.throw()
  296. def load_npc_skills(self, skills):
  297. for index, config in enumerate(skills):
  298. name = config["name"]
  299. params = config.get("params", [])
  300. spawn_order = config.get("spawn_order", index)
  301. passive = skill_map.get(name, {}).get("passive", False)
  302. # 保留被动技能的索引,避免影响其他技能的旧版召唤参数。
  303. self.skill_names.append(name)
  304. self.skill_init_times.append(0 if passive else config["init"])
  305. self.skill_intervals.append(0 if passive else config["interval"])
  306. self.skill_remains.append(0 if passive else config["max"])
  307. self.skill_params.append(params)
  308. self.skill_params_order.append(index)
  309. self.skill_spawns.append(config.get("spawns", []))
  310. self.skill_spawn_order.append(spawn_order)
  311. if passive:
  312. self.using_skill_map(name, params, spawn_order)
  313. def update_npc_blood_display(self, current_time):
  314. if not G.DISPLAY_NPC_NAME_CARD:
  315. return
  316. text = str(self.remain_blood - self.fake_blood) if G.DISPLAY_NPC_BLOOD else self.chs_name
  317. cache_key = (self.chs_name_font, text)
  318. if cache_key == self._name_display_cache_key:
  319. return
  320. self.chs_name_text = self.chs_name_font.render(text, True, (255, 255, 0))
  321. self.chs_name_text_shadow = self.chs_name_font.render(text, True, (0, 0, 0))
  322. self.chs_name_text_half_width = self.chs_name_text.get_width() // 2
  323. self._name_display_cache_key = cache_key
  324. def wander_and_detect(self, current_time):
  325. # 游走并检测玩家距离
  326. me: Hero = level.current_level.me
  327. swallow = me.swallow_attack
  328. if ((self.resentful or self.mocking) and not self.friendly
  329. and (swallow is None or (not swallow.require_aggro and swallow.user is not self))):
  330. return
  331. # 初始化时刻小于0.3s
  332. if current_time - self.npc_time_init < 300:
  333. return
  334. if self.has_patrol:
  335. self.patrol()
  336. else:
  337. # 随机运动时间
  338. if (current_time - self.last_motion) >= 50 * self.last_random:
  339. if self.speed >= (5.8 * G.GAME_SQUARE) / 1000:
  340. self.last_random = random.randint(5, 15)
  341. if 0 <= (current_time % 1200) <= 300 or (random.randint(1, 100) >= 85):
  342. self.last_motion = current_time
  343. if random.randint(1, 100) >= 25:
  344. motion = self.idx_motion[random.randint(0, 3)]
  345. self.set_motion(motion)
  346. else:
  347. self.set_motion(self.orientation)
  348. else:
  349. self.set_motion(self.orientation)
  350. else:
  351. self.set_motion(self.orientation)
  352. if swallow is not None and swallow.user is self:
  353. return # 吞噬者可以游走,同时继续自己的技能计时。
  354. # 技能初始时间更新
  355. for i in range(len(self.skill_names)):
  356. # 游荡状态下,技能初始时间永远等于当前时刻加init值
  357. self.skill_init_times[i] = self.npc_json["skills"][i].get("init", 0) + current_time
  358. self.is_skill_init = True
  359. # 检测与玩家的距离
  360. if me.district_locked and me.state == PlayerState.NORMAL:
  361. if abs(me.x_pos - self.x_pos) < self.resent_dist and abs(me.y_pos - self.y_pos) < self.resent_dist and not me.is_hide_sight():
  362. # 如果玩家活着、已进入区域锁,并且距离小于临界值 且不被障碍阻碍视野 则产生玩家仇恨
  363. self.resentful = True
  364. level.current_level.recal_npc_paths = True
  365. def patrol(self, bounds=None):
  366. current_node = self.patrol_path[self.current_patrol_node] # e.g. ["stop",5000]
  367. if current_node[0] == "stop":
  368. if self.is_patrol_switch:
  369. self.is_patrol_switch = False
  370. self.patrol_last_wait_time = pygame.time.get_ticks()
  371. if pygame.time.get_ticks() - self.patrol_last_wait_time >= current_node[1]:
  372. self.current_patrol_node = (self.current_patrol_node + 1) % self.patrol_nodes_num
  373. self.is_patrol_switch = True
  374. level.current_level.recal_npc_paths = True
  375. self.set_motion()
  376. return
  377. return
  378. else:
  379. now = (self.x, self.y)
  380. target = (current_node[1][0], current_node[1][1])
  381. if now == target:
  382. self.current_patrol_node = (self.current_patrol_node + 1) % self.patrol_nodes_num
  383. self.chase_path.clear()
  384. self.is_patrol_switch = True
  385. self.set_motion()
  386. return
  387. if self.is_patrol_switch or level.current_level.recal_npc_paths:
  388. if self.is_patrol_switch:
  389. self.is_patrol_switch = False
  390. if len(level.current_level.get_bomb_instance(current_node[1][0], current_node[1][1])) > 0:
  391. return
  392. if bounds is None:
  393. district = level.current_level.district_square_grid
  394. bounds = ((district["x1"], district["y1"]), (district["x2"], district["y2"]))
  395. self.chase_path = aStar.cal_path(now, target, *bounds, is_ghost=self.is_ghost)
  396. if now in self.chase_path.keys():
  397. _next = self.chase_path[now]
  398. if _next is None:
  399. self.set_motion()
  400. elif _next[0] > self.x:
  401. self.set_motion("R")
  402. elif _next[1] < self.y:
  403. self.set_motion("U")
  404. elif _next[0] < self.x:
  405. self.set_motion("L")
  406. elif _next[1] > self.y:
  407. self.set_motion("D")
  408. else:
  409. self.set_motion()
  410. def chase_hero(self):
  411. if (not self.resentful and not self.mocking) or self.friendly or self.imitating or (self.speed == 0 and self.original_speed == 0):
  412. return
  413. hero = level.current_level.me
  414. if hero.swallow_attack is not None and not (self.free_chasing or self.chasing_monster):
  415. if hero.swallow_attack.user is not self:
  416. self.set_motion()
  417. return
  418. me = (hero.x, hero.y)
  419. if self.free_chasing:
  420. me = self.chasing_point
  421. if self.chasing_monster and self.chasing_monster_target is not None:
  422. me = (self.chasing_monster_target.x, self.chasing_monster_target.y)
  423. # 玩家在糖泡中 定身Npc
  424. if len(level.current_level.get_bomb_instance(*me)) > 0 and not self.is_ghost and not self.free_chasing and not self.chasing_monster:
  425. self.set_motion()
  426. return
  427. now = (self.x, self.y)
  428. # 如果重新计算路径标志为True则重新追踪玩家
  429. if level.current_level.recal_npc_paths:
  430. self.chase_path = aStar.cal_path(
  431. now, me,
  432. (level.current_level.district_square_grid["x1"], level.current_level.district_square_grid["y1"]),
  433. (level.current_level.district_square_grid["x2"], level.current_level.district_square_grid["y2"]),
  434. is_ghost=self.is_ghost
  435. )
  436. if now in self.chase_path.keys():
  437. _next = self.chase_path[now]
  438. if _next is None:
  439. self.set_motion()
  440. elif _next[0] > self.x:
  441. self.set_motion("R")
  442. elif _next[1] < self.y:
  443. self.set_motion("U")
  444. elif _next[0] < self.x:
  445. self.set_motion("L")
  446. elif _next[1] > self.y:
  447. self.set_motion("D")
  448. else:
  449. self.set_motion()
  450. def half_body_damage(self, point, cl, current_time):
  451. if self.bomb_shield_num > 0:
  452. if self.protected > 0:
  453. return
  454. if self.bomb_shield_protect:
  455. self.try_damage(min(self.total_damage_bound, cl.grid_damage_blood[point]))
  456. Protect3s(self, self.skill_instances)
  457. self.energy_amount = int(max(0, self.bomb_shield_num-1))
  458. return
  459. self.try_damage(min(self.total_damage_bound, cl.grid_damage_blood[point]))
  460. self.energy_amount = int(max(0, self.bomb_shield_num - cl.grid_damage_multiples[point]))
  461. self.last_get_damage_multiple = cl.grid_damage_multiples[point]
  462. Protect005s(self, self.skill_instances)
  463. return
  464. if self.protected > 0:
  465. return
  466. self.last_get_damage_multiple = cl.grid_damage_multiples[point]
  467. self.try_damage(min(self.total_damage_bound, cl.grid_damage_blood[point]))
  468. def contact_damage(self):
  469. # 检查npc与人物的接触伤害
  470. if level.current_level.me.x == self.x and level.current_level.me.y == self.y:
  471. level.current_level.me.try_damage(self.contact, "C")
  472. def die(self):
  473. super().die()
  474. sound_player.play("npc_dead")
  475. if G.MONSTER_RECORD:
  476. if not G.CHEAT and G.ITEM == 0:
  477. new_data = {
  478. caesar_encrypt("name"): self.stats_name,
  479. caesar_encrypt("cheat"): caesar_encrypt("False"),
  480. caesar_encrypt("remain_blood"): int(caesar_encrypt(str(level.current_level.me.remain_blood)))
  481. }
  482. G.MONSTER_RECORD_LIST.append(new_data)
  483. else:
  484. new_data = {
  485. caesar_encrypt("name"): self.stats_name,
  486. caesar_encrypt("cheat"): caesar_encrypt("True"),
  487. caesar_encrypt("remain_blood"): int(caesar_encrypt(str(level.current_level.me.remain_blood)))
  488. }
  489. G.MONSTER_RECORD_LIST.append(new_data)
  490. if level.current_level.me.remain_blood <= 0:
  491. try:
  492. with open(monster_stats_file_path, encoding="utf-8") as file:
  493. self.encrypted_data = json.load(file)
  494. except:
  495. try:
  496. with open(monster_stats_file_path, encoding="utf-8_sig") as file:
  497. self.encrypted_data = json.load(file)
  498. except:
  499. # 如果文件不存在,创建新的空的achievements.json文件
  500. self.encrypted_data = {"STAT": []}
  501. with open(monster_stats_file_path, 'w', encoding="utf-8") as file:
  502. json.dump(self.encrypted_data, file, indent=2)
  503. if self.encrypted_data == {}:
  504. self.encrypted_data = {"STAT": []}
  505. try:
  506. if G.CHEAT == False and G.ITEM == 0:
  507. new_data = {
  508. caesar_encrypt("name"): self.stats_name,
  509. caesar_encrypt("cheat"): caesar_encrypt("False"),
  510. caesar_encrypt("remain_blood"): int(caesar_encrypt(str(level.current_level.me.remain_blood)))
  511. }
  512. else:
  513. new_data = {
  514. caesar_encrypt("name"): self.stats_name,
  515. caesar_encrypt("cheat"): caesar_encrypt("True"),
  516. caesar_encrypt("remain_blood"): int(caesar_encrypt(str(level.current_level.me.remain_blood)))
  517. }
  518. G.MONSTER_RECORD_LIST.append(new_data)
  519. # 添加新的加密数据
  520. for data in G.MONSTER_RECORD_LIST:
  521. self.encrypted_data["STAT"].append(data)
  522. with open(monster_stats_file_path, 'w') as file:
  523. json.dump(self.encrypted_data, file, indent=2)
  524. G.MONSTER_RECORD_LIST = []
  525. except:
  526. G.MONSTER_RECORD_LIST = []
  527. if self.blood_bar_pos != 0:
  528. try:
  529. level.current_level.ui_instances_top.remove(self.blood_bar)
  530. level.current_level.ui_instances_top.remove(self.profile)
  531. if self.long_blood_bar:
  532. for i in range(self.blood_bar_pos, self.blood_bar_pos + 3):
  533. level.current_level.boss_blood_bar_dic[i] = 0
  534. else:
  535. level.current_level.boss_blood_bar_dic[self.blood_bar_pos] = 0
  536. except Exception as e:
  537. try:
  538. print(f"血条错误 {e}: ", self.chs_name, self.blood_bar_pos)
  539. except Exception as e:
  540. print(f"npc.py: die(): {e}")
  541. self.gene_gifts()
  542. self.gene_ghost()
  543. self.is_dead = True
  544. def die_quietly(self):
  545. super().die()
  546. if self.blood_bar_pos != 0:
  547. try:
  548. level.current_level.ui_instances_top.remove(self.blood_bar)
  549. level.current_level.ui_instances_top.remove(self.profile)
  550. if self.long_blood_bar:
  551. for i in range(self.blood_bar_pos, self.blood_bar_pos + 3):
  552. level.current_level.boss_blood_bar_dic[i] = 0
  553. else:
  554. level.current_level.boss_blood_bar_dic[self.blood_bar_pos] = 0
  555. except Exception as e:
  556. try:
  557. print(f"血条错误 {e}: ", self.chs_name, self.blood_bar_pos)
  558. except Exception as e:
  559. print(f"npc.py: die(): {e}")
  560. self.gene_ghost()
  561. self.is_dead = True
  562. self.remain_blood = -1
  563. def gene_gifts(self):
  564. if self.gifts is None or not G.DROP_ITEM:
  565. return
  566. cl = level.current_level
  567. gx = int((cl.map_x_pos+1)/40-1)
  568. gy = int((cl.map_y_pos+1)/40-1)
  569. x_range = sorted(range(max(0, self.x - 2), min(self.x + 3, gx)), key=lambda k: abs(k))
  570. y_range = sorted(range(max(0, self.y - 2), min(self.y + 3, gy)), key=lambda k: abs(k))
  571. for gift in self.gifts:
  572. rand = gift["possibility"] - random.uniform(0, 1)
  573. if rand > 0:
  574. grids = []
  575. for x in x_range:
  576. for y in y_range:
  577. if (x, y) not in cl.obstacle_instances.keys() and (x, y) not in cl.item_instances.keys() and len(cl.get_bomb_instance(x, y)) == 0:
  578. grids.append((x, y))
  579. if len(grids) >= 3:
  580. break
  581. if len(grids) >= 3:
  582. break
  583. if len(grids) == 0:
  584. break
  585. random.shuffle(grids)
  586. point = grids[0]
  587. an_item = ItemInstance(self.x, self.y, level.current_level.item_instances, item.get_item(gift["name"]))
  588. an_item.throw_to(point[0], point[1], an_item.get_direction(point[0], point[1]))
  589. def gene_ghost(self):
  590. if self.death is None:
  591. return
  592. for gene in self.death:
  593. if "ghost" in gene.keys():
  594. # 生成幽灵Ghost,指定生存时间,速度,接触伤害(自身无敌 + 穿墙穿泡、无视区域)
  595. level.current_level.ghosts.append(
  596. Ghost(
  597. gene["name"], (self.x, self.y), gene["ghost"]["time"],
  598. gene["ghost"]["speed"], gene["ghost"]["contact"]
  599. )
  600. )
  601. elif gene.get("wanderer", False):
  602. from client_local.sprite.wanderer import Wanderer
  603. an_wanderer = Wanderer(gene["name"], (self.x, self.y), patrol_path=gene.get("patrol"))
  604. level.current_level.wanderers.append(an_wanderer)
  605. else:
  606. # 生成普通Npc,并给予无敌防护
  607. an_npc = Npc(gene["name"], (self.x, self.y))
  608. Protect3s(an_npc, an_npc.skill_instances)
  609. level.current_level.npcs.append(an_npc)
  610. if "inherit" in gene.keys():
  611. an_npc.remain_blood = self.remain_blood
  612. def collide_wall(self):
  613. # npc 游走时撞墙 则改变方向
  614. if self.speed >= (5.8 * G.GAME_SQUARE) / 1000:
  615. if self.orientation == "U":
  616. if random.randint(1, 100) >= 20:
  617. self.set_motion("D")
  618. else:
  619. if random.randint(1, 100) >= 40:
  620. self.set_motion("L")
  621. else:
  622. self.set_motion("R")
  623. elif self.orientation == "D":
  624. if random.randint(1, 100) >= 20:
  625. self.set_motion("U")
  626. else:
  627. if random.randint(1, 100) >= 40:
  628. self.set_motion("R")
  629. else:
  630. self.set_motion("L")
  631. elif self.orientation == "L":
  632. if random.randint(1, 100) >= 20:
  633. self.set_motion("R")
  634. else:
  635. if random.randint(1, 100) >= 40:
  636. self.set_motion("D")
  637. else:
  638. self.set_motion("U")
  639. elif self.orientation == "R":
  640. if random.randint(1, 100) >= 20:
  641. self.set_motion("L")
  642. else:
  643. if random.randint(1, 100) >= 40:
  644. self.set_motion("U")
  645. else:
  646. self.set_motion("D")
  647. else:
  648. if self.orientation == "U":
  649. self.set_motion("D")
  650. if self.orientation == "D":
  651. self.set_motion("U")
  652. if self.orientation == "L":
  653. self.set_motion("R")
  654. if self.orientation == "R":
  655. self.set_motion("L")
  656. def try_push(self, direction, offset=(0, 0)):
  657. pass
  658. def try_using_skills(self):
  659. # npc 循环使用技能
  660. swallow = level.current_level.me.swallow_attack
  661. if swallow is not None and swallow.require_aggro and swallow.user is not self and not self.friendly:
  662. self.resentful = False
  663. return
  664. if not self.resentful and not self.mocking or self.friendly:
  665. return
  666. # npc 技能时间更新
  667. self.npc_skill_time = pygame.time.get_ticks()
  668. if not self.is_skill_init:
  669. self.is_skill_init = True
  670. for i in range(len(self.skill_names)):
  671. self.skill_init_times[i] = self.npc_json["skills"][i].get("init", 0) + pygame.time.get_ticks()
  672. # 每一帧都尝试使用全部技能
  673. for i in range(len(self.skill_names)):
  674. self.use_skill(i)
  675. def use_skill(self, idx: int):
  676. if self.npc_skill_time < self.skill_init_times[idx] or self.skill_remains[idx] == 0:
  677. # 未到初始时间 或技能冷却中 或次数已用完(-1则可以无限使用)
  678. return
  679. self.skill_init_times[idx] += self.skill_intervals[idx]
  680. self.skill_remains[idx] -= 1
  681. name = self.skill_names[idx]
  682. param = self.skill_params[idx]
  683. spawn_order = self.skill_spawn_order[idx]
  684. try:
  685. self.using_skill_map(name, param, spawn_order)
  686. except Exception as e:
  687. print(f"{name}: {e}")
  688. # self.using_skill_map(name, param, spawn_order)
  689. def set_bomb(self):
  690. # npc尝试放置一个糖泡
  691. if self.state != PlayerState.NORMAL:
  692. return
  693. p = (self.x, self.y)
  694. bis = level.current_level.bomb_instances
  695. bs = level.current_level.get_bomb_instance(*p)
  696. if len(bs) > 0: # 当前位置有糖泡
  697. return
  698. BombInstance(*p, bis, self.bomb_skin, 3, 1000)
  699. def set_general_bomb(self, power, damage, skin=False):
  700. # npc尝试放置一个糖泡
  701. if self.state != PlayerState.NORMAL:
  702. return
  703. p = (self.x, self.y)
  704. bis = level.current_level.bomb_instances
  705. bs = level.current_level.get_bomb_instance(*p)
  706. if len(bs) > 0: # 当前位置有糖泡
  707. return
  708. sound_player.play("bomb")
  709. if not skin:
  710. BombInstance(*p, bis, self.bomb_skin, power, damage)
  711. else:
  712. BombInstance(*p, bis, bomb.get_bomb(skin), power, damage)
  713. def set_custom_bomb(self, x, y, power, damage):
  714. # npc尝试放置一个糖泡
  715. if self.state != PlayerState.NORMAL:
  716. return
  717. p = (x, y)
  718. bis = level.current_level.bomb_instances
  719. bs = level.current_level.get_bomb_instance(*p)
  720. if len(bs) > 0: # 当前位置有糖泡
  721. return
  722. BombInstance(*p, bis, self.bomb_skin, power, damage)
  723. def set_restoration(self, to_x, to_y):
  724. # self.x = to_x
  725. # self.y = to_y
  726. self._landing_x, self._landing_y = to_x, to_y
  727. def draw(self, screen: pygame.Surface):
  728. super().draw(screen)
  729. if G.DISPLAY_NPC_NAME_CARD and self.chs_name_show:
  730. name_x, name_y = self.x_pos - self.name_bg_x_offset, self.y_pos - 100
  731. self.chs_name_bg.set_alpha(self.temporary_alpha)
  732. screen.blit(self.chs_name_bg, (name_x, name_y))
  733. if (self.contact <= 0 and self.defense < 0
  734. and ("LandQuake" in self.skill_names or "SuperLandQuake" in self.skill_names)):
  735. icon = name_card_img_dict["undead"]
  736. icon.set_alpha(self.temporary_alpha)
  737. screen.blit(icon, (name_x - icon.get_width() - 1,
  738. name_y + (self.chs_name_bg.get_height() - icon.get_height()) // 2))
  739. self.chs_name_text_shadow.set_alpha(self.temporary_alpha)
  740. screen.blit(self.chs_name_text_shadow, (self.x_pos + 3 - self.chs_name_text_half_width, self.y_pos - 95))
  741. self.chs_name_text.set_alpha(self.temporary_alpha)
  742. screen.blit(self.chs_name_text, (self.x_pos + 2 - self.chs_name_text_half_width, self.y_pos - 95))
  743. self.render_energy(screen)
  744. def render_energy(self, screen):
  745. swallow = level.current_level.me.swallow_attack
  746. if swallow is not None and swallow.user is self:
  747. amount = swallow.escape_rounds_left
  748. elif self.has_energy:
  749. amount = self.energy_amount
  750. else:
  751. return
  752. energy_str = str(amount)
  753. max_len = len(energy_str)
  754. if max_len > 5:
  755. energy_str = '99999'
  756. x_pos_offset = -5 * max(0, max_len - 1) # 初始偏移量
  757. for i, digit in enumerate(energy_str):
  758. render_digit(screen, int(digit), self.x_pos, self.y_pos, self.temporary_alpha, x_pos_offset + 10 * i)
  759. def using_skill_map(self, skill_name, param, spawn_order, skill_spawns=None, combo_stack=None):
  760. try:
  761. combo_definition = get_skill_combo(skill_name, skill_map)
  762. if combo_definition is not None:
  763. combo_stack = list(combo_stack or [])
  764. if combo_definition.name.lower() in (name.lower() for name in combo_stack):
  765. chain = combo_stack + [combo_definition.name]
  766. raise SkillComboError("技能组合检测到循环引用: %s" % " -> ".join(chain))
  767. SkillComboRunner(
  768. self,
  769. combo_definition,
  770. param,
  771. self.skill_instances,
  772. combo_stack,
  773. )
  774. return
  775. if skill_name not in skill_map:
  776. return
  777. cl = level.current_level
  778. skill_attributes = skill_map[skill_name]
  779. skill_class = skill_attributes["skill"]
  780. skill_target = skill_attributes.get("target")
  781. skill_target_map = {"me": cl.me, "npcs": cl.npcs, "listed_me": [cl.me]}
  782. final_target = None
  783. if skill_target_map is not None:
  784. final_target = skill_target_map.get(skill_target)
  785. effect_target_map = {"self": self.skill_instances, "cl": cl.skill_instances}
  786. effect_target = effect_target_map.get(skill_attributes.get("effect"))
  787. if skill_attributes.get("old_spawn"):
  788. skill_class(
  789. self,
  790. final_target,
  791. self.skill_spawns if skill_spawns is None else skill_spawns,
  792. spawn_order,
  793. effect_target,
  794. ) # 旧版召唤
  795. elif skill_target is not None:
  796. if not skill_attributes.get("param"):
  797. skill_class(self, final_target, effect_target) # 有目标无参数
  798. else:
  799. skill_class(self, final_target, param, effect_target) # 有目标有参数
  800. else:
  801. if not skill_attributes.get("param"):
  802. skill_class(self, effect_target) # 无目标无参数
  803. else:
  804. skill_class(self, param, effect_target) # 无目标有参数
  805. except Exception as e:
  806. print(f"{skill_name}: {e}")