EliminateViewComp.ts 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772
  1. /*
  2. * @Author: mojunshou 1637302775@qq.com
  3. * @Date: 2025-03-20 15:01:09
  4. * @LastEditors: mojunshou 1637302775@qq.com
  5. * @LastEditTime: 2025-04-02 19:24:30
  6. * @Description: 消除游戏主场景
  7. */
  8. import { _decorator, Color, EventTouch, instantiate, JsonAsset, Label, Node, Prefab, randomRangeInt, Sprite, Toggle, tween, UITransform, Vec2, Vec3, Widget } from "cc";
  9. import { RandomManager } from "db://oops-framework/core/common/random/RandomManager";
  10. import { oops } from "db://oops-framework/core/Oops";
  11. import { ecs } from "db://oops-framework/libs/ecs/ECS";
  12. import { LabelChange } from "db://oops-framework/libs/gui/label/LabelChange";
  13. import { CCComp } from "db://oops-framework/module/common/CCComp";
  14. import { GameEvent } from "../../common/config/GameEvent";
  15. import { UIID } from "../../common/config/GameUIConfig";
  16. import { Button } from "cc";
  17. const { ccclass, property } = _decorator;
  18. // 游戏状态枚举
  19. enum GameState {
  20. READY, // 准备中
  21. PLAYING, // 游戏中
  22. PAUSED, // 暂停
  23. GAME_OVER // 游戏结束
  24. }
  25. // 游戏模式枚举
  26. enum GameMode {
  27. MANUAL, // 手动模式
  28. AUTO // 自动模式
  29. }
  30. // 格子状态
  31. enum CellState {
  32. EMPTY, // 空格子
  33. FILLED, // 有方块
  34. HIGHLIGHTED // 高亮(可放置)
  35. }
  36. // 新手引导步骤
  37. enum TutorialStep {
  38. NONE, // 无引导
  39. ROW_ELIMINATION, // 行消除引导
  40. COLUMN_ELIMINATION, // 列消除引导
  41. ROTATION, // 旋转引导
  42. FINAL_ELIMINATION // 最终消除引导
  43. }
  44. //网格数据接口
  45. interface GridData {
  46. name: string, // 名称
  47. status: CellState, // 状态
  48. gridNode: Node | null // 网格节点
  49. row: number, // 行
  50. col: number, // 列
  51. type: number, // 类型--gridColorKey
  52. }
  53. interface Grids {
  54. row: number,
  55. column: number,
  56. }
  57. interface EditingData {
  58. brickData: BrickData | null,
  59. gridList: GridData[],
  60. }
  61. //底部方块数据定义
  62. interface BrickData {
  63. index: number,
  64. brickKey: string | null,
  65. rotateTag: boolean,
  66. rotateFlag: boolean,
  67. gridConfig: Grids[],
  68. deg: number,
  69. brickNode: Node | null,
  70. brickInitPos: Vec3, // 方块初始位置
  71. type: number, // 方块类型--gridColorKey
  72. }
  73. interface GridConfigData {
  74. row: number,
  75. column: number,
  76. }
  77. /** 视图层对象 */
  78. @ccclass('EliminateViewComp')
  79. @ecs.register('EliminateView', false)
  80. export class EliminateViewComp extends CCComp {
  81. @property({ type: LabelChange, displayName: "自动提现金额" })
  82. private amountLb: LabelChange = null!;
  83. @property({ type: LabelChange, displayName: "额外奖励" })
  84. private awardLb: LabelChange = null!;
  85. @property({ type: Node, displayName: "tween微信钱Node" })
  86. private tweenWechatNode: Node = null!;
  87. @property({ type: Node, displayName: "tween红包Node" })
  88. private tweenRedNode: Node = null!;
  89. @property({ type: Prefab, displayName: "金币预制体" })
  90. private coinPrefab: Prefab = null!;
  91. @property({ type: Prefab, displayName: "红包预制体" })
  92. private redPacketPrefab: Prefab = null!;
  93. @property({ type: Label, displayName: "本局分数" })
  94. private lab_score: Label = null!;
  95. @property({ type: Label, displayName: "目标分数" })
  96. private lab_taget: Label = null!;
  97. @property({ type: Label, displayName: "第几块金砖" })
  98. private lab_brick: Label = null!;
  99. @property({ type: Label, displayName: "第几关" })
  100. private lab_levle: Label = null!;
  101. @property({ type: Prefab, displayName: "item预制体列表" })
  102. private itemPrefabs: Prefab[] = [];
  103. @property({ type: Node, displayName: "网格Node" })
  104. private gridNode: Node = null!;
  105. @property({ type: Node, displayName: "移动Node" })
  106. private moveNode: Node = null!;
  107. @property({ type: Node, displayName: "旋转Node" })
  108. private rotateNode: Node = null!;
  109. @property({ type: Node, displayName: "方块Node" })
  110. private brickNode: Node = null!;
  111. @property({ type: Prefab, displayName: "旋转预制体" })
  112. private rotatePrefab: Node = null!;
  113. @property({ type: Label, displayName: "累计消除次数" })
  114. private lab_total: Label = null!;
  115. @property({ type: Label, displayName: "每次放置添加的分数" })
  116. private lab_addScore: Label = null!;
  117. @property({ type: Button, displayName: "自动按钮" })
  118. private autoBtn: Button = null!;
  119. @property({ type: Button, displayName: "二倍速按钮" })
  120. private addSpeedBtn: Button = null!;
  121. //游戏配置行列
  122. private rows: number = 8; // 行数
  123. private cols: number = 8; // 列数
  124. private itemSize: number = 76.25; // 格子大小
  125. private brickNum: number = 3; // 砖块数量
  126. private gameState: GameState = GameState.READY;
  127. private score: number = 0; //本局分数
  128. private money: number = 0; //左边金钱
  129. private cash: number = 0; //右边红包钱数
  130. private totalNum: number = 0; //累计消除次数,断了就是又从0开始
  131. private _isDoubleSpeed: boolean = false; //是否开启二倍速
  132. private _doubleNum: number = 2; //除2就是开启了2倍速,除1就是关闭了2倍速
  133. //网格列表
  134. // gridsNode: Node | null = null; //中间网格区域
  135. // brickNode: Node | null = null; //底部三个item块区域
  136. // moveNode: Node | null = null; //移动层Node
  137. // rotateNode: Node | null = null; //旋转Node吧
  138. //没使用颜色
  139. notUseColor = new Color(255, 255, 255, 255)
  140. //可用的颜色
  141. usableColor = new Color(0, 255, 0, 100)
  142. //不可用的颜色
  143. unavailableColor = new Color(255, 0, 0, 100)
  144. //旋转容错
  145. rotateFaultTolerant = 10;
  146. private _isAutoFunc: (() => void) | null = null;
  147. isAutoMode: boolean = false;
  148. autoModeInterval: number = 1 // 自动模式的间隔时间(秒)
  149. autoModeTimer: number = 0 // 自动模式计时器
  150. //网格列表管理列表
  151. gridList: GridData[][] = [];
  152. //砖块列表
  153. bricksList: BrickData[] = [];
  154. //网格颜色列表
  155. gridColorList: GridData[] = [];
  156. brickConfig: { bricks?: any } = {} //方块配置
  157. editingFlag = false //编辑状态
  158. editingData: EditingData = {
  159. brickData: null,
  160. gridList: [],
  161. }
  162. //旋转标记
  163. rotateFlag = false
  164. rotateBrickData: BrickData | null = null
  165. // 添加新的属性来跟踪是否需要重置消除计数
  166. private shouldResetEliminateCount: boolean = true;
  167. // 添加配置属性 - 消除基础分
  168. @property({ displayName: "消除一行/列基础分" })
  169. private eliminateBaseScore: number = 10;
  170. //当前局数
  171. private curGameNum: number = 0;
  172. //第一通关开始新人模式
  173. //第二局开始马上播放新的弹窗
  174. //往后根据每局需要弹窗就弹窗
  175. //通关一局算一块金砖
  176. //通关比例算金砖比例
  177. private autoState: boolean = false; //自动状态
  178. /** 视图层逻辑代码分离演示 */
  179. async start() {
  180. // const entity = this.ent as ecs.Entity; // ecs.Entity 可转为当前模块的具体实体对象
  181. this.setButton();
  182. this.initButtonState(false);
  183. await this.loadConfig();
  184. this.initGrid();
  185. this.initData();
  186. this.addEventList();
  187. }
  188. addEventList() {
  189. oops.message.on(GameEvent.RestartGame, this.restartGame, this);
  190. oops.message.on(GameEvent.DoubleSpeedOpenSuccess, this.doubleSpeedOpenSuccess, this);
  191. }
  192. //初始化网格
  193. private initGrid() {
  194. // 清理现有网格
  195. this.clearExistingGrids();
  196. // 生成网格矩阵
  197. this.createGridMatrix();
  198. }
  199. //初始化按钮状态
  200. private initButtonState(state: boolean) {
  201. //自动按钮默认关闭
  202. if (this.autoBtn) {
  203. //关闭
  204. const on = this.autoBtn.node.getChildByName("on");
  205. on ? on.active = state : null;
  206. const off = this.autoBtn.node.getChildByName("off");
  207. off ? off.active = !state : null;
  208. // this.autoState = state;
  209. }
  210. }
  211. //初始化数据
  212. private initData() {
  213. // this.gameMode = GameMode.MANUAL;
  214. this.score = 0;
  215. this.money = 0;
  216. this.cash = 0;
  217. this.totalNum = 0;
  218. // this._doubleNum = 2;
  219. this.autoState = false;
  220. this.shouldResetEliminateCount = true;
  221. this.lab_score.string = this.score.toString();
  222. this.amountLb.string = this.money.toString();
  223. this.awardLb.string = this.cash.toString();
  224. }
  225. //初始化关卡信息
  226. private initLevelInfo() {
  227. //关卡通关服务器或者本地读出来
  228. // const level =
  229. }
  230. //初始化网格
  231. private async loadConfig() {
  232. let json_name: string = "gui/eliminate/config/GridConfig";
  233. return new Promise<void>((resolve, reject) => {
  234. oops.res.load(json_name, JsonAsset, (err: Error | null, res: any) => {
  235. if (res) {
  236. this.brickConfig = res.json;
  237. resolve();
  238. } else {
  239. console.log("JSON数据加载失,请检查文件");
  240. reject(err);
  241. }
  242. });
  243. });
  244. }
  245. /**
  246. * @description: 清理现有的网格数据
  247. * @return {*}
  248. */
  249. private clearExistingGrids(): void {
  250. this.gridList = [];
  251. if (this.gridNode) {
  252. this.gridNode.children.forEach(node => node.destroy());
  253. }
  254. }
  255. /**
  256. * @description: 设置网格容器大小
  257. * @return {*}
  258. */
  259. private createGridMatrix(): void {
  260. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  261. const currentRow: GridData[] = [];
  262. this.gridList.push(currentRow);
  263. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  264. const gridData = this.createGridData(rowIndex, columnIndex);
  265. currentRow.push(gridData);
  266. this.createGridNode(gridData);
  267. }
  268. }
  269. // 初始化格子状态
  270. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  271. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  272. this.gridList[rowIndex][columnIndex].status = CellState.EMPTY
  273. this.generateGrid(this.gridList[rowIndex][columnIndex])
  274. }
  275. }
  276. // 初始化方块
  277. if (this.brickNode) {
  278. if (this.brickNode) {
  279. this.brickNode.children.forEach(node => { node.destroy() });
  280. }
  281. }
  282. this.bricksList.length = 0
  283. for (let i = 1; i <= this.brickNum; i++) {
  284. this.addBrick(i)
  285. }
  286. // 清除旋转数据
  287. if (this.rotateNode) {
  288. this.rotateNode.children.forEach(node => { node.destroy() })
  289. }
  290. }
  291. /**
  292. * @description: 创建格子数据
  293. * @param {number} row
  294. * @param {number} column
  295. * @return {*}
  296. */
  297. private createGridData(row: number, column: number): GridData {
  298. return {
  299. name: `Grid-${row}-${column}`,
  300. status: CellState.EMPTY,
  301. gridNode: null,
  302. row: row,
  303. col: column,
  304. type: 0
  305. };
  306. }
  307. /**
  308. * @description: 创建网格Node
  309. * @param {GridData} gridData
  310. * @return {*}
  311. */
  312. private createGridNode(gridData: GridData): void {
  313. const gridNode = new Node(gridData.name);
  314. if (this.gridNode) {
  315. this.gridNode.addChild(gridNode);
  316. }
  317. gridData.gridNode = gridNode;
  318. // 设置网格大小
  319. gridNode.addComponent(UITransform).setContentSize(this.itemSize, this.itemSize);
  320. }
  321. /**
  322. * 生成或更新网格
  323. * @param gridData 网格数据
  324. */
  325. private generateGrid(gridData: GridData) {
  326. if (!gridData || !gridData.gridNode) {
  327. console.warn('无效的网格数据');
  328. return;
  329. }
  330. // 清理现有子节点
  331. this.clearGridChildren(gridData.gridNode);
  332. // 获取对应的预制体
  333. const prefab = this.getGridPrefab(gridData);
  334. if (!prefab) {
  335. console.warn('无法获取网格预制体');
  336. return;
  337. }
  338. // 创建并配置新节点
  339. const node = this.createNewGridNode(prefab, gridData);
  340. // 设置节点属性
  341. this.setupGridNode(node, gridData);
  342. }
  343. /**
  344. * 获取对应状态的预制体
  345. */
  346. private getGridPrefab(gridData: GridData): Prefab {
  347. if (gridData.status === CellState.EMPTY) {
  348. if (this.itemPrefabs[0]) {
  349. return this.itemPrefabs[0];
  350. } else {
  351. throw new Error('Grid prefab is not loaded');
  352. }
  353. }
  354. if (gridData.status === CellState.FILLED && gridData.type) {
  355. const type = gridData.type;
  356. return this.itemPrefabs[type];
  357. }
  358. throw new Error('Invalid grid status or missing gridColorKey');
  359. }
  360. /**
  361. * 创建网格节点
  362. */
  363. private createNewGridNode(prefab: Prefab, gridData: GridData): Node {
  364. const node = instantiate(prefab);
  365. if (gridData && gridData.gridNode) {
  366. gridData.gridNode.addChild(node);
  367. return node;
  368. }
  369. return node
  370. }
  371. /**
  372. * 设置网格节点的属性
  373. */
  374. private setupGridNode(node: Node, gridData: GridData): void {
  375. // 设置未使用状态的颜色
  376. if (gridData.status === CellState.EMPTY) {
  377. const sprite = node.getComponent(Sprite);
  378. if (sprite) {
  379. sprite.color = this.notUseColor;
  380. }
  381. }
  382. // 设置节点大小
  383. const transform = node.getComponent(UITransform);
  384. if (transform) {
  385. transform.setContentSize(
  386. this.itemSize,
  387. this.itemSize
  388. );
  389. }
  390. // 设置位置
  391. node.setPosition(Vec3.ZERO);
  392. }
  393. addBrick(index: number) {
  394. //随机名字
  395. const brickKey = Object.keys(this.brickConfig['bricks'])[randomRangeInt(0, Object.keys(this.brickConfig['bricks']).length)]
  396. const brickConfig = this.brickConfig['bricks'][brickKey];
  397. const randomIndex = oops.random.getRandomInt(1, 5);
  398. // 生成方块
  399. const brickData: BrickData = {
  400. index,
  401. brickKey: brickKey,
  402. rotateFlag: brickConfig['rotateFlag'],
  403. gridConfig: brickConfig['gridConfig'],
  404. deg: 0,
  405. brickNode: null,
  406. brickInitPos: new Vec3(),
  407. rotateTag: false,
  408. type: randomIndex,
  409. }
  410. this.bricksList.push(brickData)
  411. // 生成方块
  412. const brickNode = this.generateBrick(brickKey, randomIndex);
  413. if (this.brickNode) {
  414. this.brickNode.addChild(brickNode)
  415. }
  416. brickData.brickNode = brickNode;
  417. let offset = 220
  418. if (this.brickNum % 2 === 1) {
  419. const middleNum = Math.floor(this.brickNum / 2) + 1
  420. if (index < middleNum) {
  421. offset = - offset
  422. }
  423. else if (index === middleNum) {
  424. offset = 0
  425. }
  426. }
  427. if (brickData && brickData.brickNode) {
  428. brickData.brickNode.setPosition(offset, 0)
  429. brickData.brickNode.scale_x = 0.6;
  430. brickData.brickNode.scale_y = 0.6;
  431. brickData.brickInitPos = brickData.brickNode.getWorldPosition()
  432. }
  433. this.brickAddEvent(brickData);
  434. //2508801946299286
  435. }
  436. // 每个item生成独立的方块节点
  437. generateBrick(brickKey: string, randomIndex: number) {
  438. const brickConfig = this.brickConfig['bricks'][brickKey]
  439. let rowMin = 0
  440. let rowMax = 0
  441. let columnMin = 0
  442. let columnMax = 0
  443. brickConfig['gridConfig'].forEach((gridConfigData: GridConfigData) => {
  444. if (gridConfigData.row < rowMin) {
  445. rowMin = gridConfigData.row
  446. }
  447. else if (gridConfigData.row > rowMax) {
  448. rowMax = gridConfigData.row
  449. }
  450. if (gridConfigData.column < columnMin) {
  451. columnMin = gridConfigData.column
  452. }
  453. else if (gridConfigData.column > columnMax) {
  454. columnMax = gridConfigData.column
  455. }
  456. })
  457. const rowNum = (rowMax - rowMin + 1)
  458. const columnNum = (columnMax - columnMin + 1)
  459. // 生成独立的方块节点
  460. const brickNode = new Node()
  461. brickNode.name = brickKey
  462. // 设置方块大小
  463. const transformCom: UITransform = brickNode.addComponent(UITransform)
  464. transformCom.setContentSize(
  465. this.itemSize * columnNum,
  466. this.itemSize * rowNum
  467. )
  468. transformCom.setAnchorPoint(0.5, 0.5)
  469. // 设置方块位置
  470. const gridPrefab = this.itemPrefabs[randomIndex]
  471. //生成对应的配置方块设置地址
  472. brickConfig['gridConfig'].forEach((gridConfigData: GridConfigData) => {
  473. const gridNode = new Node()
  474. gridNode.name = 'grid'
  475. brickNode.addChild(gridNode)
  476. gridNode.addComponent(UITransform).setContentSize(this.itemSize, this.itemSize)
  477. const gridWidget: Widget = gridNode.addComponent(Widget)
  478. gridWidget.isAlignLeft = true
  479. gridWidget.left = this.itemSize * gridConfigData.column - this.itemSize * columnMin
  480. gridWidget.isAlignBottom = true
  481. gridWidget.bottom = this.itemSize * gridConfigData.row - this.itemSize * rowMin
  482. const node = instantiate(gridPrefab)
  483. gridNode.addChild(node)
  484. const uiTransform = node.getComponent(UITransform);
  485. if (uiTransform) {
  486. uiTransform.setContentSize(
  487. this.itemSize,
  488. this.itemSize,
  489. )
  490. }
  491. node.setPosition(Vec3.ZERO)
  492. node.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  493. event.preventSwallow = true;
  494. }, this);
  495. node.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  496. event.preventSwallow = true;
  497. }, this);
  498. node.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
  499. event.preventSwallow = true;
  500. }, this);
  501. })
  502. return brickNode
  503. }
  504. touchStartLocation = new Vec2()
  505. touchStartFlag = false
  506. brickAddEvent(brickData: BrickData) {
  507. const brickNode = brickData.brickNode
  508. if (!brickNode) {
  509. console.error("brickNode为空,无法添加事件");
  510. return
  511. }
  512. // 确保节点可交互
  513. brickNode.active = true;
  514. // 移除可能存在的旧事件监听器
  515. brickNode.off(Node.EventType.TOUCH_START);
  516. brickNode.off(Node.EventType.TOUCH_MOVE);
  517. brickNode.off(Node.EventType.TOUCH_END);
  518. brickNode.off(Node.EventType.TOUCH_CANCEL);
  519. // 记录初始位置和状态
  520. let startPos = new Vec3();
  521. let originalParent: Node | null = null;
  522. let isDragging = false;
  523. // 触摸开始事件
  524. brickNode.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  525. // 如果正在编辑其他方块,则忽略
  526. if (this.editingFlag) return;
  527. // 设置编辑状态
  528. this.editingFlag = true;
  529. isDragging = true;
  530. this.touchStartFlag = true;
  531. // 清空编辑中的数据
  532. this.editingData.brickData = null;
  533. this.editingData.gridList.length = 0;
  534. // 记录触摸开始位置和方块原始信息
  535. this.touchStartLocation.set(event.getUILocation());
  536. originalParent = brickNode.parent;
  537. startPos = brickNode.getWorldPosition().clone();
  538. // 将方块移到移动层并放大
  539. brickNode.setParent(this.moveNode);
  540. brickNode.setWorldPosition(startPos);
  541. tween(brickNode)
  542. .to(0.2, { scale: new Vec3(1, 1, 1) })
  543. .start();
  544. // 从方块列表中移除该方块
  545. const index = this.bricksList.findIndex(item => item === brickData);
  546. if (index > -1) {
  547. this.editingData.brickData = this.bricksList.splice(index, 1)[0];
  548. } else {
  549. console.error("未找到方块数据:", brickData);
  550. this.editingData.brickData = brickData;
  551. }
  552. // 清除旋转数据
  553. if (this.rotateFlag && this.rotateBrickData !== this.editingData.brickData) {
  554. this.rotateFlag = false;
  555. this.rotateBrickData = null;
  556. if (this.rotateNode) {
  557. this.rotateNode.children.forEach(node => { node.destroy() });
  558. }
  559. }
  560. }, this);
  561. // 触摸移动事件
  562. brickNode.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  563. if (!isDragging || !this.editingData.brickData) return;
  564. // 清除旋转数据
  565. if (event.getUILocation().subtract(this.touchStartLocation).length() >= this.rotateFaultTolerant) {
  566. this.rotateFlag = false;
  567. this.rotateBrickData = null;
  568. if (this.rotateNode) {
  569. this.rotateNode.children.forEach(node => { node.destroy() });
  570. }
  571. }
  572. // 恢复所有网格颜色
  573. this.gridColorRecovery();
  574. // 移动方块
  575. brickNode.setWorldPosition(brickNode.getWorldPosition().add(event.getUIDelta().toVec3()));
  576. // 重置编辑中的网格数据
  577. this.editingData.gridList.length = 0;
  578. // 检查方块每个子网格是否与游戏网格重叠
  579. const tempGridList: GridData[] = [];
  580. let allEmptyGrids: boolean = true; // 标记是否所有网格都为空
  581. brickNode.children.forEach((childNode) => {
  582. const childWorldPos = childNode.getWorldPosition();
  583. // 查找与子网格重叠的游戏网格
  584. let matchedGrid: GridData | null = null;
  585. for (let row = 0; row < this.rows && !matchedGrid; row++) {
  586. for (let col = 0; col < this.cols && !matchedGrid; col++) {
  587. const grid = this.gridList[row][col];
  588. if (!grid || !grid.gridNode) continue;
  589. const gridPos = grid.gridNode.getWorldPosition();
  590. if (Vec3.distance(gridPos, childWorldPos) <= (this.itemSize / 2)) {
  591. matchedGrid = grid;
  592. }
  593. }
  594. }
  595. if (matchedGrid) {
  596. tempGridList.push(matchedGrid);
  597. // 检查是否有非空网格
  598. if (matchedGrid.status !== CellState.EMPTY) {
  599. allEmptyGrids = false;
  600. }
  601. }
  602. });
  603. // 检查是否所有子网格都有对应的游戏网格,且都是空的
  604. let canPlace = tempGridList.length === brickData.gridConfig.length && allEmptyGrids;
  605. // 更新编辑中的网格列表
  606. if (canPlace) {
  607. this.editingData.gridList = [...tempGridList];
  608. }
  609. // 更新网格颜色提示 - 只改变空网格的颜色
  610. tempGridList.forEach(grid => {
  611. // 只处理空网格
  612. if (grid.status === CellState.EMPTY) {
  613. if (grid.gridNode && grid.gridNode.children[0]) {
  614. const sprite = grid.gridNode.children[0].getComponent(Sprite);
  615. if (sprite) {
  616. sprite.color = canPlace ? this.usableColor : this.unavailableColor;
  617. }
  618. }
  619. // 用于后续恢复颜色
  620. this.gridColorList.push(grid);
  621. }
  622. });
  623. }, this);
  624. // 触摸结束或取消事件
  625. const touchEndHandler = (event: EventTouch) => {
  626. if (!isDragging) return;
  627. isDragging = false;
  628. this.touchStartFlag = false;
  629. // 恢复网格颜色
  630. this.gridColorRecovery();
  631. // 防止如放回方块回弹动画时,已经触摸在另一个方块上面
  632. if (this.editingData.brickData !== brickData) return;
  633. // 检查是否可以放置
  634. if (this.editingData.brickData && this.editingData.gridList.length > 0) {
  635. // 计算放置的格子数量
  636. const placedGridCount = this.editingData.gridList.length;
  637. // 获取中心位置用于显示分数
  638. let centerPos = new Vec3(0, 0, 0);
  639. if (this.editingData.gridList.length > 0 && this.editingData.gridList[0].gridNode) {
  640. centerPos = this.editingData.gridList[0].gridNode.getWorldPosition().clone();
  641. if (this.editingData.gridList.length > 1) {
  642. // 计算所有格子的平均位置作为中心点
  643. for (let i = 1; i < this.editingData.gridList.length; i++) {
  644. const gridNode = this.editingData.gridList[i].gridNode;
  645. if (gridNode) {
  646. centerPos.add(gridNode.getWorldPosition());
  647. }
  648. }
  649. const validGridCount = this.editingData.gridList.filter(grid => grid.gridNode).length;
  650. centerPos.x /= validGridCount;
  651. centerPos.y /= validGridCount;
  652. }
  653. }
  654. // 放置方块到网格
  655. this.editingData.gridList.forEach(grid => {
  656. grid.status = CellState.FILLED;
  657. grid.type = this.editingData.brickData!.type;
  658. this.generateGrid(grid);
  659. });
  660. // 显示放置得分动画(显示一次,包含总格子数)
  661. this.showScoreAnimation(centerPos, placedGridCount);
  662. // 标记需要重置消除计数器
  663. this.shouldResetEliminateCount = true;
  664. // 销毁方块节点
  665. brickNode.destroy();
  666. // 添加新方块到待选区
  667. this.addBrick(this.editingData.brickData.index);
  668. // 检查消除
  669. this.scheduleOnce(() => {
  670. this.gridEliminate().then((hasElimination) => {
  671. // 如果没有消除,确保下次消除会重置计数
  672. if (!hasElimination) {
  673. this.shouldResetEliminateCount = true;
  674. }
  675. // 检查游戏是否结束
  676. this.prompt(false).then(canContinue => {
  677. if (!canContinue) {
  678. this.gameOver();
  679. }
  680. this.editingFlag = false;
  681. });
  682. });
  683. }, 0.1);
  684. } else if (this.rotateFlag) {
  685. // 旋转方块
  686. const brickData = this.editingData.brickData;
  687. this.brickGridRotate(brickData);
  688. // 方块放回待选区
  689. this.bricksList.push(brickData);
  690. if (this.brickNode && brickData.brickNode) {
  691. this.brickNode.addChild(brickData.brickNode);
  692. tween(brickData.brickNode)
  693. .to(0.2, {
  694. worldPosition: brickData.brickInitPos,
  695. scale: new Vec3(0.6, 0.6, 0.6)
  696. })
  697. .start();
  698. }
  699. this.editingFlag = false;
  700. } else {
  701. // 无法放置,将方块返回原位置
  702. const brickData = this.editingData.brickData;
  703. if (brickData) {
  704. this.bricksList.push(brickData);
  705. // 添加回弹动画
  706. tween(brickNode)
  707. .to(0.2, {
  708. worldPosition: brickData.brickInitPos,
  709. scale: new Vec3(0.6, 0.6, 0.6)
  710. })
  711. .call(() => {
  712. if (originalParent) {
  713. brickNode.setParent(originalParent);
  714. brickNode.setWorldPosition(brickData.brickInitPos);
  715. }
  716. this.editingFlag = false;
  717. })
  718. .start();
  719. } else {
  720. this.editingFlag = false;
  721. }
  722. }
  723. // 检查是否需要处理旋转(短距离移动视为点击)
  724. if (!this.rotateFlag &&
  725. this.editingData.brickData &&
  726. this.editingData.brickData.rotateFlag &&
  727. event.getUILocation().subtract(this.touchStartLocation).length() < this.rotateFaultTolerant) {
  728. this.rotateFlag = true;
  729. this.rotateBrickData = this.editingData.brickData;
  730. // 显示旋转提示
  731. if (this.rotatePrefab && this.rotateNode && brickNode) {
  732. const rotateIndicator = instantiate(this.rotatePrefab);
  733. this.rotateNode.addChild(rotateIndicator);
  734. rotateIndicator.setWorldPosition(brickNode.getWorldPosition());
  735. }
  736. }
  737. };
  738. brickNode.on(Node.EventType.TOUCH_END, touchEndHandler, this);
  739. brickNode.on(Node.EventType.TOUCH_CANCEL, touchEndHandler, this);
  740. }
  741. //格子颜色恢复
  742. gridColorRecovery() {
  743. while (this.gridColorList.length > 0) {
  744. const gridData = this.gridColorList.pop();
  745. if (gridData) {
  746. if (gridData.status === CellState.EMPTY) {
  747. if (gridData.gridNode) {
  748. gridData.gridNode.children[0].getComponent(Sprite)!.color = this.notUseColor;
  749. }
  750. }
  751. }
  752. }
  753. }
  754. brickGridRotate(brickData: BrickData) {
  755. const next = this.nextGridRotate(brickData.gridConfig, brickData.deg)
  756. brickData.deg = next.deg
  757. brickData.gridConfig = next.gridConfig;
  758. if (brickData.brickNode) {
  759. tween(brickData.brickNode).to(0.1, { angle: next.deg }).start();
  760. }
  761. // this.audioManager.playRotate()
  762. }
  763. //下一个旋转
  764. nextGridRotate(gridConfig: GridConfigData[], deg: number) {
  765. const newGridConfig: GridConfigData[] = []
  766. // 顺时针旋转
  767. let newDeg = deg - 90
  768. gridConfig.forEach((gridConfigData) => {
  769. // 例如(1,2) => (-2,1),可以画图分析
  770. newGridConfig.push({
  771. row: -gridConfigData.column,
  772. column: gridConfigData.row
  773. })
  774. })
  775. return { gridConfig: newGridConfig, deg: newDeg }
  776. }
  777. // 显示分数增加动画
  778. showScoreAnimation(position: Vec3, score: number) {
  779. if (!this.lab_addScore) return;
  780. // 复制得分Label
  781. const scoreLabel = instantiate(this.lab_addScore.node);
  782. scoreLabel.active = true;
  783. // 设置文本和位置
  784. const label = scoreLabel.getComponent(Label);
  785. if (label) {
  786. label.string = `+${score}`;
  787. }
  788. // 添加到场景中
  789. this.node.addChild(scoreLabel);
  790. scoreLabel.setWorldPosition(position);
  791. const num = this._isDoubleSpeed ? this._doubleNum : 1;
  792. // 创建动画效果
  793. tween(scoreLabel)
  794. .to(0.5 / num, {
  795. position: new Vec3(scoreLabel.position.x, scoreLabel.position.y + 50, 0),
  796. scale: new Vec3(1.2, 1.2, 1.2)
  797. })
  798. .to(0.3 / num, { opacity: 0 })
  799. .call(() => {
  800. scoreLabel.destroy();
  801. })
  802. .start();
  803. // 更新总分
  804. this.score += score;
  805. this.lab_score.string = this.score.toString();
  806. //计算总分够一局没有,够就马上停止,展示界面
  807. }
  808. // 显示消除次数动画
  809. showEliminateCountAnimation(yPosition: number) {
  810. if (!this.lab_total) return;
  811. // 如果需要重置计数器,先将计数归零
  812. if (this.shouldResetEliminateCount) {
  813. this.totalNum = 0;
  814. this.shouldResetEliminateCount = false;
  815. }
  816. // 增加累计消除次数
  817. this.totalNum++;
  818. // 复制总次数Label
  819. const totalLabel = instantiate(this.lab_total.node);
  820. totalLabel.active = true;
  821. // 设置文本
  822. const label = totalLabel.getComponent(Label);
  823. if (label) {
  824. label.string = `Combo${this.totalNum}`;
  825. }
  826. // 添加到场景中
  827. this.node.addChild(totalLabel);
  828. // 计算网格区域的X轴中心位置,Y轴使用传入的消除行位置
  829. const centerPos = new Vec3();
  830. if (this.gridNode) {
  831. // 获取网格区域的X轴中心
  832. const worldPos = this.gridNode.getWorldPosition();
  833. centerPos.set(worldPos.x, yPosition, worldPos.z);
  834. }
  835. totalLabel.setWorldPosition(centerPos);
  836. // 创建动画效果
  837. const num = this._isDoubleSpeed ? this._doubleNum : 1;
  838. tween(totalLabel)
  839. .to(0.3 / num, {
  840. scale: new Vec3(1.5, 1.5, 1.5),
  841. opacity: 255
  842. })
  843. .delay(0.5 / num) // 停留更长时间
  844. .to(0.4 / num, {
  845. scale: new Vec3(1.2, 1.2, 1.2),
  846. position: new Vec3(totalLabel.position.x, totalLabel.position.y + 50, 0),
  847. opacity: 0
  848. })
  849. .call(() => {
  850. totalLabel.destroy();
  851. })
  852. .start();
  853. }
  854. // 修改 gridEliminate 方法来显示消除次数
  855. gridEliminate() {
  856. return new Promise<boolean>((resolve, reject) => {
  857. const d = this.gridEliminateCheck(this.gridList)
  858. const gridEliminateList = d.gridEliminateList
  859. const eliminateRowNum = d.eliminateRowNum
  860. const eliminateColumnNum = d.eliminateColumnNum
  861. if (gridEliminateList.length < 1) {
  862. // 没有发生消除
  863. this.shouldResetEliminateCount = true; // 下一次消除需要重置计数
  864. resolve(false);
  865. return;
  866. }
  867. // 如果有消除,计算消除行的平均Y轴位置
  868. if (gridEliminateList.length > 0) {
  869. // 计算所有被消除格子的平均Y轴位置
  870. let totalY = 0;
  871. let validGrids = 0;
  872. for (const grid of gridEliminateList) {
  873. if (grid.gridNode) {
  874. totalY += grid.gridNode.getWorldPosition().y;
  875. validGrids++;
  876. }
  877. }
  878. // 计算平均Y位置
  879. const avgY = validGrids > 0 ? totalY / validGrids : 0;
  880. // 显示消除次数动画,传入Y轴位置
  881. this.showEliminateCountAnimation(avgY);
  882. }
  883. const num = this._isDoubleSpeed ? this._doubleNum : 1;
  884. gridEliminateList.forEach((gridData) => {
  885. if (gridData.gridNode?.children[0]) {
  886. const startPos = gridData.gridNode.getWorldPosition();
  887. tween(gridData.gridNode.children[0])
  888. .to(0.2 / num, { scale: new Vec3(0.5, 0.5) })
  889. .call(() => {
  890. gridData.status = CellState.EMPTY
  891. this.generateGrid(gridData)
  892. })
  893. .start()
  894. if (this.coinPrefab && this.amountLb?.node) {
  895. this.createCoinFlyAnimation(
  896. this.coinPrefab,
  897. startPos,
  898. this.amountLb.node.getWorldPosition(),
  899. 5
  900. );
  901. }
  902. //增加红包
  903. this.createCoinFlyAnimation(
  904. this.redPacketPrefab,
  905. startPos,
  906. this.awardLb.node.getWorldPosition(),
  907. 5
  908. );
  909. }
  910. })
  911. this.scheduleOnce(() => {
  912. let score = 0
  913. for (let i = 1; i <= eliminateRowNum; i++) {
  914. score += this.cols * i
  915. }
  916. for (let i = 1; i <= eliminateColumnNum; i++) {
  917. score += this.rows * i
  918. }
  919. this.score += score
  920. this.lab_score.string = this.score.toString();
  921. const lastGrid = gridEliminateList[gridEliminateList.length - 1];
  922. if (lastGrid?.gridNode && this.coinPrefab && this.amountLb?.node) {
  923. const lastPos = lastGrid.gridNode.getWorldPosition();
  924. // 添加回调函数,在金币动画完成后显示微信分数增加
  925. this.createCoinFlyAnimation(
  926. this.coinPrefab,
  927. lastPos,
  928. this.amountLb.node.getWorldPosition(),
  929. score,
  930. () => {
  931. // 显示微信分数增加动画
  932. this.showWechatScoreAnimation();
  933. }
  934. );
  935. // 添加回调函数,在红包动画完成后显示红包分数增加
  936. this.createCoinFlyAnimation(
  937. this.redPacketPrefab,
  938. lastPos,
  939. this.awardLb.node.getWorldPosition(),
  940. 5,
  941. () => {
  942. // 显示红包分数增加动画
  943. this.showRedPacketScoreAnimation();
  944. }
  945. );
  946. }
  947. // 告诉调用者有消除发生
  948. resolve(true)
  949. // 检查是否需要继续消除
  950. this.scheduleOnce(() => {
  951. // 递归调用,检查并处理连锁消除
  952. this.gridEliminate().then(() => {
  953. // 连锁消除结束,不做额外处理
  954. });
  955. }, 0.2);
  956. }, 0.2)
  957. })
  958. }
  959. gridEliminateCheck(gridList: GridData[][]) {
  960. const gridEliminateList: GridData[] = []
  961. let eliminateRowNum = 0
  962. let eliminateColumnNum = 0
  963. // 行检查
  964. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  965. const rowData = gridList[rowIndex]
  966. if (rowData.every(gridData => gridData.status === CellState.FILLED)) {
  967. rowData.forEach(gridData => {
  968. if (gridEliminateList.findIndex(data => data === gridData) < 0) {
  969. gridEliminateList.push(gridData)
  970. }
  971. })
  972. eliminateRowNum += 1
  973. }
  974. }
  975. // 列检查
  976. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  977. if (gridList.every(rowData => rowData[columnIndex].status === CellState.FILLED)) {
  978. gridList.forEach(rowData => {
  979. const gridData = rowData[columnIndex]
  980. if (gridEliminateList.findIndex(data => data === gridData) < 0) {
  981. gridEliminateList.push(gridData)
  982. }
  983. })
  984. eliminateColumnNum += 1
  985. }
  986. }
  987. return {
  988. gridEliminateList,
  989. eliminateRowNum,
  990. eliminateColumnNum,
  991. }
  992. }
  993. // 修改 createCoinFlyAnimation 方法,添加回调
  994. private createCoinFlyAnimation(prefab: Prefab, startPos: Vec3, endPos: Vec3, count: number, callback?: Function) {
  995. if (!prefab) return;
  996. let completedCount = 0;
  997. const totalCoins = Math.min(count, 10); // 限制最大数量
  998. for (let i = 0; i < totalCoins; i++) {
  999. const coin = instantiate(prefab);
  1000. this.node.addChild(coin);
  1001. coin.setWorldPosition(startPos);
  1002. // 随机偏移起始位置
  1003. const randomOffset = new Vec3(
  1004. (Math.random() - 0.5) * 50,
  1005. (Math.random() - 0.5) * 50,
  1006. 0
  1007. );
  1008. // 创建曲线动画
  1009. const num = this._isDoubleSpeed ? this._doubleNum : 1;
  1010. tween(coin)
  1011. .to(0.2 / num, {
  1012. position: new Vec3(
  1013. coin.position.x + randomOffset.x,
  1014. coin.position.y + randomOffset.y,
  1015. 0
  1016. )
  1017. })
  1018. .to(0.5 / num, { worldPosition: endPos })
  1019. .call(() => {
  1020. coin.destroy();
  1021. completedCount++;
  1022. // 所有金币动画完成后执行回调
  1023. if (completedCount === totalCoins && callback) {
  1024. callback();
  1025. }
  1026. })
  1027. .start();
  1028. }
  1029. }
  1030. // 显示微信分数增加动画
  1031. private showWechatScoreAnimation() {
  1032. if (!this.tweenWechatNode) return;
  1033. // 生成随机小数(小于1,保留2位小数)
  1034. const randomValue = Math.random() * 0.99;
  1035. const formattedValue = randomValue.toFixed(2);
  1036. // 获取并设置分数标签
  1037. const scoreLabel = this.tweenWechatNode.getChildByName("lab_num")?.getComponent(Label);
  1038. if (scoreLabel) {
  1039. scoreLabel.string = "+" + formattedValue;
  1040. }
  1041. // 保存原始位置
  1042. const originalPosition = this.tweenWechatNode.position.clone();
  1043. // 显示节点
  1044. this.tweenWechatNode.active = true;
  1045. // 创建向上移动的动画
  1046. tween(this.tweenWechatNode)
  1047. .to(0.8, {
  1048. position: new Vec3(
  1049. originalPosition.x,
  1050. originalPosition.y + 80,
  1051. originalPosition.z
  1052. ),
  1053. opacity: 255
  1054. })
  1055. .to(0.2, { opacity: 0 })
  1056. .call(() => {
  1057. // 重置位置
  1058. this.tweenWechatNode.setPosition(originalPosition);
  1059. this.tweenWechatNode.active = false;
  1060. // 更新总金额
  1061. if (this.amountLb) {
  1062. const currentAmount = parseFloat(this.amountLb.string);
  1063. const newAmount = currentAmount + parseFloat(formattedValue);
  1064. this.money = newAmount;
  1065. this.amountLb.string = newAmount.toFixed(2);
  1066. }
  1067. })
  1068. .start();
  1069. }
  1070. // 显示红包分数增加动画
  1071. private showRedPacketScoreAnimation() {
  1072. if (!this.tweenRedNode) return;
  1073. // 生成随机小数(小于1,保留2位小数)
  1074. const randomValue = Math.random() * 0.99;
  1075. const formattedValue = randomValue.toFixed(2);
  1076. // 获取并设置分数标签
  1077. const scoreLabel = this.tweenRedNode.getChildByName("lab_num")?.getComponent(Label);
  1078. if (scoreLabel) {
  1079. scoreLabel.string = "+" + formattedValue;
  1080. }
  1081. // 保存原始位置
  1082. const originalPosition = this.tweenRedNode.position.clone();
  1083. // 显示节点
  1084. this.tweenRedNode.active = true;
  1085. // 创建向上移动的动画
  1086. const num = this._isDoubleSpeed ? this._doubleNum : 1;
  1087. tween(this.tweenRedNode)
  1088. .to(0.8 / num, {
  1089. position: new Vec3(
  1090. originalPosition.x,
  1091. originalPosition.y + 80,
  1092. originalPosition.z
  1093. ),
  1094. opacity: 255
  1095. })
  1096. .to(0.2 / num, { opacity: 0 })
  1097. .call(() => {
  1098. // 重置位置
  1099. this.tweenRedNode.setPosition(originalPosition);
  1100. this.tweenRedNode.active = false;
  1101. // 更新总红包金额
  1102. if (this.awardLb) {
  1103. const currentAmount = parseFloat(this.awardLb.string);
  1104. const newAmount = currentAmount + parseFloat(formattedValue);
  1105. this.cash = newAmount;
  1106. this.awardLb.string = newAmount.toFixed(2);
  1107. }
  1108. })
  1109. .start();
  1110. }
  1111. // 提示
  1112. prompt(tipFlag = true) {
  1113. return new Promise((resolve, reject) => {
  1114. const gridPromptList: GridData[] = []
  1115. let moveFlag = false
  1116. // 找方块可消除位置
  1117. for (let rowIndex = 0; rowIndex < this.rows && !moveFlag; rowIndex++) {
  1118. for (let columnIndex = 0; columnIndex < this.cols && !moveFlag; columnIndex++) {
  1119. const gridData = this.gridList[rowIndex][columnIndex]
  1120. if (gridData.status !== CellState.EMPTY) continue
  1121. // 方块不旋转检测是否能放
  1122. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1123. const brickData = this.bricksList[brickI]
  1124. if (this.moveIf(rowIndex, columnIndex, brickData.gridConfig)) {
  1125. // 复制整体网格,以方块设置网格状态
  1126. const gridList = this.copyGridList()
  1127. brickData.gridConfig.forEach((gridConfigData) => {
  1128. gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = CellState.FILLED
  1129. })
  1130. // 检查复制的整体网格是否有可消除
  1131. if (this.gridEliminateCheck(gridList).gridEliminateList.length > 0) {
  1132. moveFlag = true
  1133. brickData.gridConfig.forEach((gridConfigData) => {
  1134. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1135. })
  1136. }
  1137. }
  1138. }
  1139. // 方块旋转检测是否能放
  1140. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1141. const brickData = this.bricksList[brickI]
  1142. if (!brickData.rotateFlag) continue
  1143. let gridConfig = brickData.gridConfig
  1144. let deg = brickData.deg
  1145. // 获得旋转的方块网格配置
  1146. for (let count = 1; count <= 3 && !moveFlag; count++) {
  1147. const next = this.nextGridRotate(gridConfig, deg)
  1148. if (this.moveIf(rowIndex, columnIndex, next.gridConfig)) {
  1149. // 复制整体网格,以方块设置网格状态
  1150. const gridList = this.copyGridList()
  1151. next.gridConfig.forEach((gridConfigData) => {
  1152. gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = CellState.FILLED
  1153. })
  1154. // 检查复制的整体网格是否有可消除
  1155. if (this.gridEliminateCheck(gridList).gridEliminateList.length > 0) {
  1156. moveFlag = true
  1157. next.gridConfig.forEach((gridConfigData) => {
  1158. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1159. })
  1160. }
  1161. }
  1162. gridConfig = next.gridConfig
  1163. deg = next.deg
  1164. }
  1165. }
  1166. }
  1167. }
  1168. // 找方块可放置位置
  1169. for (let rowIndex = 0; rowIndex < this.rows && !moveFlag; rowIndex++) {
  1170. for (let columnIndex = 0; columnIndex < this.cols && !moveFlag; columnIndex++) {
  1171. const gridData = this.gridList[rowIndex][columnIndex]
  1172. if (gridData.status !== CellState.EMPTY) continue
  1173. // 方块不旋转检测是否能放
  1174. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1175. const brickData = this.bricksList[brickI]
  1176. if (this.moveIf(rowIndex, columnIndex, brickData.gridConfig)) {
  1177. moveFlag = true
  1178. brickData.gridConfig.forEach((gridConfigData) => {
  1179. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1180. })
  1181. }
  1182. }
  1183. // 方块旋转检测是否能放
  1184. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1185. const brickData = this.bricksList[brickI]
  1186. if (!brickData.rotateFlag) continue
  1187. let gridConfig = brickData.gridConfig
  1188. let deg = brickData.deg
  1189. for (let count = 1; count <= 3 && !moveFlag; count++) {
  1190. const next = this.nextGridRotate(gridConfig, deg)
  1191. if (this.moveIf(rowIndex, columnIndex, next.gridConfig)) {
  1192. moveFlag = true
  1193. next.gridConfig.forEach((gridConfigData) => {
  1194. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1195. })
  1196. }
  1197. gridConfig = next.gridConfig
  1198. deg = next.deg
  1199. }
  1200. }
  1201. }
  1202. }
  1203. if (gridPromptList.length < 1) {
  1204. resolve(false)
  1205. return
  1206. }
  1207. if (!tipFlag) {
  1208. resolve(true)
  1209. return
  1210. }
  1211. // 提示用户(网格变绿)
  1212. gridPromptList.forEach((gridData) => {
  1213. if (gridData.gridNode && gridData.gridNode.children[0]) {
  1214. const sprite = gridData.gridNode.children[0].getComponent(Sprite);
  1215. if (sprite) {
  1216. sprite.color = this.usableColor;
  1217. }
  1218. }
  1219. // 用于恢复格子
  1220. this.gridColorList.push(gridData)
  1221. })
  1222. resolve(true)
  1223. })
  1224. }
  1225. moveIf(row: number, column: number, gridConfig: GridConfigData[]) {
  1226. let moveFlag = true
  1227. for (let i = 0; i < gridConfig.length; i++) {
  1228. const gridConfigData = gridConfig[i]
  1229. const gridI = row + gridConfigData.row
  1230. const gridJ = column + gridConfigData.column
  1231. // 边界判断
  1232. if (
  1233. gridI < 0 ||
  1234. gridI > this.rows - 1 ||
  1235. gridJ < 0 ||
  1236. gridJ > this.cols - 1
  1237. ) {
  1238. moveFlag = false
  1239. break
  1240. }
  1241. // 已用
  1242. else if (this.gridList[gridI][gridJ].status === CellState.FILLED) {
  1243. moveFlag = false
  1244. break
  1245. }
  1246. }
  1247. return moveFlag
  1248. }
  1249. // 复制整体网格
  1250. copyGridList() {
  1251. const gridList: GridData[][] = []
  1252. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1253. gridList.push([])
  1254. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1255. const gridData = this.gridList[rowIndex][columnIndex]
  1256. gridList[rowIndex].push({
  1257. name: gridData.name,
  1258. status: gridData.status,
  1259. gridNode: null,
  1260. row: gridData.row,
  1261. col: gridData.col,
  1262. type: gridData.type,
  1263. })
  1264. }
  1265. }
  1266. return gridList
  1267. }
  1268. gameOver() {
  1269. this.gameState = GameState.GAME_OVER
  1270. this.setGameState(GameState.GAME_OVER)
  1271. console.log("游戏结束")
  1272. oops.gui.open(UIID.GameOver);
  1273. }
  1274. /**
  1275. * 清理网格的子节点
  1276. */
  1277. private clearGridChildren(gridNode: Node): void {
  1278. const children = gridNode.children.slice(); // 创建副本避免遍历时修改问题
  1279. children.forEach(node => node.destroy());
  1280. }
  1281. private setGameState(state: GameState) {
  1282. this.gameState = state;
  1283. switch (state) {
  1284. case GameState.READY:
  1285. break;
  1286. case GameState.PLAYING:
  1287. break;
  1288. case GameState.PAUSED:
  1289. break;
  1290. case GameState.GAME_OVER:
  1291. //打开游戏结束界面
  1292. break;
  1293. }
  1294. }
  1295. //========================打开其他界面和按钮逻辑=======================
  1296. /** 视图对象通过 ecs.Entity.remove(eliminateViewComp) 删除组件是触发组件处理自定义释放逻辑 */
  1297. reset() {
  1298. this.node.destroy();
  1299. }
  1300. //设置按钮
  1301. private btn_setting() {
  1302. oops.gui.open(UIID.Setting);
  1303. }
  1304. //左边微信按钮
  1305. private btn_withdraw() {
  1306. oops.gui.open(UIID.WechatWithdraw);
  1307. }
  1308. //顶部红包按钮
  1309. private btn_award() {
  1310. oops.gui.open(UIID.RedPacketWithdraw);
  1311. }
  1312. //二倍速按钮
  1313. private btn_double() {
  1314. oops.gui.open(UIID.DoubleSpeed);
  1315. }
  1316. //自动按钮
  1317. private btn_auto() {
  1318. //自动放置
  1319. this.autoState = !this.autoState;
  1320. this._isDoubleSpeed = !this._isDoubleSpeed;
  1321. this.initButtonState(this.autoState);
  1322. if (this.autoState) {
  1323. this.gameState = GameState.PLAYING;
  1324. this.executeAutoPlace()
  1325. }
  1326. }
  1327. executeAutoPlace() {
  1328. if (!this.autoState || this.gameState !== GameState.PLAYING || this.editingFlag) {
  1329. return
  1330. }
  1331. console.log("开始自动放置")
  1332. const bestPlacement = this.findBestPlacement()
  1333. if (!bestPlacement) {
  1334. // 所有方块都无法放置,游戏结束
  1335. this.autoState = false
  1336. this.gameOver()
  1337. return
  1338. }
  1339. // 执行放置
  1340. this.placeBrickAtPosition(bestPlacement)
  1341. }
  1342. findBestPlacement() {
  1343. const placements = []
  1344. // 对每个方块计算所有可能的放置位置和分数
  1345. for (let brickIndex = 0; brickIndex < this.bricksList.length; brickIndex++) {
  1346. const brickData = this.bricksList[brickIndex]
  1347. // 检查不同旋转状态
  1348. let gridConfigs = [brickData.gridConfig]
  1349. let degrees = [brickData.deg]
  1350. // 如果可旋转,计算所有旋转状态
  1351. if (brickData.rotateFlag) {
  1352. for (let i = 1; i <= 3; i++) {
  1353. const next = this.nextGridRotate(
  1354. i === 1 ? brickData.gridConfig : gridConfigs[i - 1],
  1355. i === 1 ? brickData.deg : degrees[i - 1]
  1356. )
  1357. gridConfigs.push(next.gridConfig)
  1358. degrees.push(next.deg)
  1359. }
  1360. }
  1361. // 遍历所有网格位置
  1362. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1363. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1364. // 对每个旋转状态检查
  1365. for (let rotateIndex = 0; rotateIndex < gridConfigs.length; rotateIndex++) {
  1366. const currentGridConfig = gridConfigs[rotateIndex]
  1367. const currentDeg = degrees[rotateIndex]
  1368. // 检查是否可以放置
  1369. if (this.moveIf(rowIndex, columnIndex, currentGridConfig)) {
  1370. // 复制网格并模拟放置
  1371. const gridList = this.copyGridList()
  1372. currentGridConfig.forEach((gridConfigData) => {
  1373. const r = gridConfigData.row + rowIndex
  1374. const c = gridConfigData.column + columnIndex
  1375. gridList[r][c].status = CellState.FILLED
  1376. // gridList[r][c].gridColorKey = brickData.gridColorKey
  1377. gridList[r][c].type = brickData.type;
  1378. })
  1379. // 检查是否可以消除,计算分数
  1380. const elimination = this.gridEliminateCheck(gridList)
  1381. let score = 0
  1382. if (elimination.gridEliminateList.length > 0) {
  1383. // 计算消除得分
  1384. for (let i = 1; i <= elimination.eliminateRowNum; i++) {
  1385. score += this.cols * i
  1386. }
  1387. for (let i = 1; i <= elimination.eliminateColumnNum; i++) {
  1388. score += this.rows * i
  1389. }
  1390. }
  1391. // 记录此放置选项
  1392. placements.push({
  1393. brickIndex,
  1394. brickData,
  1395. rowIndex,
  1396. columnIndex,
  1397. gridConfig: currentGridConfig,
  1398. deg: currentDeg,
  1399. score,
  1400. canEliminate: elimination.gridEliminateList.length > 0
  1401. })
  1402. }
  1403. }
  1404. }
  1405. }
  1406. }
  1407. // 按优先级排序:最高分 > 有分数 > 没有分数但可放置
  1408. placements.sort((a, b) => {
  1409. // 首先按分数排序
  1410. if (a.score !== b.score) {
  1411. return b.score - a.score
  1412. }
  1413. // 其次按是否可消除排序
  1414. if (a.canEliminate !== b.canEliminate) {
  1415. return a.canEliminate ? -1 : 1
  1416. }
  1417. // 最后按照方块优先级排序(底部的方块优先)
  1418. return a.brickIndex - b.brickIndex
  1419. })
  1420. return placements.length > 0 ? placements[0] : null
  1421. }
  1422. // ... existing code ...
  1423. placeBrickAtPosition(placement) {
  1424. // 获取方块数据
  1425. const brickData = placement.brickData
  1426. const index = this.bricksList.findIndex(data => data === brickData)
  1427. if (index === -1) {
  1428. console.error("无法找到要放置的方块:", brickData)
  1429. return
  1430. }
  1431. // 从待选区移除方块
  1432. this.editingData.brickData = this.bricksList.splice(index, 1)[0]
  1433. // 如果需要旋转,执行旋转
  1434. const num = this._isDoubleSpeed ? this._doubleNum : 1;
  1435. if (brickData.deg !== placement.deg) {
  1436. // 更新方块配置和角度
  1437. brickData.gridConfig = placement.gridConfig
  1438. brickData.deg = placement.deg
  1439. // 添加旋转动画
  1440. tween(brickData.brickNode).to(0.2 / num, { angle: placement.deg }).start()
  1441. }
  1442. // 准备网格列表
  1443. this.editingData.gridList = []
  1444. placement.gridConfig.forEach((gridConfigData: GridConfigData) => {
  1445. const r = gridConfigData.row + placement.rowIndex
  1446. const c = gridConfigData.column + placement.columnIndex
  1447. this.editingData.gridList.push(this.gridList[r][c])
  1448. })
  1449. // 计算目标位置 - 使用中间位置作为基准
  1450. let centerPos = new Vec3(0, 0, 0);
  1451. let validGridCount = 0;
  1452. // 计算所有网格的平均位置
  1453. this.editingData.gridList.forEach(grid => {
  1454. if (grid.gridNode) {
  1455. const worldPos = grid.gridNode.getWorldPosition();
  1456. centerPos.add(worldPos);
  1457. validGridCount++;
  1458. }
  1459. });
  1460. // 计算平均位置
  1461. if (validGridCount > 0) {
  1462. centerPos.x /= validGridCount;
  1463. centerPos.y /= validGridCount;
  1464. centerPos.z /= validGridCount;
  1465. } else {
  1466. // 如果没有有效网格,使用第一个网格的位置作为后备
  1467. const targetGridData = this.editingData.gridList[0];
  1468. if (targetGridData && targetGridData.gridNode) {
  1469. centerPos = targetGridData.gridNode.getWorldPosition();
  1470. }
  1471. }
  1472. // 添加到移动节点里进行移动
  1473. const originPos = brickData.brickNode.getWorldPosition()
  1474. brickData.brickNode.setParent(this.moveNode)
  1475. brickData.brickNode.setWorldPosition(originPos)
  1476. // 使用动画移动到目标位置--这里的最终放置有问题
  1477. tween(brickData.brickNode)
  1478. .to(2 / num, { worldPosition: centerPos })
  1479. .call(() => {
  1480. // 动画完成后修改格子状态
  1481. this.editingData.gridList.forEach((gridData) => {
  1482. gridData.status = CellState.FILLED
  1483. gridData.type = this.editingData.brickData.type
  1484. this.generateGrid(gridData)
  1485. })
  1486. // 销毁方块
  1487. this.editingData.brickData.brickNode.destroy()
  1488. // 添加新方块
  1489. this.addBrick(this.editingData.brickData.index)
  1490. // 检查消除和游戏状态
  1491. this.gridEliminate().then(() => {
  1492. this.prompt(false).then((value: unknown) => {
  1493. const promptFlag = value as boolean;
  1494. if (!promptFlag) {
  1495. this.autoState = false
  1496. this.gameOver()
  1497. } else if (this.autoState) {
  1498. // 继续自动放置
  1499. this.scheduleOnce(() => {
  1500. this.executeAutoPlace()
  1501. }, 0.3)
  1502. }
  1503. this.editingFlag = false
  1504. })
  1505. })
  1506. })
  1507. .start()
  1508. }
  1509. doubleSpeedOpenSuccess() {
  1510. this._isDoubleSpeed = true;
  1511. //3分钟后关闭
  1512. this.scheduleOnce(() => {
  1513. this._isDoubleSpeed = false;
  1514. //关闭会自动触发二倍速弹窗,这要带参数
  1515. // oops.gui.open(UIID.DoubleSpeed, { isAutoOpen: true });
  1516. }, 180);
  1517. }
  1518. //重新开始
  1519. private restartGame() {
  1520. if (this.gameState === GameState.READY) return;
  1521. this.initData();
  1522. this.reopenGrid();
  1523. this.initButtonState(this.autoState);
  1524. }
  1525. //重新清除网格
  1526. private reopenGrid() {
  1527. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1528. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1529. this.gridList[rowIndex][columnIndex].status = CellState.EMPTY
  1530. this.generateGrid(this.gridList[rowIndex][columnIndex])
  1531. }
  1532. }
  1533. // 初始化方块
  1534. if (this.brickNode) {
  1535. if (this.brickNode) {
  1536. this.brickNode.children.forEach(node => { node.destroy() });
  1537. }
  1538. }
  1539. this.bricksList.length = 0
  1540. for (let i = 1; i <= this.brickNum; i++) {
  1541. this.addBrick(i)
  1542. }
  1543. // 清除旋转数据
  1544. if (this.rotateNode) {
  1545. this.rotateNode.children.forEach(node => { node.destroy() })
  1546. }
  1547. }
  1548. }