level.py 82 KB

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