| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359 |
- import { _decorator, Component, Node, Prefab, instantiate, Vec3, EventTouch, Color, Vec2, UITransform, find, Rect, Label, Size, Sprite, SpriteFrame, resources, Button, Collider2D, Material, tween, JsonAsset, Tween } from 'cc';
- import * as cc from 'cc';
- import { ConfigManager, WeaponConfig } from '../Core/ConfigManager';
- import { SaveDataManager } from '../LevelSystem/SaveDataManager';
- import { LevelSessionManager } from '../Core/LevelSessionManager';
- import { LevelConfigManager } from '../LevelSystem/LevelConfigManager';
- import { BlockTag } from './BlockSelection/BlockTag';
- import { BlockInfo } from './BlockSelection/BlockInfo';
- import { SkillManager } from './SkillSelection/SkillManager';
- import EventBus, { GameEvents } from '../Core/EventBus';
- import { sp } from 'cc';
- import { BundleLoader } from '../Core/BundleLoader';
- import { Audio } from '../AudioManager/AudioManager';
- import { GuideUIController } from '../../NewbieGuidePlugin-v1.0.0/NewbieGuidePlugin-v1.0.0/scripts/GuideUIController';
- import { Analytics } from '../Utils/AnalyticsManager';
- const { ccclass, property } = _decorator;
- @ccclass('BlockManager')
- export class BlockManager extends Component {
- // 预制体数组,存储10个预制体
- @property([Prefab])
- public blockPrefabs: Prefab[] = [];
-
- // 网格容器节点
- @property({
- type: Node,
- tooltip: '拖拽GridContainer节点到这里'
- })
- public gridContainer: Node = null;
-
- // 方块容器节点(kuang)
- @property({
- type: Node,
- tooltip: '拖拽kuang节点到这里'
- })
- public kuangContainer: Node = null;
-
- // Block1节点
- @property({
- type: Node,
- tooltip: '拖拽Block1节点到这里(Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block1)'
- })
- public block1Container: Node = null;
-
- // Block2节点
- @property({
- type: Node,
- tooltip: '拖拽Block2节点到这里(Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block2)'
- })
- public block2Container: Node = null;
-
- // Block3节点
- @property({
- type: Node,
- tooltip: '拖拽Block3节点到这里(Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block3)'
- })
- public block3Container: Node = null;
-
- // 价格节点装饰器
- @property({
- type: Node,
- tooltip: '拖拽Block1价格节点到这里(Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block1/db01/Price)'
- })
- public block1PriceNode: Node = null;
-
- @property({
- type: Node,
- tooltip: '拖拽Block2价格节点到这里(Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block2/db01/Price)'
- })
- public block2PriceNode: Node = null;
-
- @property({
- type: Node,
- tooltip: '拖拽Block3价格节点到这里(Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block3/db01/Price)'
- })
- public block3PriceNode: Node = null;
-
- // db标签节点装饰器
- @property({
- type: Node,
- tooltip: '拖拽Block1的db标签节点到这里(Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block1/db01)'
- })
- public block1DbNode: Node = null;
-
- @property({
- type: Node,
- tooltip: '拖拽Block2的db标签节点到这里(Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block2/db01)'
- })
- public block2DbNode: Node = null;
-
- @property({
- type: Node,
- tooltip: '拖拽Block3的db标签节点到这里(Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block3/db01)'
- })
- public block3DbNode: Node = null;
-
- // 金币标签节点
- @property({
- type: Node,
- tooltip: '拖拽CoinLabel节点到这里'
- })
- public coinLabelNode: Node = null;
-
- // 已放置方块容器节点
- @property({
- type: Node,
- tooltip: '拖拽PlacedBlocks节点到这里(Canvas/GameLevelUI/GameArea/PlacedBlocks)'
- })
- public placedBlocksContainer: Node = null;
- private guideUIController: GuideUIController = null;
-
-
- // 游戏是否已开始
- public gameStarted: boolean = false;
-
- // 移除移动冷却:相关属性/逻辑已废弃
-
- // SaveDataManager 单例
- private saveDataManager: SaveDataManager = null; // 仅用于局外数据
- private session: LevelSessionManager = null;
-
- // 方块价格标签映射
- private blockPriceMap: Map<Node, Node> = new Map();
- // 价格标签初始颜色缓存,防止多次闪烁后无法恢复
- private priceLabelOriginalColors: Map<Node, Color> = new Map();
-
- // 已经生成的块
- private blocks: Node[] = [];
- // 网格占用情况,用于控制台输出
- private gridOccupationMap: number[][] = [];
- // 网格行数和列数
- private readonly GRID_ROWS = 6;
- private readonly GRID_COLS = 11;
- // 是否已初始化网格信息
- private gridInitialized = false;
- // 存储网格节点信息
- private gridNodes: Node[][] = [];
- // 网格间距
- private gridSpacing = 54; // 默认值,将在initGridInfo中动态计算
- // 不参与占用的节点名称列表
- private readonly NON_BLOCK_NODES: string[] = ['Weapon', 'Price'];
- // 临时保存方块的原始占用格子
- private tempRemovedOccupiedGrids: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
- // 方块原始位置(在kuang中的位置)
- public originalPositions: Map<Node, Vec3> = new Map();
- // 方块当前所在的区域
- public blockLocations: Map<Node, string> = new Map();
-
- // 配置管理器
- private configManager: ConfigManager = null;
-
- // 关卡配置管理器
- private levelConfigManager: LevelConfigManager = null;
-
- // 方块武器配置映射
- private blockWeaponConfigs: Map<Node, WeaponConfig> = new Map();
-
- // 预加载的武器配置数据
- private preloadedWeaponsConfig: any = null;
-
- // 配置是否已预加载的标志
- private isWeaponsConfigPreloaded: boolean = false;
-
- private bundleLoader: BundleLoader = null;
-
- // 新手教程相关属性
- private _tutorialStep: number = 0;
- private _tutorialTargetGrids: string[] = ['Grid_3_1', 'Grid_4_1'];
- private _tutorialTargetGridsStep2: string[] = ['Grid_3_5', 'Grid_3_6'];
- private _tutorialTargetGridsStep4: string[] = ['Grid_3_9', 'Grid_4_9'];
- private _tutorialBlockContainers: Node[] = [];
- // 第二波固定形状应用标志,防止重复应用
- private _secondWaveFixedApplied: boolean = false;
-
- // 设置预加载的武器配置数据调试绘制相关
- // 调试绘制功能已迁移到GameBlockSelection
-
- /** 冷却机制已废弃,方块随时可移动 */
- // 清除所有冷却(游戏重置时调用)
- public clearAllCooldowns() { /* no-op */ }
-
- /**
- * 设置预加载的武器配置数据
- * @param weaponsConfigData 从JsonAsset获取的武器配置数据
- */
- public setPreloadedWeaponsConfig(weaponsConfigData: any): void {
- console.log('[BlockManager] 接收到预加载的武器配置数据');
- this.preloadedWeaponsConfig = weaponsConfigData;
- this.isWeaponsConfigPreloaded = true;
-
- // 验证配置数据结构
- if (weaponsConfigData && weaponsConfigData.weapons && Array.isArray(weaponsConfigData.weapons)) {
- console.log(`[BlockManager] 武器配置验证成功,包含 ${weaponsConfigData.weapons.length} 个武器`);
- } else {
- console.warn('[BlockManager] 武器配置数据结构异常');
- this.isWeaponsConfigPreloaded = false;
- }
- }
-
- /**
- * 获取预加载的武器配置,如果没有预加载则返回null
- */
- private getPreloadedWeaponsConfig(): any {
- return this.isWeaponsConfigPreloaded ? this.preloadedWeaponsConfig : null;
- }
- // 获取当前关卡的武器列表
- private async getCurrentLevelWeapons(): Promise<string[]> {
- if (!this.levelConfigManager || !this.saveDataManager) {
- console.warn('关卡配置管理器或存档管理器未初始化,使用默认武器列表');
- return [];
- }
-
- try {
- const currentLevel = this.saveDataManager.getCurrentLevel();
- const levelConfig = await this.levelConfigManager.getLevelConfig(currentLevel);
-
- if (levelConfig && levelConfig.weapons && Array.isArray(levelConfig.weapons)) {
- console.log(`关卡 ${currentLevel} 配置的武器:`, levelConfig.weapons);
- return levelConfig.weapons;
- } else {
- console.warn(`关卡 ${currentLevel} 没有配置武器列表`);
- return [];
- }
- } catch (error) {
- console.error('获取当前关卡武器配置失败:', error);
- return [];
- }
- }
-
- // 根据武器名称获取武器配置
- private getWeaponConfigByName(weaponName: string): WeaponConfig | null {
- // 优先使用预加载的配置数据
- const preloadedConfig = this.getPreloadedWeaponsConfig();
- if (preloadedConfig && preloadedConfig.weapons && Array.isArray(preloadedConfig.weapons)) {
- const weapon = preloadedConfig.weapons.find((w: any) => w.name === weaponName);
- if (weapon) {
- console.log(`[BlockManager] 从预加载配置中找到武器: ${weaponName}`);
- return weapon as WeaponConfig;
- }
- }
-
- // 如果预加载配置中没有找到,回退到ConfigManager
- if (!this.configManager) {
- console.warn(`[BlockManager] 武器配置未预加载且ConfigManager不可用,无法获取武器: ${weaponName}`);
- return null;
- }
-
- console.log(`[BlockManager] 从ConfigManager中查找武器: ${weaponName}`);
- const allWeapons = this.configManager.getAllWeapons();
- return allWeapons.find(weapon => weapon.name === weaponName) || null;
- }
- // 设置事件监听器
- private setupEventListeners() {
- const eventBus = EventBus.getInstance();
-
- // 监听重置方块管理器事件
- eventBus.on(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
-
- // 监听方块生成事件
- eventBus.on(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this);
-
- // 移除GAME_START事件监听,避免与GameBlockSelection重复生成方块
- // eventBus.on(GameEvents.GAME_START, this.onGameStartEvent, this);
-
- // 监听波次完成事件(每波结束后生成新方块)
- eventBus.on(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this);
- // 监听敌人开始生成事件(开启第4步教程)
- eventBus.on(GameEvents.ENEMY_SPAWNING_STARTED, this.onEnemySpawningStartedEvent, this);
-
- // 移除敌人对玩家方块造成伤害事件监听,因为抛掷物不攻击玩家方块
- // eventBus.on(GameEvents.ENEMY_DAMAGE_PLAYER_BLOCK, this.onEnemyDamagePlayerBlockEvent, this);
- }
-
- // 处理重置方块管理器事件
- private onResetBlockManagerEvent() {
- console.log('[BlockManager] 接收到重置方块管理器事件');
- this.onGameReset();
- }
-
- // 处理方块生成事件
- private onGenerateBlocksEvent() {
- console.log('[BlockManager] 接收到方块生成事件');
- this.generateRandomBlocksInKuang();
- // 引导:指向可拖拽的方块 - 使用步骤索引让GuideUIController使用配置的节点
- this.scheduleOnce(() => {
- if (this.guideUIController && this.block1Container) {
- // 传入步骤索引0,让GuideUIController使用配置的fingerStartNodes和fingerTargetNodes
- this.guideUIController.createPointingAnimation('guild_1', undefined, 0);
- void 0;
- }
- }, 0);
- }
- // 敌人开始生成事件:进入教程第4步,并显示Block3指引
- private onEnemySpawningStartedEvent() {
- console.log('[BlockManager] 接收到敌人生成开始事件');
- try {
- const levelOk = !!this.saveDataManager && typeof this.saveDataManager.getCurrentLevel === 'function' && this.saveDataManager.getCurrentLevel() === 1;
- const sessionOk = !!this.session && typeof this.session.getRefreshUsageCount === 'function' && typeof this.session.getAddBallUsageCount === 'function'
- && this.session.getRefreshUsageCount() === 0 && this.session.getAddBallUsageCount() === 0;
- if (!levelOk || !sessionOk) return;
- // 仅当处于第3步(等待游戏开始)时推进到第4步
- if (this._tutorialStep >= 3 && this._tutorialStep < 4) {
- this._tutorialStep = 4;
- if (this.guideUIController) {
- // 运行时注入:将已放置在 _tutorialTargetGrids 指定位置的“I”型方块设为第4步拖拽起点
- try {
- const targetGridNames = Array.isArray(this._tutorialTargetGrids) ? this._tutorialTargetGrids : [];
- const gridA = targetGridNames[0] ? this.findGridNodeByName(targetGridNames[0]) : null;
- const gridB = targetGridNames[1] ? this.findGridNodeByName(targetGridNames[1]) : null;
- const rowColA = gridA ? this.getGridRowCol(gridA) : null;
- const rowColB = gridB ? this.getGridRowCol(gridB) : null;
-
- if (rowColA && rowColB && this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
- let iBlock: Node = null;
- for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
- const block = this.placedBlocksContainer.children[i];
- const shapeId = this.getBlockShape(block);
- const occ = block['occupiedGrids'] || [];
- const hasA = occ.some(g => g.row === rowColA.row && g.col === rowColA.col);
- const hasB = occ.some(g => g.row === rowColB.row && g.col === rowColB.col);
- if (shapeId === 'I' && hasA && hasB) {
- iBlock = block;
- break;
- }
- }
- if (iBlock) {
- this.guideUIController.fingerStartNodes[3] = iBlock;
- console.log(`[BlockManager] 教程第4步拖拽起点已注入为已放置的“I”型方块: ${iBlock.name}`);
- } else {
- console.warn('[BlockManager] 未找到占用 Grid_3_1/Grid_4_1 的“I”型方块,指引将使用默认兜底位置');
- }
- }
- } catch (e) {
- console.warn(`[BlockManager] 注入教程第4步拖拽起点失败: ${e}`);
- }
- // 使用步骤索引3创建拖拽动画(起点为注入的方块,终点为编辑器配置的目标节点)
- this.guideUIController.showDragAnimationForStep(3);
- }
- console.log('[BlockManager] 教程进入第4步并显示Block3指引');
- }
- } catch (e) {
- console.warn(`[BlockManager] 处理 ENEMY_SPAWNING_STARTED 失败: ${e}`);
- }
- }
-
- // 处理游戏开始事件 - 已废弃,避免与GameBlockSelection重复生成方块
- // private onGameStartEvent() {
- // console.log('[BlockManager] 接收到游戏开始事件,生成初始方块');
- // this.generateRandomBlocksInKuang();
- // }
-
- // 处理波次完成事件
- private onWaveCompletedEvent() {
- console.log('[BlockManager] 接收到波次完成事件,生成新方块');
- this.generateRandomBlocksInKuang();
- // 引导:波次结束后新生成方块也展示指引 - 使用步骤索引让GuideUIController使用配置的节点
- this.scheduleOnce(() => {
- if (this.guideUIController && this.block1Container) {
- // 传入步骤索引0,让GuideUIController使用配置的fingerStartNodes和fingerTargetNodes
- this.guideUIController.createPointingAnimation('guild_1', undefined, 0);
- void 0;
- }
- }, 0);
- }
-
-
- /**
- * 摧毁玩家方块
- */
- private destroyPlayerBlock(blockNode: Node) {
- console.log(`[BlockManager] 摧毁玩家方块: ${blockNode.name}`);
-
- // 清理方块占用的网格位置
- this.clearOccupiedPositions(blockNode);
-
- // 播放摧毁效果
- this.playBlockDestroyEffect(blockNode);
-
- // 延迟销毁节点,让效果播放完成
- this.scheduleOnce(() => {
- if (blockNode && blockNode.isValid) {
- blockNode.destroy();
- }
- }, 0.5);
- }
-
- /**
- * 播放方块受伤效果
- */
- private playBlockDamageEffect(blockNode: Node) {
- // 简单的闪烁效果
- const originalOpacity = blockNode.getComponent(Sprite)?.color.a || 255;
-
- tween(blockNode)
- .to(0.1, { scale: new Vec3(0.9, 0.9, 1) })
- .to(0.1, { scale: new Vec3(1, 1, 1) })
- .start();
-
- // 颜色闪烁
- const sprite = blockNode.getComponent(Sprite);
- if (sprite) {
- const originalColor = new Color(sprite.color);
- sprite.color = new Color(255, 100, 100, originalOpacity); // 红色闪烁
-
- this.scheduleOnce(() => {
- if (sprite && sprite.node && sprite.node.isValid) {
- sprite.color = originalColor;
- }
- }, 0.2);
- }
- }
-
- /**
- * 播放方块摧毁效果
- */
- private playBlockDestroyEffect(blockNode: Node) {
- // 缩放消失效果
- tween(blockNode)
- .to(0.3, { scale: new Vec3(0, 0, 1) })
- .start();
-
- // 透明度消失效果
- const sprite = blockNode.getComponent(Sprite);
- if (sprite) {
- tween(sprite)
- .to(0.3, { color: new Color(sprite.color.r, sprite.color.g, sprite.color.b, 0) })
- .start();
- }
- }
-
- start() {
- console.log('[BlockManager] 开始初始化BlockManager');
-
- // 获取配置管理器
- this.configManager = ConfigManager.getInstance();
- if (!this.configManager) {
- console.error('[BlockManager] 无法获取ConfigManager实例');
- } else {
- console.log('[BlockManager] ConfigManager实例获取成功,配置加载状态:', this.configManager.isConfigLoaded());
- }
-
- // 获取关卡配置管理器
- this.levelConfigManager = LevelConfigManager.getInstance();
- if (!this.levelConfigManager) {
- console.error('[BlockManager] 无法获取LevelConfigManager实例');
- } else {
- console.log('[BlockManager] LevelConfigManager实例获取成功');
- }
-
- // 获取BundleLoader实例
- this.bundleLoader = BundleLoader.getInstance();
- // 如果没有指定GridContainer,尝试找到它
- if (!this.gridContainer) {
- this.gridContainer = find('Canvas/GameLevelUI/GameArea/GridContainer');
- if (!this.gridContainer) {
- console.error('找不到GridContainer节点');
- return;
- }
- }
-
- // 如果没有指定kuangContainer,尝试找到它
- if (!this.kuangContainer) {
- this.kuangContainer = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang');
- if (!this.kuangContainer) {
- console.error('找不到kuang节点');
- return;
- }
- }
-
- // 如果没有指定Block1Container,尝试找到它
- if (!this.block1Container) {
- this.block1Container = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block1');
- if (!this.block1Container) {
- console.error('找不到Block1节点');
- return;
- }
- }
-
- // 如果没有指定Block2Container,尝试找到它
- if (!this.block2Container) {
- this.block2Container = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block2');
- if (!this.block2Container) {
- console.error('找不到Block2节点');
- return;
- }
- }
-
- // 如果没有指定Block3Container,尝试找到它
- if (!this.block3Container) {
- this.block3Container = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block3');
- if (!this.block3Container) {
- console.error('找不到Block3节点');
- return;
- }
- }
-
- // 如果没有指定coinLabelNode,尝试找到它
- if (!this.coinLabelNode) {
- this.coinLabelNode = find('Canvas/GameLevelUI/CoinNode/CoinLabel');
- if (!this.coinLabelNode) {
- console.error('找不到CoinLabel节点');
- return;
- }
- }
-
- // 如果没有指定placedBlocksContainer,尝试找到它
- if (!this.placedBlocksContainer) {
- this.placedBlocksContainer = find('Canvas/GameLevelUI/GameArea/PlacedBlocks');
- }
-
- // 如果没有指定价格节点,尝试找到它们
- if (!this.block1PriceNode) {
- this.block1PriceNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block1/db01/Price');
- if (!this.block1PriceNode) {
- console.warn('找不到Block1价格节点');
- }
- }
-
- if (!this.block2PriceNode) {
- this.block2PriceNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block2/db01/Price');
- if (!this.block2PriceNode) {
- console.warn('找不到Block2价格节点');
- }
- }
-
- if (!this.block3PriceNode) {
- this.block3PriceNode = find('Canvas/GameLevelUI/BlockSelectionUI/diban/kuang/Block3/db01/Price');
- if (!this.block3PriceNode) {
- console.warn('找不到Block3价格节点');
- }
- }
-
- // 确保有PlacedBlocks节点用于存放已放置的方块
- this.ensurePlacedBlocksNode();
-
- // 获取数据管理器
- this.saveDataManager = SaveDataManager.getInstance();
- this.session = LevelSessionManager.inst;
-
- // 初始化玩家金币显示
- this.updateCoinDisplay();
-
- // 初始化网格信息
- this.initGridInfo();
-
- // 初始化网格占用情况
- this.initGridOccupationMap();
-
- // 设置事件监听器
- this.setupEventListeners();
- // 新手引导控制器初始化(从 Canvas 获取已挂载的组件)
- const canvas = find('Canvas');
- this.guideUIController = canvas ? canvas.getComponent(GuideUIController) : null;
- if (!this.guideUIController) {
- console.warn('[BlockManager] Canvas未挂载GuideUIController组件,指引功能不可用');
- }
-
- // 调试绘制功能已迁移到GameBlockSelection
-
- // 移除自动生成方块逻辑,改为事件触发
- // 方块生成现在通过以下事件触发:
- // - GAME_START: 游戏开始时
- // - WAVE_COMPLETED: 每波敌人消灭后
- // - GENERATE_BLOCKS: 手动触发生成
- }
-
- // 确保有PlacedBlocks节点
- ensurePlacedBlocksNode() {
- // 如果已经通过拖拽设置了节点,直接使用
- if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
- return;
- }
-
- // 尝试查找节点(优先 GameArea)
- this.placedBlocksContainer = find('Canvas/GameLevelUI/GameArea/PlacedBlocks');
- if (this.placedBlocksContainer) {
- return;
- }
-
- // 如果找不到,创建新节点并优先挂到 GameArea
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- const gameLevelUI = find('Canvas/GameLevelUI');
- this.placedBlocksContainer = new Node('PlacedBlocks');
- if (gameArea) {
- gameArea.addChild(this.placedBlocksContainer);
- console.log('已在GameArea下创建PlacedBlocks节点');
- } else if (gameLevelUI) {
- gameLevelUI.addChild(this.placedBlocksContainer);
- console.warn('[BlockManager] 未找到GameArea,PlacedBlocks暂挂GameLevelUI');
- } else {
- cc.director.getScene()?.addChild(this.placedBlocksContainer);
- console.warn('[BlockManager] 未找到GameLevelUI和GameArea,PlacedBlocks暂挂场景根节点');
- }
- if (!this.placedBlocksContainer.getComponent(UITransform)) {
- this.placedBlocksContainer.addComponent(UITransform);
- }
- }
-
- // 初始化网格信息
- initGridInfo() {
- if (!this.gridContainer || this.gridInitialized) return;
- this.gridNodes = [];
- for (let row = 0; row < this.GRID_ROWS; row++) {
- this.gridNodes[row] = [];
- }
-
- for (let i = 0; i < this.gridContainer.children.length; i++) {
- const grid = this.gridContainer.children[i];
- if (grid.name.startsWith('Grid_')) {
- const parts = grid.name.split('_');
- if (parts.length === 3) {
- const row = parseInt(parts[1]);
- const col = parseInt(parts[2]);
- if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
- this.gridNodes[row][col] = grid;
- }
- }
- }
- }
- // 动态计算网格间距,适应不同分辨率
- this.calculateGridSpacing();
- this.gridInitialized = true;
- }
- // 动态计算网格间距
- private calculateGridSpacing() {
- // 优先使用相邻行之间的距离计算间距
- if (this.GRID_ROWS > 1 && this.GRID_COLS > 0) {
- if (this.gridNodes[0][0] && this.gridNodes[1][0]) {
- const pos1 = this.gridNodes[0][0].position;
- const pos2 = this.gridNodes[1][0].position;
- this.gridSpacing = Math.abs(pos2.y - pos1.y);
- console.log(`动态计算网格间距(行间距): ${this.gridSpacing}`);
- return;
- }
- }
-
- // 如果行间距计算失败,尝试使用相邻列之间的距离
- if (this.GRID_COLS > 1 && this.GRID_ROWS > 0) {
- if (this.gridNodes[0][0] && this.gridNodes[0][1]) {
- const pos1 = this.gridNodes[0][0].position;
- const pos2 = this.gridNodes[0][1].position;
- this.gridSpacing = Math.abs(pos2.x - pos1.x);
- console.log(`动态计算网格间距(列间距): ${this.gridSpacing}`);
- return;
- }
- }
- // 如果都失败了,保持默认值
- console.warn(`无法动态计算网格间距,使用默认值: ${this.gridSpacing}`);
- }
- // 获取当前网格间距
- public getGridSpacing(): number {
- return this.gridSpacing;
- }
- // 初始化网格占用情况
- initGridOccupationMap() {
- this.gridOccupationMap = [];
- for (let row = 0; row < this.GRID_ROWS; row++) {
- const rowArray: number[] = [];
- for (let col = 0; col < this.GRID_COLS; col++) {
- rowArray.push(0);
- }
- this.gridOccupationMap.push(rowArray);
- }
- }
-
- // 在kuang下生成三个方块(基于关卡配置)
- private async generateRandomBlocksInKuang() {
- this.clearBlocks();
- // 优先检查预加载的武器配置
- if (this.isWeaponsConfigPreloaded) {
- const preloadedConfig = this.getPreloadedWeaponsConfig();
- if (preloadedConfig && preloadedConfig.weapons && preloadedConfig.blockSizes) {
- console.log('[BlockManager] 使用预加载的武器配置生成方块');
- // 直接使用预加载配置继续生成方块
- // 跳过ConfigManager的等待逻辑
- } else {
- console.warn('[BlockManager] 预加载配置不完整,回退到ConfigManager模式');
- this.isWeaponsConfigPreloaded = false;
- }
- }
- // 如果没有预加载配置,检查ConfigManager
- if (!this.isWeaponsConfigPreloaded) {
- // 检查配置管理器是否可用
- if (!this.configManager) {
- console.error('[BlockManager] ConfigManager实例未找到,延迟2秒后重试');
- this.scheduleOnce(() => {
- this.generateRandomBlocksInKuang();
- }, 2.0);
- return;
- }
- // 检查武器配置是否已加载(不需要等待所有配置完成)
- const weaponsConfigLoaded = !!this.configManager['weaponsConfig'];
- const blockSizesAvailable = weaponsConfigLoaded && !!this.configManager['weaponsConfig'].blockSizes;
- if (!weaponsConfigLoaded) {
- console.log('[BlockManager] 武器配置未加载完成,延迟2秒后重试生成方块');
- this.scheduleOnce(() => {
- this.generateRandomBlocksInKuang();
- }, 2.0);
- return;
- }
- if (!blockSizesAvailable) {
- console.log('[BlockManager] 武器配置已加载但blockSizes缺失,延迟2秒后重试');
- this.scheduleOnce(() => {
- this.generateRandomBlocksInKuang();
- }, 2.0);
- return;
- }
- }
- if (this.blockPrefabs.length === 0) {
- console.error('没有可用的预制体');
- return;
- }
-
- // 使用Block1、Block2、Block3节点作为方块容器
- const blockContainers = [
- this.block1Container,
- this.block2Container,
- this.block3Container
- ];
-
- // 检查所有Block容器是否存在
- for (let i = 0; i < blockContainers.length; i++) {
- if (!blockContainers[i]) {
- console.error(`找不到Block${i + 1}节点`);
- return;
- }
- }
-
- // 方块在各自容器中的位置偏移(相对于容器中心)
- const offsets = [
- new Vec3(0, 0, 0), // Block1中心
- new Vec3(0, 0, 0), // Block2中心
- new Vec3(0, 0, 0) // Block3中心
- ];
-
- // 价格节点使用装饰器属性
- const priceNodes = [
- this.block1PriceNode,
- this.block2PriceNode,
- this.block3PriceNode
- ];
-
- // 获取当前关卡的武器配置列表
- const levelWeapons = await this.getCurrentLevelWeapons();
- // 是否处于新手引导的首次生成场景(第1关、未使用过刷新/加球、且尚未放置方块)
- const isNewbieTutorial = this.isNewbieTutorialContext();
- if (isNewbieTutorial) {
- console.log('[BlockManager] 检测到新手引导场景,优先生成固定形状的方块');
- }
- // 第二波固定形状场景(第4步完成后首次波次结束进入第二次选方块)
- const isSecondWaveFixed = this.shouldApplySecondWaveFixedShapes();
- if (isSecondWaveFixed) {
- console.log('[BlockManager] 检测到第二波固定形状场景,按要求生成固定形状');
- }
-
- for (let i = 0; i < 3; i++) {
- let weaponConfig: WeaponConfig | null = null;
-
- // 优先使用关卡配置的武器,确保符合关卡设计
- if (levelWeapons.length > 0) {
- const randomWeaponName = levelWeapons[Math.floor(Math.random() * levelWeapons.length)];
- weaponConfig = this.getWeaponConfigByName(randomWeaponName);
-
- if (!weaponConfig) {
- console.warn(`关卡配置的武器 "${randomWeaponName}" 在武器配置文件中未找到`);
- }
- }
-
- // 如果关卡没有配置武器或获取失败,使用随机武器
- if (!weaponConfig) {
- weaponConfig = this.configManager.getRandomWeapon();
- }
-
- // 最后的兜底处理
- if (!weaponConfig) {
- console.warn('无法获取武器配置,使用默认武器');
- // 尝试获取一个基础武器作为兜底
- const allWeapons = this.configManager.getAllWeapons();
- if (allWeapons.length > 0) {
- weaponConfig = allWeapons[0];
- }
- }
-
- if (!weaponConfig) {
- console.error(`无法获取第 ${i + 1} 个武器配置`);
- continue;
- }
-
- // 选择形状ID:新手引导优先使用固定形状,否则随机
- let targetShapeId: string | null = null;
- if (isNewbieTutorial) {
- targetShapeId = this.getTutorialShapeForIndex(i, weaponConfig);
- console.log(`[BlockManager] 新手引导为武器 ${weaponConfig.name} 指定形状: ${targetShapeId ?? '未找到合适形状,回退随机'}`);
- }
- // 第二波固定形状选择(优先于随机)
- if (!targetShapeId && isSecondWaveFixed) {
- targetShapeId = this.getSecondWaveShapeForIndex(i, weaponConfig);
- console.log(`[BlockManager] 第二波固定为武器 ${weaponConfig.name} 指定形状: ${targetShapeId ?? '未找到合适形状,回退随机'}`);
- }
- if (!targetShapeId) {
- try {
- const shapeCosts = weaponConfig.inGameCostConfig?.shapeCosts;
- if (shapeCosts && Object.keys(shapeCosts).length > 0) {
- const availableShapes = Object.keys(shapeCosts);
- targetShapeId = availableShapes[Math.floor(Math.random() * availableShapes.length)];
- console.log(`[BlockManager] 为武器 ${weaponConfig.name} 随机选择形状: ${targetShapeId}`);
- console.log(`[BlockManager] 可用形状列表: ${availableShapes.join(', ')}`);
- } else {
- console.warn(`[BlockManager] 武器 ${weaponConfig.name} 没有配置shapeCosts或为空`);
- }
- } catch (error) {
- console.warn(`[BlockManager] 无法从武器配置获取形状信息: ${error}`);
- }
- }
-
- // 基于武器配置和目标形状选择合适的预制体
- console.log(`[BlockManager] 开始为武器 ${weaponConfig.name} 选择预制体,目标形状: ${targetShapeId || '未指定'}`);
- const prefab = this.selectPrefabForWeapon(weaponConfig, targetShapeId);
- console.log(`[BlockManager] 预制体选择结果: ${prefab ? '成功' : '失败'}`);
- if (!prefab) {
- console.error(`无法为武器 ${weaponConfig.name} 选择合适的预制体`);
- continue;
- }
-
- const block = instantiate(prefab);
- blockContainers[i].addChild(block);
-
- block.position = offsets[i];
-
- // 设置方块名称
- block.name = `WeaponBlock_${weaponConfig.id}`;
-
- // 保存武器配置到方块
- this.blockWeaponConfigs.set(block, weaponConfig);
- block['weaponConfig'] = weaponConfig;
- block['weaponId'] = weaponConfig.id;
-
- this.originalPositions.set(block, offsets[i].clone());
- this.blockLocations.set(block, `block${i + 1}`);
- this.blocks.push(block);
-
- // 关联Block容器与方块(替代原来的dbNode关联)
- this.associateBlockContainerWithBlock(block, blockContainers[i]);
-
- // 设置方块位置信息到blockLocations映射中
- const blockLocation = `block${i + 1}`;
- this.blockLocations.set(block, blockLocation);
-
- // 设置方块的武器外观,传入目标形状ID以确保正确加载图片
- this.setupBlockWeaponVisual(block, weaponConfig, targetShapeId);
-
- // 设置BlockInfo组件信息,传入容器位置信息
- this.setupBlockInfo(block, weaponConfig, targetShapeId, blockLocation);
-
- // 处理价格显示 - 在BlockInfo设置完成后调用,确保能正确读取shapePrice
- if (priceNodes[i]) {
- this.blockPriceMap.set(block, priceNodes[i]);
- priceNodes[i].active = true;
-
- // 根据武器配置和方块形状设置价格
- this.setBlockPriceByWeaponConfig(block, priceNodes[i]);
- } else {
- console.warn(`Block${i + 1}容器下找不到Price节点`);
- }
-
- // 为新生成的方块添加标签
- BlockTag.addTag(block);
- console.log(`[BlockManager] 为方块 ${block.name} 添加标签,UUID: ${block.uuid}`);
- }
-
- // 通过事件机制通知GameBlockSelection为新生成的方块设置拖拽事件
- if (this.blocks.length > 0) {
- const eventBus = EventBus.getInstance();
- eventBus.emit(GameEvents.SETUP_BLOCK_DRAG_EVENTS, this.blocks.slice());
- console.log(`[BlockManager] 发送方块拖拽事件设置请求,方块数量: ${this.blocks.length}`);
- }
-
- this.updateCoinDisplay();
- // 第二波固定生成已应用后标记,避免后续波次重复
- if (isSecondWaveFixed) {
- this._secondWaveFixedApplied = true;
- }
- }
- /**
- * 新手引导环境判定:仅在第1关、未使用过刷新/加球、且未放置任何方块时生效
- */
- private isNewbieTutorialContext(): boolean {
- try {
- const levelOk = !!this.saveDataManager && typeof this.saveDataManager.getCurrentLevel === 'function' && this.saveDataManager.getCurrentLevel() === 1;
- const sessionOk = !!this.session && typeof this.session.getRefreshUsageCount === 'function' && typeof this.session.getAddBallUsageCount === 'function'
- && this.session.getRefreshUsageCount() === 0 && this.session.getAddBallUsageCount() === 0;
- // 教程在第1-4步期间保持限制,第4步为空目标表示不限制
- const tutorialActive = this._tutorialStep < 5;
- return levelOk && sessionOk && tutorialActive;
- } catch (e) {
- console.warn(`[BlockManager] 新手引导上下文检测失败: ${e}`);
- return false;
- }
- }
- /**
- * 扩展教程事件上下文:用于第5-6步仅触发事件,不施加位置限制
- */
- private isExtendedTutorialEventContext(): boolean {
- try {
- const levelOk = !!this.saveDataManager && typeof this.saveDataManager.getCurrentLevel === 'function' && this.saveDataManager.getCurrentLevel() === 1;
- const sessionOk = !!this.session && typeof this.session.getRefreshUsageCount === 'function' && typeof this.session.getAddBallUsageCount === 'function'
- && this.session.getRefreshUsageCount() === 0 && this.session.getAddBallUsageCount() === 0;
- return this._tutorialStep >= 5 && this._tutorialStep < 7 && levelOk && sessionOk;
- } catch (e) {
- console.warn(`[BlockManager] 扩展教程事件上下文检测失败: ${e}`);
- return false;
- }
- }
- // 新增:教程阶段对场上已放置方块的移动控制
- public canMovePlacedBlocks(): boolean {
- try {
- // 非新手引导环境允许自由移动
- if (!this.isNewbieTutorialContext() && !this.isExtendedTutorialEventContext()) {
- return true;
- }
- // 新手引导阶段:仅在第4步允许移动,或第6步完成(_tutorialStep >= 7)后恢复自由移动
- return this._tutorialStep === 4 || this._tutorialStep >= 7;
- } catch (e) {
- return true;
- }
- }
- /**
- * 新手引导下为第 i 个容器选择固定形状(I、S、L),并确保形状在该武器可用
- */
- private getTutorialShapeForIndex(index: number, weaponConfig: WeaponConfig): string | null {
- const preferredOrder = ['I', 'H-I', 'L'];
- const desired = preferredOrder[index % preferredOrder.length];
- const shapeCosts = weaponConfig?.inGameCostConfig?.shapeCosts || null;
- if (shapeCosts && typeof shapeCosts === 'object') {
- if (shapeCosts[desired] !== undefined) {
- return desired;
- }
- // 选择首个在该武器可用的优先形状
- const fallbackPreferred = preferredOrder.find(s => shapeCosts[s] !== undefined);
- if (fallbackPreferred) {
- return fallbackPreferred;
- }
- const anyShape = Object.keys(shapeCosts)[0];
- return anyShape || null;
- }
- return null;
- }
-
- /**
- * 第二波(教程第4步完成后的首次波次结束后)固定形状判定
- */
- private shouldApplySecondWaveFixedShapes(): boolean {
- try {
- const levelOk = !!this.saveDataManager && typeof this.saveDataManager.getCurrentLevel === 'function' && this.saveDataManager.getCurrentLevel() === 1;
- const sessionOk = !!this.session && typeof this.session.getRefreshUsageCount === 'function' && typeof this.session.getAddBallUsageCount === 'function'
- && this.session.getRefreshUsageCount() === 0 && this.session.getAddBallUsageCount() === 0;
- // 第4步完成后(_tutorialStep >= 5),且未应用过第二波固定形状
- return this._tutorialStep >= 5 && levelOk && sessionOk && !this._secondWaveFixedApplied;
- } catch (e) {
- console.warn(`[BlockManager] 第二波固定形状上下文检测失败: ${e}`);
- return false;
- }
- }
-
- /**
- * 第二波固定形状选择:Block2 -> “H-I”,Block3 -> “I”,Block1 -> “I”
- * 如果目标形状在该武器不可用,按固定列表内可用形状回退
- */
- private getSecondWaveShapeForIndex(index: number, weaponConfig: WeaponConfig): string | null {
- const preferredOrder = ['I', 'H-I', 'I'];
- const desired = preferredOrder[index % preferredOrder.length];
- const shapeCosts = weaponConfig?.inGameCostConfig?.shapeCosts || null;
- if (shapeCosts && typeof shapeCosts === 'object') {
- if (shapeCosts[desired] !== undefined) {
- return desired;
- }
- const fallbackPreferred = preferredOrder.find(s => shapeCosts[s] !== undefined);
- if (fallbackPreferred) {
- return fallbackPreferred;
- }
- const anyShape = Object.keys(shapeCosts)[0];
- return anyShape || null;
- }
- return null;
- }
-
- // 将db节点与方块关联
- // 将Block容器与方块关联
- associateBlockContainerWithBlock(block: Node, blockContainer: Node) {
- block['blockContainer'] = blockContainer;
-
- block.on(Node.EventType.TRANSFORM_CHANGED, () => {
- if (blockContainer && block.parent) {
- const location = this.blockLocations.get(block);
-
- if (location === 'grid') {
- // 方块在网格区域时,隐藏整个db标签节点
- this.hideDbLabel(block);
- return;
- }
-
- // 检查方块是否正在被拖动,如果是则隐藏整个db标签节点
- if (block['isDragging']) {
- this.hideDbLabel(block);
- return;
- }
-
- // 方块在Block容器区域时,显示整个db标签节点
- if (location && location.startsWith('block')) {
- this.showDbLabel(block);
- }
- }
- });
- }
-
- // 保留原方法以兼容可能的调用(现在委托给新方法)
- associateDbNodeWithBlock(block: Node, dbNode: Node) {
- this.associateBlockContainerWithBlock(block, dbNode);
- }
-
- // 更新金币显示
- updateCoinDisplay() {
- if (this.coinLabelNode) {
- const label = this.coinLabelNode.getComponent(Label);
- if (label) {
- const coins = this.session.getCoins();
- label.string = coins.toString();
- }
- }
- }
-
- // 获取方块价格
- getBlockPrice(block: Node): number {
- const priceNode = this.blockPriceMap.get(block);
- if (priceNode) {
- const label = priceNode.getComponent(Label);
- if (label) {
- const price = parseInt(label.string);
- if (!isNaN(price)) {
- return price;
- }
- }
- }
- return 50;
- }
-
- // 隐藏价格标签
- hidePriceLabel(block: Node) {
- const priceNode = this.blockPriceMap.get(block);
- if (priceNode) {
- priceNode.active = false;
- }
- }
-
- // 显示价格标签
- showPriceLabel(block: Node) {
- const priceNode = this.blockPriceMap.get(block);
- if (priceNode) {
- priceNode.active = true;
- }
- }
-
- // 隐藏整个db标签节点(包括价格标签)
- hideDbLabel(originalBlock: Node) {
- // 检查方块是否已经放置成功(不在原始容器中),如果是则不需要隐藏价格标签
- const blockLocation = this.blockLocations.get(originalBlock);
- if (blockLocation === 'grid' || originalBlock['placedBefore']) {
- // 已放置成功的方块(包括合成后的方块)不需要隐藏价格标签
- console.log(`[BlockManager] 方块 ${originalBlock.name} 已放置成功,跳过隐藏价格标签操作`);
- return;
- }
-
- // 只有在kuang区域的方块才需要隐藏价格标签
- if (!originalBlock.parent ||
- (originalBlock.parent !== this.block1Container &&
- originalBlock.parent !== this.block2Container &&
- originalBlock.parent !== this.block3Container)) {
- console.log(`[BlockManager] 方块 ${originalBlock.name} 不在原始容器中,跳过隐藏价格标签操作`);
- return;
- }
-
- // 隐藏价格标签
- this.hidePriceLabel(originalBlock);
- console.log(`[BlockManager] 隐藏价格标签: ${originalBlock.name}`);
-
- // 根据原始方块找到对应的db节点
- let dbNode: Node = null;
- if (originalBlock.parent === this.block1Container) {
- dbNode = this.block1DbNode;
- } else if (originalBlock.parent === this.block2Container) {
- dbNode = this.block2DbNode;
- } else if (originalBlock.parent === this.block3Container) {
- dbNode = this.block3DbNode;
- }
-
- console.log(`[BlockManager] db标签节点: ${dbNode ? dbNode.name : 'null'}`);
- if (dbNode) {
- dbNode.active = false;
- console.log(`[BlockManager] 隐藏db标签节点: ${dbNode.name}`);
- } else {
- console.log(`[BlockManager] 未找到对应的db节点`);
- }
- }
-
- // 显示整个db标签节点(包括价格标签)
- showDbLabel(originalBlock: Node) {
- // 检查方块是否已经放置成功(不在原始容器中),如果是则不需要显示价格标签
- const blockLocation = this.blockLocations.get(originalBlock);
- if (blockLocation === 'grid' || originalBlock['placedBefore']) {
- // 已放置成功的方块(包括合成后的方块)不需要显示价格标签
- console.log(`[BlockManager] 方块 ${originalBlock.name} 已放置成功,跳过显示价格标签操作`);
- return;
- }
-
- // 只有在kuang区域的方块才需要显示价格标签
- if (!originalBlock.parent ||
- (originalBlock.parent !== this.block1Container &&
- originalBlock.parent !== this.block2Container &&
- originalBlock.parent !== this.block3Container)) {
- console.log(`[BlockManager] 方块 ${originalBlock.name} 不在原始容器中,跳过显示价格标签操作`);
- return;
- }
-
- // 根据原始方块找到对应的db节点
- let dbNode: Node = null;
- if (originalBlock.parent === this.block1Container) {
- dbNode = this.block1DbNode;
- } else if (originalBlock.parent === this.block2Container) {
- dbNode = this.block2DbNode;
- } else if (originalBlock.parent === this.block3Container) {
- dbNode = this.block3DbNode;
- }
-
- console.log(`[BlockManager] db标签节点: ${dbNode ? dbNode.name : 'null'}`);
- if (dbNode) {
- dbNode.active = true;
- console.log(`[BlockManager] 显示db标签节点: ${dbNode.name}`);
- } else {
- console.log(`[BlockManager] 未找到对应的db节点`);
- }
- // 显示价格标签
- this.showPriceLabel(originalBlock);
- }
-
- // 扣除玩家金币
- deductPlayerCoins(amount: number): boolean {
- const success = this.session.spendCoins(amount);
- if (success) {
- this.updateCoinDisplay();
- }
- return success;
- }
-
- // 显示金币不足时的价格标签闪烁效果
- showInsufficientCoinsEffect(block: Node) {
- const priceNode = this.blockPriceMap.get(block);
- if (!priceNode) {
- console.warn('[BlockManager] 找不到方块对应的价格标签');
- return;
- }
-
- const label = priceNode.getComponent(Label);
- if (!label) {
- console.warn('[BlockManager] 价格节点缺少Label组件');
- return;
- }
- // 首次缓存原始颜色,后续使用缓存避免在红色中被覆盖
- if (!this.priceLabelOriginalColors.has(priceNode)) {
- this.priceLabelOriginalColors.set(priceNode, label.color.clone());
- }
- const cachedOriginal = this.priceLabelOriginalColors.get(priceNode)!;
- const originalColor = cachedOriginal.clone();
-
- // 设置红色
- const redColor = new Color(255, 0, 0, 255);
- // 停止已有动画,避免堆叠导致颜色停留在红色
- Tween.stopAllByTarget(label);
- // 统一从原始颜色开始,避免中途状态影响效果
- label.color = originalColor.clone();
- // 创建闪烁动画:变红 -> 恢复原色,重复3次,最后确保恢复原色
- tween(label)
- .to(0.2, { color: redColor })
- .to(0.2, { color: originalColor })
- .to(0.2, { color: redColor })
- .to(0.2, { color: originalColor })
- .to(0.2, { color: redColor })
- .to(1.0, { color: originalColor })
- .start();
-
- // 发送显示资源不足Toast事件
- EventBus.getInstance().emit(GameEvents.SHOW_RESOURCE_TOAST, {
- message: '金币不足',
- duration: 2.0
- });
-
- console.log('[BlockManager] 显示金币不足效果');
- }
-
- // 归还玩家金币
- refundPlayerCoins(amount: number) {
- this.session.addCoins(amount);
- this.updateCoinDisplay();
- }
-
- // 设置拖拽事件方法已迁移到GameBlockSelection
-
-
- // 清除临时保存的占用状态
- clearTempStoredOccupiedGrids(block: Node) {
- const index = this.tempRemovedOccupiedGrids.findIndex(item => item.block === block);
- if (index === -1) return;
-
- this.tempRemovedOccupiedGrids.splice(index, 1);
- }
-
- // 清除特定方块的占用状态
- public clearOccupiedPositions(block: Node) {
- if (!this.gridInitialized) return;
-
- const occupiedGrids = block['occupiedGrids'];
- if (!occupiedGrids || occupiedGrids.length === 0) return;
-
- // 清除网格占用状态
- for (const grid of occupiedGrids) {
- if (grid.row >= 0 && grid.row < this.GRID_ROWS &&
- grid.col >= 0 && grid.col < this.GRID_COLS) {
- this.gridOccupationMap[grid.row][grid.col] = 0;
- }
- }
-
- // 清除方块的占用记录
- block['occupiedGrids'] = [];
- }
-
- // 尝试将方块放置到网格中
- tryPlaceBlockToGrid(block: Node): boolean {
- console.log(`[BlockManager] 尝试放置方块 ${block.name} 到网格`);
-
- if (!this.gridContainer || !this.gridInitialized) {
- console.log(`[BlockManager] 网格容器或网格未初始化`);
- return false;
- }
-
- let b1Node = block;
- if (block.name !== 'B1') {
- b1Node = block.getChildByName('B1');
- if (!b1Node) {
- console.log(`[BlockManager] 方块 ${block.name} 没有B1子节点`);
- return false;
- }
- }
-
- const b1WorldPos = b1Node.parent.getComponent(UITransform).convertToWorldSpaceAR(b1Node.position);
- const gridPos = this.gridContainer.getComponent(UITransform).convertToNodeSpaceAR(b1WorldPos);
-
- console.log(`[BlockManager] B1世界坐标:`, b1WorldPos);
- console.log(`[BlockManager] 网格本地坐标:`, gridPos);
-
- const gridSize = this.gridContainer.getComponent(UITransform).contentSize;
- const halfWidth = gridSize.width / 2;
- const halfHeight = gridSize.height / 2;
-
- const tolerance = this.gridSpacing * 0.5;
- if (gridPos.x < -halfWidth - tolerance || gridPos.x > halfWidth + tolerance ||
- gridPos.y < -halfHeight - tolerance || gridPos.y > halfHeight + tolerance) {
- console.log(`[BlockManager] 方块超出网格边界`);
- return false;
- }
-
- const nearestGrid = this.findNearestGridNode(gridPos);
- if (!nearestGrid) {
- console.log(`[BlockManager] 找不到最近的网格节点`);
- return false;
- }
- // 新手教程限制:只允许放置到指定网格
- if (this.isNewbieTutorialContext()) {
- const isValidTutorialPlacement = this.validateTutorialPlacement(block, nearestGrid);
- if (!isValidTutorialPlacement) {
- console.log(`[BlockManager] 新手教程:方块不能放置到此网格`);
- return false;
- }
- }
- // 扩展教程(第5-6步):只允许拖到指定格子
- if (this._tutorialStep >= 5 && this._tutorialStep < 7) {
- const basePair = this._tutorialStep >= 6 ? this._tutorialTargetGridsStep4 : this._tutorialTargetGridsStep2;
- if (basePair && basePair.length === 2) {
- const parse = (name: string) => {
- const m = name.match(/^Grid_(\d+)_(\d+)$/);
- return m ? { row: parseInt(m[1]), col: parseInt(m[2]) } : null;
- };
- const pairKey = (arr: string[]) => arr.slice().sort().join('|');
- const p0 = parse(basePair[0]);
- const p1 = parse(basePair[1]);
- if (p0 && p1) {
- let anchor = p0;
- if (p0.row !== p1.row) {
- anchor = p0.row < p1.row ? p0 : p1;
- } else if (p0.col !== p1.col) {
- anchor = p0.col < p1.col ? p0 : p1;
- }
- const horizontalPair = [`Grid_${anchor.row}_${anchor.col}`, `Grid_${anchor.row}_${anchor.col + 1}`];
- const verticalPair = [`Grid_${anchor.row}_${anchor.col}`, `Grid_${anchor.row + 1}_${anchor.col}`];
- const allowedPairs = new Set<string>([
- pairKey(horizontalPair),
- pairKey(verticalPair),
- pairKey(basePair),
- ]);
- const targetRowCol = this.getGridRowCol(nearestGrid);
- if (!targetRowCol) return false;
- const parts = this.getBlockParts(block);
- const occupiedNames: string[] = [];
- for (let i = 0; i < parts.length; i++) {
- const part = parts[i];
- const row = targetRowCol.row - part.y;
- const col = targetRowCol.col + part.x;
- occupiedNames.push(`Grid_${row}_${col}`);
- }
- const occupiedKey = pairKey(occupiedNames);
- if (!allowedPairs.has(occupiedKey)) {
- console.log(`[BlockManager] 扩展教程:方块不能放置到此网格`);
- return false;
- }
- }
- }
- }
-
- return this.tryPlaceBlockToSpecificGrid(block, nearestGrid);
- }
- /**
- * 验证新手教程中的方块放置是否有效
- */
- private validateTutorialPlacement(block: Node, targetGrid: Node): boolean {
- // 基础目标对(当前步骤)
- const basePair = this._tutorialStep >= 4 ? this._tutorialTargetGridsStep4
- : this._tutorialStep >= 2 ? this._tutorialTargetGridsStep2 : this._tutorialTargetGrids;
- if (!basePair || basePair.length !== 2) {
- return true; // 配置不完整不强制
- }
- // 辅助:解析与配对键
- const parse = (name: string) => {
- const m = name.match(/^Grid_(\d+)_(\d+)$/);
- return m ? { row: parseInt(m[1]), col: parseInt(m[2]) } : null;
- };
- const pairKey = (arr: string[]) => arr.slice().sort().join('|');
- const p0 = parse(basePair[0]);
- const p1 = parse(basePair[1]);
- if (!p0 || !p1) return true;
- // 选择锚点(行不同取较小行,否则取较小列)
- let anchor = p0;
- if (p0.row !== p1.row) {
- anchor = p0.row < p1.row ? p0 : p1;
- } else if (p0.col !== p1.col) {
- anchor = p0.col < p1.col ? p0 : p1;
- }
- // 从基础对推导允许的横/竖两种占位对
- const horizontalPair = [`Grid_${anchor.row}_${anchor.col}`, `Grid_${anchor.row}_${anchor.col + 1}`];
- const verticalPair = [`Grid_${anchor.row}_${anchor.col}`, `Grid_${anchor.row + 1}_${anchor.col}`];
- const allowedPairs = new Set<string>([
- pairKey(horizontalPair),
- pairKey(verticalPair),
- pairKey(basePair),
- ]);
- // 计算实际占用格子
- const targetRowCol = this.getGridRowCol(targetGrid);
- if (!targetRowCol) return false;
- const parts = this.getBlockParts(block);
- const occupiedNames: string[] = [];
- for (let i = 0; i < parts.length; i++) {
- const part = parts[i];
- const row = targetRowCol.row - part.y;
- const col = targetRowCol.col + part.x;
- occupiedNames.push(`Grid_${row}_${col}`);
- }
- const occupiedKey = pairKey(occupiedNames);
- const ok = allowedPairs.has(occupiedKey);
- if (!ok) {
- console.log(`[BlockManager] 新手教程:需要占用任一允许对,当前占用为 ${occupiedNames.join('、')}`);
- }
- return ok;
- }
- /**
- * 获取指定名称的网格节点
- */
- private findGridNodeByName(gridName: string): Node | null {
- if (!this.gridContainer || !this.gridInitialized) {
- return null;
- }
- for (let row = 0; row < this.GRID_ROWS; row++) {
- for (let col = 0; col < this.GRID_COLS; col++) {
- const gridNode = this.gridNodes[row][col];
- if (gridNode && gridNode.name === gridName) {
- return gridNode;
- }
- }
- }
- return null;
- }
-
- // 找到最近的网格节点
- public findNearestGridNode(position: Vec3): Node {
- if (!this.gridContainer || !this.gridInitialized) return null;
-
- let nearestNode: Node = null;
- let minDistance = Number.MAX_VALUE;
-
- for (let row = 0; row < this.GRID_ROWS; row++) {
- for (let col = 0; col < this.GRID_COLS; col++) {
- const grid = this.gridNodes[row][col];
- if (grid) {
- const distance = Vec3.distance(position, grid.position);
- if (distance < minDistance) {
- minDistance = distance;
- nearestNode = grid;
- }
- }
- }
- }
-
- if (minDistance > this.gridSpacing * 2) {
- return null;
- }
-
- return nearestNode;
- }
-
- // 尝试将方块放置到指定的网格节点
- tryPlaceBlockToSpecificGrid(block: Node, targetGrid: Node): boolean {
- let b1Node = block;
- if (block.name !== 'B1') {
- b1Node = block.getChildByName('B1');
- if (!b1Node) {
- return false;
- }
- }
-
- if (!this.canPlaceBlockAt(block, targetGrid)) {
- return false;
- }
-
- // 在放置前缓存一次教程上下文判定,避免放置后 hasPlacedBlocks 改变导致不触发
- const tutorialContextBeforePlacement = this.isNewbieTutorialContext();
-
- const gridCenterWorldPos = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(targetGrid.position);
- const targetWorldPos = gridCenterWorldPos.clone();
-
- const b1LocalPos = b1Node.position.clone();
-
- let rootTargetWorldPos;
- if (b1Node === block) {
- rootTargetWorldPos = targetWorldPos.clone();
- } else {
- rootTargetWorldPos = new Vec3(
- targetWorldPos.x - b1LocalPos.x,
- targetWorldPos.y - b1LocalPos.y,
- targetWorldPos.z
- );
- }
-
- const rootTargetLocalPos = block.parent.getComponent(UITransform).convertToNodeSpaceAR(rootTargetWorldPos);
-
- block.position = rootTargetLocalPos;
- this.markOccupiedPositions(block, targetGrid);
-
- // 当方块从kuang区域拖到网格时,恢复植物图标的正常缩放
- // 根据新的预制体结构,武器节点直接位于方块根节点下
- let weaponNode = block.getChildByName('Weapon');
-
- // 兼容旧结构:如果直接查找失败,尝试B1/Weapon路径
- if (!weaponNode && b1Node) {
- weaponNode = b1Node.getChildByName('Weapon');
- }
-
- if (weaponNode) {
- weaponNode.setScale(0.4, 0.4, 1.0);
- console.log(`[BlockManager] 方块 ${block.name} 放置到网格,植物图标缩放设置为0.4倍`);
- }
- // 引导:放置成功后隐藏指引与高亮
- if (this.guideUIController) {
- this.guideUIController.hideAllGuideUI();
- void 0;
- }
- // 新手教程:触发方块放置事件(使用放置前的上下文判定)
- if (tutorialContextBeforePlacement) {
- this.handleTutorialBlockPlacement(block, targetGrid);
- } else if (this.isExtendedTutorialEventContext()) {
- // 扩展步骤(第5-6步)也触发事件判断,但不进行位置限制
- this.handleTutorialBlockPlacement(block, targetGrid);
- }
-
- return true;
- }
-
- /**
- * 统一判断:拖拽放置步骤完成(占用目标格子对 + 可选期望方块)
- */
- private isTutorialPlacementCompleted(block: Node, targetGrid: Node, gridPair: string[], expectedBlock?: Node): boolean {
- if (!gridPair || gridPair.length !== 2) return false;
- if (expectedBlock) {
- const originContainer = (block as any)['blockContainer'] as Node | undefined;
- let matches = false;
- // 1) 期望为实际方块:直接等值
- if (block === expectedBlock) {
- matches = true;
- }
- // 2) 期望为容器:使用生成来源容器匹配
- if (!matches && originContainer && originContainer === expectedBlock) {
- matches = true;
- }
- // 3) 兼容:尚在容器层级下(未移动出容器)
- if (!matches) {
- let p = block.parent;
- while (p) {
- if (p === expectedBlock) { matches = true; break; }
- p = p.parent;
- }
- }
- if (!matches) {
- console.log(`[BlockManager] 教程:放置的方块未匹配期望(容器或生成来源)`);
- return false;
- }
- }
- const parse = (name: string) => {
- const m = name.match(/^Grid_(\d+)_(\d+)$/);
- return m ? { row: parseInt(m[1]), col: parseInt(m[2]) } : null;
- };
- const pairKey = (arr: string[]) => arr.slice().sort().join('|');
- const p0 = parse(gridPair[0]);
- const p1 = parse(gridPair[1]);
- if (!p0 || !p1) return false;
- let anchor = p0;
- if (p0.row !== p1.row) {
- anchor = p0.row < p1.row ? p0 : p1;
- } else if (p0.col !== p1.col) {
- anchor = p0.col < p1.col ? p0 : p1;
- }
- const horizontalPair = [`Grid_${anchor.row}_${anchor.col}`, `Grid_${anchor.row}_${anchor.col + 1}`];
- const verticalPair = [`Grid_${anchor.row}_${anchor.col}`, `Grid_${anchor.row + 1}_${anchor.col}`];
- const allowedPairs = new Set<string>([
- pairKey(horizontalPair),
- pairKey(verticalPair),
- pairKey(gridPair),
- ]);
- const targetRowCol = this.getGridRowCol(targetGrid);
- if (!targetRowCol) return false;
- const parts = this.getBlockParts(block);
- const occupiedNames: string[] = [];
- for (let i = 0; i < parts.length; i++) {
- const part = parts[i];
- const row = targetRowCol.row - part.y;
- const col = targetRowCol.col + part.x;
- occupiedNames.push(`Grid_${row}_${col}`);
- }
- const occupiedKey = pairKey(occupiedNames);
- const ok = allowedPairs.has(occupiedKey);
- if (!ok) {
- console.log(`[BlockManager] 教程:占用 ${occupiedNames.join('、')} 未匹配允许对`);
- }
- return ok;
- }
- /**
- * 处理教程方块放置事件(统一结束判断)
- */
- private handleTutorialBlockPlacement(block: cc.Node, targetGrid: cc.Node): void {
- // 第6步:使用 _tutorialTargetGridsStep4 + 期望方块校验(fingerStartNodes[5])
- if (this._tutorialStep >= 6) {
- const expectedStep6 = this.guideUIController ? this.guideUIController.fingerStartNodes[5] : null;
- const completedStep6 = this.isTutorialPlacementCompleted(block, targetGrid, this._tutorialTargetGridsStep4, expectedStep6 || undefined);
- if (completedStep6) {
- EventBus.getInstance().emit(GameEvents.TUTORIAL_BLOCK_5_PLACED);
- this._tutorialStep = 7;
- console.log(`[BlockManager] 教程第六步完成`);
- }
- return;
- }
- // 第5步:使用 _tutorialTargetGridsStep2 + 期望方块校验(fingerStartNodes[4])
- if (this._tutorialStep >= 5) {
- const expectedStep5 = this.guideUIController ? this.guideUIController.fingerStartNodes[4] : null;
- const completedStep5 = this.isTutorialPlacementCompleted(block, targetGrid, this._tutorialTargetGridsStep2, expectedStep5 || undefined);
- if (completedStep5) {
- EventBus.getInstance().emit(GameEvents.TUTORIAL_BLOCK_4_PLACED);
- this._tutorialStep = 6;
- console.log(`[BlockManager] 教程第五步完成`);
- }
- return;
- }
- // 第4步:使用 _tutorialTargetGridsStep4 + 期望方块校验(fingerStartNodes[3])
- if (this._tutorialStep >= 4) {
- const expected = this.guideUIController ? this.guideUIController.fingerStartNodes[3] : null;
- const completed = this.isTutorialPlacementCompleted(block, targetGrid, this._tutorialTargetGridsStep4, expected || undefined);
- if (completed) {
- EventBus.getInstance().emit(GameEvents.TUTORIAL_BLOCK_3_PLACED);
- this._tutorialStep = 5;
- // 教程第四步完成后,强制结束场上任何拖拽并恢复碰撞
- this.forceEnableBlockCollidersAndEndDrags();
- console.log(`[BlockManager] 教程第四步完成`);
- }
- return;
- }
- // 第2步:使用 _tutorialTargetGridsStep2 + 期望方块校验(fingerStartNodes[1])
- if (this._tutorialStep >= 2) {
- const expected = this.guideUIController ? this.guideUIController.fingerStartNodes[1] : null;
- const completed = this.isTutorialPlacementCompleted(block, targetGrid, this._tutorialTargetGridsStep2, expected || undefined);
- if (!completed) return;
- EventBus.getInstance().emit(GameEvents.TUTORIAL_BLOCK_2_PLACED);
- this._tutorialStep = 3;
- console.log(`[BlockManager] 教程第二步完成`);
- return;
- }
- // 第1步:使用 _tutorialTargetGrids + 期望方块校验(fingerStartNodes[0])
- {
- const expected = this.guideUIController ? this.guideUIController.fingerStartNodes[0] : null;
- const completed = this.isTutorialPlacementCompleted(block, targetGrid, this._tutorialTargetGrids, expected || undefined);
- if (!completed) return;
- EventBus.getInstance().emit(GameEvents.TUTORIAL_BLOCK_1_PLACED);
- // 运行时注入 Drag[2] 的起点为刚刚放置到场上的方块(Drag[0] 的结果)
- if (this.guideUIController) {
- try {
- this.guideUIController.setStartNodeForDragConfigIndex(2, block);
- } catch (e) {
- console.warn(`[BlockManager] 注入 Drag[2] 起点失败: ${e}`);
- }
- }
- this._tutorialStep = 2;
- console.log(`[BlockManager] 教程第一步完成`);
- return;
- }
- }
- /**
- * 教程保护:强制让场上方块立即可被小球碰撞,并结束拖拽状态
- * 适用场景:例如第四步自动放置发生在玩家仍在拖拽时
- */
- private forceEnableBlockCollidersAndEndDrags(): void {
- try {
- if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
- return;
- }
- const children = this.placedBlocksContainer.children.slice();
- for (let i = 0; i < children.length; i++) {
- const block = children[i];
- if (!block || !block.isValid) continue;
- // 只处理有效的方块节点(根或含B1)
- const isBlockLike = block.name.includes('Block') || !!block.getChildByName('B1');
- if (!isBlockLike) continue;
- // 清除拖拽标记
- (block as any)['isDragging'] = false;
- // 在教程保护场景下,确保位置标记为 grid(避免后续逻辑误判)
- this.blockLocations.set(block, 'grid');
- // 启用根节点碰撞体
- const rootCol = block.getComponent(Collider2D);
- if (rootCol && !rootCol.enabled) {
- rootCol.enabled = true;
- }
- // 启用B1子节点的碰撞体(如存在)
- const b1 = block.getChildByName('B1');
- if (b1) {
- const b1Col = b1.getComponent(Collider2D);
- if (b1Col && !b1Col.enabled) {
- b1Col.enabled = true;
- }
- }
- // 通知BallController拖拽结束,确保不再忽略碰撞
- try {
- EventBus.getInstance().emit(GameEvents.BLOCK_DRAG_END, { block });
- } catch (e) {
- // 安静失败,不影响主流程
- }
- }
- // 循环处理完毕后,广播全局强制结束拖拽事件,清理拖拽上下文
- try {
- EventBus.getInstance().emit(GameEvents.FORCE_END_ALL_DRAGS);
- } catch (e) {
- // 安静失败,不影响主流程
- }
- } catch (e) {
- console.warn('[BlockManager] 教程保护:恢复方块碰撞与拖拽状态失败:', e);
- }
- }
-
- // 检查方块是否可以放置在指定位置
- canPlaceBlockAt(block: Node, targetGrid: Node): boolean {
-
- if (!this.gridInitialized) {
- console.log(`[BlockManager] 网格未初始化`);
- return false;
- }
-
- const targetRowCol = this.getGridRowCol(targetGrid);
- if (!targetRowCol) {
- console.log(`[BlockManager] 无法获取目标网格的行列信息`);
- return false;
- }
-
- const parts = this.getBlockParts(block);
-
- for (let i = 0; i < parts.length; i++) {
- const part = parts[i];
- const row = targetRowCol.row - part.y;
- const col = targetRowCol.col + part.x;
-
-
- if (row < 0 || row >= this.GRID_ROWS || col < 0 || col >= this.GRID_COLS) {
- console.log(`[BlockManager] 部件${i} 超出网格边界: row=${row}, col=${col}, 网格大小=${this.GRID_ROWS}x${this.GRID_COLS}`);
- return false;
- }
-
- if (this.gridOccupationMap[row][col] === 1) {
- console.log(`[BlockManager] 部件${i} 位置已被占用: row=${row}, col=${col}`);
- return false;
- }
- }
-
- return true;
- }
-
- // 获取网格行列索引
- getGridRowCol(gridNode: Node): { row: number, col: number } | null {
- if (!gridNode || !gridNode.name.startsWith('Grid_')) return null;
-
- const parts = gridNode.name.split('_');
- if (parts.length === 3) {
- const row = parseInt(parts[1]);
- const col = parseInt(parts[2]);
-
- if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
- return { row, col };
- }
- }
-
- return null;
- }
-
- // 获取指定行列的网格世界坐标(用于调试绘制)
- public getGridWorldPosition(row: number, col: number): Vec3 | null {
- if (!this.gridInitialized || !this.gridNodes[row] || !this.gridNodes[row][col]) {
- return null;
- }
-
- const gridNode = this.gridNodes[row][col];
- return this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(gridNode.position);
- }
-
- // 获取方块的所有部分节点及其相对坐标
- getBlockParts(block: Node): { node: Node, x: number, y: number }[] {
- const parts: { node: Node, x: number, y: number }[] = [];
-
- // 检查根节点是否有B1子节点,如果有,则B1是实际的形状根节点
- const b1Node = block.getChildByName('B1');
- if (b1Node) {
- // B1节点作为形状的根节点和坐标原点(0,0)
- // 将B1节点本身添加为第一个部分
- parts.push({ node: b1Node, x: 0, y: 0 });
- // 然后递归查找B1的子节点,但要避免重复添加B1本身
- this.findBlockParts(b1Node, parts, 0, 0, true);
- } else {
- // 没有B1节点,使用根节点作为形状根节点
- parts.push({ node: block, x: 0, y: 0 });
- this.findBlockParts(block, parts, 0, 0, false);
- }
-
- return parts;
- }
-
- // 递归查找方块的所有部分
- findBlockParts(node: Node, result: { node: Node, x: number, y: number }[], parentX: number, parentY: number, skipRoot: boolean = false) {
- for (let i = 0; i < node.children.length; i++) {
- const child = node.children[i];
-
- if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
- continue;
- }
-
- let x = parentX;
- let y = parentY;
-
- const match = child.name.match(/^\((-?\d+),(-?\d+)\)$/);
- if (match) {
- x = parseInt(match[1]);
- y = parseInt(match[2]);
- result.push({ node: child, x, y });
- } else if (child.name.startsWith('B')) {
- const relativeX = Math.round(child.position.x / this.gridSpacing);
- const relativeY = -Math.round(child.position.y / this.gridSpacing);
-
- x = parentX + relativeX;
- y = parentY + relativeY;
-
- // 避免重复添加已经在result中的节点
- const existingPart = result.find(part => part.node === child);
- if (!existingPart) {
- result.push({ node: child, x, y });
- }
- }
-
- this.findBlockParts(child, result, x, y, false);
- }
- }
-
- // 标记方块占用的格子
- public markOccupiedPositions(block: Node, targetGrid: Node) {
- if (!this.gridInitialized) return;
-
- const targetRowCol = this.getGridRowCol(targetGrid);
- if (!targetRowCol) return;
-
- const parts = this.getBlockParts(block);
-
- block['occupiedGrids'] = [];
-
- for (const part of parts) {
- const row = targetRowCol.row - part.y;
- const col = targetRowCol.col + part.x;
-
- if (row >= 0 && row < this.GRID_ROWS && col >= 0 && col < this.GRID_COLS) {
- this.gridOccupationMap[row][col] = 1;
-
- block['occupiedGrids'] = block['occupiedGrids'] || [];
- block['occupiedGrids'].push({ row, col });
- }
- }
- }
-
- // 清除方块
- clearBlocks() {
- console.log('[BlockManager] clearBlocks开始,当前方块总数:', this.blocks.length);
- const blocksToRemove = [];
-
- for (const block of this.blocks) {
- if (block.isValid) {
- const location = this.blockLocations.get(block);
- // 清除kuang区域和Block容器中的方块
- if (location === 'kuang' || location === 'block1' || location === 'block2' || location === 'block3') {
- blocksToRemove.push(block);
- }
- }
- }
-
- console.log('[BlockManager] 找到需要清理的方块数量:', blocksToRemove.length);
-
- for (const block of blocksToRemove) {
- const dbNode = block['dbNode'];
- if (dbNode && dbNode.isValid) {
- block.off(Node.EventType.TRANSFORM_CHANGED);
-
- const kuangNode = this.kuangContainer;
- if (kuangNode) {
- const dbName = dbNode.name;
- if (!kuangNode.getChildByName(dbName)) {
- dbNode.parent = kuangNode;
- }
- }
- }
-
- const index = this.blocks.indexOf(block);
- if (index !== -1) {
- this.blocks.splice(index, 1);
- }
-
- this.originalPositions.delete(block);
- this.blockLocations.delete(block);
- this.blockPriceMap.delete(block);
- // 清理武器配置映射
- this.blockWeaponConfigs.delete(block);
-
- console.log('[BlockManager] 销毁方块:', block.name, '位置:', this.blockLocations.get(block));
- block.destroy();
- }
-
- console.log('[BlockManager] clearBlocks完成,剩余方块总数:', this.blocks.length);
- }
-
- // 游戏开始时调用
- onGameStart() {
- this.gameStarted = true;
-
- for (const block of this.blocks) {
- if (block.isValid) {
- const location = this.blockLocations.get(block);
-
- if (location === 'grid') {
- const dbNode = block['dbNode'];
- if (dbNode) {
- dbNode.active = false;
- }
-
- this.moveBlockToPlacedBlocks(block);
- this.addLockedVisualHint(block);
-
- // 游戏开始后放置的方块移除标签,不能再放回kuang
- BlockTag.removeTag(block);
- }
- }
- }
- }
-
- // 游戏重置时调用
- onGameReset() {
- console.log('[BlockManager] 游戏重置,清理所有状态');
- console.log('[BlockManager] 重置前方块总数:', this.blocks.length);
-
- this.gameStarted = false;
- this.clearAllCooldowns();
-
- // 清理已放置的方块
- console.log('[BlockManager] 开始清理已放置的方块');
- this.clearPlacedBlocks();
-
- // 重置网格占用状态
- console.log('[BlockManager] 开始重置网格占用状态');
- this.resetGridOccupation();
-
- // 清理kuang区域的方块
- console.log('[BlockManager] 开始清理kuang区域的方块');
- this.clearBlocks();
-
- // 清理所有方块标签
- console.log('[BlockManager] 开始清理所有方块标签');
- BlockTag.clearAllTags();
-
- console.log('[BlockManager] 清理后方块总数:', this.blocks.length);
-
- console.log('[BlockManager] 游戏重置完成 - 方块生成将由StartGame流程处理');
- }
-
- // 清理已放置的方块
- private clearPlacedBlocks() {
- if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
- console.log('[BlockManager] PlacedBlocks容器无效,跳过清理');
- return;
- }
-
- console.log(`[BlockManager] 清理已放置方块,当前数量: ${this.placedBlocksContainer.children.length}`);
-
- // 清理PlacedBlocks容器中的所有方块
- const placedBlocks = [...this.placedBlocksContainer.children];
- let clearedCount = 0;
-
- for (const block of placedBlocks) {
- if (block && block.isValid) {
- // 从blocks数组中移除
- const index = this.blocks.indexOf(block);
- if (index !== -1) {
- this.blocks.splice(index, 1);
- }
-
- // 清理相关映射
- this.originalPositions.delete(block);
- this.blockLocations.delete(block);
- this.blockPriceMap.delete(block);
- this.blockWeaponConfigs.delete(block);
-
- console.log('[BlockManager] 销毁已放置方块:', block.name);
- // 销毁方块
- block.destroy();
- clearedCount++;
- }
- }
-
- console.log(`[BlockManager] 已清理 ${clearedCount} 个已放置方块`);
- }
-
- // 重置网格占用状态
- public resetGridOccupation() {
- console.log('[BlockManager] 重置网格占用状态');
-
- // 重新初始化网格占用地图
- this.gridOccupationMap = [];
- for (let row = 0; row < this.GRID_ROWS; row++) {
- this.gridOccupationMap[row] = [];
- for (let col = 0; col < this.GRID_COLS; col++) {
- this.gridOccupationMap[row][col] = 0;
- }
- }
- // 清理临时存储的占用状态
- this.tempRemovedOccupiedGrids = [];
- }
-
- // 添加视觉提示,表明方块已锁定
- addLockedVisualHint(block: Node) {
- const children = block.children;
- for (let i = 0; i < children.length; i++) {
- const child = children[i];
- if (this.NON_BLOCK_NODES.indexOf(child.name) !== -1) {
- continue;
- }
-
- child.setScale(new Vec3(0.95, 0.95, 1));
- }
-
- }
-
- // 将方块移动到PlacedBlocks节点下
- moveBlockToPlacedBlocks(block: Node) {
- if (!this.placedBlocksContainer) {
- console.error('PlacedBlocks容器未设置');
- return;
- }
-
- if (!this.placedBlocksContainer.isValid) {
- console.error('PlacedBlocks容器已失效');
- return;
- }
-
- const worldPosition = new Vec3();
- block.getWorldPosition(worldPosition);
-
- // 移除旧的触摸事件监听器
- block.off(Node.EventType.TOUCH_START);
- block.off(Node.EventType.TOUCH_MOVE);
- block.off(Node.EventType.TOUCH_END);
- block.off(Node.EventType.TOUCH_CANCEL);
-
- block.removeFromParent();
- this.placedBlocksContainer.addChild(block);
- block.setWorldPosition(worldPosition);
- // Scheme D:将方块(B1参考点)对齐到最近网格中心
- try {
- const b1Node = block.name === 'B1' ? block : block.getChildByName('B1');
- if (b1Node && this.gridContainer) {
- const b1WorldPos = b1Node.worldPosition.clone();
- const nearestGrid = this.findNearestGridNode(b1WorldPos);
- if (nearestGrid) {
- const gridCenterWorld = this.gridContainer.getComponent(UITransform).convertToWorldSpaceAR(nearestGrid.position);
- if (b1Node === block) {
- block.setWorldPosition(gridCenterWorld);
- } else {
- const b1Local = b1Node.position.clone();
- const rootTargetWorldPos = new Vec3(
- gridCenterWorld.x - b1Local.x,
- gridCenterWorld.y - b1Local.y,
- gridCenterWorld.z
- );
- block.setWorldPosition(rootTargetWorldPos);
- }
- }
- }
- } catch (e) {
- console.warn('[BlockManager] 对齐网格中心失败,保留原位置:', e);
- }
-
- // 通过事件机制重新设置拖拽事件
- const eventBus = EventBus.getInstance();
- eventBus.emit(GameEvents.SETUP_BLOCK_DRAG_EVENTS, [block]);
- console.log(`[BlockManager] 为移动到PlacedBlocks的方块 ${block.name} 重新设置拖拽事件`);
- }
-
- // 根据武器配置选择合适的预制体
- private selectPrefabForWeapon(weaponConfig: WeaponConfig, targetShapeId?: string): Prefab | null {
- if (this.blockPrefabs.length === 0) {
- return null;
- }
-
- // 如果指定了目标形状ID,尝试找到匹配的预制体
- if (targetShapeId) {
- const matchingPrefab = this.findPrefabByShape(targetShapeId);
- if (matchingPrefab) {
- console.log(`[BlockManager] 为武器 ${weaponConfig.name} 找到匹配形状 ${targetShapeId} 的预制体`);
- return matchingPrefab;
- }
- }
-
- // 如果没有指定形状或没有找到匹配的预制体,使用随机选择
- const randomIndex = Math.floor(Math.random() * this.blockPrefabs.length);
- const selectedPrefab = this.blockPrefabs[randomIndex];
-
- console.log(`[BlockManager] 为武器 ${weaponConfig.name} 选择随机预制体 (索引: ${randomIndex})`);
-
- return selectedPrefab;
- }
-
- // 根据形状ID查找匹配的预制体(按照Block+形状ID的命名规则)
- private findPrefabByShape(targetShapeId: string): Prefab | null {
- // 构建预期的预制体名称:Block + 形状ID
- const expectedPrefabName = `Block${targetShapeId}`;
-
- console.log(`[BlockManager] 寻找形状 ${targetShapeId} 的预制体,期望名称: ${expectedPrefabName}`);
- console.log(`[BlockManager] 当前可用预制体数量: ${this.blockPrefabs.length}`);
-
- // 输出所有可用预制体的详细信息
- this.blockPrefabs.forEach((prefab, index) => {
- console.log(`[BlockManager] 预制体[${index}]: ${prefab.name} (匹配: ${prefab.name === expectedPrefabName})`);
- });
-
- for (const prefab of this.blockPrefabs) {
- if (prefab.name === expectedPrefabName) {
- console.log(`[BlockManager] ✓ 找到匹配形状 ${targetShapeId} 的预制体: ${prefab.name}`);
- return prefab;
- }
- }
-
- console.log(`[BlockManager] ✗ 未找到匹配形状 ${targetShapeId} 的预制体 (期望名称: ${expectedPrefabName})`);
- return null;
- }
-
- // 根据武器配置和方块形状设置价格
- private setBlockPriceByWeaponConfig(block: Node, priceNode: Node) {
- const label = priceNode.getComponent(Label);
- if (!label) {
- return;
- }
- // 从Node子节点获取BlockInfo组件(新预制体结构)
- const nodeChild = block.getChildByName('Node');
- const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
-
- if (!blockInfo) {
- label.string = "10";
- return;
- }
-
- // 直接使用BlockInfo的shapePrice,如果为0则使用默认价格10
- let basePrice = blockInfo.shapePrice > 0 ? blockInfo.shapePrice : 10;
- // 应用便宜技能效果
- const skillManager = SkillManager.getInstance();
- let finalPrice = basePrice;
- if (skillManager) {
- const cheaperSkillLevel = skillManager.getSkillLevel('cheaper_units');
- finalPrice = Math.ceil(SkillManager.calculateCheaperUnitsPrice(basePrice, cheaperSkillLevel));
- }
- label.string = finalPrice.toString();
- }
- // 计算方块占用的格子数量
-
- // 设置方块的武器外观
- private setupBlockWeaponVisual(block: Node, weaponConfig: WeaponConfig, targetShapeId?: string) {
- // 确保方块节点上也有 weaponConfig 属性
- block['weaponConfig'] = weaponConfig;
-
- // 如果提供了目标形状ID,直接使用它加载对应的稀有度图片
- if (targetShapeId) {
- this.loadBlockRarityImageByShape(block, weaponConfig.rarity || 'common', targetShapeId);
- } else {
- // 否则使用原有逻辑从方块结构推断形状
- this.loadBlockRarityImage(block, weaponConfig.rarity || 'common');
- }
-
- // 加载武器图标
- this.loadWeaponIcon(block, weaponConfig);
- }
-
- /**
- * 设置方块的BlockInfo组件信息
- * @param block 方块节点
- * @param weaponConfig 武器配置
- * @param targetShapeId 目标形状ID
- * @param blockLocation 方块所在位置
- */
- private setupBlockInfo(block: Node, weaponConfig: WeaponConfig, targetShapeId?: string, blockLocation?: string) {
- // 从Node子节点获取BlockInfo组件(新预制体结构)
- const nodeChild = block.getChildByName('Node');
- const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
- if (!blockInfo) {
- console.warn(`[BlockManager] 方块 ${block.name} 没有BlockInfo组件`);
- return;
- }
-
- // 设置基础信息
- blockInfo.blockName = weaponConfig.name || block.name;
- blockInfo.blockId = weaponConfig.id || weaponConfig.name;
-
- // 设置稀有度
- const rarityMap = { 'common': 0, 'uncommon': 1, 'rare': 2, 'epic': 3 };
- blockInfo.rarity = rarityMap[weaponConfig.rarity] || 0;
-
- // 设置稀有度颜色
- blockInfo.rarityColor = this.getRarityColor(weaponConfig.rarity);
- // 设置形状信息
- if (targetShapeId) {
- blockInfo.shapeId = targetShapeId;
- const shapeInfo = this.getBlockShapeInfo(block);
- if (shapeInfo && shapeInfo.shape) {
- // 计算形状大小
- const rows = shapeInfo.shape.length;
- const cols = shapeInfo.shape[0] ? shapeInfo.shape[0].length : 0;
- blockInfo.shapeSize = new cc.Vec2(cols, rows);
- }
- }
-
- // 设置武器配置(在形状ID设置之后,这样可以正确计算形状价格)
- blockInfo.setWeaponConfig(weaponConfig);
-
- // 设置位置信息
- blockInfo.currentLocation = blockLocation || 'kuang';
- blockInfo.gridPosition = new cc.Vec2(-1, -1);
-
- // 设置状态信息
- blockInfo.isPlaced = false;
- blockInfo.isDraggable = true;
- blockInfo.isMergeable = true;
-
- // 设置方块标签
- const tags = [];
- if (weaponConfig.type) tags.push(weaponConfig.type);
- if (weaponConfig.rarity) tags.push(weaponConfig.rarity);
- if (targetShapeId) tags.push(targetShapeId);
- blockInfo.setBlockTags(tags);
-
- // 查找稀有度和武器图标
- // 根据新的预制体结构,武器节点直接位于方块根节点下
- let weaponNode = block.getChildByName('Weapon');
-
- // 兼容旧结构:如果直接查找失败,尝试B1/Weapon路径
- if (!weaponNode) {
- const b1Node = block.getChildByName('B1');
- if (b1Node) {
- weaponNode = b1Node.getChildByName('Weapon');
- }
- }
-
- if (weaponNode) {
- const weaponSprite = weaponNode.getComponent(Sprite);
- if (weaponSprite) {
- blockInfo.weaponSprite = weaponSprite;
- }
- }
-
- // 更新显示
- blockInfo.updatePriceDisplay();
- blockInfo.updateRarityDisplay();
-
- console.log(`[BlockManager] 已设置方块 ${block.name} 的BlockInfo组件信息`);
- }
-
- /**
- * 获取稀有度对应的颜色
- * @param rarity 稀有度
- * @returns 颜色对象
- */
- private getRarityColor(rarity: string): cc.Color {
- switch (rarity) {
- case 'common':
- return cc.Color.WHITE;
- case 'uncommon':
- return cc.Color.GREEN;
- case 'rare':
- return cc.Color.BLUE;
- case 'epic':
- return cc.Color.MAGENTA;
- default:
- return cc.Color.WHITE;
- }
- }
-
- // 设置方块稀有度颜色
- private setBlockRarityColor(block: Node, rarity: string) {
- this.loadBlockRarityImage(block, rarity);
- }
-
- // 公共方法:应用方块稀有度图片(供外部调用)
- public applyBlockRarityColor(block: Node, rarity: string) {
- // Add null safety check for block
- if (!block || !block.isValid) {
- return;
- }
-
- // 使用图片替代颜色
- this.loadBlockRarityImage(block, rarity);
- }
-
- // 根据稀有度和指定形状ID加载对应的图片
- private async loadBlockRarityImageByShape(block: Node, rarity: string, shapeId: string) {
- if (!block || !block.isValid) {
- return;
- }
-
- console.log(`[BlockManager] 直接使用形状ID ${shapeId} 加载稀有度图片`);
-
- // 首先尝试从BlockInfo组件获取稀有度图标(新预制体结构)
- const nodeChild = block.getChildByName('Node');
- const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
- if (blockInfo) {
- const rarityIcon = blockInfo.getRarityIcon();
- if (rarityIcon) {
- this.applySpriteFrameToBlock(block, rarityIcon);
- console.log(`[BlockManager] ✓ 从BlockInfo组件获取稀有度图标: ${rarity}`);
- return;
- } else {
- console.warn(`[BlockManager] BlockInfo组件中没有找到稀有度图标,稀有度: ${rarity}`);
- }
- } else {
- console.warn(`[BlockManager] 方块没有BlockInfo组件,回退到路径加载模式`);
- }
-
- // 回退到原有的路径加载逻辑
- const baseImageName = this.getBaseImageNameByShape(shapeId);
- if (!baseImageName) {
- console.warn(`[BlockManager] 无法映射形状ID ${shapeId} 到图片名称`);
- this.applyBlockRarityColorFallback(block, rarity);
- return;
- }
-
- // 构建图片路径
- const imagePath = `images/Blocks/${rarity}/${baseImageName}/spriteFrame`;
- console.log(`[BlockManager] 回退加载图片路径: ${imagePath}`);
-
- try {
- // 优先使用 assetManager.getBundle('resources')
- const resourcesBundle = cc.assetManager.getBundle('resources');
- if (resourcesBundle) {
- resourcesBundle.load(imagePath, SpriteFrame, (err, spriteFrame) => {
- if (err) {
- console.warn(`[BlockManager] Bundle加载失败: ${err.message},尝试使用resources.load`);
- this.loadImageWithResourcesLoad(block, imagePath);
- } else {
- this.applySpriteFrameToBlock(block, spriteFrame);
- console.log(`[BlockManager] ✓ Bundle成功加载图片: ${imagePath}`);
- }
- });
- } else {
- console.warn('[BlockManager] resources bundle不可用,使用resources.load');
- this.loadImageWithResourcesLoad(block, imagePath);
- }
- } catch (error) {
- console.error(`[BlockManager] 加载图片时发生错误: ${error}`);
- this.applyBlockRarityColorFallback(block, rarity);
- }
- }
-
- // 根据稀有度和方块形状加载对应的图片
- private async loadBlockRarityImage(block: Node, rarity: string) {
- if (!block || !block.isValid) {
- return;
- }
-
- // 首先尝试从BlockInfo组件获取稀有度图标(新预制体结构)
- const nodeChild = block.getChildByName('Node');
- const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
- if (blockInfo) {
- const rarityIcon = blockInfo.getRarityIcon();
- if (rarityIcon) {
- this.applySpriteFrameToBlock(block, rarityIcon);
- console.log(`[BlockManager] ✓ 从BlockInfo组件获取稀有度图标: ${rarity}`);
- return;
- } else {
- console.warn(`[BlockManager] BlockInfo组件中没有找到稀有度图标,稀有度: ${rarity}`);
- }
- } else {
- console.warn(`[BlockManager] 方块没有BlockInfo组件,回退到路径加载模式`);
- }
-
- // 回退到原有的路径加载逻辑
- const shapeId = this.getBlockShape(block);
- if (!shapeId) {
- console.warn('[BlockManager] 无法获取方块形状,跳过图片加载');
- this.applyBlockRarityColorFallback(block, rarity);
- return;
- }
-
- // 使用形状ID加载图片
- this.loadBlockRarityImageByShape(block, rarity, shapeId);
- }
-
- // 辅助方法:使用resources.load加载图片
- private loadImageWithResourcesLoad(block: Node, imagePath: string) {
- resources.load(imagePath, SpriteFrame, (err, spriteFrame) => {
- if (err) {
- console.error(`[BlockManager] ✗ 图片加载失败: ${imagePath}, 错误: ${err.message}`);
- // 使用颜色回退方案
- const rarity = this.getBlockRarity(block) || 'common';
- this.applyBlockRarityColorFallback(block, rarity);
- } else {
- this.applySpriteFrameToBlock(block, spriteFrame);
- console.log(`[BlockManager] ✓ Resources成功加载图片: ${imagePath}`);
- }
- });
- }
-
- // 辅助方法:将SpriteFrame应用到方块
- private applySpriteFrameToBlock(block: Node, spriteFrame: SpriteFrame) {
- // 新的预制体结构:Sprite组件在Node子节点上
- const nodeChild = block.getChildByName('Node');
- if (nodeChild) {
- const sprite = nodeChild.getComponent(Sprite);
- if (sprite) {
- sprite.spriteFrame = spriteFrame;
- } else {
- console.warn('[BlockManager] Node子节点没有Sprite组件');
- }
- } else {
- console.warn('[BlockManager] 方块节点没有找到Node子节点');
- }
- }
-
- // 根据形状ID映射到基础图片名称
- private getBaseImageNameByShape(shapeId: string): string | null {
- // 根据实际图片文件名映射,不包含文件扩展名
- switch (shapeId) {
- case 'I':
- return 'BlockI';
- case 'H-I':
- return 'BlockH-I';
- case 'L':
- case 'L2':
- case 'L3':
- case 'L4':
- return 'BlockL';
- case 'S':
- case 'F-S':
- return 'BlockS';
- case 'T':
- case 'D-T':
- return 'BlockD-T';
- default:
- // 对于未知形状,尝试直接使用形状ID
- return `Block${shapeId}`;
- }
- }
-
- // 颜色模式回退方法(当图片加载失败时使用)
- private applyBlockRarityColorFallback(block: Node, rarity: string) {
- // 新的预制体结构:Sprite组件在Node子节点上
- const nodeChild = block.getChildByName('Node');
- if (!nodeChild) {
- console.warn('[BlockManager] 方块节点没有找到Node子节点');
- return;
- }
-
- const sprite = nodeChild.getComponent(Sprite);
- if (!sprite || !sprite.isValid) {
- console.warn('[BlockManager] Node子节点没有Sprite组件');
- return;
- }
-
- // 根据稀有度设置颜色
- let color: Color;
- switch (rarity) {
- case 'common':
- color = new Color(255, 255, 255); // 白色
- break;
- case 'uncommon':
- color = new Color(0, 255, 0); // 绿色
- break;
- case 'rare':
- color = new Color(0, 100, 255); // 蓝色
- break;
- case 'epic':
- color = new Color(160, 32, 240); // 紫色
- break;
- default:
- color = new Color(255, 255, 255); // 默认白色
- }
-
- sprite.color = color;
- console.log(`[BlockManager] 回退到颜色模式设置方块稀有度: ${rarity}`, color);
- }
-
-
- // 加载武器图标
- private async loadWeaponIcon(block: Node, weaponConfig: WeaponConfig) {
- // 根据新的预制体结构,武器节点直接位于方块根节点下
- let weaponNode = block.getChildByName('Weapon');
-
- // 兼容旧结构:如果直接查找失败,尝试B1/Weapon路径
- if (!weaponNode) {
- const b1Node = block.getChildByName('B1');
- if (b1Node) {
- weaponNode = b1Node.getChildByName('Weapon');
- }
- }
-
- if (!weaponNode) {
- console.warn('找不到Weapon节点');
- return;
- }
-
- const weaponSprite = weaponNode.getComponent(Sprite);
- if (!weaponSprite) {
- console.warn('Weapon节点上没有Sprite组件');
- return;
- }
-
- // 获取武器配置中的图片路径
- const weaponSprites = weaponConfig.visualConfig?.weaponSprites;
- if (!weaponSprites) {
- console.warn(`武器 ${weaponConfig.name} 没有配置图片信息`);
- return;
- }
-
- // 获取第一个可用的精灵路径(通常是'I'形状)
- let spritePath: string;
- if (typeof weaponSprites === 'string') {
- spritePath = weaponSprites;
- } else {
- // 优先使用'I'形状,如果没有则使用第一个可用的
- const keys = Object.keys(weaponSprites);
- spritePath = weaponSprites['I'] || (keys.length > 0 ? weaponSprites[keys[0]] : null);
- }
-
- if (!spritePath) {
- console.warn(`武器 ${weaponConfig.name} 没有可用的精灵路径`);
- return;
- }
-
- // 转换路径格式,去除"images/"前缀
- const bundlePath = spritePath.replace(/^images\//, '');
-
- try {
- // 使用BundleLoader从images Bundle加载SpriteFrame,添加/spriteFrame后缀
- const spriteFrame = await this.bundleLoader.loadSpriteFrame(`${bundlePath}/spriteFrame`);
-
- // Add comprehensive null safety checks before setting spriteFrame
- if (weaponSprite && weaponSprite.isValid &&
- weaponNode && weaponNode.isValid &&
- block && block.isValid &&
- spriteFrame && spriteFrame.isValid) {
- weaponSprite.spriteFrame = spriteFrame;
-
- // 设置武器图标初始大小为0.4倍
- weaponNode.setScale(0.4, 0.4, 1.0);
- console.log(`[BlockManager] 武器图标加载完成,设置初始缩放为0.4倍: ${weaponConfig.name}`);
-
- // 应用武器图标的旋转(不再使用位置偏移)
- const blockShape = this.getBlockShape(block);
- this.rotateWeaponIconByShape(weaponNode, blockShape, weaponConfig.id);
- }
- } catch (err) {
- console.warn(`加载武器图片失败: ${bundlePath}`, err);
- }
- }
-
- // 武器类型和方块形状组合的旋转角度配置
- private readonly WEAPON_SHAPE_ROTATION_ANGLES: { [weaponId: string]: { [shapeId: string]: number } } = {
- 'pea_shooter': {
- 'I': 0, // 毛豆射手竖条形状
- 'H-I': 90, // 毛豆射手横条形状
- 'L': 0, // 毛豆射手L型
- 'S': 0, // 毛豆射手S型
- 'D-T': 0 // 毛豆射手倒T型
- },
- 'sharp_carrot': {
- 'I': 0, // 尖胡萝卜竖条形状
- 'H-I': 90, // 尖胡萝卜横条形状,旋转适配水平方向
- 'L': -15, // 尖胡萝卜L型,轻微调整
- 'S': 15, // 尖胡萝卜S型,轻微调整
- 'D-T': 0 // 尖胡萝卜倒T型
- },
- 'saw_grass': {
- 'I': 0, // 锯齿草竖条形状
- 'H-I': 0, // 锯齿草横条形状
- 'L': -45, // 锯齿草L型,更大角度适配锯齿形状
- 'S': 30, // 锯齿草S型,适配锯齿弯曲
- 'D-T': 0 // 锯齿草倒T型
- },
- 'watermelon_bomb': {
- 'I': 0, // 西瓜炸弹竖条形状
- 'H-I': 0, // 西瓜炸弹横条形状,圆形炸弹不需要旋转
- 'L': 0, // 西瓜炸弹L型
- 'S': 0, // 西瓜炸弹S型
- 'D-T': 0 // 西瓜炸弹倒T型
- },
- 'boomerang_plant': {
- 'I': 0, // 回旋镖植物竖条形状
- 'H-I': 90, // 回旋镖植物横条形状,旋转适配飞行方向
- 'L': -30, // 回旋镖植物L型
- 'S': -10, // 回旋镖植物S型,适配回旋轨迹
- 'D-T': -80 // 回旋镖植物倒T型
- },
- 'hot_pepper': {
- 'I': 0, // 辣椒竖条形状
- 'H-I': 90, // 辣椒横条形状
- 'L': 0, // 辣椒L型
- 'S': 0, // 辣椒S型
- 'D-T': 0 // 辣椒倒T型
- },
- 'cactus_shotgun': {
- 'I': 0, // 仙人掌霰弹枪竖条形状
- 'H-I': 90, // 仙人掌霰弹枪横条形状
- 'L': -20, // 仙人掌霰弹枪L型
- 'S': 20, // 仙人掌霰弹枪S型
- 'D-T': 0 // 仙人掌霰弹枪倒T型
- },
- 'okra_missile': {
- 'I': 0, // 秋葵导弹竖条形状
- 'H-I': 90, // 秋葵导弹横条形状,旋转适配发射方向
- 'L': -10, // 秋葵导弹L型
- 'S': 10, // 秋葵导弹S型
- 'D-T': 0 // 秋葵导弹倒T型
- },
- 'mace_club': {
- 'I': -45, // 狼牙棒竖条形状
- 'H-I': 0, // 狼牙棒横条形状
- 'L': -90, // 狼牙棒L型,适配棒状武器
- 'S': -90, // 狼牙棒S型
- 'D-T': 0 // 狼牙棒倒T型
- }
- };
-
- // 默认旋转角度配置(当武器类型未配置时使用)
- private readonly DEFAULT_SHAPE_ROTATION_ANGLES: { [key: string]: number } = {
- 'I': 0, // 竖条形状,保持原始方向
- 'H-I': 90, // 横I型,旋转90度适配水平方向
- 'L': -15, // L型,轻微左倾适配L形状的转角
- 'S': 15, // S型,轻微右倾适配S形状的弯曲
- 'D-T': 0 // 倒T型,保持原始方向
- };
-
- // 根据武器类型和方块形状调整武器图标位置(完全保留预制体原始旋转值,不应用额外旋转)
- private rotateWeaponIconByShape(weaponNode: Node, shapeId: string | null, weaponId?: string) {
- if (!weaponNode || !shapeId) return;
-
- // 保存预制体的原始旋转角度
- const originalAngle = weaponNode.angle;
-
- console.log(`保留预制体原始旋转角度: ${originalAngle}度,不应用额外旋转`);
- }
-
- // 设置特定武器和形状的旋转角度
- public setWeaponShapeRotationAngle(weaponId: string, shapeId: string, angle: number) {
- if (!this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
- this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId] = {};
- }
- this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] = angle;
- console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度为: ${angle}度`);
- }
-
- // 设置默认形状的旋转角度
- public setDefaultShapeRotationAngle(shapeId: string, angle: number) {
- this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] = angle;
- console.log(`已更新默认形状 ${shapeId} 的旋转角度为: ${angle}度`);
- }
-
-
- // 获取特定武器和形状的旋转角度
- public getWeaponShapeRotationAngle(weaponId: string, shapeId: string): number {
- if (this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId]) {
- return this.WEAPON_SHAPE_ROTATION_ANGLES[weaponId][shapeId] || 0;
- }
- return 0;
- }
-
- // 获取默认形状的旋转角度
- public getDefaultShapeRotationAngle(shapeId: string): number {
- return this.DEFAULT_SHAPE_ROTATION_ANGLES[shapeId] || 0;
- }
-
-
- // 设置特定武器和形状的旋转角度
- public setWeaponShapeTransform(weaponId: string, shapeId: string, angle: number) {
- this.setWeaponShapeRotationAngle(weaponId, shapeId, angle);
- console.log(`已更新武器 ${weaponId} 形状 ${shapeId} 的旋转角度: ${angle}度`);
- }
-
- // 设置默认形状的旋转角度
- public setDefaultShapeTransform(shapeId: string, angle: number) {
- this.setDefaultShapeRotationAngle(shapeId, angle);
- console.log(`已更新默认形状 ${shapeId} 的旋转角度: ${angle}度`);
- }
-
- // 重新应用所有已放置方块的武器图标位置和旋转
- public refreshAllWeaponIconRotations() {
- // 遍历所有已放置的方块
- if (this.placedBlocksContainer) {
- this.placedBlocksContainer.children.forEach(block => {
- const weaponConfig = this.getBlockWeaponConfig(block);
- if (weaponConfig) {
- // 根据新的预制体结构:Weapon节点直接在方块根节点下
- let weaponNode = block.getChildByName('Weapon');
- // 向后兼容:如果没找到,尝试旧的B1/Weapon路径
- if (!weaponNode) {
- const b1Node = block.getChildByName('B1');
- if (b1Node) {
- weaponNode = b1Node.getChildByName('Weapon');
- }
- }
- if (weaponNode) {
- const shapeId = this.getBlockShape(block);
- this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
- }
- }
- });
- }
-
- // 遍历kuang区域的方块
- this.blocks.forEach(block => {
- const weaponConfig = this.getBlockWeaponConfig(block);
- if (weaponConfig) {
- // 根据新的预制体结构:Weapon节点直接在方块根节点下
- let weaponNode = block.getChildByName('Weapon');
- // 向后兼容:如果没找到,尝试旧的B1/Weapon路径
- if (!weaponNode) {
- const b1Node = block.getChildByName('B1');
- if (b1Node) {
- weaponNode = b1Node.getChildByName('Weapon');
- }
- }
- if (weaponNode) {
- const shapeId = this.getBlockShape(block);
- this.rotateWeaponIconByShape(weaponNode, shapeId, weaponConfig.id);
- }
- }
- });
- }
-
- // 根据方块获取武器配置
- public getBlockWeaponConfig(block: Node): WeaponConfig | null {
- return this.blockWeaponConfigs.get(block) || block['weaponConfig'] || null;
- }
-
- // 获取方块的武器ID
- public getBlockWeaponId(block: Node): string | null {
- const weaponConfig = this.getBlockWeaponConfig(block);
- return weaponConfig ? weaponConfig.id : null;
- }
- // 获取方块的形状
- public getBlockShape(block: Node): string | null {
- const weaponConfig = this.getBlockWeaponConfig(block);
- if (!weaponConfig) return null;
-
- // 从方块结构推断形状
- const shapeInfo = this.getBlockShapeInfo(block);
- return shapeInfo ? shapeInfo.id : 'I';
- }
-
- // 获取方块的详细形状信息(包括形状ID和名称)
- public getBlockShapeInfo(block: Node): { id: string, name: string, shape: number[][] } | null {
- const actualShape = this.extractShapeFromBlock(block);
- console.log(`[BlockManager] 提取的实际形状矩阵:`, actualShape);
-
- let blockShapes = null;
-
- // 优先使用预加载的配置
- if (this.isWeaponsConfigPreloaded && this.preloadedWeaponsConfig) {
- blockShapes = this.preloadedWeaponsConfig.blockSizes;
- console.log(`[BlockManager] 使用预加载配置,形状数量: ${blockShapes ? blockShapes.length : 0}`);
- } else {
- // 回退到ConfigManager
- blockShapes = this.configManager.getBlockShapes();
- console.log(`[BlockManager] 使用ConfigManager,形状数量: ${blockShapes ? blockShapes.length : 0}`);
- }
-
- if (!blockShapes) {
- console.log(`[BlockManager] 警告:无法获取形状配置`);
- return null;
- }
-
- // 寻找匹配的形状配置
- for (const shapeConfig of blockShapes) {
- console.log(`[BlockManager] 比较形状 ${shapeConfig.id}:`, shapeConfig.shape);
- if (this.compareShapeMatrices(actualShape, shapeConfig.shape)) {
- console.log(`[BlockManager] 找到匹配形状: ${shapeConfig.id}`);
- return {
- id: shapeConfig.id,
- name: shapeConfig.name,
- shape: shapeConfig.shape
- };
- }
- }
-
- console.log(`[BlockManager] 警告:未找到匹配的形状,使用默认形状 I`);
- return null;
- }
- // 从方块结构推断形状
- private inferBlockShapeFromStructure(block: Node): string {
- // 直接从B1节点结构读取形状矩阵
- const actualShape = this.extractShapeFromBlock(block);
-
- // 返回默认形状ID,实际形状矩阵已通过extractShapeFromBlock获取
- return 'I';
- }
-
-
- // 从方块实例中提取形状矩阵
- private extractShapeFromBlock(block: Node): number[][] {
- const parts = this.getBlockParts(block);
-
- // 创建4x4矩阵
- const matrix: number[][] = [];
- for (let i = 0; i < 4; i++) {
- matrix[i] = [0, 0, 0, 0];
- }
-
- // 找到最小坐标作为偏移基准
- let minX = 0, minY = 0;
- for (const part of parts) {
- minX = Math.min(minX, part.x);
- minY = Math.min(minY, part.y);
- }
-
- // 填充矩阵,将坐标标准化到从(0,0)开始
- for (const part of parts) {
- const matrixX = part.x - minX;
- const matrixY = (part.y - minY); // 不需要Y轴翻转,直接使用相对坐标
-
- if (matrixX >= 0 && matrixX < 4 && matrixY >= 0 && matrixY < 4) {
- matrix[matrixY][matrixX] = 1;
- }
- }
-
- // 移除矩阵翻转操作,保持原始坐标系
-
- return matrix;
- }
-
- // 比较两个形状矩阵是否相同
- private compareShapeMatrices(matrix1: number[][], matrix2: number[][]): boolean {
- if (matrix1.length !== matrix2.length) return false;
-
- for (let i = 0; i < matrix1.length; i++) {
- if (matrix1[i].length !== matrix2[i].length) return false;
- for (let j = 0; j < matrix1[i].length; j++) {
- if (matrix1[i][j] !== matrix2[i][j]) return false;
- }
- }
-
- return true;
- }
- // 检查两个方块是否可以合成(相同形状相同种类)
- private canMergeBlocks(block1: Node, block2: Node): boolean {
- console.log(`[BlockManager] 开始检查方块合成条件`);
- console.log(`[BlockManager] 方块1名称: ${block1.name}, 方块2名称: ${block2.name}`);
-
- // 检查稀有度
- const rarity1 = this.getBlockRarity(block1);
- const rarity2 = this.getBlockRarity(block2);
- console.log(`[BlockManager] 稀有度检查: ${rarity1} vs ${rarity2}`);
- if (rarity1 !== rarity2) {
- console.log(`[BlockManager] 稀有度不匹配: ${rarity1} vs ${rarity2}`);
- return false;
- }
-
- // 检查武器ID(种类)
- const weaponId1 = this.getBlockWeaponId(block1);
- const weaponId2 = this.getBlockWeaponId(block2);
- console.log(`[BlockManager] 武器ID检查: ${weaponId1} vs ${weaponId2}`);
- if (weaponId1 !== weaponId2) {
- console.log(`[BlockManager] 武器种类不匹配: ${weaponId1} vs ${weaponId2}`);
- return false;
- }
-
- // 使用精确的形状矩阵比较
- const shape1 = this.extractShapeFromBlock(block1);
- const shape2 = this.extractShapeFromBlock(block2);
- console.log(`[BlockManager] 形状矩阵1:`, shape1);
- console.log(`[BlockManager] 形状矩阵2:`, shape2);
-
- if (!this.compareShapeMatrices(shape1, shape2)) {
- console.log(`[BlockManager] 形状矩阵不匹配`);
- return false;
- }
-
- console.log(`[BlockManager] 方块可以合成: 稀有度=${rarity1}, 种类=${weaponId1}`);
- return true;
- }
-
- /**
- * 显示所有db标签节点
- */
- showAllDbNodes() {
- if (this.block1DbNode) {
- this.block1DbNode.active = true;
- console.log("显示Block1的db标签节点");
- }
- if (this.block2DbNode) {
- this.block2DbNode.active = true;
- console.log("显示Block2的db标签节点");
- }
- if (this.block3DbNode) {
- this.block3DbNode.active = true;
- console.log("显示Block3的db标签节点");
- }
- }
- // 刷新方块 - 重新生成三个新的武器方块
- public refreshBlocks() {
- // 移除PlacedBlocks容器中所有方块的标签
- if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
- BlockTag.removeTagsInContainer(this.placedBlocksContainer);
- }
-
- // 保存已放置方块的占用信息
- const placedBlocksOccupation: { block: Node, occupiedGrids: { row: number, col: number }[] }[] = [];
- if (this.placedBlocksContainer && this.placedBlocksContainer.isValid) {
- for (let i = 0; i < this.placedBlocksContainer.children.length; i++) {
- const block = this.placedBlocksContainer.children[i];
- const occupiedGrids = block['occupiedGrids'];
- if (occupiedGrids && occupiedGrids.length > 0) {
- placedBlocksOccupation.push({
- block: block,
- occupiedGrids: [...occupiedGrids]
- });
- }
- }
- }
-
- // 生成新的方块
- this.generateRandomBlocksInKuang();
-
- // 显示所有db标签节点
- this.showAllDbNodes();
-
- }
- // 检查是否有已放置的方块
- public hasPlacedBlocks(): boolean {
- if (!this.placedBlocksContainer || !this.placedBlocksContainer.isValid) {
- console.log('[BlockManager] PlacedBlocks容器无效');
- return false;
- }
- const blockCount = this.placedBlocksContainer.children.length;
- console.log(`[BlockManager] 已放置方块数量: ${blockCount}`);
-
- // 检查容器中是否有子节点(方块)
- return blockCount > 0;
- }
- /* =================== 合成逻辑 =================== */
- private readonly rarityOrder: string[] = ['common','uncommon','rare','epic'];
- /** 检查当前放置的方块能否与相同稀有度的方块合成 */
- public async tryMergeBlock(block: Node) {
- try {
- const rarity = this.getBlockRarity(block);
- if (!rarity) return;
- // 在 placedBlocksContainer 中寻找与之重叠且可以合成的其他方块
- if (!this.placedBlocksContainer) return;
- const blockBB = this.getWorldAABB(block);
- for (const other of this.placedBlocksContainer.children) {
- if (other === block) continue;
-
- // 使用新的合成检查方法
- if (!this.canMergeBlocks(block, other)) continue;
- const otherBB = this.getWorldAABB(other);
- if (this.rectIntersects(blockBB, otherBB)) {
- // 找到合成目标
- await this.performMerge(block, other, rarity);
- break;
- }
- }
- } catch (error) {
- console.error('[BlockManager] tryMergeBlock 发生错误:', error);
- // 合成失败不影响游戏继续,只记录错误
- }
- }
- private async performMerge(target: Node, source: Node, rarity: string) {
- try {
- console.log(`[BlockManager] 开始合成方块: 目标=${target.name}, 源=${source.name}, 稀有度=${rarity}`);
- // 先立即触发合成特效,避免后续异步逻辑造成播放延迟
- const worldPos = new Vec3();
- target.getWorldPosition(worldPos);
- this.spawnMergeSmoke(worldPos);
- this.playUpgradeEffect(target);
-
- // 注意:参与合成的方块都在网格中,它们的db标签本来就应该是隐藏的
- // 不需要调用hideDbLabel,因为这些方块已经不在block容器中了
- // 在扩展教程(第5-6步)中,合成即可视为完成,触发教程完成判断
- if (this.isExtendedTutorialEventContext()) {
- let gridNode: Node | null = null;
- const occupied = (target as any)['occupiedGrids'];
- if (occupied && occupied.length > 0) {
- const first = occupied[0];
- if (first && this.gridNodes[first.row] && this.gridNodes[first.row][first.col]) {
- gridNode = this.gridNodes[first.row][first.col];
- }
- }
- // 如果能定位到目标格子,则用源方块+该格子进行教程完成判定
- if (gridNode) {
- this.handleTutorialBlockPlacement(source, gridNode);
- }
- }
- // 销毁被合并方块
- source.destroy();
- // 升级稀有度
- const nextRarity = this.getNextRarity(rarity);
- if (nextRarity) {
- console.log(`[BlockManager] 合成成功,稀有度升级: ${rarity} -> ${nextRarity}`);
-
- // 播放合成成功音效
- Audio.playSFX('data/弹球音效/level up 2');
-
- // 追踪合成等级达成事件(仅追踪2-4级)
- const rarityMap = { 'uncommon': 2, 'rare': 3, 'epic': 4 };
- const mergeLevel = rarityMap[nextRarity];
- if (mergeLevel) {
- // 获取武器和形状信息用于埋点
- const weaponConfig = this.blockWeaponConfigs.get(target);
- const weaponType = weaponConfig ? weaponConfig.name : 'unknown';
- const shapeType = this.getBlockShape(target) || 'unknown';
-
- // 调用埋点方法
- Analytics.trackBlockMergeLevel(mergeLevel, weaponType, shapeType);
- console.log(`[BlockManager] 埋点追踪: 合成等级${mergeLevel}, 武器=${weaponType}, 形状=${shapeType}`);
- }
-
- // 获取当前武器配置
- const currentConfig = this.blockWeaponConfigs.get(target);
- if (currentConfig) {
- // 保存原始武器名称用于日志输出
- const originalWeaponName = currentConfig.name;
-
- try {
- // 获取当前关卡允许的武器列表
- const levelWeapons = await this.getCurrentLevelWeapons();
-
- // 检查是否应该限制在关卡配置的武器范围内
- if (levelWeapons.length > 0) {
- // 如果当前武器不在关卡配置中,说明是通过合成获得的,应该保持原武器不变,只升级稀有度
- if (!levelWeapons.some(weapon => weapon === originalWeaponName)) {
- console.log(`[BlockManager] 武器 ${originalWeaponName} 不在关卡配置中,保持原武器,只升级稀有度`);
- }
-
- // 无论如何,都只升级稀有度,不改变武器类型
- const upgradedConfig = { ...currentConfig };
- upgradedConfig.rarity = nextRarity;
- this.blockWeaponConfigs.set(target, upgradedConfig);
- // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
- (target as any)['weaponConfig'] = upgradedConfig;
- console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
- } else {
- // 如果没有关卡配置限制,正常升级稀有度
- const upgradedConfig = { ...currentConfig };
- upgradedConfig.rarity = nextRarity;
- this.blockWeaponConfigs.set(target, upgradedConfig);
- // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
- (target as any)['weaponConfig'] = upgradedConfig;
- console.log(`[BlockManager] 武器配置升级: ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
- }
- } catch (weaponError) {
- console.error('[BlockManager] 获取关卡武器配置失败:', weaponError);
- // 武器配置获取失败时,仍然升级稀有度
- const upgradedConfig = { ...currentConfig };
- upgradedConfig.rarity = nextRarity;
- this.blockWeaponConfigs.set(target, upgradedConfig);
- // 同时更新方块节点的 weaponConfig 属性,供 BallController 使用
- (target as any)['weaponConfig'] = upgradedConfig;
- console.log(`[BlockManager] 武器配置升级(降级处理): ${originalWeaponName} 稀有度 ${rarity} -> ${nextRarity}`);
- }
- }
- // 同步更新BlockInfo组件的稀有度(新预制体结构)
- const nodeChild = target.getChildByName('Node');
- const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
- if (blockInfo) {
- // 将稀有度字符串转换为数字
- const rarityMap = { 'common': 0, 'uncommon': 1, 'rare': 2, 'epic': 3 };
- const rarityNumber = rarityMap[nextRarity] !== undefined ? rarityMap[nextRarity] : 0;
- blockInfo.rarity = rarityNumber;
-
- // 更新稀有度显示
- blockInfo.updateRarityDisplay();
-
- console.log(`[BlockManager] BlockInfo稀有度已更新: ${rarity} -> ${nextRarity} (${rarityNumber})`);
- } else {
- console.warn(`[BlockManager] 未找到BlockInfo组件,无法更新稀有度显示`);
- }
-
- // 更新方块图片
- this.loadBlockRarityImage(target, nextRarity);
- }
- // 递归检查是否还能继续合成
- if (nextRarity) {
- await this.tryMergeBlock(target);
- }
-
- console.log(`[BlockManager] 合成完成`);
- } catch (error) {
- console.error('[BlockManager] performMerge 发生错误:', error);
- // 合成失败时重新抛出错误,让上层处理
- throw error;
- }
- }
- private getBlockRarity(block: Node): string | null {
- console.log(`[BlockManager] getBlockRarity 调用,方块名称: ${block.name}, UUID: ${block.uuid}`);
-
- // 从Node子节点获取BlockInfo组件(适配新的预制体结构)
- const nodeChild = block.getChildByName('Node');
- const blockInfo = nodeChild ? nodeChild.getComponent(BlockInfo) : null;
- if (blockInfo) {
- const rarityName = blockInfo.getRarityName();
- console.log(`[BlockManager] 从BlockInfo组件获取稀有度: ${rarityName}`);
- return rarityName;
- }
-
- console.log(`[BlockManager] 未找到BlockInfo组件`);
- return null;
- }
- private getNextRarity(rarity: string): string | null {
- const idx = this.rarityOrder.indexOf(rarity);
- if (idx === -1 || idx >= this.rarityOrder.length - 1) return null;
- return this.rarityOrder[idx + 1];
- }
- private getWorldAABB(node: Node): Rect {
- const ui = node.getComponent(UITransform);
- if (!ui) return new Rect();
- const pos = node.worldPosition;
- const width = ui.width;
- const height = ui.height;
- return new Rect(pos.x - width/2, pos.y - height/2, width, height);
- }
- private rectIntersects(a: Rect, b: Rect): boolean {
- return a.x < b.x + b.width &&
- a.x + a.width > b.x &&
- a.y < b.y + b.height &&
- a.y + a.height > b.y;
- }
- /** 生成烟雾特效 */
- private spawnMergeSmoke(worldPos: Vec3) {
- // 使用BundleLoader加载Animation Bundle中的特效资源
- // 转换路径格式,去除"Animation/"前缀
- const bundlePath = 'WeaponTx/tx0003/tx0003';
-
- BundleLoader.loadSkeletonData(bundlePath).then((sData: sp.SkeletonData) => {
- if (!sData) {
- console.warn('加载合成烟雾动画失败: 资源为空');
- return;
- }
- const node = new Node('MergeSmoke');
- const skeleton = node.addComponent(sp.Skeleton);
- skeleton.skeletonData = sData;
- skeleton.premultipliedAlpha = false;
- skeleton.setAnimation(0, 'animation', false);
- skeleton.setCompleteListener(() => node.destroy());
- const canvas = find('Canvas');
- if (canvas) canvas.addChild(node);
- node.setWorldPosition(worldPos);
- }).catch((err) => {
- console.warn('加载合成烟雾动画失败:', err);
- });
- }
- /** 播放升级特效动画 */
- private playUpgradeEffect(target: Node) {
- try {
- // 获取目标方块的世界坐标
- const worldPos = new Vec3();
- target.getWorldPosition(worldPos);
-
- // 使用BundleLoader加载升级特效动画
- const path = 'WeaponBurnAni/shengji';
- BundleLoader.loadSkeletonData(path).then((sData: sp.SkeletonData) => {
- if (!sData) {
- console.warn('[BlockManager] 加载升级特效动画失败: 资源为空');
- return;
- }
-
- // 创建特效节点
- const effectNode = new Node('UpgradeEffect');
- const skeleton = effectNode.addComponent(sp.Skeleton);
- skeleton.skeletonData = sData;
- skeleton.premultipliedAlpha = false;
-
- // 播放动画
- skeleton.setAnimation(0, 'animation', false);
-
- // 监听动画完成事件,播放完成后销毁节点
- skeleton.setCompleteListener(() => {
- effectNode.destroy();
- console.log('[BlockManager] 升级特效播放完成');
- });
-
- // 添加到Canvas并设置位置
- const canvas = find('Canvas');
- if (canvas) {
- canvas.addChild(effectNode);
- effectNode.setWorldPosition(worldPos);
- console.log('[BlockManager] 开始播放升级特效动画');
- } else {
- console.warn('[BlockManager] 未找到Canvas节点,无法播放升级特效');
- effectNode.destroy();
- }
- }).catch((err) => {
- console.warn('[BlockManager] 加载升级特效动画失败:', err);
- });
-
- } catch (error) {
- console.error('[BlockManager] 播放升级特效失败:', error);
- }
- }
- /** 在放置失败时尝试与现有方块进行合成 */
- public tryMergeOnOverlap(draggedBlock: Node): boolean {
- console.log(`[BlockManager] tryMergeOnOverlap 开始检查合成`);
- console.log(`[BlockManager] 拖拽方块名称: ${draggedBlock.name}`);
-
- if (!this.placedBlocksContainer) {
- console.log(`[BlockManager] placedBlocksContainer 不存在`);
- return false;
- }
-
- const rarity = this.getBlockRarity(draggedBlock);
- if (!rarity) {
- console.log(`[BlockManager] 拖拽方块稀有度为空`);
- return false;
- }
-
- console.log(`[BlockManager] 拖拽方块稀有度: ${rarity}`);
- console.log(`[BlockManager] 已放置方块数量: ${this.placedBlocksContainer.children.length}`);
- const dragBB = this.getWorldAABB(draggedBlock);
- for (const target of this.placedBlocksContainer.children) {
- if (target === draggedBlock) continue;
-
- console.log(`[BlockManager] 检查与方块 ${target.name} 的合成可能性`);
-
- // 使用新的合成检查方法
- if (!this.canMergeBlocks(draggedBlock, target)) {
- console.log(`[BlockManager] 与方块 ${target.name} 无法合成`);
- continue;
- }
- const targetBB = this.getWorldAABB(target);
- console.log(`[BlockManager] 检查方块碰撞`);
- if (this.rectIntersects(dragBB, targetBB)) {
- console.log(`[BlockManager] 方块重叠,执行合成`);
- // 扩展教程(第5-6步):仅允许在指定格子处合成
- if (this._tutorialStep >= 5 && this._tutorialStep < 7) {
- const basePair = this._tutorialStep >= 6 ? this._tutorialTargetGridsStep4 : this._tutorialTargetGridsStep2;
- if (basePair && basePair.length === 2) {
- const pairKey = (arr: string[]) => arr.slice().sort().join('|');
- const occupied = (target as any)['occupiedGrids'] as { row: number, col: number }[] | undefined;
- if (occupied && occupied.length >= 2) {
- const occupiedNames = occupied.map(g => `Grid_${g.row}_${g.col}`);
- const parse = (name: string) => {
- const m = name.match(/^Grid_(\d+)_(\d+)$/);
- return m ? { row: parseInt(m[1]), col: parseInt(m[2]) } : null;
- };
- const p0 = parse(basePair[0]);
- const p1 = parse(basePair[1]);
- if (p0 && p1) {
- let anchor = p0;
- if (p0.row !== p1.row) {
- anchor = p0.row < p1.row ? p0 : p1;
- } else if (p0.col !== p1.col) {
- anchor = p0.col < p1.col ? p0 : p1;
- }
- const horizontalPair = [`Grid_${anchor.row}_${anchor.col}`, `Grid_${anchor.row}_${anchor.col + 1}`];
- const verticalPair = [`Grid_${anchor.row}_${anchor.col}`, `Grid_${anchor.row + 1}_${anchor.col}`];
- const allowedPairs = new Set<string>([
- pairKey(horizontalPair),
- pairKey(verticalPair),
- pairKey(basePair),
- ]);
- const occupiedKey = pairKey(occupiedNames);
- if (!allowedPairs.has(occupiedKey)) {
- console.log(`[BlockManager] 扩展教程:目标位置不在要求格子,禁止合成`);
- continue;
- }
- }
- }
- }
- }
- // 执行合并:目标保留,拖拽方块销毁
- this.performMerge(target, draggedBlock, rarity);
- return true;
- } else {
- console.log(`[BlockManager] 方块不重叠,跳过合成`);
- }
- }
- console.log(`[BlockManager] 没有找到可合成的方块`);
- return false;
- }
-
- // 调试绘制功能已迁移到GameBlockSelection
-
- // 输出格子占用情况矩阵
- public printGridOccupationMatrix() {
- console.log('[BlockManager] 格子占用情况de矩阵 (6行11列):');
- for (let row = 0; row < this.GRID_ROWS; row++) {
- let rowStr = '';
- for (let col = 0; col < this.GRID_COLS; col++) {
- rowStr += this.gridOccupationMap[row][col] + ' ';
- }
- console.log(`第${row + 1}行: ${rowStr.trim()}`);
- }
- }
-
- // 通过GameBlockSelection刷新方块占用情况
-
- onDestroy() {
- // 调试绘制功能已迁移到GameBlockSelection
-
- // 清理事件监听
- const eventBus = EventBus.getInstance();
- eventBus.off(GameEvents.RESET_BLOCK_MANAGER, this.onResetBlockManagerEvent, this);
- eventBus.off(GameEvents.GENERATE_BLOCKS, this.onGenerateBlocksEvent, this);
- // 移除GAME_START事件清理,因为已不再监听该事件
- // eventBus.off(GameEvents.GAME_START, this.onGameStartEvent, this);
- eventBus.off(GameEvents.WAVE_COMPLETED, this.onWaveCompletedEvent, this);
- }
- }
|