| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776 |
- import os
- import pygame
- import random
- import ast
- import json
- import math
- import time
- from json import JSONDecodeError
- import numpy as np
- from collections import defaultdict
- from client_local.const import game as G
- from client_local.frame import floor
- from client_local.frame import obstacle
- from client_local.music import music_loader
- from client_local.sound import sound_player
- from client_local.sprite import obstacle_instance as oi
- from client_local.sprite.flame_instance import FlameState as FS
- from client_local.sprite.hero import Hero
- from client_local.sprite.pet import Pet
- from client_local.sprite.item_instance import ItemState as IS
- from client_local.sprite.bomb_instance import BombInstance
- from client_local.effect.effect_instance import ReadyGo, DistrictAlarm, EnvironmentEffect, EffectState, IntroChatPlayer, EndingSequencePlayer
- from client_local.sprite.npc import Npc
- from client_local.ui.game.blood_bar import BloodBar, MapBloodBar, MapResouceBar, ResourceBloodBar
- from client_local.ui.game.dlg_pveFunc import DlgPveFunc
- from client_local.ui.game.game_top import GameTop
- from client_local.ui.game.misc_510 import Misc510
- from client_local.ui.game.player_icon import PlayerIcon, ResourceIcon
- from client_local.ui.game.score_board import ScoreBoard, Timer
- from client_local.ui.game.status_bar import StatusBar
- from client_local.ui.game.message_input import InputEntry, InputLevel
- from client_local.file_loader.fileLoader import load_json, load_png
- from client_local.skill.skill import WinEffect, TransportSuccessEffect
- from client_local.skill.level_skill import LevelSkillWithInterval, DebuffPoisonGrid, LevelParticle
- from client_local.utils.json_saver import AsyncJsonSaver
- from datetime import datetime
- current_level = None
- level_font = None
- Y_SCALE_FACTOR = 1 # 用于地震效果,画面会按比例以中间为基准进行上下偏移实现压缩效果
- max_alpha = 255 # 最大透明度
- circleMasks = {}
- MASK_STEP = 20
- lightBoltMasks = {}
- for i in range(1, 10):
- # 在蒙版上画出三个指定坐标及其周围100像素范围的圆形(透明度衰减)
- circle_radius = i*MASK_STEP
- circleMask = pygame.Surface((circle_radius*2, circle_radius*2), pygame.SRCALPHA)
- circleMask.fill((0, 0, 0, 0))
- for r in range(circle_radius):
- R = circle_radius-r
- alpha = max_alpha - int((max_alpha / circle_radius) * R)
- pygame.draw.circle(circleMask, (alpha, alpha, alpha, alpha), (circle_radius, circle_radius), R)
- circleMasks[i] = circleMask
- def init_level_fonts():
- global level_font
- level_font = pygame.font.Font("res/font/simsun.ttc", 16)
- def get_player_coordinates():
- players = current_level.game.players
- coords = []
- for player in players:
- coords.append((player.x_pos,player.y_pos))
- return coords
- def get_light_npc_coordinates():
- coords = []
- for npc in current_level.npcs:
- coords.append((npc.x_pos, npc.y_pos))
- return coords
- _last_light_states = None
- _last_colour_light_states = None
- # def get_player_mask(mask_surface, bgl):
- # """
- # 只在光源状态变化时才重绘遮罩;否则直接返回上次绘制结果。
- # """
- # global _last_light_states
- # # 收集当前所有光源状态 (x, y, light)
- # curr = []
- # for p in [current_level.me] + current_level.npcs + list(current_level.obstacle_instances.values()):
- # if p.light:
- # curr.append((p.x_pos, p.y_pos, p.light))
- # curr_key = tuple(curr)
- # # 如果没变化,直接复用
- # if curr_key == _last_light_states:
- # return mask_surface
- # # 状态变化:重绘
- # _last_light_states = curr_key
- # bgl = max(0, min(bgl, 255))
- # fill = mask_surface.fill
- # blit = mask_surface.blit
- # masks = circleMasks
- # fill((bgl, bgl, bgl, 0))
- # for x, y, light in curr:
- # # 叠加亮度
- # cm = masks[light]
- # r = light * MASK_STEP
- # blit(cm, (x - r, y - r - 15),
- # special_flags=pygame.BLEND_RGBA_ADD)
- # return mask_surface
- def _render_light_mask(mask_surface, colour, lights, origin, previous_key):
- """只缓存、绘制会影响视口的光源;保留重复光源原有的叠加亮度。"""
- view_x, view_y = origin
- bounds = mask_surface.get_rect()
- visible = []
- for x, y, light in lights:
- cm = circleMasks[light]
- r = light * MASK_STEP
- pos = (int(x - view_x - r), int(y - view_y - r - 15))
- if bounds.colliderect(cm.get_rect(topleft=pos)):
- visible.append((pos, light))
- key = (id(current_level), id(mask_surface), mask_surface.get_size(), colour, tuple(visible))
- if key != previous_key:
- mask_surface.fill((*colour, 0))
- for pos, light in visible:
- mask_surface.blit(circleMasks[light], pos, special_flags=pygame.BLEND_RGBA_ADD)
- return key
- def get_player_mask(mask_surface, bgl, source_origin=(0, 0)):
- global _last_light_states
- # 收集当前所有光源状态 (x, y, light)
- curr = []
- for p in [current_level.me]:
- if p.light and (not p.is_hide_sight()):
- curr.append((p.x_pos, p.y_pos, p.light))
- for p in current_level.npcs:
- if p.light and (not p.is_hide_sight()):
- curr.append((p.x_pos, p.y_pos, p.light))
- for p in current_level.obstacle_instances.values():
- if p.light:
- curr.append((p.x_pos, p.y_pos, p.light))
- # 旧版先画到整图大小的局部遮罩,再由震屏移动遮罩;保持原来的取整顺序。
- local_lights = []
- view_rect = pygame.Rect(
- current_level.scroll_x_pos, current_level.scroll_y_pos,
- G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS
- )
- for x, y, light in curr:
- r = light * MASK_STEP
- if not view_rect.inflate(2 * r, 2 * (r + 15)).collidepoint(x, y):
- continue
- local_lights.append((
- int(x - current_level.scroll_x_pos - r) + r,
- int(y - current_level.scroll_y_pos - r - 15) + r + 15,
- light
- ))
- bgl = max(0, min(bgl, 255))
- _last_light_states = _render_light_mask(
- mask_surface, (bgl, bgl, bgl), local_lights, source_origin, _last_light_states
- )
- return mask_surface
- def special_colour_mask(mask_surface, rgb, origin):
- global _last_colour_light_states
- colour = tuple(min(max(rgb[i], 0), 255) for i in range(3))
- curr = []
- for player in [current_level.me] + current_level.npcs + list(current_level.obstacle_instances.values()):
- if player.light:
- # 原彩色遮罩先在世界坐标中 blit,再截取;保留浮点坐标的取整顺序。
- r = player.light * MASK_STEP
- curr.append((int(player.x_pos - r) + r, int(player.y_pos - r - 15) + r + 15, player.light))
- _last_colour_light_states = _render_light_mask(
- mask_surface, colour, curr, origin, _last_colour_light_states
- )
- return mask_surface
- def get_y(elem):
- return elem.get_y()
- def caesar_encrypt(text, k=3):
- encrypted_text = ""
- for char in text:
- if char.isalpha():
- # 处理字母
- if char.isupper():
- encrypted_char = chr((ord(char) - ord('A') + k) % 26 + ord('A'))
- else:
- encrypted_char = chr((ord(char) - ord('a') + k) % 26 + ord('a'))
- elif char.isdigit():
- # 处理数字
- encrypted_char = str((int(char) + k) % 10)
- else:
- # 其他字符保持不变
- encrypted_char = char
- encrypted_text += encrypted_char
- return encrypted_text
- class MainArea(pygame.Surface):
- def __init__(self, size, flags=0):
- super().__init__(size, flags)
- def blit(self, source, dest, area=None, special_flags=0):
- if Y_SCALE_FACTOR == 1:
- dest = (dest[0], int(dest[1]))
- else:
- relative_y = dest[1] - current_level.scroll_y_pos - G.MAIN_AREA_Y_POS//2
- scale_bias_value = relative_y * (1 - Y_SCALE_FACTOR)
- dest = (dest[0], int(dest[1] - scale_bias_value))
- return super().blit(source, dest, area, special_flags)
- class Level:
- def __init__(
- self, your_name: str, map_name: str, me: Hero, music_volume, accumulation_time, game=None,
- transport_map_total=0, transport_map_remain=0
- ):
- from client_local.control import Control
- self.game: Control = game
- global current_level
- current_level = self
- self.times_num = 0 # 秒计数器,每秒累加
- self.frames_num = 0 # 帧计数器,每秒清空
- self.frame_rate_text_font = level_font
- self.me = me
- self.pets = []
- self.your_name = your_name
- self.map_name = map_name
- self.map_json = None
- self.map_x = None # 关卡横向格子数
- self.map_y = None # 关卡纵向格子数
- self.map_x_pos = None # 关卡最大x坐标
- self.map_y_pos = None # 关卡最大y坐标
- self.map_grids = None # 关卡全部的点坐标集合
- self.scroll_x_pos = None # 卷轴滚动x像素
- self.scroll_y_pos = None # 卷轴滚动y像素
- self.scroll_x_pos_max = None # 卷轴最大滚动x像素
- self.scroll_y_pos_max = None # 卷轴最大滚动y像素
- self.map_title = None # 关卡中文名称
- self.map_time = 0 # 关卡总时长
- self.level_time = 0
- self.map_init_time = None # 关卡加载时刻
- self.map_remaining_time = None # 关卡剩余时间
- self.map_music = None # 关卡背景音乐
- self.map_ambience = None # 背景音效
- self.map_music_volume = music_volume # 关卡背景音乐音量大小
- self.finish_at = None # 地图过关点(x, y)
- G.TOTAL_TRANSPORT = 0
- self.transport_map_total = transport_map_total
- self.transport_map_remain = transport_map_remain
- self.transport_obstacle = []
- self.water_reflect_obstacles = []
- self._water_reflection_base_cache = {}
- self._water_reflection_distort_cache = {}
- self._water_reflection_image_cache = {}
- self._water_reflection_draw_cache = {}
- self._water_submerged_entity_cache = {}
- self._sun_reflection_cache = {}
- self._water_reflection_wave_frame = -1
- self._water_reflection_cache_limit = 512
- self.transport_resource_init_points = []
- self.earth_quake_direction = None
- self.earth_quake_init_tick = 0 # 地震初始化tick
- self.earth_quake_left_times = 0 # 地震剩余次数
- self.earth_quake_strength = 0 # 地震强度
- self.earth_quake_times = 0 # 地震次数
- self.earth_quake_decrease = True # 地震强度是否递减
- self.current_time = pygame.time.get_ticks()
- self.background_layers = [] # 地板下方的地图背景图层
- self.floor_image = None # 游戏主区域的地板背景
- self.flame_instances = None # FlameInstance对象列表
- self.item_instances = None # (x, y) --> ItemInstance对象
- self.obstacle_instances = None # (x, y) --> ObstacleInstance对象
- self.obstacle_instances_update = None # 屏幕范围内的ObstacleInstance对象列表
- self.obstacle_instances_need_to_update = True # 需要更新列表
- self.bomb_instances = None # BombInstance对象列表
- self.ui_instances_bot = None # 位于main_area下的UIInstance对象列表
- self.ui_instances_top = None # 位于main_area上的UIInstance对象列表
- self.block = None # 三维NumPy对象,阻挡玩家
- self.block_flame = None # 三维NumPy对象,阻挡糖跑
- self.slide_orientation = dict() # (x, y) --> (m, n) m网格传送带方向 0无 1右 2上 3左 4下 n速度
- self.grid_damage_blood = dict() # 网格伤害血量
- self.grid_damage_time = defaultdict(None) # 网格伤害时刻 只有糖泡爆炸时才会增加
- self.grid_damage_multiples = dict() # 伤害次数(倍数)
- # self.grid_damage_orientations = dict() # 网格伤害方向
- self.grid_damage_orientations = defaultdict(set)
- self.path_map = dict() # 缓存怪物追踪路径
- self.grid_damage_frame = False # 用于判断糖泡伤害瞬间与玩家位置是否重合 只有爆炸帧才是True
- self.accumulation_time = accumulation_time # 网格伤害延迟时间
- self.main_area = None # 游戏主区域
- self.main_area_offset = None # 游戏主区域相对左上角的偏移
- self.skill_instances = list() # 交予level托管的skill_instances,例如陷阱,不随npc死亡而消失
- self.effects_behind = list() # 关卡底层技能特效
- self.effects_front = list() # 关卡顶层技能特效
- self.effects_screen = list() # 屏幕级的技能特效 不随卷轴移动
- self.left_black = None # 屏幕右侧黑条
- self.grid_bomb_time_at = dict() # 糖泡伤害时刻
- self.level_variables = dict()
- self.blood_bar = None
- self.status_bar = None
- self.score_board = None
- self.time_board = None
- self.npcs = list() # 存活npc列表
- self.ghosts = list() # 存活僵尸列表
- self.wanderers = list()
- self.teammates = list()
- self.recal_npc_paths = True # 重新计算Npc路径的标志位 仅当玩家进入区域、糖泡施放与爆炸、玩家网格位置发生变化、障碍被摧毁时置为True
- self.recal_ghost_paths = True # 重新计算Ghost路径的标志位 仅当玩家移动
- self.display_name_card = False # 显示npc姓名牌
- self.display_npc_blood = False # 显示npc姓名牌
- self.district_idx = 0 # 当前区域 从1开始
- self.district_square = None # 当前区域 左上右下点像素坐标
- self.district_square_grid = None # 当前区域 左上右下点坐标
- self.district_alarming = False # 当前正在显示警戒
- self.district_all_finished = False # 已完成全部区域的标志
- self.finish_flag = False # 当前map结束的标志位
- self.district_json = None
- self.read_district_json = False
- self.custom_finish_flag = False
- self.custom_next_map = None
- self.portal = dict()
- self.portal_set = []
- self.has_achievemeny_check = False
- self.intro_chat_active = False
- self.intro_chat_started = False
- self.intro_chat_player = None
- self.ending_sequence_active = False
- self.pending_ending_sequence = None
- self.ending_sequence_scheduled = False
- self.ending_sequence_started = False
- self.ending_sequence_start_time = 0
- self.ending_sequence_player = None
- self._static_sorted = [] # [(y, tie, obj), ...] 已排序
- self._static_dirty = True # 静态层是否需要重排
- self._cached_item_count = -1 # 用于检测 item dict 变化(低配版)
- self.is_transport = False # 是否为运输模式
- self.map_blood_bar = None # 地图血条
- self.resource_bar = None # 资源受损条
- self.transport_buff_num = 0 # 资源buff
- self.transport_destination = None
- self.special_music_volume = 1 # 若需放大音乐
- self.load_map_json() # 加载地图
- self.load_ui() # 加载ui界面
- self.load_background_png() # 加载地板下方背景
- self.load_floor() # 加载地板
- self.load_obstacle() # 加载障碍
- self.load_music() # 加载音乐
- if self.is_transport:
- self.resource_bar.set_max_blood(G.TOTAL_TRANSPORT)
- # 遮罩只覆盖视口;彩色/黑暗模式使用独立缓存,避免同时开启时互相污染。
- self.mask_surface = pygame.Surface((G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS), pygame.SRCALPHA).convert_alpha()
- self.colour_mask_surface = pygame.Surface((G.MAIN_AREA_X_POS + 1, G.MAIN_AREA_Y_POS), pygame.SRCALPHA).convert_alpha()
- self.haunt_Mode = False
- self.bg_light = 0
- self.sunny = False
- self.underwater = False
- self.rgb_light = [0, 0, 0]
- self.special_rgb = False
- self.boss_blood_bar_dic = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0} # boss血条显示
- self.dark_trap = set() # debuff毒陷阱集合
- self.small_dark_trap = set() # debuff毒陷阱集合
- self.poison_dic = dict() # 改良版毒陷阱字典
- self.async_json_saver = AsyncJsonSaver()
- ReadyGo(self.effects_screen)
- self.map_json = load_json(f"game/map/{self.map_name}.json")
- G.ENVIRONMENT_EFFECT = self.map_json["basic"].get("environment_effect", [])
- if len(G.ENVIRONMENT_EFFECT) > 0:
- for en in G.ENVIRONMENT_EFFECT:
- EnvironmentEffect(self.effects_screen, en)
- self.haunt_Mode = self.map_json["basic"].get("haunted", False)
- self.bg_light = self.map_json["basic"].get("bg_light", 0)
- global _last_light_states, _last_colour_light_states
- _last_light_states = None
- _last_colour_light_states = None
- self.mask_surface.fill((self.bg_light, self.bg_light, self.bg_light, 0))
- self.sunny = bool(self.map_json["basic"].get("sunny", False))
- self.underwater = self.map_json["basic"].get("underwater", False)
- G.UNDERWATER = self.underwater
- G.WATER_DAMPING = self.map_json["basic"].get("water_damping", 200)
- self.buff_hero = self.map_json["basic"].get("buff_hero", {})
- if self.buff_hero != {}:
- if self.me.hero_name in self.buff_hero.keys():
- buff_info = self.buff_hero[self.me.hero_name]
- self.me.blood += int(buff_info.get("blood", 0))
- self.me.remain_blood += int(buff_info.get("blood", 0))
- self.blood_bar.set_max_blood(self.me.blood)
- G.CUMULATION_HERO_BLOOD += int(buff_info.get("blood", 0))
- self.me.standard_defense += int(buff_info.get("defense", 0))
- self.me.defense += int(buff_info.get("defense", 0))
- self.me.standard_damage += int(buff_info.get("damage", 0))
- self.me.damage += int(buff_info.get("damage", 0))
- txt = buff_info.get("text", "")
- if txt != "":
- self.message_entry.new_message(sender="??", message=txt, colour=[255, 255, 255])
- if "teammate" in self.map_json["basic"].keys():
- from client_local.sprite.teammate import Teammate
- for mate in self.map_json["basic"].get("teammate", []):
- a_mate = Teammate(mate["name"], (self.me.x, self.me.y), guard_pos=tuple(mate.get("guard_pos", (0, 0))))
- self.teammates.append(a_mate)
- if "rgb_light" in self.map_json["basic"].keys():
- self.rgb_light = self.map_json["basic"]["rgb_light"]
- self.special_rgb = True
- self.particle_effect = self.map_json["basic"].get("particles", None)
- self.particles = set()
- self.last_particle_time = 0
- self.last_particle_update_time = 0
- if G.PET is not None:
- self.pets.append(Pet(G.PET, (self.me.x, self.me.y), owner=self.me, num=1))
- if "level_skill" in self.map_json["basic"].keys():
- for skills in self.map_json["basic"]["level_skill"]:
- skill_name = skills.get("skill_name", "")
- param = skills.get("param", dict())
- params = {"skill_name": skill_name, "param": param}
- params["init"] = skills.get("init", 0)
- params["interval"] = skills.get("interval", 100000)
- LevelSkillWithInterval(self.me, self.me, params, self.skill_instances)
- # 紫色毒陷阱判断
- DebuffPoisonGrid(self.me, self.npcs, self.skill_instances)
- def set_level_variables(self, name, value):
- self.level_variables[name] = value
- def get_level_variables(self, name, default_value):
- return self.level_variables.get(name, default_value)
- def load_map_json(self):
- # 加载关卡json文件
- map_json = load_json("game/map/" + self.map_name + ".json")
- self.map_json = map_json
- if not self.read_district_json:
- self.read_district_json = True
- self.district_json = self.map_json["districts"]
- self.me.set_xy(map_json["basic"]["begin"][0], map_json["basic"]["begin"][1])
- if len(self.pets) > 0:
- for pet in self.pets:
- pet.set_xy(map_json["basic"]["begin"][0], map_json["basic"]["begin"][1])
- # 地图大小-像素
- self.map_x = int(map_json["basic"]["width"])
- self.map_y = int(map_json["basic"]["height"])
- G.CURRENT_MAP_HEIGHT = int(map_json["basic"]["height"])
- G.CURRENT_MAP_WIDTH = int(map_json["basic"]["width"])
- self.map_x_pos = self.map_x * G.GAME_SQUARE - 1
- self.map_y_pos = self.map_y * G.GAME_SQUARE - 1
- self.map_grids = set()
- for x in range(self.map_x):
- for y in range(self.map_y):
- self.map_grids.add((x, y))
- self.scroll_x_pos = map_json["basic"]["scroll"][0] * G.GAME_SQUARE
- self.scroll_y_pos = map_json["basic"]["scroll"][1] * G.GAME_SQUARE
- self.scroll_x_pos_max = max(0, self.map_x_pos - G.MAIN_AREA_X * G.GAME_SQUARE)
- self.scroll_y_pos_max = max(0, self.map_y_pos - G.MAIN_AREA_Y * G.GAME_SQUARE)
- self.map_init_time = pygame.time.get_ticks()
- self.map_music = map_json["basic"]["music"]
- self.flame_instances = list()
- self.item_instances = dict()
- self.obstacle_instances = dict()
- self.obstacle_instances_update = list()
- self.bomb_instances = list()
- self._bomb_position_index = {}
- self._bomb_index_dirty = True
- self.ui_instances_bot = list()
- self.ui_instances_top = list()
- self.block = np.zeros((2, self.map_x + 1, self.map_y + 1), dtype=np.int64)
- self.block_flame = np.zeros((2, self.map_x + 1, self.map_y + 1), dtype=np.int64)
- # 生成网格伤害二元组映射
- for x in range(self.map_x):
- for y in range(self.map_y):
- self.grid_damage_blood[(x, y)] = 0
- self.grid_damage_time[(x, y)] = 0
- self.grid_damage_multiples[(x, y)] = 0
- # self.grid_damage_orientations[(x, y)] = set()
- self.grid_bomb_time_at[(x, y)] = 0
- self.district_square_grid = {"x1": 0, "x2": 0, "y1": 0, "y2": 0}
- self.district_square = {"x1": 0, "x2": 0, "y1": 0, "y2": 0}
- if "finish" in self.map_json["basic"].keys():
- self.finish_at = (self.map_json["basic"]["finish"][0], self.map_json["basic"]["finish"][1])
- self.main_area = MainArea((self.map_x_pos, self.map_y_pos)).convert()
- self.left_black = pygame.Surface((1, 600))
- if "haunted" in self.map_json["basic"].keys():
- self.haunt_Mode = self.map_json["basic"]['haunted']
- if "bg_light" in self.map_json["basic"].keys():
- self.bg_light = self.map_json["basic"]["bg_light"]
- self.is_transport = self.map_json["basic"].get("is_transport", False)
- if self.is_transport:
- self.transport_resource_init_points = self.map_json["basic"].get("transport_resource_init", [])
- self.transport_destination = self.map_json["basic"].get("transport_destination", None)
- self.map_blood_bar = MapResouceBar(
- self.transport_map_total,
- self.transport_map_remain
- )
- self.ui_instances_top.append(self.map_blood_bar)
- self.resource_bar = ResourceBloodBar(self.me)
- self.ui_instances_top.append(self.resource_bar)
- self.ui_instances_top.append(ResourceIcon())
- if "underwater" in self.map_json["basic"].keys():
- self.underwater = self.map_json["basic"]["underwater"]
- G.UNDERWATER = self.underwater
- else:
- G.UNDERWATER = False
- if "water_damping" in self.map_json["basic"].keys():
- G.WATER_DAMPING = self.map_json["basic"]["water_damping"]
- else:
- G.WATER_DAMPING = 200
- if "rgb_light" in self.map_json["basic"].keys():
- self.rgb_light = self.map_json["basic"]["rgb_light"]
- self.special_rgb = True
- if "ambience" in self.map_json["basic"].keys():
- self.map_ambience = self.map_json["basic"]["ambience"]
- else:
- self.map_ambience = None
- self.special_music_volume = max(
- 0.0, float(self.map_json["basic"].get("music_volume", 1))
- )
- if "portal" in self.map_json["basic"].keys():
- self.portal = self.map_json["basic"]["portal"]
- for key in self.portal.keys():
- self.portal_set.append([ast.literal_eval(key), self.portal[key]["type"], self.portal[key]["target"]])
- else:
- self.portal = {}
- self.portal_set = []
- G.CURRENT_LEVEL += 1
- G.KILLED_NPC = 0
- G.MAP_NAME = self.map_name
- G.HAS_RECORD = False
- G.TOTAL_NPC = 0
- for dis in self.map_json["districts"]:
- G.TOTAL_NPC += len(dis["npcs"])
- 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:
- G.CHEAT = False
- else:
- G.CHEAT = True
- def try_start_intro_chat(self):
- if self.intro_chat_started:
- return
- basic = self.map_json.get("basic", {})
- intro_chat = basic.get("intro_chat", [])
- if not intro_chat:
- return
- if self.map_name in G.INTRO_CHAT_READ_MAPS:
- return
- self.intro_chat_started = True
- self.intro_chat_player = IntroChatPlayer(self.effects_screen, self.map_name, intro_chat)
- def advance_intro_chat(self):
- if self.intro_chat_player is not None:
- self.intro_chat_player.advance()
- def schedule_ending_sequence(self):
- if self.pending_ending_sequence is None or self.ending_sequence_scheduled:
- return
- self.ending_sequence_scheduled = True
- self.ending_sequence_start_time = pygame.time.get_ticks() + 9000
- def start_ending_sequence_if_needed(self):
- if not self.ending_sequence_scheduled or self.ending_sequence_started:
- return
- if self.current_time < self.ending_sequence_start_time:
- return
- self.ending_sequence_started = True
- self.ending_sequence_active = True
- self.ending_sequence_player = EndingSequencePlayer(self.effects_screen, self.pending_ending_sequence)
- def advance_ending_sequence(self):
- if self.ending_sequence_player is not None:
- self.ending_sequence_player.advance()
- def load_ui(self):
- self.ui_instances_bot.append(GameTop())
- self.status_bar = StatusBar()
- self.status_bar.set_prop_imgs(self.me)
- if self.map_x < 16:
- self.score_board = ScoreBoard()
- self.score_board.set_time(300)
- self.ui_instances_bot.append(self.score_board)
- else:
- self.ui_instances_top.append(DlgPveFunc())
- if G.SHOW_TIME:
- self.time_board = Timer()
- self.time_board.set_time(300)
- self.ui_instances_top.append(self.time_board)
- self.ui_instances_top.append(self.status_bar)
- self.ui_instances_top.append(Misc510())
- self.ui_instances_top.append(PlayerIcon(self.me.icon_img))
- if not G.SHOW_INPUT:
- G.SHOW_INPUT = True
- self.message_entry = InputEntry() # 聊天输入框
- else:
- self.message_entry = InputLevel() # 聊天输入框
- self.ui_instances_top.append(self.message_entry)
- self.blood_bar = BloodBar(self.me)
- self.blood_bar.set_name(self.your_name)
- self.ui_instances_top.append(self.blood_bar)
- def draw_water_reflections(self, surface):
- if not self.water_reflect_obstacles:
- return
- view_rect = pygame.Rect(self.scroll_x_pos, self.scroll_y_pos, G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS)
- for water in list(self.water_reflect_obstacles):
- self.draw_water_reflection_for_obstacle(surface, water, view_rect)
- def draw_water_reflection_for_obstacle(self, surface, water, view_rect=None):
- if view_rect is None:
- view_rect = pygame.Rect(self.scroll_x_pos, self.scroll_y_pos, G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS)
- if getattr(water, "state", None) == oi.ObstacleState.DEAD:
- return
- wave_frame = self.get_water_wave_frame()
- for tile_rect, reflection in self.get_water_reflection_entries(water, wave_frame):
- if tile_rect.colliderect(view_rect):
- surface.blit(reflection, tile_rect.topleft)
- self.draw_sun_reflections_for_obstacle(surface, water, view_rect, wave_frame)
- def get_water_wave_frame(self):
- wave_frame = self.current_time // 160
- if wave_frame != self._water_reflection_wave_frame:
- self._water_reflection_wave_frame = wave_frame
- self._water_reflection_distort_cache.clear()
- self._water_reflection_draw_cache.clear()
- return wave_frame
- def get_water_reflection_entries(self, water, wave_frame):
- cache_key = (id(water), water.x, water.y, wave_frame)
- cached = self._water_reflection_draw_cache.get(cache_key)
- if cached is not None:
- return cached
- entries = []
- width = water.obstacle.get("WIDTH", 1)
- height = water.obstacle.get("HEIGHT", 1)
- for dx in range(width):
- for dy in range(height):
- cell_x = water.x + dx
- cell_y = water.y + dy
- tile_rect = pygame.Rect(
- cell_x * G.GAME_SQUARE,
- cell_y * G.GAME_SQUARE,
- G.GAME_SQUARE,
- G.GAME_SQUARE
- )
- reflection = self.build_water_reflection(cell_x, cell_y, tile_rect, wave_frame)
- if reflection is not None:
- entries.append((tile_rect, reflection))
- if len(self._water_reflection_draw_cache) > self._water_reflection_cache_limit:
- self._water_reflection_draw_cache.clear()
- self._water_reflection_draw_cache[cache_key] = entries
- return entries
- def build_water_reflection(self, cell_x, cell_y, tile_rect, wave_frame):
- if cell_y <= 0:
- return None
- seen = set()
- candidates = []
- signature = []
- for x in range(max(0, cell_x - 4), min(self.map_x, cell_x + 5)):
- for source_y in (cell_y - 1, cell_y - 2):
- if source_y < 0:
- continue
- obstacle_ref = self.obstacle_instances.get((x, source_y))
- if obstacle_ref is None or getattr(obstacle_ref, "water_reflect", False):
- continue
- oid = id(obstacle_ref)
- if oid in seen:
- continue
- image = getattr(obstacle_ref, "image", None)
- rect = getattr(obstacle_ref, "rect", None)
- if image is None or rect is None or image.get_width() <= 1 or image.get_height() <= 1:
- continue
- water_origin_y = obstacle_ref.y + obstacle_ref.obstacle.get("HEIGHT", 1)
- segment_idx = cell_y - water_origin_y
- if segment_idx < 0 or segment_idx > 1:
- continue
- if segment_idx == 1 and not self.is_water_reflect_cell(cell_x, cell_y - 1):
- continue
- reflected_image = self.get_water_reflection_image(image)
- segment_y = 0 if segment_idx == 0 else G.GAME_SQUARE
- if segment_y >= reflected_image.get_height():
- continue
- image_rect = pygame.Rect(rect.x, rect.y, reflected_image.get_width(), reflected_image.get_height())
- overlap_left = max(image_rect.left, tile_rect.left)
- overlap_right = min(image_rect.right, tile_rect.right)
- if overlap_left >= overlap_right:
- continue
- seen.add(oid)
- candidates.append((obstacle_ref, reflected_image, image_rect, overlap_left, overlap_right, segment_y, segment_idx))
- signature.append((oid, id(image), image_rect.x, image_rect.width, image_rect.height, segment_idx))
- if not candidates:
- return None
- signature = tuple(signature)
- base_key = (cell_x, cell_y, signature)
- tile = self._water_reflection_base_cache.get(base_key)
- if tile is None:
- tile = pygame.Surface((G.GAME_SQUARE, G.GAME_SQUARE), pygame.SRCALPHA, 32)
- for _, image, image_rect, overlap_left, overlap_right, segment_y, segment_idx in candidates:
- self.blit_obstacle_reflection(tile, image, image_rect, overlap_left, overlap_right, tile_rect, segment_y, segment_idx)
- if len(self._water_reflection_base_cache) > self._water_reflection_cache_limit:
- self._water_reflection_base_cache.clear()
- self._water_reflection_base_cache[base_key] = tile
- distorted_key = (base_key, wave_frame)
- distorted = self._water_reflection_distort_cache.get(distorted_key)
- if distorted is None:
- distorted = self.distort_water_reflection(tile, wave_frame)
- self._water_reflection_distort_cache[distorted_key] = distorted
- return distorted
- def draw_sun_reflections_for_obstacle(self, surface, water, view_rect, wave_frame):
- if not self.sunny:
- return
- width = water.obstacle.get("WIDTH", 1)
- height = water.obstacle.get("HEIGHT", 1)
- for dx in range(width):
- for dy in range(height):
- cell_x = water.x + dx
- cell_y = water.y + dy
- tile_rect = pygame.Rect(
- cell_x * G.GAME_SQUARE,
- cell_y * G.GAME_SQUARE,
- G.GAME_SQUARE,
- G.GAME_SQUARE
- )
- if not tile_rect.colliderect(view_rect):
- continue
- sun_reflection = self.get_sun_reflection_for_water_cell(cell_x, cell_y, tile_rect, wave_frame)
- if sun_reflection is not None:
- surface.blit(sun_reflection, tile_rect.topleft)
- def get_sun_reflection_for_water_cell(self, cell_x, cell_y, tile_rect, wave_frame):
- if not self.sunny:
- return None
- center_x = self.scroll_x_pos + G.MAIN_AREA_X_POS // 2
- center_y = self.scroll_y_pos + G.MAIN_AREA_Y_POS // 2
- sun_w = 68
- sun_h = 34
- sun_rect = pygame.Rect(center_x - sun_w // 2, center_y - sun_h // 2, sun_w, sun_h)
- overlap = sun_rect.clip(tile_rect)
- if overlap.width <= 0 or overlap.height <= 0:
- return None
- key = (overlap.x - sun_rect.x, overlap.y - sun_rect.y, overlap.width, overlap.height)
- cached = self._sun_reflection_cache.get(key)
- if cached is None:
- full_sun = pygame.Surface((sun_w, sun_h), pygame.SRCALPHA, 32)
- pygame.draw.ellipse(full_sun, (255, 244, 202, 210), (0, 0, sun_w, sun_h))
- sun_piece = full_sun.subsurface(pygame.Rect(key)).copy()
- sun = pygame.Surface((G.GAME_SQUARE, G.GAME_SQUARE), pygame.SRCALPHA, 32)
- sun.blit(sun_piece, (overlap.x - tile_rect.x, overlap.y - tile_rect.y))
- if len(self._sun_reflection_cache) > 64:
- self._sun_reflection_cache.clear()
- self._sun_reflection_cache[key] = sun
- cached = sun
- distorted_key = ("sun", key, wave_frame)
- distorted = self._water_reflection_distort_cache.get(distorted_key)
- if distorted is None:
- distorted = self.distort_water_reflection(cached, wave_frame)
- self._water_reflection_distort_cache[distorted_key] = distorted
- return distorted
- def is_water_reflect_cell(self, cell_x, cell_y):
- obstacle_ref = self.obstacle_instances.get((cell_x, cell_y))
- return obstacle_ref is not None and getattr(obstacle_ref, "water_reflect", False)
- def get_render_view_rect(self):
- # 最终画面从 scroll_x_pos - 1 截取,保留这一列及原光照视口的右边界。
- return pygame.Rect(
- self.scroll_x_pos - 1, self.scroll_y_pos,
- G.MAIN_AREA_X_POS + 1, G.MAIN_AREA_Y_POS
- ).clip(self.main_area.get_rect())
- def apply_light_masks(self):
- quake_y = int((self.scroll_y_pos + G.MAIN_AREA_Y_POS // 2) * (1 - Y_SCALE_FACTOR))
- if self.special_rgb:
- # 旧版整图遮罩在 MainArea.blit 中也受震屏偏移影响。
- # 反推可见的源区域,再以原生 blit 合成,避免重复施加偏移。
- source_rect = self.get_render_view_rect().move(0, -quake_y).clip(self.main_area.get_rect())
- if source_rect.w and source_rect.h:
- special_colour_mask(self.colour_mask_surface, self.rgb_light, source_rect.topleft)
- pygame.Surface.blit(
- self.main_area, self.colour_mask_surface,
- (source_rect.x, source_rect.y + quake_y),
- (0, 0, source_rect.w, source_rect.h),
- special_flags=pygame.BLEND_RGBA_MULT
- )
- if self.haunt_Mode:
- view_rect = pygame.Rect(
- self.scroll_x_pos, self.scroll_y_pos,
- G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS
- ).clip(self.main_area.get_rect())
- # subsurface 仍是 MainArea,旧版局部遮罩 blit 也带有 quake_y 偏移。
- source_rect = pygame.Rect(0, -quake_y, view_rect.w, view_rect.h).clip(self.main_area.get_rect())
- if source_rect.w and source_rect.h:
- get_player_mask(self.mask_surface, self.bg_light, source_rect.topleft)
- pygame.Surface.blit(
- self.main_area, self.mask_surface,
- (view_rect.x + source_rect.x, view_rect.y + source_rect.y + quake_y),
- (0, 0, source_rect.w, source_rect.h),
- special_flags=pygame.BLEND_RGBA_MULT
- )
- def draw_dynamic_object(self, obj):
- if not self.should_draw_water_submerged(obj):
- obj.draw(self.main_area)
- return
- old_flag = getattr(obj, "_water_submerged_draw", False)
- obj._water_submerged_draw = True
- try:
- obj.draw(self.main_area)
- finally:
- obj._water_submerged_draw = old_flag
- def should_draw_water_submerged(self, obj):
- if obj is not self.me and not isinstance(obj, Npc):
- return False
- if not hasattr(obj, "image") or obj.image is None:
- return False
- return self.is_water_reflect_cell(obj.x, obj.y)
- def get_water_submerged_entity_image(self, image):
- key = (id(image), image.get_width(), image.get_height())
- cached = self._water_submerged_entity_cache.get(key)
- if cached is not None:
- return cached
- w, h = image.get_size()
- if w <= 1 or h <= 1:
- return image
- bottom_h = min(20, h)
- result = image.copy().convert_alpha()
- bottom_rect = pygame.Rect(0, h - bottom_h, w, bottom_h)
- strip = image.subsurface(bottom_rect).copy()
- small = pygame.transform.smoothscale(strip, (max(1, w // 2), max(1, bottom_h // 2)))
- strip = pygame.transform.smoothscale(small, (w, bottom_h)).convert_alpha()
- strip.set_alpha(95)
- result.fill((0, 0, 0, 0), bottom_rect)
- result.blit(strip, bottom_rect.topleft)
- if len(self._water_submerged_entity_cache) > self._water_reflection_cache_limit:
- self._water_submerged_entity_cache.clear()
- self._water_submerged_entity_cache[key] = result
- return result
- def draw_water_submerged_image(self, screen, image, pos, split_y, alpha):
- w, h = image.get_size()
- split_y = max(0, min(h, int(split_y)))
- if split_y >= h:
- image.set_alpha(alpha)
- screen.blit(image, pos)
- return
- if split_y > 0:
- image.set_alpha(alpha)
- screen.blit(image, pos, pygame.Rect(0, 0, w, split_y))
- bottom_h = h - split_y
- key = (id(image), w, h, split_y, alpha)
- strip = self._water_submerged_entity_cache.get(key)
- if strip is None:
- strip = image.subsurface(pygame.Rect(0, split_y, w, bottom_h)).copy()
- small = pygame.transform.smoothscale(strip, (max(1, w // 2), max(1, bottom_h // 2)))
- strip = pygame.transform.smoothscale(small, (w, bottom_h)).convert_alpha()
- strip.set_alpha(min(alpha, 95))
- if len(self._water_submerged_entity_cache) > self._water_reflection_cache_limit:
- self._water_submerged_entity_cache.clear()
- self._water_submerged_entity_cache[key] = strip
- screen.blit(strip, (pos[0], pos[1] + split_y))
- def get_water_reflection_image(self, image):
- key = (id(image), image.get_width(), image.get_height())
- reflected = self._water_reflection_image_cache.get(key)
- if reflected is not None:
- return reflected
- flipped = pygame.transform.flip(image, False, True)
- reflected_h = max(1, int(image.get_height() * 0.8))
- reflected = pygame.transform.smoothscale(flipped, (image.get_width(), reflected_h)).convert_alpha()
- if len(self._water_reflection_image_cache) > self._water_reflection_cache_limit:
- self._water_reflection_image_cache.clear()
- self._water_reflection_image_cache[key] = reflected
- return reflected
- def blit_obstacle_reflection(self, tile, image, image_rect, overlap_left, overlap_right, tile_rect, segment_y, segment_idx):
- src_x = overlap_left - image_rect.left
- src_w = overlap_right - overlap_left
- if segment_idx == 0:
- src_h = min(G.GAME_SQUARE, image.get_height() - segment_y)
- dest_h = src_h
- alpha = 92
- else:
- src_h = image.get_height() - segment_y
- dest_h = G.GAME_SQUARE
- alpha = 52
- return self.blit_reflection_band(tile, image, src_x, segment_y, src_w, src_h, overlap_left - tile_rect.left, 0, dest_h, alpha)
- def blit_reflection_band(self, tile, image, src_x, src_y, src_w, src_h, dest_x, dest_y, dest_h, alpha):
- if src_w <= 0 or src_h <= 0 or dest_h <= 0:
- return False
- src_rect = pygame.Rect(src_x, src_y, src_w, src_h)
- src_rect = src_rect.clip(image.get_rect())
- if src_rect.width <= 0 or src_rect.height <= 0:
- return False
- piece = image.subsurface(src_rect).copy()
- if src_rect.height != dest_h:
- piece = pygame.transform.smoothscale(piece, (src_rect.width, dest_h)).convert_alpha()
- piece.set_alpha(alpha)
- tile.blit(piece, (dest_x, dest_y))
- return True
- def distort_water_reflection(self, source, wave_frame):
- w, h = source.get_size()
- if w <= 2 or h <= 2:
- return source
- small = pygame.transform.smoothscale(source, (max(1, w // 2), max(1, h // 2)))
- source = pygame.transform.smoothscale(small, (w, h)).convert_alpha()
- result = pygame.Surface((w, h), pygame.SRCALPHA, 32)
- phase = wave_frame * 0.65
- band_h = 5
- for y in range(0, h, band_h):
- offset = int(math.sin(phase + y * 0.35) * 2)
- result.blit(source, (offset, y), (0, y, w, band_h))
- return result
- def earth_quake_effect(self, strength=0.1, times=3, duration_per_time=200, decrease=True, direction=None):
- """屏幕震动效果,强度表示移动像素数量,times表示震动次数,duration_per_time表示每次震动持续时间"""
- if direction is None:
- direction = random.choice([0, 1])
- self.earth_quake_direction = direction
- if direction == 0:
- self.earth_quake_duration_per_time = duration_per_time
- strength *= 2
- else:
- self.earth_quake_duration_per_time = duration_per_time // 2
- self.earth_quake_strength = strength
- self.earth_quake_times = times
- self.earth_quake_time = pygame.time.get_ticks()
- self.earth_quake_decrease = decrease
- def run_earth_quake_effect(self, screen: pygame.Surface = None):
- """运行屏幕震动效果"""
- global Y_SCALE_FACTOR
- if self.earth_quake_strength <= 0 or self.earth_quake_times <= 0:
- Y_SCALE_FACTOR = 1
- return
- now = pygame.time.get_ticks()
- if now - self.earth_quake_time >= self.earth_quake_duration_per_time:
- self.earth_quake_times -= 1
- self.earth_quake_time = now
- if self.earth_quake_decrease:
- self.earth_quake_strength = self.earth_quake_strength * 0.5
- if self.earth_quake_times <= 0:
- self.earth_quake_strength = 0
- return
- # 计算偏移量(抛物线计算当前高度)
- t = (now - self.earth_quake_time) / self.earth_quake_duration_per_time
- Y_SCALE_FACTOR = 1 - self.earth_quake_strength * t * (1 - t)
- MAX_BIAS = G.MAIN_AREA_Y_POS * (1-Y_SCALE_FACTOR)//2
- screen.fill((0, 0, 0, 0), rect=(0, 21, G.MAIN_AREA_X_POS, MAX_BIAS))
- def load_background_png(self):
- self.background_layers = []
- for layer in self.map_json["basic"].get("background_png", []):
- if isinstance(layer, str):
- layer = {"name": layer, "move": False}
- name = layer.get("name")
- if not name:
- continue
- path = name if "/" in name or "\\" in name else f"res/img/background/{name}"
- image = load_png(path).convert_alpha()
- if layer.get("move", False):
- image = self.crop_background_to_map_ratio(image)
- image = self.scale_background_to_cover_view(image)
- else:
- target_size = (G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS)
- if image.get_size() != target_size:
- image = pygame.transform.smoothscale(image, target_size).convert_alpha()
- self.background_layers.append({
- "image": image,
- "move": bool(layer.get("move", False)),
- })
- def crop_background_to_map_ratio(self, image):
- img_w, img_h = image.get_size()
- if img_w <= 0 or img_h <= 0 or self.map_y_pos <= 0:
- return image
- map_ratio = self.map_x_pos / self.map_y_pos
- img_ratio = img_w / img_h
- if img_ratio > map_ratio:
- crop_w = max(1, int(img_h * map_ratio))
- crop_rect = pygame.Rect((img_w - crop_w) // 2, 0, crop_w, img_h)
- else:
- crop_h = max(1, int(img_w / map_ratio))
- crop_rect = pygame.Rect(0, (img_h - crop_h) // 2, img_w, crop_h)
- return image.subsurface(crop_rect).copy()
- def scale_background_to_cover_view(self, image):
- img_w, img_h = image.get_size()
- if img_w <= 0 or img_h <= 0:
- return image
- scale = max(G.MAIN_AREA_X_POS / img_w, G.MAIN_AREA_Y_POS / img_h, 1)
- if scale <= 1:
- return image
- target_size = (max(1, int(img_w * scale)), max(1, int(img_h * scale)))
- return pygame.transform.smoothscale(image, target_size).convert_alpha()
- def draw_background_png(self):
- for layer in self.background_layers:
- if layer["move"]:
- image = layer["image"]
- img_w, img_h = image.get_size()
- src_x = self.get_background_scroll_pos(
- self.scroll_x_pos, self.scroll_x_pos_max, img_w, G.MAIN_AREA_X_POS
- )
- src_y = self.get_background_scroll_pos(
- self.scroll_y_pos, self.scroll_y_pos_max, img_h, G.MAIN_AREA_Y_POS
- )
- area_w = min(G.MAIN_AREA_X_POS, img_w)
- area_h = min(G.MAIN_AREA_Y_POS, img_h)
- dest_x = self.scroll_x_pos + max(0, (G.MAIN_AREA_X_POS - img_w) // 2)
- dest_y = self.scroll_y_pos + max(0, (G.MAIN_AREA_Y_POS - img_h) // 2)
- self.main_area.blit(image, (dest_x, dest_y), pygame.Rect(src_x, src_y, area_w, area_h))
- else:
- self.main_area.blit(layer["image"], (self.scroll_x_pos, self.scroll_y_pos))
- def get_background_scroll_pos(self, scroll_pos, scroll_max, image_size, view_size):
- bg_scroll_max = max(0, image_size - view_size)
- if bg_scroll_max <= 0:
- return 0
- if scroll_max <= 0:
- return bg_scroll_max // 2
- return int(bg_scroll_max * max(0, min(1, scroll_pos / scroll_max)))
- def load_floor(self):
- # 加载地板floor
- self.floor_image = pygame.Surface((self.map_x_pos, self.map_y_pos), flags=pygame.HWSURFACE).convert_alpha()
- if self.background_layers:
- self.floor_image.fill((0, 0, 0, 0))
- # 块区域加载
- for f in self.map_json["floors"]:
- for square in f["squares"]:
- for x in range(square["x1"], square["x2"] + 1):
- for y in range(square["y1"], square["y2"] + 1):
- img = floor.get_floor(f["type"], f["name"])
- self.floor_image.blit(img, (x * G.GAME_SQUARE, y * G.GAME_SQUARE))
- # 单个加载
- for f in self.map_json["floor"]:
- img = floor.get_floor(f["type"], f["name"])
- for point in f["points"]:
- self.floor_image.blit(img, (point["x"] * G.GAME_SQUARE, point["y"] * G.GAME_SQUARE))
- def load_obstacle(self):
- # 加载障碍obstacle_instance
- # 块区域加载
- for o in self.map_json["obstacles"]:
- obs, obs_json = obstacle.get_obstacle(o["type"], o["name"])
- for square in o["squares"]:
- for x in range(square["x1"], square["x2"] + 1):
- for y in range(square["y1"], square["y2"] + 1):
- oi.ObstacleInstance(x, y, self.obstacle_instances, obs, obs_json)
- # 单个加载
- for o in self.map_json["obstacle"]:
- obs, obs_json = obstacle.get_obstacle(o["type"], o["name"])
- for point in o["points"]:
- oi.ObstacleInstance(point["x"], point["y"], self.obstacle_instances, obs, obs_json)
- if self.is_transport:
- rs_num = 0
- obs, obs_json = obstacle.get_obstacle("eden", "elem1")
- for x, y in self.transport_resource_init_points:
- if rs_num >= G.RESOUCE_NUM:
- break
- oi.ObstacleInstance(x, y, self.obstacle_instances, obs, obs_json)
- rs_num += 1
- def load_music(self):
- music_loader.play(self.map_music, self.map_music_volume * self.special_music_volume)
- if self.map_ambience is not None:
- music_loader.play_ambience(self.map_ambience, self.map_music_volume * self.special_music_volume)
- else:
- music_loader.stop_ambience()
- def check_weak_achievement(self):
- 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:
- return True
- else:
- return False
- def check_achievement(self):
- 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:
- return True
- else:
- return False
- def check_full_achievement(self):
- 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:
- return True
- else:
- return False
- def record_achievement(self):
- pass
- def update_map_tranport_remain(self, new_remain):
- path = f"game/map/{self.map_name}.json"
- map_json = load_json(path)
- map_json["basic"]["transport_remain"] = new_remain
- self.async_json_saver.save(path, map_json)
- def check_game_achievement(self):
- if self.check_full_achievement() and not G.HAS_RECORD_FULL:
- G.HAS_RECORD_FULL = True
- # 构建保存文件的路径
- user_documents_folder = os.path.expanduser("~\\Documents") # 获取用户的"文档"文件夹路径
- qqtpve_folder = os.path.join(user_documents_folder, "QQTPVE") # 构建QQTPVE文件夹路径
- os.makedirs(qqtpve_folder, exist_ok=True) # 确保QQTPVE文件夹存在,如果不存在则创建
- full_achievements_file_path = os.path.join(qqtpve_folder, "full_achievements.json") # 构建full_achievements.json文件路径
- try:
- with open(full_achievements_file_path, encoding="utf-8") as file:
- encrypted_data = json.load(file)
- except:
- try:
- with open(full_achievements_file_path, encoding="utf-8_sig") as file:
- encrypted_data = json.load(file)
- except:
- # 如果文件不存在,创建新的空的achievements.json文件
- encrypted_data = {"STAT": []}
- with open(full_achievements_file_path, 'w', encoding="utf-8") as file:
- json.dump(encrypted_data, file, indent=2)
- if encrypted_data == {}:
- encrypted_data = {"STAT": []}
- # 新的数据
- new_data = {
- caesar_encrypt("name"): caesar_encrypt(G.MAP_SET_NAME),
- caesar_encrypt("last_map_name"): caesar_encrypt(G.MAP_NAME),
- caesar_encrypt("map_order"): int(caesar_encrypt(str(G.CURRENT_LEVEL))),
- caesar_encrypt("LV"): int(caesar_encrypt(str(self.me.blood))),
- caesar_encrypt("time"): caesar_encrypt(datetime.now().strftime("%Y-%m-%d %H:%M:%S")),
- caesar_encrypt("game_time_min"): int(caesar_encrypt(str(self.map_time//60))),
- caesar_encrypt("game_time_sec"): int(caesar_encrypt(str(self.map_time%60)))
- }
- # 添加新的加密数据
- encrypted_data["STAT"].append(new_data)
- with open(full_achievements_file_path, 'w') as file:
- json.dump(encrypted_data, file, indent=2)
- if G.CURRENT_LEVEL == G.TOTAL_LEVEL:
- G.CUMULATION_INJURE += self.me.blood - self.me.remain_blood
- if self.check_weak_achievement() and G.CURRENT_LEVEL == G.TOTAL_LEVEL and not G.HAS_RECORD:
- G.HAS_RECORD = True
- sound_player.playWin("PlayerWin")
- if self.is_transport:
- if self.transport_map_remain > 0:
- TransportSuccessEffect(self.me, self.me, self.transport_map_remain, self.skill_instances)
- current_amount = max(G.TOTAL_TRANSPORT - G.CUMULATION_RESOURCE_LEAK + 50, 0) * (1 - G.CUMULATION_INJURE / G.CUMULATION_HERO_BLOOD)
- current_amount = max(current_amount, 0)
- new_remain = max(0, self.transport_map_remain - current_amount)
- current_amount = int(current_amount)
- new_remain = int(new_remain)
- if new_remain > 0:
- msg_txt = f"本次成功运输{current_amount}点资源,当前还剩余{new_remain}/{self.transport_map_total}"
- else:
- msg_txt = f"本次成功运输{current_amount}点资源,当前地图所有运输任务已完成!!!"
- self.message_entry.new_message(sender="运输助手", message=msg_txt, colour=[95, 191, 255])
- self.update_map_tranport_remain(new_remain)
- self.map_blood_bar.update_remain_blood(new_remain)
- else:
- if G.CUMULATION_INJURE == 0:
- WinEffect(self.me, self.me, "super", self.skill_instances)
- elif G.CUMULATION_INJURE < min(4500, self.me.blood):
- WinEffect(self.me, self.me, "ultra", self.skill_instances)
- else:
- WinEffect(self.me, self.me, "big", self.skill_instances)
- current_amount = max(G.TOTAL_TRANSPORT - G.CUMULATION_RESOURCE_LEAK + 50, 0) * (1 - G.CUMULATION_INJURE / G.CUMULATION_HERO_BLOOD)
- current_amount = max(current_amount, 0)
- current_amount = int(current_amount)
- if current_amount > 0:
- msg_txt = f"当前区域运输目标已完成,本次额外运输{current_amount}点资源"
- self.message_entry.new_message(sender="运输助手", message=msg_txt, colour=[95, 191, 255])
- else:
- if G.ITEM == 0:
- if G.CUMULATION_INJURE == 0:
- WinEffect(self.me, self.me, "super", self.skill_instances)
- elif G.CUMULATION_INJURE < min(4500, self.me.blood):
- WinEffect(self.me, self.me, "ultra", self.skill_instances)
- else:
- WinEffect(self.me, self.me, "big", self.skill_instances)
- else:
- WinEffect(self.me, self.me, "normal", self.skill_instances)
- if G.ITEM == 0:
- # 构建保存文件的路径
- user_documents_folder = os.path.expanduser("~\\Documents") # 获取用户的"文档"文件夹路径
- qqtpve_folder = os.path.join(user_documents_folder, "QQTPVE") # 构建QQTPVE文件夹路径
- os.makedirs(qqtpve_folder, exist_ok=True) # 确保QQTPVE文件夹存在,如果不存在则创建
- achievements_file_path = os.path.join(qqtpve_folder, "achievements.json") # 构建achievements.json文件路径
- monster_stats_file_path = os.path.join(qqtpve_folder, "monster_stats.json") # 构建json文件路径
- try:
- with open(achievements_file_path, encoding="utf-8") as file:
- encrypted_data = json.load(file)
- except:
- try:
- with open(achievements_file_path, encoding="utf-8_sig") as file:
- encrypted_data = json.load(file)
- except:
- # 如果文件不存在,创建新的空的achievements.json文件
- encrypted_data = {"STAT": []}
- with open(achievements_file_path, 'w', encoding="utf-8") as file:
- json.dump(encrypted_data, file, indent=2)
- if encrypted_data == {}:
- encrypted_data = {"STAT": []}
- # 新的数据
- new_data = {caesar_encrypt("name"): caesar_encrypt(G.MAP_SET_NAME),
- caesar_encrypt("last_map_name"): caesar_encrypt(G.MAP_NAME),
- caesar_encrypt("LV"): int(caesar_encrypt(str(self.me.blood))),
- caesar_encrypt("time"): caesar_encrypt(datetime.now().strftime("%Y-%m-%d %H:%M:%S")),
- caesar_encrypt("game_time_min"): int(caesar_encrypt(str(self.map_time//60))),
- caesar_encrypt("game_time_sec"): int(caesar_encrypt(str(self.map_time%60))),
- caesar_encrypt("remain_blood"): int(caesar_encrypt(str(self.me.remain_blood)))}
- try:
- # 添加新的加密数据
- encrypted_data["STAT"].append(new_data)
- with open(achievements_file_path, 'w') as file:
- json.dump(encrypted_data, file, indent=2)
- except:
- pass
- try:
- with open(monster_stats_file_path, encoding="utf-8") as file:
- self.encrypted_data_m = json.load(file)
- except:
- try:
- with open(monster_stats_file_path, encoding="utf-8_sig") as file:
- self.encrypted_data_m = json.load(file)
- except:
- # 如果文件不存在,创建新的空的json文件
- self.encrypted_data_m = {"STAT": []}
- with open(monster_stats_file_path, 'w', encoding="utf-8") as file:
- json.dump(self.encrypted_data_m, file, indent=2)
- if self.encrypted_data_m == {}:
- self.encrypted_data_m = {"STAT": []}
- try:
- for data in G.MONSTER_RECORD_LIST:
- self.encrypted_data_m["STAT"].append(data)
- with open(monster_stats_file_path, 'w') as file:
- json.dump(self.encrypted_data_m, file, indent=2)
- G.MONSTER_RECORD_LIST = []
- except:
- G.MONSTER_RECORD_LIST = []
- else:
- if G.CURRENT_LEVEL == G.TOTAL_LEVEL:
- WinEffect(self.me, self.me, "normal", self.skill_instances)
- if G.CURRENT_LEVEL == G.TOTAL_LEVEL:
- self.schedule_ending_sequence()
- def load_district_and_enemies(self):
- if len(self.npcs) > 0: # npc还没有被杀光
- return
- self.me.district_locked = False # 解除玩家区域锁
- if self.district_idx >= len(self.map_json["districts"]): # 已完成最后一个区域
- self.district_square = {"x1": 0, "x2": 0, "y1": 0, "y2": 0}
- self.district_square_grid = {"x1": 0, "x2": 0, "y1": 0, "y2": 0}
- self.district_all_finished = True
- if not self.has_achievemeny_check:
- self.has_achievemeny_check = True
- self.check_game_achievement()
- return
- self.district_idx += 1
- a_district = self.map_json["districts"][self.district_idx - 1]
- valid_poison_set = set()
- self.district_square = a_district["square"].copy()
- self.district_square_grid["x1"] = self.district_square["x1"]
- self.district_square_grid["x2"] = self.district_square["x2"]
- self.district_square_grid["y1"] = self.district_square["y1"]
- self.district_square_grid["y2"] = self.district_square["y2"]
- # 将district_square的四个点转化为像素坐标
- self.district_square["x1"] = self.district_square["x1"] * G.GAME_SQUARE + G.HALF_GAME_SQUARE
- self.district_square["x2"] = self.district_square["x2"] * G.GAME_SQUARE + G.HALF_GAME_SQUARE
- self.district_square["y1"] = self.district_square["y1"] * G.GAME_SQUARE + G.HALF_GAME_SQUARE
- self.district_square["y2"] = self.district_square["y2"] * G.GAME_SQUARE + G.HALF_GAME_SQUARE
- for g in self.ghosts:
- # 加载新区域时删除旧区域的幽灵,以及新加载出来的幽灵
- if g.time == 0:
- self.ghosts.remove(g)
- for n in a_district["npcs"]:
- # 载入新区域的npc
- patrol = n.get("patrol", None)
- if patrol is not None:
- self.npcs.append(Npc(n["name"], (n["x"], n["y"]), patrol_path=patrol))
- else:
- self.npcs.append(Npc(n["name"], (n["x"], n["y"])))
- for district in self.map_json["districts"][self.district_idx-1:]:
- x1, y1, x2, y2 = district["square"]["x1"], district["square"]["y1"], district["square"]["x2"], district["square"]["y2"]
- for point in self.poison_dic.keys():
- if x1 <= point[0] <= x2 and y1 <= point[1] <= y2:
- valid_poison_set.add(point)
- G.HAS_RECORD_FULL = False
- G.HAS_GOLDEN = False
- # 清除冗余紫陷阱
- old_keys = [ky for ky in self.poison_dic.keys()]
- for point in old_keys:
- if point not in valid_poison_set:
- self.poison_dic[point][4].state = EffectState.DEAD
- del self.poison_dic[point]
- def update(self, screen: pygame.Surface):
- # a = pygame.time.get_ticks()
- self.current_time = pygame.time.get_ticks()
- self.run_earth_quake_effect(screen) # 运行屏幕震动效果
- # 刷新帧率
- self.display_frame_rate(self.current_time, screen)
- # 刷新剩余时间
- if self.score_board is not None:
- map_remaining_time = math.ceil(
- (self.map_time * 1000) // 1000) + 1
- self.score_board.set_time(map_remaining_time)
- if self.time_board is not None:
- map_remaining_time = math.ceil(
- (self.level_time * 1000) // 1000)
- self.time_board.set_time(map_remaining_time)
- self.start_ending_sequence_if_needed()
- if not self.intro_chat_started and self.current_time - self.map_init_time > 3000:
- self.try_start_intro_chat()
- # 刷新区域
- if not self.intro_chat_active and self.current_time - self.map_init_time > 3000:
- self.load_district_and_enemies()
- # 恢复帧爆炸位
- self.grid_damage_frame -= 1
- # 刷新糖泡
- for b in self.bomb_instances:
- b.update()
- # 刷新游荡者
- for w in self.wanderers:
- if w.remain_blood <= 0:
- self.wanderers.remove(w)
- else:
- if abs(w.x - self.me.x) <= 20 and abs(w.y - self.me.y) <= 20:
- w.update()
- # 刷新友军
- for t in self.teammates:
- if t.remain_blood <= 0:
- self.teammates.remove(t)
- else:
- t.update()
- # 刷新npc
- for n in self.npcs:
- if n.remain_blood <= 0:
- self.npcs.remove(n)
- else:
- n.update()
- self.recal_npc_paths = False
- # 刷新宠物
- if len(self.pets) > 0:
- for pet in self.pets:
- pet.update()
- # 刷新ghost
- for g in self.ghosts:
- if g.remain_time <= 0:
- self.ghosts.remove(g)
- else:
- g.update()
- self.recal_ghost_paths = False
- # 刷新人物
- self.me.update()
- # 检测过关
- self.pass_map()
- # 检测传送门
- self.portal_map()
- # 刷新糖浆
- new_flames = []
- for f in self.flame_instances:
- if f.state == FS.DEAD:
- continue
- f.update()
- if f.state != FS.DEAD:
- new_flames.append(f)
- self.flame_instances = new_flames
- # 刷新item
- for key in list(self.item_instances.keys()):
- i = self.item_instances[key]
- if i.state == IS.DEAD:
- self.item_instances.pop(key)
- else:
- i.update()
- # 刷新障碍
- # if self.obstacle_instances_need_to_update:
- # self.update_obstacles_update_list()
- # 只有当真的 rebuild obstacle_instances_update 时,才标脏
- if self.obstacle_instances_need_to_update:
- self.update_obstacles_update_list()
- self._static_dirty = True
- # 当 dict 发生变化时标脏(低配版:靠计数变化)
- if len(self.item_instances) != self._cached_item_count:
- self._cached_item_count = len(self.item_instances)
- self._static_dirty = True
- for o in self.obstacle_instances_update:
- o.update()
- self.transport_buff_num = 0
- for o in self.transport_obstacle:
- if o.transport_remain > 0:
- o.update()
- if o.in_safe_zone:
- self.transport_buff_num += 1
- # 刷新技能
- for s in self.skill_instances:
- s.update()
- # 刷新特效
- for e in self.effects_behind:
- e.update()
- for e in self.effects_front:
- e.update()
- for e in self.effects_screen:
- e.update()
- # 刷新ui
- for u in self.ui_instances_top:
- u.update()
- for u in self.ui_instances_bot:
- u.update()
- # 只裁剪绘制,不跳过 update/draw 中的状态处理。
- # 原生 blit 会在震屏坐标变换后裁剪;自定义 blender 同样遵守此范围。
- previous_clip = self.main_area.get_clip()
- self.main_area.set_clip(self.get_render_view_rect())
- if Y_SCALE_FACTOR != 1:
- MAX_BIAS = G.MAIN_AREA_Y_POS * (1-Y_SCALE_FACTOR)//2
- # 上下MAX_BIAS区域填充(0,0,0,0)
- self.main_area.fill((255, 255, 255, 0), (self.scroll_x_pos, self.scroll_y_pos + 21, G.MAIN_AREA_X_POS, MAX_BIAS))
- # 显示地板下方背景
- self.draw_background_png()
- # 显示地板
- self.main_area.blit(
- self.floor_image,
- (self.scroll_x_pos, self.scroll_y_pos),
- (self.scroll_x_pos, self.scroll_y_pos, G.MAIN_AREA_X_POS, G.MAIN_AREA_Y_POS)
- )
- # 显示底层特效
- for e in self.effects_behind:
- e.draw(self.main_area)
- # 显示人物和障碍
- # if len(self.pets) > 0:
- # draw_seq = self.pets + \
- # [self.me] + \
- # self.npcs + \
- # self.wanderers + \
- # self.teammates + \
- # self.ghosts + \
- # self.bomb_instances + \
- # self.obstacle_instances_update + \
- # self.flame_instances + \
- # list(self.item_instances.values())
- # else:
- # draw_seq = [self.me] + \
- # self.npcs + \
- # self.wanderers + \
- # self.teammates + \
- # self.ghosts + \
- # self.bomb_instances + \
- # self.obstacle_instances_update + \
- # self.flame_instances + \
- # list(self.item_instances.values())
- # draw_seq.sort(key=get_y)
- # for d in draw_seq:
- # d.draw(self.main_area)
- # 重建静态已排序列表(只在 dirty 时做)
- if self._static_dirty:
- static_objs = []
- # 现在参与 y-sort 的“基本静态”候选
- # obstacle_instances_update:位置不动,但“可见集合”会变
- static_objs.extend(self.obstacle_instances_update)
- # items:大多数情况下不动(被拾取/生成时才变)
- static_objs.extend(self.item_instances.values())
- # 预计算 y,避免 merge 时反复 getattr/get_y
- tmp = []
- tie = 0
- for o in static_objs:
- y = o.get_y() if hasattr(o, "get_y") else getattr(o, "y_pos", 0)
- tmp.append((y, tie, o))
- tie += 1
- tmp.sort(key=lambda t: (t[0], t[1]))
- self._static_sorted = tmp
- self._static_dirty = False
- # 动态层:每帧组装 + 排序
- dyn = []
- append = dyn.append
- extend = dyn.extend
- if self.pets:
- extend(self.pets)
- append(self.me)
- extend(self.npcs)
- extend(self.wanderers)
- extend(self.teammates)
- extend(self.ghosts)
- extend(self.bomb_instances)
- extend(self.flame_instances)
- dyn_tmp = []
- tie = 0
- for o in dyn:
- y = o.get_y() if hasattr(o, "get_y") else getattr(o, "y_pos", 0)
- dyn_tmp.append((y, tie, o))
- tie += 1
- dyn_tmp.sort(key=lambda t: (t[0], t[1]))
- # merge:两路有序序列 O(n) 绘制
- i = 0
- j = 0
- A = self._static_sorted
- B = dyn_tmp
- draw = self.main_area.blit
- while i < len(A) and j < len(B):
- if A[i][0] <= B[j][0]:
- static_obj = A[i][2]
- static_obj.draw(self.main_area)
- if getattr(static_obj, "water_reflect", False):
- self.draw_water_reflection_for_obstacle(self.main_area, static_obj)
- i += 1
- else:
- self.draw_dynamic_object(B[j][2])
- j += 1
- while i < len(A):
- static_obj = A[i][2]
- static_obj.draw(self.main_area)
- if getattr(static_obj, "water_reflect", False):
- self.draw_water_reflection_for_obstacle(self.main_area, static_obj)
- i += 1
- while j < len(B):
- self.draw_dynamic_object(B[j][2])
- j += 1
- self.apply_light_masks()
- # 显示顶层特效
- for e in self.effects_front:
- e.draw(self.main_area)
- self.main_area.set_clip(previous_clip)
- # 显示下ui
- for u in self.ui_instances_bot:
- u.draw(screen)
- # 显示主区域
- 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))
- # 显示上ui
- for u in self.ui_instances_top:
- u.draw(screen)
- # 显示屏幕特效
- for e in self.effects_screen:
- try:
- e.draw(screen)
- except Exception as e:
- print(e)
- self.update_particles(screen, current_time=self.current_time)
- # 左侧黑条
- screen.blit(self.left_black, (0, 0))
- # 重置糖泡爆炸音效位
- BombInstance.sound_played = False
- # 重置糖泡爆炸方向记录
- self.grid_damage_orientations.clear()
- # print(pygame.time.get_ticks() - a)
- def update_particles(self, screen, current_time):
- if self.particle_effect is None:
- return
- if current_time - self.last_particle_time >= 150:
- self.last_particle_time = current_time
- x = random.randint(0, screen.get_width())
- y = screen.get_height() - 65
- self.particles.add(LevelParticle(x, y, color=self.particle_effect))
- if current_time - self.last_particle_update_time >= 10:
- self.last_particle_update_time = current_time
- new_particles = set()
- for p in self.particles:
- p.update()
- if p.is_alive():
- new_particles.add(p)
- self.particles = new_particles
- for p in self.particles:
- p.draw(screen)
- def update_obstacles_update_list(self):
- self.obstacle_instances_need_to_update = False
- self.obstacle_instances_update.clear()
- 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):
- 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):
- if (x, y) in self.obstacle_instances.keys():
- an_obstacle = self.obstacle_instances[(x, y)]
- self.obstacle_instances_update.append(an_obstacle)
- def display_frame_rate(self, current_time, screen):
- self.frames_num += 1
- current_time_div_1000 = current_time // 1000
- if current_time_div_1000 > self.times_num:
- self.times_num = current_time_div_1000
- G.TIME = self.times_num
- self.map_time = self.times_num - G.LASTMAPTIME
- self.level_time = self.times_num - G.LAST_LEVEL_TIME
- if G.DISPLAY_FRAME_RATE:
- if G.SHOW_STAT:
- # 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))
- 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))
- else:
- 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))
- screen.blit(img, (100, 0))
- self.frames_num = 0
- def pass_map(self):
- # 尝试置finish_flag为True
- if self.district_all_finished and self.finish_at is not None:
- if self.me.x == self.finish_at[0] and self.me.y == self.finish_at[1]:
- self.finish_flag = True
- G.LAST_LEVEL_TIME = self.times_num
- G.CUMULATION_INJURE += (self.me.blood - self.me.remain_blood)
- if self.is_transport:
- resouce_next = 0
- injured = 0
- for o in self.transport_obstacle:
- if o.transport_remain > 0 and o.in_safe_zone:
- injured += o.transport_amount - o.transport_remain
- resouce_next += 1
- G.RESOUCE_NUM = resouce_next
- if G.CURRENT_LEVEL == 1:
- G.TOTAL_TRANSPORT = resouce_next
- G.CUMULATION_RESOURCE_LEAK = injured
- # 传送门,参数格式: {"[x1,y1]":{"type": "level", "target": [x2,y2]}, "[x3,y3]":{"type": "map", "target": 3}, "[x4,y4]":{"type": "map_set", "target": "Mo1"}}
- def portal_map(self):
- if len(self.portal_set) != 0:
- for point in self.portal_set:
- if self.me.x == point[0][0] and self.me.y == point[0][1]:
- port_type, target = point[1], point[2]
- sound_player.play("X08_01")
- # 地图内闪现
- if port_type == "level":
- self.me.set_xy(target[0], target[1])
- self.scroll_map()
- # 跳到当前第几关
- elif port_type == "map":
- target = max(1, int(target))
- G.CURRENT_LEVEL = target - 1
- self.game.map_set_at = target - 2
- self.finish_flag = True
- G.LAST_LEVEL_TIME = self.times_num
- # 在后面插入一关
- elif port_type == "insert":
- map_name = target
- hero_name = self.game.cfg_json["your_hero"]
- character_color = self.game.cfg_json["your_character_color"]
- self.game.set_level(self.your_name, map_name, hero_name, character_color, is_reset=False)
- G.LAST_LEVEL_TIME = self.times_num
- G.CURRENT_LEVEL -= 1
- else:
- self.game.reset(target) # 换大地图
- def scroll_map(self):
- # 滚动地图
- MAX_DIST = 20 # 单次最大滚动距离
- scroll_x_old = self.scroll_x_pos
- scroll_y_old = self.scroll_y_pos
- if self.me.x_pos > self.scroll_x_pos + G.R_SCROLL:
- # 向右滚动
- self.scroll_x_pos = max(0, min(self.me.x_pos - G.R_SCROLL, self.scroll_x_pos_max))
- elif self.me.x_pos < self.scroll_x_pos + G.L_SCROLL:
- # 向左滚动
- self.scroll_x_pos = max(0, min(self.me.x_pos - G.L_SCROLL, self.scroll_x_pos_max))
- if self.me.y_pos > self.scroll_y_pos + G.D_SCROLL:
- # 向下滚动
- self.scroll_y_pos = max(0, min(self.me.y_pos - G.D_SCROLL, self.scroll_y_pos_max))
- elif self.me.y_pos < self.scroll_y_pos + G.U_SCROLL:
- # 向上滚动
- self.scroll_y_pos = max(0, min(self.me.y_pos - G.U_SCROLL, self.scroll_y_pos_max))
- if self.current_time - self.map_init_time > 3000:
- # 限制滚动速度
- if self.scroll_x_pos - scroll_x_old > MAX_DIST:
- self.scroll_x_pos = scroll_x_old + MAX_DIST
- self.obstacle_instances_need_to_update = True
- if self.scroll_x_pos - scroll_x_old < -MAX_DIST:
- self.scroll_x_pos = scroll_x_old - MAX_DIST
- self.obstacle_instances_need_to_update = True
- if self.scroll_y_pos - scroll_y_old > MAX_DIST:
- self.scroll_y_pos = scroll_y_old + MAX_DIST
- self.obstacle_instances_need_to_update = True
- if self.scroll_y_pos - scroll_y_old < -MAX_DIST:
- self.scroll_y_pos = scroll_y_old - MAX_DIST
- self.obstacle_instances_need_to_update = True
- # 限制滚动范围
- if self.scroll_x_pos > self.scroll_x_pos_max:
- self.scroll_x_pos = self.scroll_x_pos_max
- if self.scroll_y_pos > self.scroll_y_pos_max:
- self.scroll_y_pos = self.scroll_y_pos_max
- '''
- def scroll_map(self):
- # 滚动地图
- if self.me.x_pos > self.scroll_x_pos + G.R_SCROLL:
- # 向右滚动
- self.scroll_x_pos = max(0, min(self.me.x_pos - G.R_SCROLL, self.scroll_x_pos_max))
- elif self.me.x_pos < self.scroll_x_pos + G.L_SCROLL:
- # 向左滚动
- self.scroll_x_pos = max(0, min(self.me.x_pos - G.L_SCROLL, self.scroll_x_pos_max))
- if self.me.y_pos > self.scroll_y_pos + G.D_SCROLL:
- # 向下滚动
- self.scroll_y_pos = max(0, min(self.me.y_pos - G.D_SCROLL, self.scroll_y_pos_max))
- elif self.me.y_pos < self.scroll_y_pos + G.U_SCROLL:
- # 向上滚动
- self.scroll_y_pos = max(0, min(self.me.y_pos - G.U_SCROLL, self.scroll_y_pos_max))
- '''
- def alarm_district(self):
- # 显示当前区域的警戒
- if self.district_alarming:
- return
- DistrictAlarm(self.effects_behind)
- def get_bomb_instance(self, x, y):
- # 同一次位置变化后的所有查询共享索引;保持原列表中的同格糖泡顺序。
- if self._bomb_index_dirty:
- positions = {}
- for bomb in self.bomb_instances:
- if not bomb.throwing:
- positions.setdefault((bomb.x, bomb.y), []).append(bomb)
- self._bomb_position_index = positions
- self._bomb_index_dirty = False
- # 调用者可能在遍历中引爆/删除糖泡,不能把索引内部的列表暴露出去。
- return list(self._bomb_position_index.get((x, y), ()))
- def get_an_npc(self, name, point):
- return Npc(name, point)
|