| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655 |
- 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
- # 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 get_player_mask(mask_surface, bgl):
- 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))
- curr_key = (
- id(current_level),
- current_level.scroll_x_pos,
- current_level.scroll_y_pos,
- mask_surface.get_width(),
- mask_surface.get_height(),
- bgl,
- 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
- # 先把整表清空为 bgl 灰底
- fill((bgl, bgl, bgl, 0))
- # ---- 新增:计算屏幕视口,并在后面用 inflate 方式做相交测试 ----
- from client_local.const import game as G
- # world-space 下的视口矩形
- view_rect = pygame.Rect(
- current_level.scroll_x_pos,
- current_level.scroll_y_pos,
- G.MAIN_AREA_X_POS,
- G.MAIN_AREA_Y_POS
- )
- # ---------------------------------------------------------
- view_x, view_y = current_level.scroll_x_pos, current_level.scroll_y_pos
- for x, y, light in curr:
- r = light * MASK_STEP
- sx = x - view_x - r # ← 世界 → 屏幕
- sy = y - view_y - r - 15
- cm = masks[light]
- # 膨胀法:把视口向外各扩 r(水平方向)和 (r+15)(垂直方向)
- if not view_rect.inflate(2*r, 2*(r+15)).collidepoint(x, y):
- continue
- # 叠加亮度
- mask_surface.blit(cm, (sx, sy), special_flags=pygame.BLEND_RGBA_ADD)
- return mask_surface
- def special_colour_mask(mask_surface, rgb):
- r = min(max(rgb[0], 0), 255)
- g = min(max(rgb[1], 0), 255)
- b = min(max(rgb[2], 0), 255)
- mask_surface.fill((r, g, b, 0)) # 初始
- for player in [current_level.me] + current_level.npcs + list(current_level.obstacle_instances.values()):
- x, y = player.x_pos, player.y_pos
- if player.light == 0:
- continue
- circleMask = circleMasks[player.light]
- circle_radius = player.light*MASK_STEP
- # 叠加亮度
- mask_surface.blit(circleMask, (x-circle_radius, y-circle_radius-15),special_flags=pygame.BLEND_RGBA_ADD) # 15是补偿值(大概是角色中心)
- 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):
- 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))
- 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.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_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((self.map_x_pos, self.map_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_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.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
- if "music_volume" in self.map_json["basic"].keys():
- self.special_music_volume = self.map_json["basic"]["music_volume"]
- 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 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_floor(self):
- # 加载地板floor
- self.floor_image = pygame.Surface((self.map_x_pos, self.map_y_pos), flags=pygame.HWSURFACE).convert_alpha()
- # 块区域加载
- 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()
- 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.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
- if self.special_rgb:
- self.mask_surface = special_colour_mask(self.mask_surface, self.rgb_light)
- self.main_area.blit(self.mask_surface, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
- if self.haunt_Mode:
- # 只在 get_player_mask 检测到状态变化时才重绘 mask_surface
- get_player_mask(self.mask_surface, self.bg_light)
- 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())
- # 取 main_area 的子 Surface(不拷贝像素,O(1))
- sub_main = self.main_area.subsurface(view_rect)
- # 将 mask_surface 乘进子 Surface,而不是整张 main_area
- sub_main.blit(self.mask_surface, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
- # 显示顶层特效
- for e in self.effects_front:
- e.draw(self.main_area)
- # 显示下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):
- # 获取(x, y)处的所有糖泡list
- bs = list()
- for b in self.bomb_instances:
- if b.x == x and b.y == y and not b.throwing:
- bs.append(b)
- return bs
- def get_an_npc(self, name, point):
- return Npc(name, point)
|