level.py 86 KB

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