npc.py 35 KB

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