level.py 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  1. import os
  2. import pygame
  3. import random
  4. import ast
  5. import json
  6. import math
  7. import time
  8. from json import JSONDecodeError
  9. import numpy as np
  10. from collections import defaultdict
  11. from client_local.const import game as G
  12. from client_local.frame import floor
  13. from client_local.frame import obstacle
  14. from client_local.music import music_loader
  15. from client_local.sound import sound_player
  16. from client_local.sprite import obstacle_instance as oi
  17. from client_local.sprite.flame_instance import FlameState as FS
  18. from client_local.sprite.hero import Hero
  19. from client_local.sprite.pet import Pet
  20. from client_local.sprite.item_instance import ItemState as IS
  21. from client_local.sprite.bomb_instance import BombInstance
  22. from client_local.effect.effect_instance import ReadyGo, DistrictAlarm, EnvironmentEffect, EffectState, IntroChatPlayer, EndingSequencePlayer
  23. from client_local.sprite.npc import Npc
  24. from client_local.ui.game.blood_bar import BloodBar, MapBloodBar, MapResouceBar, ResourceBloodBar
  25. from client_local.ui.game.dlg_pveFunc import DlgPveFunc
  26. from client_local.ui.game.game_top import GameTop
  27. from client_local.ui.game.misc_510 import Misc510
  28. from client_local.ui.game.player_icon import PlayerIcon, ResourceIcon
  29. from client_local.ui.game.score_board import ScoreBoard, Timer
  30. from client_local.ui.game.status_bar import StatusBar
  31. from client_local.ui.game.message_input import InputEntry, InputLevel
  32. from client_local.file_loader.fileLoader import load_json, load_png
  33. from client_local.skill.skill import WinEffect, TransportSuccessEffect
  34. from client_local.skill.level_skill import LevelSkillWithInterval, DebuffPoisonGrid, LevelParticle
  35. from client_local.utils.json_saver import AsyncJsonSaver
  36. from datetime import datetime
  37. current_level = None
  38. level_font = None
  39. Y_SCALE_FACTOR = 1 # 用于地震效果,画面会按比例以中间为基准进行上下偏移实现压缩效果
  40. max_alpha = 255 # 最大透明度
  41. circleMasks = {}
  42. MASK_STEP = 20
  43. lightBoltMasks = {}
  44. for i in range(1, 10):
  45. # 在蒙版上画出三个指定坐标及其周围100像素范围的圆形(透明度衰减)
  46. circle_radius = i*MASK_STEP
  47. circleMask = pygame.Surface((circle_radius*2, circle_radius*2), pygame.SRCALPHA)
  48. circleMask.fill((0, 0, 0, 0))
  49. for r in range(circle_radius):
  50. R = circle_radius-r
  51. alpha = max_alpha - int((max_alpha / circle_radius) * R)
  52. pygame.draw.circle(circleMask, (alpha, alpha, alpha, alpha), (circle_radius, circle_radius), R)
  53. circleMasks[i] = circleMask
  54. def init_level_fonts():
  55. global level_font
  56. level_font = pygame.font.Font("res/font/simsun.ttc", 16)
  57. def get_player_coordinates():
  58. players = current_level.game.players
  59. coords = []
  60. for player in players:
  61. coords.append((player.x_pos,player.y_pos))
  62. return coords
  63. def get_light_npc_coordinates():
  64. coords = []
  65. for npc in current_level.npcs:
  66. coords.append((npc.x_pos, npc.y_pos))
  67. return coords
  68. _last_light_states = None
  69. # def get_player_mask(mask_surface, bgl):
  70. # """
  71. # 只在光源状态变化时才重绘遮罩;否则直接返回上次绘制结果。
  72. # """
  73. # global _last_light_states
  74. # # 收集当前所有光源状态 (x, y, light)
  75. # curr = []
  76. # for p in [current_level.me] + current_level.npcs + list(current_level.obstacle_instances.values()):
  77. # if p.light:
  78. # curr.append((p.x_pos, p.y_pos, p.light))
  79. # curr_key = tuple(curr)
  80. # # 如果没变化,直接复用
  81. # if curr_key == _last_light_states:
  82. # return mask_surface
  83. # # 状态变化:重绘
  84. # _last_light_states = curr_key
  85. # bgl = max(0, min(bgl, 255))
  86. # fill = mask_surface.fill
  87. # blit = mask_surface.blit
  88. # masks = circleMasks
  89. # fill((bgl, bgl, bgl, 0))
  90. # for x, y, light in curr:
  91. # # 叠加亮度
  92. # cm = masks[light]
  93. # r = light * MASK_STEP
  94. # blit(cm, (x - r, y - r - 15),
  95. # special_flags=pygame.BLEND_RGBA_ADD)
  96. # return mask_surface
  97. def get_player_mask(mask_surface, bgl):
  98. global _last_light_states
  99. # 收集当前所有光源状态 (x, y, light)
  100. curr = []
  101. for p in [current_level.me]:
  102. if p.light and (not p.is_hide_sight()):
  103. curr.append((p.x_pos, p.y_pos, p.light))
  104. for p in current_level.npcs:
  105. if p.light and (not p.is_hide_sight()):
  106. curr.append((p.x_pos, p.y_pos, p.light))
  107. for p in current_level.obstacle_instances.values():
  108. if p.light:
  109. curr.append((p.x_pos, p.y_pos, p.light))
  110. curr_key = (
  111. id(current_level),
  112. current_level.scroll_x_pos,
  113. current_level.scroll_y_pos,
  114. mask_surface.get_width(),
  115. mask_surface.get_height(),
  116. bgl,
  117. tuple(curr),
  118. )
  119. if curr_key == _last_light_states:
  120. return mask_surface
  121. _last_light_states = curr_key
  122. bgl = max(0, min(bgl, 255))
  123. fill = mask_surface.fill
  124. blit = mask_surface.blit
  125. masks = circleMasks
  126. # 先把整表清空为 bgl 灰底
  127. fill((bgl, bgl, bgl, 0))
  128. # ---- 新增:计算屏幕视口,并在后面用 inflate 方式做相交测试 ----
  129. from client_local.const import game as G
  130. # world-space 下的视口矩形
  131. view_rect = pygame.Rect(
  132. current_level.scroll_x_pos,
  133. current_level.scroll_y_pos,
  134. G.MAIN_AREA_X_POS,
  135. G.MAIN_AREA_Y_POS
  136. )
  137. # ---------------------------------------------------------
  138. view_x, view_y = current_level.scroll_x_pos, current_level.scroll_y_pos
  139. for x, y, light in curr:
  140. r = light * MASK_STEP
  141. sx = x - view_x - r # ← 世界 → 屏幕
  142. sy = y - view_y - r - 15
  143. cm = masks[light]
  144. # 膨胀法:把视口向外各扩 r(水平方向)和 (r+15)(垂直方向)
  145. if not view_rect.inflate(2*r, 2*(r+15)).collidepoint(x, y):
  146. continue
  147. # 叠加亮度
  148. mask_surface.blit(cm, (sx, sy), special_flags=pygame.BLEND_RGBA_ADD)
  149. return mask_surface
  150. def special_colour_mask(mask_surface, rgb):
  151. r = min(max(rgb[0], 0), 255)
  152. g = min(max(rgb[1], 0), 255)
  153. b = min(max(rgb[2], 0), 255)
  154. mask_surface.fill((r, g, b, 0)) # 初始
  155. for player in [current_level.me] + current_level.npcs + list(current_level.obstacle_instances.values()):
  156. x, y = player.x_pos, player.y_pos
  157. if player.light == 0:
  158. continue
  159. circleMask = circleMasks[player.light]
  160. circle_radius = player.light*MASK_STEP
  161. # 叠加亮度
  162. mask_surface.blit(circleMask, (x-circle_radius, y-circle_radius-15),special_flags=pygame.BLEND_RGBA_ADD) # 15是补偿值(大概是角色中心)
  163. return mask_surface
  164. def get_y(elem):
  165. return elem.get_y()
  166. def caesar_encrypt(text, k=3):
  167. encrypted_text = ""
  168. for char in text:
  169. if char.isalpha():
  170. # 处理字母
  171. if char.isupper():
  172. encrypted_char = chr((ord(char) - ord('A') + k) % 26 + ord('A'))
  173. else:
  174. encrypted_char = chr((ord(char) - ord('a') + k) % 26 + ord('a'))
  175. elif char.isdigit():
  176. # 处理数字
  177. encrypted_char = str((int(char) + k) % 10)
  178. else:
  179. # 其他字符保持不变
  180. encrypted_char = char
  181. encrypted_text += encrypted_char
  182. return encrypted_text
  183. class MainArea(pygame.Surface):
  184. def __init__(self, size, flags=0):
  185. super().__init__(size, flags)
  186. def blit(self, source, dest, area=None, special_flags=0):
  187. relative_y = dest[1] - current_level.scroll_y_pos - G.MAIN_AREA_Y_POS//2
  188. scale_bias_value = relative_y * (1 - Y_SCALE_FACTOR)
  189. dest = (dest[0], int(dest[1] - scale_bias_value))
  190. super().blit(source, dest, area, special_flags)
  191. class Level:
  192. def __init__(
  193. self, your_name: str, map_name: str, me: Hero, music_volume, accumulation_time, game=None,
  194. transport_map_total=0, transport_map_remain=0
  195. ):
  196. from client_local.control import Control
  197. self.game: Control = game
  198. global current_level
  199. current_level = self
  200. self.times_num = 0 # 秒计数器,每秒累加
  201. self.frames_num = 0 # 帧计数器,每秒清空
  202. self.frame_rate_text_font = level_font
  203. self.me = me
  204. self.pets = []
  205. self.your_name = your_name
  206. self.map_name = map_name
  207. self.map_json = None
  208. self.map_x = None # 关卡横向格子数
  209. self.map_y = None # 关卡纵向格子数
  210. self.map_x_pos = None # 关卡最大x坐标
  211. self.map_y_pos = None # 关卡最大y坐标
  212. self.map_grids = None # 关卡全部的点坐标集合
  213. self.scroll_x_pos = None # 卷轴滚动x像素
  214. self.scroll_y_pos = None # 卷轴滚动y像素
  215. self.scroll_x_pos_max = None # 卷轴最大滚动x像素
  216. self.scroll_y_pos_max = None # 卷轴最大滚动y像素
  217. self.map_title = None # 关卡中文名称
  218. self.map_time = 0 # 关卡总时长
  219. self.level_time = 0
  220. self.map_init_time = None # 关卡加载时刻
  221. self.map_remaining_time = None # 关卡剩余时间
  222. self.map_music = None # 关卡背景音乐
  223. self.map_ambience = None # 背景音效
  224. self.map_music_volume = music_volume # 关卡背景音乐音量大小
  225. self.finish_at = None # 地图过关点(x, y)
  226. G.TOTAL_TRANSPORT = 0
  227. self.transport_map_total = transport_map_total
  228. self.transport_map_remain = transport_map_remain
  229. self.transport_obstacle = []
  230. self.water_reflect_obstacles = []
  231. self._water_reflection_base_cache = {}
  232. self._water_reflection_distort_cache = {}
  233. self._water_reflection_image_cache = {}
  234. self._water_reflection_draw_cache = {}
  235. self._water_submerged_entity_cache = {}
  236. self._sun_reflection_cache = {}
  237. self._water_reflection_wave_frame = -1
  238. self._water_reflection_cache_limit = 512
  239. self.transport_resource_init_points = []
  240. self.earth_quake_direction = None
  241. self.earth_quake_init_tick = 0 # 地震初始化tick
  242. self.earth_quake_left_times = 0 # 地震剩余次数
  243. self.earth_quake_strength = 0 # 地震强度
  244. self.earth_quake_times = 0 # 地震次数
  245. self.earth_quake_decrease = True # 地震强度是否递减
  246. self.current_time = pygame.time.get_ticks()
  247. self.background_layers = [] # 地板下方的地图背景图层
  248. self.floor_image = None # 游戏主区域的地板背景
  249. self.flame_instances = None # FlameInstance对象列表
  250. self.item_instances = None # (x, y) --> ItemInstance对象
  251. self.obstacle_instances = None # (x, y) --> ObstacleInstance对象
  252. self.obstacle_instances_update = None # 屏幕范围内的ObstacleInstance对象列表
  253. self.obstacle_instances_need_to_update = True # 需要更新列表
  254. self.bomb_instances = None # BombInstance对象列表
  255. self.ui_instances_bot = None # 位于main_area下的UIInstance对象列表
  256. self.ui_instances_top = None # 位于main_area上的UIInstance对象列![](C:/Users/dell/AppData/Local/Temp/previewfile_2896918733.gif)表
  257. self.block = None # 三维NumPy对象,阻挡玩家
  258. self.block_flame = None # 三维NumPy对象,阻挡糖跑
  259. self.slide_orientation = dict() # (x, y) --> (m, n) m网格传送带方向 0无 1右 2上 3左 4下 n速度
  260. self.grid_damage_blood = dict() # 网格伤害血量
  261. self.grid_damage_time = defaultdict(None) # 网格伤害时刻 只有糖泡爆炸时才会增加
  262. self.grid_damage_multiples = dict() # 伤害次数(倍数)
  263. # self.grid_damage_orientations = dict() # 网格伤害方向
  264. self.grid_damage_orientations = defaultdict(set)
  265. self.path_map = dict() # 缓存怪物追踪路径
  266. self.grid_damage_frame = False # 用于判断糖泡伤害瞬间与玩家位置是否重合 只有爆炸帧才是True
  267. self.accumulation_time = accumulation_time # 网格伤害延迟时间
  268. self.main_area = None # 游戏主区域
  269. self.main_area_offset = None # 游戏主区域相对左上角的偏移
  270. self.skill_instances = list() # 交予level托管的skill_instances,例如陷阱,不随npc死亡而消失
  271. self.effects_behind = list() # 关卡底层技能特效
  272. self.effects_front = list() # 关卡顶层技能特效
  273. self.effects_screen = list() # 屏幕级的技能特效 不随卷轴移动
  274. self.left_black = None # 屏幕右侧黑条
  275. self.grid_bomb_time_at = dict() # 糖泡伤害时刻
  276. self.level_variables = dict()
  277. self.blood_bar = None
  278. self.status_bar = None
  279. self.score_board = None
  280. self.time_board = None
  281. self.npcs = list() # 存活npc列表
  282. self.ghosts = list() # 存活僵尸列表
  283. self.wanderers = list()
  284. self.teammates = list()
  285. self.recal_npc_paths = True # 重新计算Npc路径的标志位 仅当玩家进入区域、糖泡施放与爆炸、玩家网格位置发生变化、障碍被摧毁时置为True
  286. self.recal_ghost_paths = True # 重新计算Ghost路径的标志位 仅当玩家移动
  287. self.display_name_card = False # 显示npc姓名牌
  288. self.display_npc_blood = False # 显示npc姓名牌
  289. self.district_idx = 0 # 当前区域 从1开始
  290. self.district_square = None # 当前区域 左上右下点像素坐标
  291. self.district_square_grid = None # 当前区域 左上右下点坐标
  292. self.district_alarming = False # 当前正在显示警戒
  293. self.district_all_finished = False # 已完成全部区域的标志
  294. self.finish_flag = False # 当前map结束的标志位
  295. self.district_json = None
  296. self.read_district_json = False
  297. self.custom_finish_flag = False
  298. self.custom_next_map = None
  299. self.portal = dict()
  300. self.portal_set = []
  301. self.has_achievemeny_check = False
  302. self.intro_chat_active = False
  303. self.intro_chat_started = False
  304. self.intro_chat_player = None
  305. self.ending_sequence_active = False
  306. self.pending_ending_sequence = None
  307. self.ending_sequence_scheduled = False
  308. self.ending_sequence_started = False
  309. self.ending_sequence_start_time = 0
  310. self.ending_sequence_player = None
  311. self._static_sorted = [] # [(y, tie, obj), ...] 已排序
  312. self._static_dirty = True # 静态层是否需要重排
  313. self._cached_item_count = -1 # 用于检测 item dict 变化(低配版)
  314. self.is_transport = False # 是否为运输模式
  315. self.map_blood_bar = None # 地图血条
  316. self.resource_bar = None # 资源受损条
  317. self.transport_buff_num = 0 # 资源buff
  318. self.transport_destination = None
  319. self.special_music_volume = 1 # 若需放大音乐
  320. self.load_map_json() # 加载地图
  321. self.load_ui() # 加载ui界面
  322. self.load_background_png() # 加载地板下方背景
  323. self.load_floor() # 加载地板
  324. self.load_obstacle() # 加载障碍
  325. self.load_music() # 加载音乐
  326. if self.is_transport:
  327. self.resource_bar.set_max_blood(G.TOTAL_TRANSPORT)
  328. self.mask_surface = pygame.Surface((self.map_x_pos, self.map_y_pos), pygame.SRCALPHA).convert_alpha()
  329. self.haunt_Mode = False
  330. self.bg_light = 0
  331. self.sunny = False
  332. self.underwater = False
  333. self.rgb_light = [0, 0, 0]
  334. self.special_rgb = False
  335. self.boss_blood_bar_dic = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0} # boss血条显示
  336. self.dark_trap = set() # debuff毒陷阱集合
  337. self.small_dark_trap = set() # debuff毒陷阱集合
  338. self.poison_dic = dict() # 改良版毒陷阱字典
  339. self.async_json_saver = AsyncJsonSaver()
  340. ReadyGo(self.effects_screen)
  341. self.map_json = load_json(f"game/map/{self.map_name}.json")
  342. G.ENVIRONMENT_EFFECT = self.map_json["basic"].get("environment_effect", [])
  343. if len(G.ENVIRONMENT_EFFECT) > 0:
  344. for en in G.ENVIRONMENT_EFFECT:
  345. EnvironmentEffect(self.effects_screen, en)
  346. self.haunt_Mode = self.map_json["basic"].get("haunted", False)
  347. self.bg_light = self.map_json["basic"].get("bg_light", 0)
  348. global _last_light_states
  349. _last_light_states = None
  350. self.mask_surface.fill((self.bg_light, self.bg_light, self.bg_light, 0))
  351. self.sunny = bool(self.map_json["basic"].get("sunny", False))
  352. self.underwater = self.map_json["basic"].get("underwater", False)
  353. G.UNDERWATER = self.underwater
  354. G.WATER_DAMPING = self.map_json["basic"].get("water_damping", 200)
  355. self.buff_hero = self.map_json["basic"].get("buff_hero", {})
  356. if self.buff_hero != {}:
  357. if self.me.hero_name in self.buff_hero.keys():
  358. buff_info = self.buff_hero[self.me.hero_name]
  359. self.me.blood += int(buff_info.get("blood", 0))
  360. self.me.remain_blood += int(buff_info.get("blood", 0))
  361. self.blood_bar.set_max_blood(self.me.blood)
  362. G.CUMULATION_HERO_BLOOD += int(buff_info.get("blood", 0))
  363. self.me.standard_defense += int(buff_info.get("defense", 0))
  364. self.me.defense += int(buff_info.get("defense", 0))
  365. self.me.standard_damage += int(buff_info.get("damage", 0))
  366. self.me.damage += int(buff_info.get("damage", 0))
  367. txt = buff_info.get("text", "")
  368. if txt != "":
  369. self.message_entry.new_message(sender="??", message=txt, colour=[255, 255, 255])
  370. if "teammate" in self.map_json["basic"].keys():
  371. from client_local.sprite.teammate import Teammate
  372. for mate in self.map_json["basic"].get("teammate", []):
  373. a_mate = Teammate(mate["name"], (self.me.x, self.me.y), guard_pos=tuple(mate.get("guard_pos", (0, 0))))
  374. self.teammates.append(a_mate)
  375. if "rgb_light" in self.map_json["basic"].keys():
  376. self.rgb_light = self.map_json["basic"]["rgb_light"]
  377. self.special_rgb = True
  378. self.particle_effect = self.map_json["basic"].get("particles", None)
  379. self.particles = set()
  380. self.last_particle_time = 0
  381. self.last_particle_update_time = 0
  382. if G.PET is not None:
  383. self.pets.append(Pet(G.PET, (self.me.x, self.me.y), owner=self.me, num=1))
  384. if "level_skill" in self.map_json["basic"].keys():
  385. for skills in self.map_json["basic"]["level_skill"]:
  386. skill_name = skills.get("skill_name", "")
  387. param = skills.get("param", dict())
  388. params = {"skill_name": skill_name, "param": param}
  389. params["init"] = skills.get("init", 0)
  390. params["interval"] = skills.get("interval", 100000)
  391. LevelSkillWithInterval(self.me, self.me, params, self.skill_instances)
  392. # 紫色毒陷阱判断
  393. DebuffPoisonGrid(self.me, self.npcs, self.skill_instances)
  394. def set_level_variables(self, name, value):
  395. self.level_variables[name] = value
  396. def get_level_variables(self, name, default_value):
  397. return self.level_variables.get(name, default_value)
  398. def load_map_json(self):
  399. # 加载关卡json文件
  400. map_json = load_json("game/map/" + self.map_name + ".json")
  401. self.map_json = map_json
  402. if not self.read_district_json:
  403. self.read_district_json = True
  404. self.district_json = self.map_json["districts"]
  405. self.me.set_xy(map_json["basic"]["begin"][0], map_json["basic"]["begin"][1])
  406. if len(self.pets) > 0:
  407. for pet in self.pets:
  408. pet.set_xy(map_json["basic"]["begin"][0], map_json["basic"]["begin"][1])
  409. # 地图大小-像素
  410. self.map_x = int(map_json["basic"]["width"])
  411. self.map_y = int(map_json["basic"]["height"])
  412. G.CURRENT_MAP_HEIGHT = int(map_json["basic"]["height"])
  413. G.CURRENT_MAP_WIDTH = int(map_json["basic"]["width"])
  414. self.map_x_pos = self.map_x * G.GAME_SQUARE - 1
  415. self.map_y_pos = self.map_y * G.GAME_SQUARE - 1
  416. self.map_grids = set()
  417. for x in range(self.map_x):
  418. for y in range(self.map_y):
  419. self.map_grids.add((x, y))
  420. self.scroll_x_pos = map_json["basic"]["scroll"][0] * G.GAME_SQUARE
  421. self.scroll_y_pos = map_json["basic"]["scroll"][1] * G.GAME_SQUARE
  422. self.scroll_x_pos_max = max(0, self.map_x_pos - G.MAIN_AREA_X * G.GAME_SQUARE)
  423. self.scroll_y_pos_max = max(0, self.map_y_pos - G.MAIN_AREA_Y * G.GAME_SQUARE)
  424. self.map_init_time = pygame.time.get_ticks()
  425. self.map_music = map_json["basic"]["music"]
  426. self.flame_instances = list()
  427. self.item_instances = dict()
  428. self.obstacle_instances = dict()
  429. self.obstacle_instances_update = list()
  430. self.bomb_instances = list()
  431. self.ui_instances_bot = list()
  432. self.ui_instances_top = list()
  433. self.block = np.zeros((2, self.map_x + 1, self.map_y + 1), dtype=np.int64)
  434. self.block_flame = np.zeros((2, self.map_x + 1, self.map_y + 1), dtype=np.int64)
  435. # 生成网格伤害二元组映射
  436. for x in range(self.map_x):
  437. for y in range(self.map_y):
  438. self.grid_damage_blood[(x, y)] = 0
  439. self.grid_damage_time[(x, y)] = 0
  440. self.grid_damage_multiples[(x, y)] = 0
  441. # self.grid_damage_orientations[(x, y)] = set()
  442. self.grid_bomb_time_at[(x, y)] = 0
  443. self.district_square_grid = {"x1": 0, "x2": 0, "y1": 0, "y2": 0}
  444. self.district_square = {"x1": 0, "x2": 0, "y1": 0, "y2": 0}
  445. if "finish" in self.map_json["basic"].keys():
  446. self.finish_at = (self.map_json["basic"]["finish"][0], self.map_json["basic"]["finish"][1])
  447. self.main_area = MainArea((self.map_x_pos, self.map_y_pos)).convert()
  448. self.left_black = pygame.Surface((1, 600))
  449. if "haunted" in self.map_json["basic"].keys():
  450. self.haunt_Mode = self.map_json["basic"]['haunted']
  451. if "bg_light" in self.map_json["basic"].keys():
  452. self.bg_light = self.map_json["basic"]["bg_light"]
  453. self.is_transport = self.map_json["basic"].get("is_transport", False)
  454. if self.is_transport:
  455. self.transport_resource_init_points = self.map_json["basic"].get("transport_resource_init", [])
  456. self.transport_destination = self.map_json["basic"].get("transport_destination", None)
  457. self.map_blood_bar = MapResouceBar(
  458. self.transport_map_total,
  459. self.transport_map_remain
  460. )
  461. self.ui_instances_top.append(self.map_blood_bar)
  462. self.resource_bar = ResourceBloodBar(self.me)
  463. self.ui_instances_top.append(self.resource_bar)
  464. self.ui_instances_top.append(ResourceIcon())
  465. if "underwater" in self.map_json["basic"].keys():
  466. self.underwater = self.map_json["basic"]["underwater"]
  467. G.UNDERWATER = self.underwater
  468. else:
  469. G.UNDERWATER = False
  470. if "water_damping" in self.map_json["basic"].keys():
  471. G.WATER_DAMPING = self.map_json["basic"]["water_damping"]
  472. else:
  473. G.WATER_DAMPING = 200
  474. if "rgb_light" in self.map_json["basic"].keys():
  475. self.rgb_light = self.map_json["basic"]["rgb_light"]
  476. self.special_rgb = True
  477. if "ambience" in self.map_json["basic"].keys():
  478. self.map_ambience = self.map_json["basic"]["ambience"]
  479. else:
  480. self.map_ambience = None
  481. self.special_music_volume = max(
  482. 0.0, float(self.map_json["basic"].get("music_volume", 1))
  483. )
  484. if "portal" in self.map_json["basic"].keys():
  485. self.portal = self.map_json["basic"]["portal"]
  486. for key in self.portal.keys():
  487. self.portal_set.append([ast.literal_eval(key), self.portal[key]["type"], self.portal[key]["target"]])
  488. else:
  489. self.portal = {}
  490. self.portal_set = []
  491. G.CURRENT_LEVEL += 1
  492. G.KILLED_NPC = 0
  493. G.MAP_NAME = self.map_name
  494. G.HAS_RECORD = False
  495. G.TOTAL_NPC = 0
  496. for dis in self.map_json["districts"]:
  497. G.TOTAL_NPC += len(dis["npcs"])
  498. if self.me.blood <= 4500 and self.me.standard_damage <= 3500+G.SPECIAL_DAMAGE and self.me.standard_defense <= G.SPECIAL_DEFENSE and self.me.standard_power <= 3+G.SPECIAL_POWER and self.me.standard_speed <= 0.234 and G.ITEM == 0:
  499. G.CHEAT = False
  500. else:
  501. G.CHEAT = True
  502. def try_start_intro_chat(self):
  503. if self.intro_chat_started:
  504. return
  505. basic = self.map_json.get("basic", {})
  506. intro_chat = basic.get("intro_chat", [])
  507. if not intro_chat:
  508. return
  509. if self.map_name in G.INTRO_CHAT_READ_MAPS:
  510. return
  511. self.intro_chat_started = True
  512. self.intro_chat_player = IntroChatPlayer(self.effects_screen, self.map_name, intro_chat)
  513. def advance_intro_chat(self):
  514. if self.intro_chat_player is not None:
  515. self.intro_chat_player.advance()
  516. def schedule_ending_sequence(self):
  517. if self.pending_ending_sequence is None or self.ending_sequence_scheduled:
  518. return
  519. self.ending_sequence_scheduled = True
  520. self.ending_sequence_start_time = pygame.time.get_ticks() + 9000
  521. def start_ending_sequence_if_needed(self):
  522. if not self.ending_sequence_scheduled or self.ending_sequence_started:
  523. return
  524. if self.current_time < self.ending_sequence_start_time:
  525. return
  526. self.ending_sequence_started = True
  527. self.ending_sequence_active = True
  528. self.ending_sequence_player = EndingSequencePlayer(self.effects_screen, self.pending_ending_sequence)
  529. def advance_ending_sequence(self):
  530. if self.ending_sequence_player is not None:
  531. self.ending_sequence_player.advance()
  532. def load_ui(self):
  533. self.ui_instances_bot.append(GameTop())
  534. self.status_bar = StatusBar()
  535. self.status_bar.set_prop_imgs(self.me)
  536. if self.map_x < 16:
  537. self.score_board = ScoreBoard()
  538. self.score_board.set_time(300)
  539. self.ui_instances_bot.append(self.score_board)
  540. else:
  541. self.ui_instances_top.append(DlgPveFunc())
  542. if G.SHOW_TIME:
  543. self.time_board = Timer()
  544. self.time_board.set_time(300)
  545. self.ui_instances_top.append(self.time_board)
  546. self.ui_instances_top.append(self.status_bar)
  547. self.ui_instances_top.append(Misc510())
  548. self.ui_instances_top.append(PlayerIcon(self.me.icon_img))
  549. if not G.SHOW_INPUT:
  550. G.SHOW_INPUT = True
  551. self.message_entry = InputEntry() # 聊天输入框
  552. else:
  553. self.message_entry = InputLevel() # 聊天输入框
  554. self.ui_instances_top.append(self.message_entry)
  555. self.blood_bar = BloodBar(self.me)
  556. self.blood_bar.set_name(self.your_name)
  557. self.ui_instances_top.append(self.blood_bar)
  558. def draw_water_reflections(self, surface):
  559. if not self.water_reflect_obstacles:
  560. return
  561. view_rect = pygame.Rect(self.scroll_x_pos, self.scroll_y_pos, G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS)
  562. for water in list(self.water_reflect_obstacles):
  563. self.draw_water_reflection_for_obstacle(surface, water, view_rect)
  564. def draw_water_reflection_for_obstacle(self, surface, water, view_rect=None):
  565. if view_rect is None:
  566. view_rect = pygame.Rect(self.scroll_x_pos, self.scroll_y_pos, G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS)
  567. if getattr(water, "state", None) == oi.ObstacleState.DEAD:
  568. return
  569. wave_frame = self.get_water_wave_frame()
  570. for tile_rect, reflection in self.get_water_reflection_entries(water, wave_frame):
  571. if tile_rect.colliderect(view_rect):
  572. surface.blit(reflection, tile_rect.topleft)
  573. self.draw_sun_reflections_for_obstacle(surface, water, view_rect, wave_frame)
  574. def get_water_wave_frame(self):
  575. wave_frame = self.current_time // 160
  576. if wave_frame != self._water_reflection_wave_frame:
  577. self._water_reflection_wave_frame = wave_frame
  578. self._water_reflection_distort_cache.clear()
  579. self._water_reflection_draw_cache.clear()
  580. return wave_frame
  581. def get_water_reflection_entries(self, water, wave_frame):
  582. cache_key = (id(water), water.x, water.y, wave_frame)
  583. cached = self._water_reflection_draw_cache.get(cache_key)
  584. if cached is not None:
  585. return cached
  586. entries = []
  587. width = water.obstacle.get("WIDTH", 1)
  588. height = water.obstacle.get("HEIGHT", 1)
  589. for dx in range(width):
  590. for dy in range(height):
  591. cell_x = water.x + dx
  592. cell_y = water.y + dy
  593. tile_rect = pygame.Rect(
  594. cell_x * G.GAME_SQUARE,
  595. cell_y * G.GAME_SQUARE,
  596. G.GAME_SQUARE,
  597. G.GAME_SQUARE
  598. )
  599. reflection = self.build_water_reflection(cell_x, cell_y, tile_rect, wave_frame)
  600. if reflection is not None:
  601. entries.append((tile_rect, reflection))
  602. if len(self._water_reflection_draw_cache) > self._water_reflection_cache_limit:
  603. self._water_reflection_draw_cache.clear()
  604. self._water_reflection_draw_cache[cache_key] = entries
  605. return entries
  606. def build_water_reflection(self, cell_x, cell_y, tile_rect, wave_frame):
  607. if cell_y <= 0:
  608. return None
  609. seen = set()
  610. candidates = []
  611. signature = []
  612. for x in range(max(0, cell_x - 4), min(self.map_x, cell_x + 5)):
  613. for source_y in (cell_y - 1, cell_y - 2):
  614. if source_y < 0:
  615. continue
  616. obstacle_ref = self.obstacle_instances.get((x, source_y))
  617. if obstacle_ref is None or getattr(obstacle_ref, "water_reflect", False):
  618. continue
  619. oid = id(obstacle_ref)
  620. if oid in seen:
  621. continue
  622. image = getattr(obstacle_ref, "image", None)
  623. rect = getattr(obstacle_ref, "rect", None)
  624. if image is None or rect is None or image.get_width() <= 1 or image.get_height() <= 1:
  625. continue
  626. water_origin_y = obstacle_ref.y + obstacle_ref.obstacle.get("HEIGHT", 1)
  627. segment_idx = cell_y - water_origin_y
  628. if segment_idx < 0 or segment_idx > 1:
  629. continue
  630. if segment_idx == 1 and not self.is_water_reflect_cell(cell_x, cell_y - 1):
  631. continue
  632. reflected_image = self.get_water_reflection_image(image)
  633. segment_y = 0 if segment_idx == 0 else G.GAME_SQUARE
  634. if segment_y >= reflected_image.get_height():
  635. continue
  636. image_rect = pygame.Rect(rect.x, rect.y, reflected_image.get_width(), reflected_image.get_height())
  637. overlap_left = max(image_rect.left, tile_rect.left)
  638. overlap_right = min(image_rect.right, tile_rect.right)
  639. if overlap_left >= overlap_right:
  640. continue
  641. seen.add(oid)
  642. candidates.append((obstacle_ref, reflected_image, image_rect, overlap_left, overlap_right, segment_y, segment_idx))
  643. signature.append((oid, id(image), image_rect.x, image_rect.width, image_rect.height, segment_idx))
  644. if not candidates:
  645. return None
  646. signature = tuple(signature)
  647. base_key = (cell_x, cell_y, signature)
  648. tile = self._water_reflection_base_cache.get(base_key)
  649. if tile is None:
  650. tile = pygame.Surface((G.GAME_SQUARE, G.GAME_SQUARE), pygame.SRCALPHA, 32)
  651. for _, image, image_rect, overlap_left, overlap_right, segment_y, segment_idx in candidates:
  652. self.blit_obstacle_reflection(tile, image, image_rect, overlap_left, overlap_right, tile_rect, segment_y, segment_idx)
  653. if len(self._water_reflection_base_cache) > self._water_reflection_cache_limit:
  654. self._water_reflection_base_cache.clear()
  655. self._water_reflection_base_cache[base_key] = tile
  656. distorted_key = (base_key, wave_frame)
  657. distorted = self._water_reflection_distort_cache.get(distorted_key)
  658. if distorted is None:
  659. distorted = self.distort_water_reflection(tile, wave_frame)
  660. self._water_reflection_distort_cache[distorted_key] = distorted
  661. return distorted
  662. def draw_sun_reflections_for_obstacle(self, surface, water, view_rect, wave_frame):
  663. if not self.sunny:
  664. return
  665. width = water.obstacle.get("WIDTH", 1)
  666. height = water.obstacle.get("HEIGHT", 1)
  667. for dx in range(width):
  668. for dy in range(height):
  669. cell_x = water.x + dx
  670. cell_y = water.y + dy
  671. tile_rect = pygame.Rect(
  672. cell_x * G.GAME_SQUARE,
  673. cell_y * G.GAME_SQUARE,
  674. G.GAME_SQUARE,
  675. G.GAME_SQUARE
  676. )
  677. if not tile_rect.colliderect(view_rect):
  678. continue
  679. sun_reflection = self.get_sun_reflection_for_water_cell(cell_x, cell_y, tile_rect, wave_frame)
  680. if sun_reflection is not None:
  681. surface.blit(sun_reflection, tile_rect.topleft)
  682. def get_sun_reflection_for_water_cell(self, cell_x, cell_y, tile_rect, wave_frame):
  683. if not self.sunny:
  684. return None
  685. center_x = self.scroll_x_pos + G.MAIN_AREA_X_POS // 2
  686. center_y = self.scroll_y_pos + G.MAIN_AREA_Y_POS // 2
  687. sun_w = 68
  688. sun_h = 34
  689. sun_rect = pygame.Rect(center_x - sun_w // 2, center_y - sun_h // 2, sun_w, sun_h)
  690. overlap = sun_rect.clip(tile_rect)
  691. if overlap.width <= 0 or overlap.height <= 0:
  692. return None
  693. key = (overlap.x - sun_rect.x, overlap.y - sun_rect.y, overlap.width, overlap.height)
  694. cached = self._sun_reflection_cache.get(key)
  695. if cached is None:
  696. full_sun = pygame.Surface((sun_w, sun_h), pygame.SRCALPHA, 32)
  697. pygame.draw.ellipse(full_sun, (255, 244, 202, 210), (0, 0, sun_w, sun_h))
  698. sun_piece = full_sun.subsurface(pygame.Rect(key)).copy()
  699. sun = pygame.Surface((G.GAME_SQUARE, G.GAME_SQUARE), pygame.SRCALPHA, 32)
  700. sun.blit(sun_piece, (overlap.x - tile_rect.x, overlap.y - tile_rect.y))
  701. if len(self._sun_reflection_cache) > 64:
  702. self._sun_reflection_cache.clear()
  703. self._sun_reflection_cache[key] = sun
  704. cached = sun
  705. distorted_key = ("sun", key, wave_frame)
  706. distorted = self._water_reflection_distort_cache.get(distorted_key)
  707. if distorted is None:
  708. distorted = self.distort_water_reflection(cached, wave_frame)
  709. self._water_reflection_distort_cache[distorted_key] = distorted
  710. return distorted
  711. def is_water_reflect_cell(self, cell_x, cell_y):
  712. obstacle_ref = self.obstacle_instances.get((cell_x, cell_y))
  713. return obstacle_ref is not None and getattr(obstacle_ref, "water_reflect", False)
  714. def draw_dynamic_object(self, obj):
  715. if not self.should_draw_water_submerged(obj):
  716. obj.draw(self.main_area)
  717. return
  718. old_flag = getattr(obj, "_water_submerged_draw", False)
  719. obj._water_submerged_draw = True
  720. try:
  721. obj.draw(self.main_area)
  722. finally:
  723. obj._water_submerged_draw = old_flag
  724. def should_draw_water_submerged(self, obj):
  725. if obj is not self.me and not isinstance(obj, Npc):
  726. return False
  727. if not hasattr(obj, "image") or obj.image is None:
  728. return False
  729. return self.is_water_reflect_cell(obj.x, obj.y)
  730. def get_water_submerged_entity_image(self, image):
  731. key = (id(image), image.get_width(), image.get_height())
  732. cached = self._water_submerged_entity_cache.get(key)
  733. if cached is not None:
  734. return cached
  735. w, h = image.get_size()
  736. if w <= 1 or h <= 1:
  737. return image
  738. bottom_h = min(20, h)
  739. result = image.copy().convert_alpha()
  740. bottom_rect = pygame.Rect(0, h - bottom_h, w, bottom_h)
  741. strip = image.subsurface(bottom_rect).copy()
  742. small = pygame.transform.smoothscale(strip, (max(1, w // 2), max(1, bottom_h // 2)))
  743. strip = pygame.transform.smoothscale(small, (w, bottom_h)).convert_alpha()
  744. strip.set_alpha(95)
  745. result.fill((0, 0, 0, 0), bottom_rect)
  746. result.blit(strip, bottom_rect.topleft)
  747. if len(self._water_submerged_entity_cache) > self._water_reflection_cache_limit:
  748. self._water_submerged_entity_cache.clear()
  749. self._water_submerged_entity_cache[key] = result
  750. return result
  751. def draw_water_submerged_image(self, screen, image, pos, split_y, alpha):
  752. w, h = image.get_size()
  753. split_y = max(0, min(h, int(split_y)))
  754. if split_y >= h:
  755. image.set_alpha(alpha)
  756. screen.blit(image, pos)
  757. return
  758. if split_y > 0:
  759. image.set_alpha(alpha)
  760. screen.blit(image, pos, pygame.Rect(0, 0, w, split_y))
  761. bottom_h = h - split_y
  762. key = (id(image), w, h, split_y, alpha)
  763. strip = self._water_submerged_entity_cache.get(key)
  764. if strip is None:
  765. strip = image.subsurface(pygame.Rect(0, split_y, w, bottom_h)).copy()
  766. small = pygame.transform.smoothscale(strip, (max(1, w // 2), max(1, bottom_h // 2)))
  767. strip = pygame.transform.smoothscale(small, (w, bottom_h)).convert_alpha()
  768. strip.set_alpha(min(alpha, 95))
  769. if len(self._water_submerged_entity_cache) > self._water_reflection_cache_limit:
  770. self._water_submerged_entity_cache.clear()
  771. self._water_submerged_entity_cache[key] = strip
  772. screen.blit(strip, (pos[0], pos[1] + split_y))
  773. def get_water_reflection_image(self, image):
  774. key = (id(image), image.get_width(), image.get_height())
  775. reflected = self._water_reflection_image_cache.get(key)
  776. if reflected is not None:
  777. return reflected
  778. flipped = pygame.transform.flip(image, False, True)
  779. reflected_h = max(1, int(image.get_height() * 0.8))
  780. reflected = pygame.transform.smoothscale(flipped, (image.get_width(), reflected_h)).convert_alpha()
  781. if len(self._water_reflection_image_cache) > self._water_reflection_cache_limit:
  782. self._water_reflection_image_cache.clear()
  783. self._water_reflection_image_cache[key] = reflected
  784. return reflected
  785. def blit_obstacle_reflection(self, tile, image, image_rect, overlap_left, overlap_right, tile_rect, segment_y, segment_idx):
  786. src_x = overlap_left - image_rect.left
  787. src_w = overlap_right - overlap_left
  788. if segment_idx == 0:
  789. src_h = min(G.GAME_SQUARE, image.get_height() - segment_y)
  790. dest_h = src_h
  791. alpha = 92
  792. else:
  793. src_h = image.get_height() - segment_y
  794. dest_h = G.GAME_SQUARE
  795. alpha = 52
  796. return self.blit_reflection_band(tile, image, src_x, segment_y, src_w, src_h, overlap_left - tile_rect.left, 0, dest_h, alpha)
  797. def blit_reflection_band(self, tile, image, src_x, src_y, src_w, src_h, dest_x, dest_y, dest_h, alpha):
  798. if src_w <= 0 or src_h <= 0 or dest_h <= 0:
  799. return False
  800. src_rect = pygame.Rect(src_x, src_y, src_w, src_h)
  801. src_rect = src_rect.clip(image.get_rect())
  802. if src_rect.width <= 0 or src_rect.height <= 0:
  803. return False
  804. piece = image.subsurface(src_rect).copy()
  805. if src_rect.height != dest_h:
  806. piece = pygame.transform.smoothscale(piece, (src_rect.width, dest_h)).convert_alpha()
  807. piece.set_alpha(alpha)
  808. tile.blit(piece, (dest_x, dest_y))
  809. return True
  810. def distort_water_reflection(self, source, wave_frame):
  811. w, h = source.get_size()
  812. if w <= 2 or h <= 2:
  813. return source
  814. small = pygame.transform.smoothscale(source, (max(1, w // 2), max(1, h // 2)))
  815. source = pygame.transform.smoothscale(small, (w, h)).convert_alpha()
  816. result = pygame.Surface((w, h), pygame.SRCALPHA, 32)
  817. phase = wave_frame * 0.65
  818. band_h = 5
  819. for y in range(0, h, band_h):
  820. offset = int(math.sin(phase + y * 0.35) * 2)
  821. result.blit(source, (offset, y), (0, y, w, band_h))
  822. return result
  823. def earth_quake_effect(self, strength=0.1, times=3, duration_per_time=200, decrease=True, direction=None):
  824. """屏幕震动效果,强度表示移动像素数量,times表示震动次数,duration_per_time表示每次震动持续时间"""
  825. if direction is None:
  826. direction = random.choice([0, 1])
  827. self.earth_quake_direction = direction
  828. if direction == 0:
  829. self.earth_quake_duration_per_time = duration_per_time
  830. strength *= 2
  831. else:
  832. self.earth_quake_duration_per_time = duration_per_time // 2
  833. self.earth_quake_strength = strength
  834. self.earth_quake_times = times
  835. self.earth_quake_time = pygame.time.get_ticks()
  836. self.earth_quake_decrease = decrease
  837. def run_earth_quake_effect(self, screen: pygame.Surface = None):
  838. """运行屏幕震动效果"""
  839. global Y_SCALE_FACTOR
  840. if self.earth_quake_strength <= 0 or self.earth_quake_times <= 0:
  841. Y_SCALE_FACTOR = 1
  842. return
  843. now = pygame.time.get_ticks()
  844. if now - self.earth_quake_time >= self.earth_quake_duration_per_time:
  845. self.earth_quake_times -= 1
  846. self.earth_quake_time = now
  847. if self.earth_quake_decrease:
  848. self.earth_quake_strength = self.earth_quake_strength * 0.5
  849. if self.earth_quake_times <= 0:
  850. self.earth_quake_strength = 0
  851. return
  852. # 计算偏移量(抛物线计算当前高度)
  853. t = (now - self.earth_quake_time) / self.earth_quake_duration_per_time
  854. Y_SCALE_FACTOR = 1 - self.earth_quake_strength * t * (1 - t)
  855. MAX_BIAS = G.MAIN_AREA_Y_POS * (1-Y_SCALE_FACTOR)//2
  856. screen.fill((0, 0, 0, 0), rect=(0, 21, G.MAIN_AREA_X_POS, MAX_BIAS))
  857. def load_background_png(self):
  858. self.background_layers = []
  859. for layer in self.map_json["basic"].get("background_png", []):
  860. if isinstance(layer, str):
  861. layer = {"name": layer, "move": False}
  862. name = layer.get("name")
  863. if not name:
  864. continue
  865. path = name if "/" in name or "\\" in name else f"res/img/background/{name}"
  866. image = load_png(path).convert_alpha()
  867. if layer.get("move", False):
  868. image = self.crop_background_to_map_ratio(image)
  869. image = self.scale_background_to_cover_view(image)
  870. else:
  871. target_size = (G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS)
  872. if image.get_size() != target_size:
  873. image = pygame.transform.smoothscale(image, target_size).convert_alpha()
  874. self.background_layers.append({
  875. "image": image,
  876. "move": bool(layer.get("move", False)),
  877. })
  878. def crop_background_to_map_ratio(self, image):
  879. img_w, img_h = image.get_size()
  880. if img_w <= 0 or img_h <= 0 or self.map_y_pos <= 0:
  881. return image
  882. map_ratio = self.map_x_pos / self.map_y_pos
  883. img_ratio = img_w / img_h
  884. if img_ratio > map_ratio:
  885. crop_w = max(1, int(img_h * map_ratio))
  886. crop_rect = pygame.Rect((img_w - crop_w) // 2, 0, crop_w, img_h)
  887. else:
  888. crop_h = max(1, int(img_w / map_ratio))
  889. crop_rect = pygame.Rect(0, (img_h - crop_h) // 2, img_w, crop_h)
  890. return image.subsurface(crop_rect).copy()
  891. def scale_background_to_cover_view(self, image):
  892. img_w, img_h = image.get_size()
  893. if img_w <= 0 or img_h <= 0:
  894. return image
  895. scale = max(G.MAIN_AREA_X_POS / img_w, G.MAIN_AREA_Y_POS / img_h, 1)
  896. if scale <= 1:
  897. return image
  898. target_size = (max(1, int(img_w * scale)), max(1, int(img_h * scale)))
  899. return pygame.transform.smoothscale(image, target_size).convert_alpha()
  900. def draw_background_png(self):
  901. for layer in self.background_layers:
  902. if layer["move"]:
  903. image = layer["image"]
  904. img_w, img_h = image.get_size()
  905. src_x = self.get_background_scroll_pos(
  906. self.scroll_x_pos, self.scroll_x_pos_max, img_w, G.MAIN_AREA_X_POS
  907. )
  908. src_y = self.get_background_scroll_pos(
  909. self.scroll_y_pos, self.scroll_y_pos_max, img_h, G.MAIN_AREA_Y_POS
  910. )
  911. area_w = min(G.MAIN_AREA_X_POS, img_w)
  912. area_h = min(G.MAIN_AREA_Y_POS, img_h)
  913. dest_x = self.scroll_x_pos + max(0, (G.MAIN_AREA_X_POS - img_w) // 2)
  914. dest_y = self.scroll_y_pos + max(0, (G.MAIN_AREA_Y_POS - img_h) // 2)
  915. self.main_area.blit(image, (dest_x, dest_y), pygame.Rect(src_x, src_y, area_w, area_h))
  916. else:
  917. self.main_area.blit(layer["image"], (self.scroll_x_pos, self.scroll_y_pos))
  918. def get_background_scroll_pos(self, scroll_pos, scroll_max, image_size, view_size):
  919. bg_scroll_max = max(0, image_size - view_size)
  920. if bg_scroll_max <= 0:
  921. return 0
  922. if scroll_max <= 0:
  923. return bg_scroll_max // 2
  924. return int(bg_scroll_max * max(0, min(1, scroll_pos / scroll_max)))
  925. def load_floor(self):
  926. # 加载地板floor
  927. self.floor_image = pygame.Surface((self.map_x_pos, self.map_y_pos), flags=pygame.HWSURFACE).convert_alpha()
  928. if self.background_layers:
  929. self.floor_image.fill((0, 0, 0, 0))
  930. # 块区域加载
  931. for f in self.map_json["floors"]:
  932. for square in f["squares"]:
  933. for x in range(square["x1"], square["x2"] + 1):
  934. for y in range(square["y1"], square["y2"] + 1):
  935. img = floor.get_floor(f["type"], f["name"])
  936. self.floor_image.blit(img, (x * G.GAME_SQUARE, y * G.GAME_SQUARE))
  937. # 单个加载
  938. for f in self.map_json["floor"]:
  939. img = floor.get_floor(f["type"], f["name"])
  940. for point in f["points"]:
  941. self.floor_image.blit(img, (point["x"] * G.GAME_SQUARE, point["y"] * G.GAME_SQUARE))
  942. def load_obstacle(self):
  943. # 加载障碍obstacle_instance
  944. # 块区域加载
  945. for o in self.map_json["obstacles"]:
  946. obs, obs_json = obstacle.get_obstacle(o["type"], o["name"])
  947. for square in o["squares"]:
  948. for x in range(square["x1"], square["x2"] + 1):
  949. for y in range(square["y1"], square["y2"] + 1):
  950. oi.ObstacleInstance(x, y, self.obstacle_instances, obs, obs_json)
  951. # 单个加载
  952. for o in self.map_json["obstacle"]:
  953. obs, obs_json = obstacle.get_obstacle(o["type"], o["name"])
  954. for point in o["points"]:
  955. oi.ObstacleInstance(point["x"], point["y"], self.obstacle_instances, obs, obs_json)
  956. if self.is_transport:
  957. rs_num = 0
  958. obs, obs_json = obstacle.get_obstacle("eden", "elem1")
  959. for x, y in self.transport_resource_init_points:
  960. if rs_num >= G.RESOUCE_NUM:
  961. break
  962. oi.ObstacleInstance(x, y, self.obstacle_instances, obs, obs_json)
  963. rs_num += 1
  964. def load_music(self):
  965. music_loader.play(self.map_music, self.map_music_volume * self.special_music_volume)
  966. if self.map_ambience is not None:
  967. music_loader.play_ambience(self.map_ambience, self.map_music_volume * self.special_music_volume)
  968. else:
  969. music_loader.stop_ambience()
  970. def check_weak_achievement(self):
  971. if self.me.blood <= 4500 and self.me.standard_damage <= 3500+G.SPECIAL_DAMAGE and self.me.standard_power <= 3+G.SPECIAL_POWER and self.me.defense <= G.SPECIAL_DEFENSE and self.me.standard_speed <= 0.234*G.SPECIAL_SPEED:
  972. return True
  973. else:
  974. return False
  975. def check_achievement(self):
  976. if self.me.blood <= 4500 and self.me.standard_damage <= 3500+G.SPECIAL_DAMAGE and self.me.standard_power <= 3+G.SPECIAL_POWER and self.me.defense <= G.SPECIAL_DEFENSE and self.me.standard_speed <= 0.234*G.SPECIAL_SPEED and G.ITEM == 0:
  977. return True
  978. else:
  979. return False
  980. def check_full_achievement(self):
  981. if not G.HAS_GOLDEN and 4500 >= self.me.blood == self.me.remain_blood and self.me.standard_damage <= 3500+G.SPECIAL_DAMAGE and self.me.standard_power <= 3+G.SPECIAL_POWER and self.me.defense <= G.SPECIAL_DEFENSE and self.me.standard_speed <= 0.234*G.SPECIAL_SPEED and G.ITEM == 0:
  982. return True
  983. else:
  984. return False
  985. def record_achievement(self):
  986. pass
  987. def update_map_tranport_remain(self, new_remain):
  988. path = f"game/map/{self.map_name}.json"
  989. map_json = load_json(path)
  990. map_json["basic"]["transport_remain"] = new_remain
  991. self.async_json_saver.save(path, map_json)
  992. def check_game_achievement(self):
  993. if self.check_full_achievement() and not G.HAS_RECORD_FULL:
  994. G.HAS_RECORD_FULL = True
  995. # 构建保存文件的路径
  996. user_documents_folder = os.path.expanduser("~\\Documents") # 获取用户的"文档"文件夹路径
  997. qqtpve_folder = os.path.join(user_documents_folder, "QQTPVE") # 构建QQTPVE文件夹路径
  998. os.makedirs(qqtpve_folder, exist_ok=True) # 确保QQTPVE文件夹存在,如果不存在则创建
  999. full_achievements_file_path = os.path.join(qqtpve_folder, "full_achievements.json") # 构建full_achievements.json文件路径
  1000. try:
  1001. with open(full_achievements_file_path, encoding="utf-8") as file:
  1002. encrypted_data = json.load(file)
  1003. except:
  1004. try:
  1005. with open(full_achievements_file_path, encoding="utf-8_sig") as file:
  1006. encrypted_data = json.load(file)
  1007. except:
  1008. # 如果文件不存在,创建新的空的achievements.json文件
  1009. encrypted_data = {"STAT": []}
  1010. with open(full_achievements_file_path, 'w', encoding="utf-8") as file:
  1011. json.dump(encrypted_data, file, indent=2)
  1012. if encrypted_data == {}:
  1013. encrypted_data = {"STAT": []}
  1014. # 新的数据
  1015. new_data = {
  1016. caesar_encrypt("name"): caesar_encrypt(G.MAP_SET_NAME),
  1017. caesar_encrypt("last_map_name"): caesar_encrypt(G.MAP_NAME),
  1018. caesar_encrypt("map_order"): int(caesar_encrypt(str(G.CURRENT_LEVEL))),
  1019. caesar_encrypt("LV"): int(caesar_encrypt(str(self.me.blood))),
  1020. caesar_encrypt("time"): caesar_encrypt(datetime.now().strftime("%Y-%m-%d %H:%M:%S")),
  1021. caesar_encrypt("game_time_min"): int(caesar_encrypt(str(self.map_time//60))),
  1022. caesar_encrypt("game_time_sec"): int(caesar_encrypt(str(self.map_time%60)))
  1023. }
  1024. # 添加新的加密数据
  1025. encrypted_data["STAT"].append(new_data)
  1026. with open(full_achievements_file_path, 'w') as file:
  1027. json.dump(encrypted_data, file, indent=2)
  1028. if G.CURRENT_LEVEL == G.TOTAL_LEVEL:
  1029. G.CUMULATION_INJURE += self.me.blood - self.me.remain_blood
  1030. if self.check_weak_achievement() and G.CURRENT_LEVEL == G.TOTAL_LEVEL and not G.HAS_RECORD:
  1031. G.HAS_RECORD = True
  1032. sound_player.playWin("PlayerWin")
  1033. if self.is_transport:
  1034. if self.transport_map_remain > 0:
  1035. TransportSuccessEffect(self.me, self.me, self.transport_map_remain, self.skill_instances)
  1036. current_amount = max(G.TOTAL_TRANSPORT - G.CUMULATION_RESOURCE_LEAK + 50, 0) * (1 - G.CUMULATION_INJURE / G.CUMULATION_HERO_BLOOD)
  1037. current_amount = max(current_amount, 0)
  1038. new_remain = max(0, self.transport_map_remain - current_amount)
  1039. current_amount = int(current_amount)
  1040. new_remain = int(new_remain)
  1041. if new_remain > 0:
  1042. msg_txt = f"本次成功运输{current_amount}点资源,当前还剩余{new_remain}/{self.transport_map_total}"
  1043. else:
  1044. msg_txt = f"本次成功运输{current_amount}点资源,当前地图所有运输任务已完成!!!"
  1045. self.message_entry.new_message(sender="运输助手", message=msg_txt, colour=[95, 191, 255])
  1046. self.update_map_tranport_remain(new_remain)
  1047. self.map_blood_bar.update_remain_blood(new_remain)
  1048. else:
  1049. if G.CUMULATION_INJURE == 0:
  1050. WinEffect(self.me, self.me, "super", self.skill_instances)
  1051. elif G.CUMULATION_INJURE < min(4500, self.me.blood):
  1052. WinEffect(self.me, self.me, "ultra", self.skill_instances)
  1053. else:
  1054. WinEffect(self.me, self.me, "big", self.skill_instances)
  1055. current_amount = max(G.TOTAL_TRANSPORT - G.CUMULATION_RESOURCE_LEAK + 50, 0) * (1 - G.CUMULATION_INJURE / G.CUMULATION_HERO_BLOOD)
  1056. current_amount = max(current_amount, 0)
  1057. current_amount = int(current_amount)
  1058. if current_amount > 0:
  1059. msg_txt = f"当前区域运输目标已完成,本次额外运输{current_amount}点资源"
  1060. self.message_entry.new_message(sender="运输助手", message=msg_txt, colour=[95, 191, 255])
  1061. else:
  1062. if G.ITEM == 0:
  1063. if G.CUMULATION_INJURE == 0:
  1064. WinEffect(self.me, self.me, "super", self.skill_instances)
  1065. elif G.CUMULATION_INJURE < min(4500, self.me.blood):
  1066. WinEffect(self.me, self.me, "ultra", self.skill_instances)
  1067. else:
  1068. WinEffect(self.me, self.me, "big", self.skill_instances)
  1069. else:
  1070. WinEffect(self.me, self.me, "normal", self.skill_instances)
  1071. if G.ITEM == 0:
  1072. # 构建保存文件的路径
  1073. user_documents_folder = os.path.expanduser("~\\Documents") # 获取用户的"文档"文件夹路径
  1074. qqtpve_folder = os.path.join(user_documents_folder, "QQTPVE") # 构建QQTPVE文件夹路径
  1075. os.makedirs(qqtpve_folder, exist_ok=True) # 确保QQTPVE文件夹存在,如果不存在则创建
  1076. achievements_file_path = os.path.join(qqtpve_folder, "achievements.json") # 构建achievements.json文件路径
  1077. monster_stats_file_path = os.path.join(qqtpve_folder, "monster_stats.json") # 构建json文件路径
  1078. try:
  1079. with open(achievements_file_path, encoding="utf-8") as file:
  1080. encrypted_data = json.load(file)
  1081. except:
  1082. try:
  1083. with open(achievements_file_path, encoding="utf-8_sig") as file:
  1084. encrypted_data = json.load(file)
  1085. except:
  1086. # 如果文件不存在,创建新的空的achievements.json文件
  1087. encrypted_data = {"STAT": []}
  1088. with open(achievements_file_path, 'w', encoding="utf-8") as file:
  1089. json.dump(encrypted_data, file, indent=2)
  1090. if encrypted_data == {}:
  1091. encrypted_data = {"STAT": []}
  1092. # 新的数据
  1093. new_data = {caesar_encrypt("name"): caesar_encrypt(G.MAP_SET_NAME),
  1094. caesar_encrypt("last_map_name"): caesar_encrypt(G.MAP_NAME),
  1095. caesar_encrypt("LV"): int(caesar_encrypt(str(self.me.blood))),
  1096. caesar_encrypt("time"): caesar_encrypt(datetime.now().strftime("%Y-%m-%d %H:%M:%S")),
  1097. caesar_encrypt("game_time_min"): int(caesar_encrypt(str(self.map_time//60))),
  1098. caesar_encrypt("game_time_sec"): int(caesar_encrypt(str(self.map_time%60))),
  1099. caesar_encrypt("remain_blood"): int(caesar_encrypt(str(self.me.remain_blood)))}
  1100. try:
  1101. # 添加新的加密数据
  1102. encrypted_data["STAT"].append(new_data)
  1103. with open(achievements_file_path, 'w') as file:
  1104. json.dump(encrypted_data, file, indent=2)
  1105. except:
  1106. pass
  1107. try:
  1108. with open(monster_stats_file_path, encoding="utf-8") as file:
  1109. self.encrypted_data_m = json.load(file)
  1110. except:
  1111. try:
  1112. with open(monster_stats_file_path, encoding="utf-8_sig") as file:
  1113. self.encrypted_data_m = json.load(file)
  1114. except:
  1115. # 如果文件不存在,创建新的空的json文件
  1116. self.encrypted_data_m = {"STAT": []}
  1117. with open(monster_stats_file_path, 'w', encoding="utf-8") as file:
  1118. json.dump(self.encrypted_data_m, file, indent=2)
  1119. if self.encrypted_data_m == {}:
  1120. self.encrypted_data_m = {"STAT": []}
  1121. try:
  1122. for data in G.MONSTER_RECORD_LIST:
  1123. self.encrypted_data_m["STAT"].append(data)
  1124. with open(monster_stats_file_path, 'w') as file:
  1125. json.dump(self.encrypted_data_m, file, indent=2)
  1126. G.MONSTER_RECORD_LIST = []
  1127. except:
  1128. G.MONSTER_RECORD_LIST = []
  1129. else:
  1130. if G.CURRENT_LEVEL == G.TOTAL_LEVEL:
  1131. WinEffect(self.me, self.me, "normal", self.skill_instances)
  1132. if G.CURRENT_LEVEL == G.TOTAL_LEVEL:
  1133. self.schedule_ending_sequence()
  1134. def load_district_and_enemies(self):
  1135. if len(self.npcs) > 0: # npc还没有被杀光
  1136. return
  1137. self.me.district_locked = False # 解除玩家区域锁
  1138. if self.district_idx >= len(self.map_json["districts"]): # 已完成最后一个区域
  1139. self.district_square = {"x1": 0, "x2": 0, "y1": 0, "y2": 0}
  1140. self.district_square_grid = {"x1": 0, "x2": 0, "y1": 0, "y2": 0}
  1141. self.district_all_finished = True
  1142. if not self.has_achievemeny_check:
  1143. self.has_achievemeny_check = True
  1144. self.check_game_achievement()
  1145. return
  1146. self.district_idx += 1
  1147. a_district = self.map_json["districts"][self.district_idx - 1]
  1148. valid_poison_set = set()
  1149. self.district_square = a_district["square"].copy()
  1150. self.district_square_grid["x1"] = self.district_square["x1"]
  1151. self.district_square_grid["x2"] = self.district_square["x2"]
  1152. self.district_square_grid["y1"] = self.district_square["y1"]
  1153. self.district_square_grid["y2"] = self.district_square["y2"]
  1154. # 将district_square的四个点转化为像素坐标
  1155. self.district_square["x1"] = self.district_square["x1"] * G.GAME_SQUARE + G.HALF_GAME_SQUARE
  1156. self.district_square["x2"] = self.district_square["x2"] * G.GAME_SQUARE + G.HALF_GAME_SQUARE
  1157. self.district_square["y1"] = self.district_square["y1"] * G.GAME_SQUARE + G.HALF_GAME_SQUARE
  1158. self.district_square["y2"] = self.district_square["y2"] * G.GAME_SQUARE + G.HALF_GAME_SQUARE
  1159. for g in self.ghosts:
  1160. # 加载新区域时删除旧区域的幽灵,以及新加载出来的幽灵
  1161. if g.time == 0:
  1162. self.ghosts.remove(g)
  1163. for n in a_district["npcs"]:
  1164. # 载入新区域的npc
  1165. patrol = n.get("patrol", None)
  1166. if patrol is not None:
  1167. self.npcs.append(Npc(n["name"], (n["x"], n["y"]), patrol_path=patrol))
  1168. else:
  1169. self.npcs.append(Npc(n["name"], (n["x"], n["y"])))
  1170. for district in self.map_json["districts"][self.district_idx-1:]:
  1171. x1, y1, x2, y2 = district["square"]["x1"], district["square"]["y1"], district["square"]["x2"], district["square"]["y2"]
  1172. for point in self.poison_dic.keys():
  1173. if x1 <= point[0] <= x2 and y1 <= point[1] <= y2:
  1174. valid_poison_set.add(point)
  1175. G.HAS_RECORD_FULL = False
  1176. G.HAS_GOLDEN = False
  1177. # 清除冗余紫陷阱
  1178. old_keys = [ky for ky in self.poison_dic.keys()]
  1179. for point in old_keys:
  1180. if point not in valid_poison_set:
  1181. self.poison_dic[point][4].state = EffectState.DEAD
  1182. del self.poison_dic[point]
  1183. def update(self, screen: pygame.Surface):
  1184. # a = pygame.time.get_ticks()
  1185. self.current_time = pygame.time.get_ticks()
  1186. self.run_earth_quake_effect(screen) # 运行屏幕震动效果
  1187. # 刷新帧率
  1188. self.display_frame_rate(self.current_time, screen)
  1189. # 刷新剩余时间
  1190. if self.score_board is not None:
  1191. map_remaining_time = math.ceil(
  1192. (self.map_time * 1000) // 1000) + 1
  1193. self.score_board.set_time(map_remaining_time)
  1194. if self.time_board is not None:
  1195. map_remaining_time = math.ceil(
  1196. (self.level_time * 1000) // 1000)
  1197. self.time_board.set_time(map_remaining_time)
  1198. self.start_ending_sequence_if_needed()
  1199. if not self.intro_chat_started and self.current_time - self.map_init_time > 3000:
  1200. self.try_start_intro_chat()
  1201. # 刷新区域
  1202. if not self.intro_chat_active and self.current_time - self.map_init_time > 3000:
  1203. self.load_district_and_enemies()
  1204. # 恢复帧爆炸位
  1205. self.grid_damage_frame -= 1
  1206. # 刷新糖泡
  1207. for b in self.bomb_instances:
  1208. b.update()
  1209. # 刷新游荡者
  1210. for w in self.wanderers:
  1211. if w.remain_blood <= 0:
  1212. self.wanderers.remove(w)
  1213. else:
  1214. if abs(w.x - self.me.x) <= 20 and abs(w.y - self.me.y) <= 20:
  1215. w.update()
  1216. # 刷新友军
  1217. for t in self.teammates:
  1218. if t.remain_blood <= 0:
  1219. self.teammates.remove(t)
  1220. else:
  1221. t.update()
  1222. # 刷新npc
  1223. for n in self.npcs:
  1224. if n.remain_blood <= 0:
  1225. self.npcs.remove(n)
  1226. else:
  1227. n.update()
  1228. self.recal_npc_paths = False
  1229. # 刷新宠物
  1230. if len(self.pets) > 0:
  1231. for pet in self.pets:
  1232. pet.update()
  1233. # 刷新ghost
  1234. for g in self.ghosts:
  1235. if g.remain_time <= 0:
  1236. self.ghosts.remove(g)
  1237. else:
  1238. g.update()
  1239. self.recal_ghost_paths = False
  1240. # 刷新人物
  1241. self.me.update()
  1242. # 检测过关
  1243. self.pass_map()
  1244. # 检测传送门
  1245. self.portal_map()
  1246. # 刷新糖浆
  1247. new_flames = []
  1248. for f in self.flame_instances:
  1249. if f.state == FS.DEAD:
  1250. continue
  1251. f.update()
  1252. if f.state != FS.DEAD:
  1253. new_flames.append(f)
  1254. self.flame_instances = new_flames
  1255. # 刷新item
  1256. for key in list(self.item_instances.keys()):
  1257. i = self.item_instances[key]
  1258. if i.state == IS.DEAD:
  1259. self.item_instances.pop(key)
  1260. else:
  1261. i.update()
  1262. # 刷新障碍
  1263. # if self.obstacle_instances_need_to_update:
  1264. # self.update_obstacles_update_list()
  1265. # 只有当真的 rebuild obstacle_instances_update 时,才标脏
  1266. if self.obstacle_instances_need_to_update:
  1267. self.update_obstacles_update_list()
  1268. self._static_dirty = True
  1269. # 当 dict 发生变化时标脏(低配版:靠计数变化)
  1270. if len(self.item_instances) != self._cached_item_count:
  1271. self._cached_item_count = len(self.item_instances)
  1272. self._static_dirty = True
  1273. for o in self.obstacle_instances_update:
  1274. o.update()
  1275. self.transport_buff_num = 0
  1276. for o in self.transport_obstacle:
  1277. if o.transport_remain > 0:
  1278. o.update()
  1279. if o.in_safe_zone:
  1280. self.transport_buff_num += 1
  1281. # 刷新技能
  1282. for s in self.skill_instances:
  1283. s.update()
  1284. # 刷新特效
  1285. for e in self.effects_behind:
  1286. e.update()
  1287. for e in self.effects_front:
  1288. e.update()
  1289. for e in self.effects_screen:
  1290. e.update()
  1291. # 刷新ui
  1292. for u in self.ui_instances_top:
  1293. u.update()
  1294. for u in self.ui_instances_bot:
  1295. u.update()
  1296. if Y_SCALE_FACTOR != 1:
  1297. MAX_BIAS = G.MAIN_AREA_Y_POS * (1-Y_SCALE_FACTOR)//2
  1298. # 上下MAX_BIAS区域填充(0,0,0,0)
  1299. self.main_area.fill((255, 255, 255, 0), (self.scroll_x_pos, self.scroll_y_pos + 21, G.MAIN_AREA_X_POS, MAX_BIAS))
  1300. # 显示地板下方背景
  1301. self.draw_background_png()
  1302. # 显示地板
  1303. self.main_area.blit(
  1304. self.floor_image,
  1305. (self.scroll_x_pos, self.scroll_y_pos),
  1306. (self.scroll_x_pos, self.scroll_y_pos, G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS)
  1307. )
  1308. # 显示底层特效
  1309. for e in self.effects_behind:
  1310. e.draw(self.main_area)
  1311. # 显示人物和障碍
  1312. # if len(self.pets) > 0:
  1313. # draw_seq = self.pets + \
  1314. # [self.me] + \
  1315. # self.npcs + \
  1316. # self.wanderers + \
  1317. # self.teammates + \
  1318. # self.ghosts + \
  1319. # self.bomb_instances + \
  1320. # self.obstacle_instances_update + \
  1321. # self.flame_instances + \
  1322. # list(self.item_instances.values())
  1323. # else:
  1324. # draw_seq = [self.me] + \
  1325. # self.npcs + \
  1326. # self.wanderers + \
  1327. # self.teammates + \
  1328. # self.ghosts + \
  1329. # self.bomb_instances + \
  1330. # self.obstacle_instances_update + \
  1331. # self.flame_instances + \
  1332. # list(self.item_instances.values())
  1333. # draw_seq.sort(key=get_y)
  1334. # for d in draw_seq:
  1335. # d.draw(self.main_area)
  1336. # 重建静态已排序列表(只在 dirty 时做)
  1337. if self._static_dirty:
  1338. static_objs = []
  1339. # 现在参与 y-sort 的“基本静态”候选
  1340. # obstacle_instances_update:位置不动,但“可见集合”会变
  1341. static_objs.extend(self.obstacle_instances_update)
  1342. # items:大多数情况下不动(被拾取/生成时才变)
  1343. static_objs.extend(self.item_instances.values())
  1344. # 预计算 y,避免 merge 时反复 getattr/get_y
  1345. tmp = []
  1346. tie = 0
  1347. for o in static_objs:
  1348. y = o.get_y() if hasattr(o, "get_y") else getattr(o, "y_pos", 0)
  1349. tmp.append((y, tie, o))
  1350. tie += 1
  1351. tmp.sort(key=lambda t: (t[0], t[1]))
  1352. self._static_sorted = tmp
  1353. self._static_dirty = False
  1354. # 动态层:每帧组装 + 排序
  1355. dyn = []
  1356. append = dyn.append
  1357. extend = dyn.extend
  1358. if self.pets:
  1359. extend(self.pets)
  1360. append(self.me)
  1361. extend(self.npcs)
  1362. extend(self.wanderers)
  1363. extend(self.teammates)
  1364. extend(self.ghosts)
  1365. extend(self.bomb_instances)
  1366. extend(self.flame_instances)
  1367. dyn_tmp = []
  1368. tie = 0
  1369. for o in dyn:
  1370. y = o.get_y() if hasattr(o, "get_y") else getattr(o, "y_pos", 0)
  1371. dyn_tmp.append((y, tie, o))
  1372. tie += 1
  1373. dyn_tmp.sort(key=lambda t: (t[0], t[1]))
  1374. # merge:两路有序序列 O(n) 绘制
  1375. i = 0
  1376. j = 0
  1377. A = self._static_sorted
  1378. B = dyn_tmp
  1379. draw = self.main_area.blit
  1380. while i < len(A) and j < len(B):
  1381. if A[i][0] <= B[j][0]:
  1382. static_obj = A[i][2]
  1383. static_obj.draw(self.main_area)
  1384. if getattr(static_obj, "water_reflect", False):
  1385. self.draw_water_reflection_for_obstacle(self.main_area, static_obj)
  1386. i += 1
  1387. else:
  1388. self.draw_dynamic_object(B[j][2])
  1389. j += 1
  1390. while i < len(A):
  1391. static_obj = A[i][2]
  1392. static_obj.draw(self.main_area)
  1393. if getattr(static_obj, "water_reflect", False):
  1394. self.draw_water_reflection_for_obstacle(self.main_area, static_obj)
  1395. i += 1
  1396. while j < len(B):
  1397. self.draw_dynamic_object(B[j][2])
  1398. j += 1
  1399. if self.special_rgb:
  1400. self.mask_surface = special_colour_mask(self.mask_surface, self.rgb_light)
  1401. self.main_area.blit(self.mask_surface, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
  1402. if self.haunt_Mode:
  1403. # 只在 get_player_mask 检测到状态变化时才重绘 mask_surface
  1404. get_player_mask(self.mask_surface, self.bg_light)
  1405. view_rect = pygame.Rect(
  1406. self.scroll_x_pos,
  1407. self.scroll_y_pos,
  1408. G.MAIN_AREA_X_POS,
  1409. G.MAIN_AREA_Y_POS
  1410. ).clip(self.main_area.get_rect())
  1411. # 取 main_area 的子 Surface(不拷贝像素,O(1))
  1412. sub_main = self.main_area.subsurface(view_rect)
  1413. # 将 mask_surface 乘进子 Surface,而不是整张 main_area
  1414. sub_main.blit(self.mask_surface, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
  1415. # 显示顶层特效
  1416. for e in self.effects_front:
  1417. e.draw(self.main_area)
  1418. # 显示下ui
  1419. for u in self.ui_instances_bot:
  1420. u.draw(screen)
  1421. # 显示主区域
  1422. screen.blit(self.main_area, (0, 21), (self.scroll_x_pos - 1, self.scroll_y_pos, G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS))
  1423. # 显示上ui
  1424. for u in self.ui_instances_top:
  1425. u.draw(screen)
  1426. # 显示屏幕特效
  1427. for e in self.effects_screen:
  1428. try:
  1429. e.draw(screen)
  1430. except Exception as e:
  1431. print(e)
  1432. self.update_particles(screen, current_time=self.current_time)
  1433. # 左侧黑条
  1434. screen.blit(self.left_black, (0, 0))
  1435. # 重置糖泡爆炸音效位
  1436. BombInstance.sound_played = False
  1437. # 重置糖泡爆炸方向记录
  1438. self.grid_damage_orientations.clear()
  1439. # print(pygame.time.get_ticks() - a)
  1440. def update_particles(self, screen, current_time):
  1441. if self.particle_effect is None:
  1442. return
  1443. if current_time - self.last_particle_time >= 150:
  1444. self.last_particle_time = current_time
  1445. x = random.randint(0, screen.get_width())
  1446. y = screen.get_height() - 65
  1447. self.particles.add(LevelParticle(x, y, color=self.particle_effect))
  1448. if current_time - self.last_particle_update_time >= 10:
  1449. self.last_particle_update_time = current_time
  1450. new_particles = set()
  1451. for p in self.particles:
  1452. p.update()
  1453. if p.is_alive():
  1454. new_particles.add(p)
  1455. self.particles = new_particles
  1456. for p in self.particles:
  1457. p.draw(screen)
  1458. def update_obstacles_update_list(self):
  1459. self.obstacle_instances_need_to_update = False
  1460. self.obstacle_instances_update.clear()
  1461. for x in range(int(self.scroll_x_pos / G.GAME_SQUARE), int((self.scroll_x_pos + G.MAIN_AREA_X_POS) / G.GAME_SQUARE) + 1):
  1462. for y in range(int(self.scroll_y_pos / G.GAME_SQUARE), int((self.scroll_y_pos + G.MAIN_AREA_Y_POS) / G.GAME_SQUARE) + 1):
  1463. if (x, y) in self.obstacle_instances.keys():
  1464. an_obstacle = self.obstacle_instances[(x, y)]
  1465. self.obstacle_instances_update.append(an_obstacle)
  1466. def display_frame_rate(self, current_time, screen):
  1467. self.frames_num += 1
  1468. current_time_div_1000 = current_time // 1000
  1469. if current_time_div_1000 > self.times_num:
  1470. self.times_num = current_time_div_1000
  1471. G.TIME = self.times_num
  1472. self.map_time = self.times_num - G.LASTMAPTIME
  1473. self.level_time = self.times_num - G.LAST_LEVEL_TIME
  1474. if G.DISPLAY_FRAME_RATE:
  1475. if G.SHOW_STAT:
  1476. # img = self.frame_rate_text_font.render("{:04d}, 游戏时长 - {:03d}:{:02d}, 关卡:{:02d}/{:02d}, 杀敌:{:03d}/{:03d}, v={:}".format(self.frames_num, self.map_time//60, self.map_time%60, G.CURRENT_LEVEL, G.TOTAL_LEVEL, G.KILLED_NPC, G.TOTAL_NPC, self.me.speed), False, (255, 255, 255), (0, 0, 0))
  1477. img = self.frame_rate_text_font.render("{:04d}, 游戏时长 - {:03d}:{:02d}, 关卡:{:02d}/{:02d}, 杀敌:{:03d}/{:03d}".format(self.frames_num, self.map_time//60, self.map_time%60, G.CURRENT_LEVEL, G.TOTAL_LEVEL, G.KILLED_NPC, G.TOTAL_NPC), False, (255, 255, 255), (0, 0, 0))
  1478. else:
  1479. img = self.frame_rate_text_font.render("{:04d}, 游戏时长 - {:03d}:{:02d}".format(self.frames_num, self.map_time//60, self.map_time%60), False, (255, 255, 255), (0, 0, 0))
  1480. screen.blit(img, (100, 0))
  1481. self.frames_num = 0
  1482. def pass_map(self):
  1483. # 尝试置finish_flag为True
  1484. if self.district_all_finished and self.finish_at is not None:
  1485. if self.me.x == self.finish_at[0] and self.me.y == self.finish_at[1]:
  1486. self.finish_flag = True
  1487. G.LAST_LEVEL_TIME = self.times_num
  1488. G.CUMULATION_INJURE += (self.me.blood - self.me.remain_blood)
  1489. if self.is_transport:
  1490. resouce_next = 0
  1491. injured = 0
  1492. for o in self.transport_obstacle:
  1493. if o.transport_remain > 0 and o.in_safe_zone:
  1494. injured += o.transport_amount - o.transport_remain
  1495. resouce_next += 1
  1496. G.RESOUCE_NUM = resouce_next
  1497. if G.CURRENT_LEVEL == 1:
  1498. G.TOTAL_TRANSPORT = resouce_next
  1499. G.CUMULATION_RESOURCE_LEAK = injured
  1500. # 传送门,参数格式: {"[x1,y1]":{"type": "level", "target": [x2,y2]}, "[x3,y3]":{"type": "map", "target": 3}, "[x4,y4]":{"type": "map_set", "target": "Mo1"}}
  1501. def portal_map(self):
  1502. if len(self.portal_set) != 0:
  1503. for point in self.portal_set:
  1504. if self.me.x == point[0][0] and self.me.y == point[0][1]:
  1505. port_type, target = point[1], point[2]
  1506. sound_player.play("X08_01")
  1507. # 地图内闪现
  1508. if port_type == "level":
  1509. self.me.set_xy(target[0], target[1])
  1510. self.scroll_map()
  1511. # 跳到当前第几关
  1512. elif port_type == "map":
  1513. target = max(1, int(target))
  1514. G.CURRENT_LEVEL = target - 1
  1515. self.game.map_set_at = target - 2
  1516. self.finish_flag = True
  1517. G.LAST_LEVEL_TIME = self.times_num
  1518. # 在后面插入一关
  1519. elif port_type == "insert":
  1520. map_name = target
  1521. hero_name = self.game.cfg_json["your_hero"]
  1522. character_color = self.game.cfg_json["your_character_color"]
  1523. self.game.set_level(self.your_name, map_name, hero_name, character_color, is_reset=False)
  1524. G.LAST_LEVEL_TIME = self.times_num
  1525. G.CURRENT_LEVEL -= 1
  1526. else:
  1527. self.game.reset(target) # 换大地图
  1528. def scroll_map(self):
  1529. # 滚动地图
  1530. MAX_DIST = 20 # 单次最大滚动距离
  1531. scroll_x_old = self.scroll_x_pos
  1532. scroll_y_old = self.scroll_y_pos
  1533. if self.me.x_pos > self.scroll_x_pos + G.R_SCROLL:
  1534. # 向右滚动
  1535. self.scroll_x_pos = max(0, min(self.me.x_pos - G.R_SCROLL, self.scroll_x_pos_max))
  1536. elif self.me.x_pos < self.scroll_x_pos + G.L_SCROLL:
  1537. # 向左滚动
  1538. self.scroll_x_pos = max(0, min(self.me.x_pos - G.L_SCROLL, self.scroll_x_pos_max))
  1539. if self.me.y_pos > self.scroll_y_pos + G.D_SCROLL:
  1540. # 向下滚动
  1541. self.scroll_y_pos = max(0, min(self.me.y_pos - G.D_SCROLL, self.scroll_y_pos_max))
  1542. elif self.me.y_pos < self.scroll_y_pos + G.U_SCROLL:
  1543. # 向上滚动
  1544. self.scroll_y_pos = max(0, min(self.me.y_pos - G.U_SCROLL, self.scroll_y_pos_max))
  1545. if self.current_time - self.map_init_time > 3000:
  1546. # 限制滚动速度
  1547. if self.scroll_x_pos - scroll_x_old > MAX_DIST:
  1548. self.scroll_x_pos = scroll_x_old + MAX_DIST
  1549. self.obstacle_instances_need_to_update = True
  1550. if self.scroll_x_pos - scroll_x_old < -MAX_DIST:
  1551. self.scroll_x_pos = scroll_x_old - MAX_DIST
  1552. self.obstacle_instances_need_to_update = True
  1553. if self.scroll_y_pos - scroll_y_old > MAX_DIST:
  1554. self.scroll_y_pos = scroll_y_old + MAX_DIST
  1555. self.obstacle_instances_need_to_update = True
  1556. if self.scroll_y_pos - scroll_y_old < -MAX_DIST:
  1557. self.scroll_y_pos = scroll_y_old - MAX_DIST
  1558. self.obstacle_instances_need_to_update = True
  1559. # 限制滚动范围
  1560. if self.scroll_x_pos > self.scroll_x_pos_max:
  1561. self.scroll_x_pos = self.scroll_x_pos_max
  1562. if self.scroll_y_pos > self.scroll_y_pos_max:
  1563. self.scroll_y_pos = self.scroll_y_pos_max
  1564. '''
  1565. def scroll_map(self):
  1566. # 滚动地图
  1567. if self.me.x_pos > self.scroll_x_pos + G.R_SCROLL:
  1568. # 向右滚动
  1569. self.scroll_x_pos = max(0, min(self.me.x_pos - G.R_SCROLL, self.scroll_x_pos_max))
  1570. elif self.me.x_pos < self.scroll_x_pos + G.L_SCROLL:
  1571. # 向左滚动
  1572. self.scroll_x_pos = max(0, min(self.me.x_pos - G.L_SCROLL, self.scroll_x_pos_max))
  1573. if self.me.y_pos > self.scroll_y_pos + G.D_SCROLL:
  1574. # 向下滚动
  1575. self.scroll_y_pos = max(0, min(self.me.y_pos - G.D_SCROLL, self.scroll_y_pos_max))
  1576. elif self.me.y_pos < self.scroll_y_pos + G.U_SCROLL:
  1577. # 向上滚动
  1578. self.scroll_y_pos = max(0, min(self.me.y_pos - G.U_SCROLL, self.scroll_y_pos_max))
  1579. '''
  1580. def alarm_district(self):
  1581. # 显示当前区域的警戒
  1582. if self.district_alarming:
  1583. return
  1584. DistrictAlarm(self.effects_behind)
  1585. def get_bomb_instance(self, x, y):
  1586. # 获取(x, y)处的所有糖泡list
  1587. bs = list()
  1588. for b in self.bomb_instances:
  1589. if b.x == x and b.y == y and not b.throwing:
  1590. bs.append(b)
  1591. return bs
  1592. def get_an_npc(self, name, point):
  1593. return Npc(name, point)