EliminateViewComp.ts 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768
  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 17:55:03
  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. //网格列表
  133. // gridsNode: Node | null = null; //中间网格区域
  134. // brickNode: Node | null = null; //底部三个item块区域
  135. // moveNode: Node | null = null; //移动层Node
  136. // rotateNode: Node | null = null; //旋转Node吧
  137. //没使用颜色
  138. notUseColor = new Color(255, 255, 255, 255)
  139. //可用的颜色
  140. usableColor = new Color(0, 255, 0, 100)
  141. //不可用的颜色
  142. unavailableColor = new Color(255, 0, 0, 100)
  143. //旋转容错
  144. rotateFaultTolerant = 10;
  145. private _isAutoFunc: (() => void) | null = null;
  146. isAutoMode: boolean = false;
  147. autoModeInterval: number = 1 // 自动模式的间隔时间(秒)
  148. autoModeTimer: number = 0 // 自动模式计时器
  149. //网格列表管理列表
  150. gridList: GridData[][] = [];
  151. //砖块列表
  152. bricksList: BrickData[] = [];
  153. //网格颜色列表
  154. gridColorList: GridData[] = [];
  155. brickConfig: { bricks?: any } = {} //方块配置
  156. editingFlag = false //编辑状态
  157. editingData: EditingData = {
  158. brickData: null,
  159. gridList: [],
  160. }
  161. //旋转标记
  162. rotateFlag = false
  163. rotateBrickData: BrickData | null = null
  164. // 添加新的属性来跟踪是否需要重置消除计数
  165. private shouldResetEliminateCount: boolean = true;
  166. private consecutiveEliminations: boolean = false;
  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.autoState = false;
  219. this.shouldResetEliminateCount = true;
  220. this.consecutiveEliminations = false;
  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. this.consecutiveEliminations = true;
  665. // 销毁方块节点
  666. brickNode.destroy();
  667. // 添加新方块到待选区
  668. this.addBrick(this.editingData.brickData.index);
  669. // 检查消除
  670. this.scheduleOnce(() => {
  671. this.gridEliminate().then((hasElimination) => {
  672. // 如果没有消除,确保下次消除会重置计数
  673. if (!hasElimination) {
  674. this.shouldResetEliminateCount = true;
  675. }
  676. // 检查游戏是否结束
  677. this.prompt(false).then(canContinue => {
  678. if (!canContinue) {
  679. this.gameOver();
  680. }
  681. this.editingFlag = false;
  682. });
  683. });
  684. }, 0.1);
  685. } else if (this.rotateFlag) {
  686. // 旋转方块
  687. const brickData = this.editingData.brickData;
  688. this.brickGridRotate(brickData);
  689. // 方块放回待选区
  690. this.bricksList.push(brickData);
  691. if (this.brickNode && brickData.brickNode) {
  692. this.brickNode.addChild(brickData.brickNode);
  693. tween(brickData.brickNode)
  694. .to(0.2, {
  695. worldPosition: brickData.brickInitPos,
  696. scale: new Vec3(0.6, 0.6, 0.6)
  697. })
  698. .start();
  699. }
  700. this.editingFlag = false;
  701. } else {
  702. // 无法放置,将方块返回原位置
  703. const brickData = this.editingData.brickData;
  704. if (brickData) {
  705. this.bricksList.push(brickData);
  706. // 添加回弹动画
  707. tween(brickNode)
  708. .to(0.2, {
  709. worldPosition: brickData.brickInitPos,
  710. scale: new Vec3(0.6, 0.6, 0.6)
  711. })
  712. .call(() => {
  713. if (originalParent) {
  714. brickNode.setParent(originalParent);
  715. brickNode.setWorldPosition(brickData.brickInitPos);
  716. }
  717. this.editingFlag = false;
  718. })
  719. .start();
  720. } else {
  721. this.editingFlag = false;
  722. }
  723. }
  724. // 检查是否需要处理旋转(短距离移动视为点击)
  725. if (!this.rotateFlag &&
  726. this.editingData.brickData &&
  727. this.editingData.brickData.rotateFlag &&
  728. event.getUILocation().subtract(this.touchStartLocation).length() < this.rotateFaultTolerant) {
  729. this.rotateFlag = true;
  730. this.rotateBrickData = this.editingData.brickData;
  731. // 显示旋转提示
  732. if (this.rotatePrefab && this.rotateNode && brickNode) {
  733. const rotateIndicator = instantiate(this.rotatePrefab);
  734. this.rotateNode.addChild(rotateIndicator);
  735. rotateIndicator.setWorldPosition(brickNode.getWorldPosition());
  736. }
  737. }
  738. };
  739. brickNode.on(Node.EventType.TOUCH_END, touchEndHandler, this);
  740. brickNode.on(Node.EventType.TOUCH_CANCEL, touchEndHandler, this);
  741. }
  742. //格子颜色恢复
  743. gridColorRecovery() {
  744. while (this.gridColorList.length > 0) {
  745. const gridData = this.gridColorList.pop();
  746. if (gridData) {
  747. if (gridData.status === CellState.EMPTY) {
  748. if (gridData.gridNode) {
  749. gridData.gridNode.children[0].getComponent(Sprite)!.color = this.notUseColor;
  750. }
  751. }
  752. }
  753. }
  754. }
  755. brickGridRotate(brickData: BrickData) {
  756. const next = this.nextGridRotate(brickData.gridConfig, brickData.deg)
  757. brickData.deg = next.deg
  758. brickData.gridConfig = next.gridConfig;
  759. if (brickData.brickNode) {
  760. tween(brickData.brickNode).to(0.1, { angle: next.deg }).start();
  761. }
  762. // this.audioManager.playRotate()
  763. }
  764. //下一个旋转
  765. nextGridRotate(gridConfig: GridConfigData[], deg: number) {
  766. const newGridConfig: GridConfigData[] = []
  767. // 顺时针旋转
  768. let newDeg = deg - 90
  769. gridConfig.forEach((gridConfigData) => {
  770. // 例如(1,2) => (-2,1),可以画图分析
  771. newGridConfig.push({
  772. row: -gridConfigData.column,
  773. column: gridConfigData.row
  774. })
  775. })
  776. return { gridConfig: newGridConfig, deg: newDeg }
  777. }
  778. // 显示分数增加动画
  779. showScoreAnimation(position: Vec3, score: number) {
  780. if (!this.lab_addScore) return;
  781. // 复制得分Label
  782. const scoreLabel = instantiate(this.lab_addScore.node);
  783. scoreLabel.active = true;
  784. // 设置文本和位置
  785. const label = scoreLabel.getComponent(Label);
  786. if (label) {
  787. label.string = `+${score}`;
  788. }
  789. // 添加到场景中
  790. this.node.addChild(scoreLabel);
  791. scoreLabel.setWorldPosition(position);
  792. // 创建动画效果
  793. tween(scoreLabel)
  794. .to(0.5, {
  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, { 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. tween(totalLabel)
  838. .to(0.3, {
  839. scale: new Vec3(1.5, 1.5, 1.5),
  840. opacity: 255
  841. })
  842. .delay(0.5) // 停留更长时间
  843. .to(0.4, {
  844. scale: new Vec3(1.2, 1.2, 1.2),
  845. position: new Vec3(totalLabel.position.x, totalLabel.position.y + 50, 0),
  846. opacity: 0
  847. })
  848. .call(() => {
  849. totalLabel.destroy();
  850. })
  851. .start();
  852. }
  853. // 修改 gridEliminate 方法来显示消除次数
  854. gridEliminate() {
  855. return new Promise<boolean>((resolve, reject) => {
  856. const d = this.gridEliminateCheck(this.gridList)
  857. const gridEliminateList = d.gridEliminateList
  858. const eliminateRowNum = d.eliminateRowNum
  859. const eliminateColumnNum = d.eliminateColumnNum
  860. if (gridEliminateList.length < 1) {
  861. // 没有发生消除
  862. this.shouldResetEliminateCount = true; // 下一次消除需要重置计数
  863. this.consecutiveEliminations = false; // 不是连续消除
  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. // 标记为连续消除
  881. this.consecutiveEliminations = true;
  882. // 显示消除次数动画,传入Y轴位置
  883. this.showEliminateCountAnimation(avgY);
  884. }
  885. gridEliminateList.forEach((gridData) => {
  886. if (gridData.gridNode?.children[0]) {
  887. const startPos = gridData.gridNode.getWorldPosition();
  888. tween(gridData.gridNode.children[0])
  889. .to(0.2, { scale: new Vec3(0.5, 0.5) })
  890. .call(() => {
  891. gridData.status = CellState.EMPTY
  892. this.generateGrid(gridData)
  893. })
  894. .start()
  895. if (this.coinPrefab && this.amountLb?.node) {
  896. this.createCoinFlyAnimation(
  897. this.coinPrefab,
  898. startPos,
  899. this.amountLb.node.getWorldPosition(),
  900. 5
  901. );
  902. }
  903. //增加红包
  904. this.createCoinFlyAnimation(
  905. this.redPacketPrefab,
  906. startPos,
  907. this.awardLb.node.getWorldPosition(),
  908. 5
  909. );
  910. }
  911. })
  912. this.scheduleOnce(() => {
  913. let score = 0
  914. for (let i = 1; i <= eliminateRowNum; i++) {
  915. score += this.cols * i
  916. }
  917. for (let i = 1; i <= eliminateColumnNum; i++) {
  918. score += this.rows * i
  919. }
  920. this.score += score
  921. this.lab_score.string = this.score.toString();
  922. const lastGrid = gridEliminateList[gridEliminateList.length - 1];
  923. if (lastGrid?.gridNode && this.coinPrefab && this.amountLb?.node) {
  924. const lastPos = lastGrid.gridNode.getWorldPosition();
  925. // 添加回调函数,在金币动画完成后显示微信分数增加
  926. this.createCoinFlyAnimation(
  927. this.coinPrefab,
  928. lastPos,
  929. this.amountLb.node.getWorldPosition(),
  930. score,
  931. () => {
  932. // 显示微信分数增加动画
  933. this.showWechatScoreAnimation();
  934. }
  935. );
  936. // 添加回调函数,在红包动画完成后显示红包分数增加
  937. this.createCoinFlyAnimation(
  938. this.redPacketPrefab,
  939. lastPos,
  940. this.awardLb.node.getWorldPosition(),
  941. 5,
  942. () => {
  943. // 显示红包分数增加动画
  944. this.showRedPacketScoreAnimation();
  945. }
  946. );
  947. }
  948. // 告诉调用者有消除发生
  949. resolve(true)
  950. // 检查是否需要继续消除
  951. this.scheduleOnce(() => {
  952. // 递归调用,检查并处理连锁消除
  953. this.gridEliminate().then(() => {
  954. // 连锁消除结束,不做额外处理
  955. });
  956. }, 0.2);
  957. }, 0.2)
  958. })
  959. }
  960. gridEliminateCheck(gridList: GridData[][]) {
  961. const gridEliminateList: GridData[] = []
  962. let eliminateRowNum = 0
  963. let eliminateColumnNum = 0
  964. // 行检查
  965. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  966. const rowData = gridList[rowIndex]
  967. if (rowData.every(gridData => gridData.status === CellState.FILLED)) {
  968. rowData.forEach(gridData => {
  969. if (gridEliminateList.findIndex(data => data === gridData) < 0) {
  970. gridEliminateList.push(gridData)
  971. }
  972. })
  973. eliminateRowNum += 1
  974. }
  975. }
  976. // 列检查
  977. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  978. if (gridList.every(rowData => rowData[columnIndex].status === CellState.FILLED)) {
  979. gridList.forEach(rowData => {
  980. const gridData = rowData[columnIndex]
  981. if (gridEliminateList.findIndex(data => data === gridData) < 0) {
  982. gridEliminateList.push(gridData)
  983. }
  984. })
  985. eliminateColumnNum += 1
  986. }
  987. }
  988. return {
  989. gridEliminateList,
  990. eliminateRowNum,
  991. eliminateColumnNum,
  992. }
  993. }
  994. // 修改 createCoinFlyAnimation 方法,添加回调
  995. private createCoinFlyAnimation(prefab: Prefab, startPos: Vec3, endPos: Vec3, count: number, callback?: Function) {
  996. if (!prefab) return;
  997. let completedCount = 0;
  998. const totalCoins = Math.min(count, 10); // 限制最大数量
  999. for (let i = 0; i < totalCoins; i++) {
  1000. const coin = instantiate(prefab);
  1001. this.node.addChild(coin);
  1002. coin.setWorldPosition(startPos);
  1003. // 随机偏移起始位置
  1004. const randomOffset = new Vec3(
  1005. (Math.random() - 0.5) * 50,
  1006. (Math.random() - 0.5) * 50,
  1007. 0
  1008. );
  1009. // 创建曲线动画
  1010. tween(coin)
  1011. .to(0.2, {
  1012. position: new Vec3(
  1013. coin.position.x + randomOffset.x,
  1014. coin.position.y + randomOffset.y,
  1015. 0
  1016. )
  1017. })
  1018. .to(0.5, { 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. tween(this.tweenRedNode)
  1087. .to(0.8, {
  1088. position: new Vec3(
  1089. originalPosition.x,
  1090. originalPosition.y + 80,
  1091. originalPosition.z
  1092. ),
  1093. opacity: 255
  1094. })
  1095. .to(0.2, { opacity: 0 })
  1096. .call(() => {
  1097. // 重置位置
  1098. this.tweenRedNode.setPosition(originalPosition);
  1099. this.tweenRedNode.active = false;
  1100. // 更新总红包金额
  1101. if (this.awardLb) {
  1102. const currentAmount = parseFloat(this.awardLb.string);
  1103. const newAmount = currentAmount + parseFloat(formattedValue);
  1104. this.cash = newAmount;
  1105. this.awardLb.string = newAmount.toFixed(2);
  1106. }
  1107. })
  1108. .start();
  1109. }
  1110. // 提示
  1111. prompt(tipFlag = true) {
  1112. return new Promise((resolve, reject) => {
  1113. const gridPromptList: GridData[] = []
  1114. let moveFlag = false
  1115. // 找方块可消除位置
  1116. for (let rowIndex = 0; rowIndex < this.rows && !moveFlag; rowIndex++) {
  1117. for (let columnIndex = 0; columnIndex < this.cols && !moveFlag; columnIndex++) {
  1118. const gridData = this.gridList[rowIndex][columnIndex]
  1119. if (gridData.status !== CellState.EMPTY) continue
  1120. // 方块不旋转检测是否能放
  1121. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1122. const brickData = this.bricksList[brickI]
  1123. if (this.moveIf(rowIndex, columnIndex, brickData.gridConfig)) {
  1124. // 复制整体网格,以方块设置网格状态
  1125. const gridList = this.copyGridList()
  1126. brickData.gridConfig.forEach((gridConfigData) => {
  1127. gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = CellState.FILLED
  1128. })
  1129. // 检查复制的整体网格是否有可消除
  1130. if (this.gridEliminateCheck(gridList).gridEliminateList.length > 0) {
  1131. moveFlag = true
  1132. brickData.gridConfig.forEach((gridConfigData) => {
  1133. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1134. })
  1135. }
  1136. }
  1137. }
  1138. // 方块旋转检测是否能放
  1139. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1140. const brickData = this.bricksList[brickI]
  1141. if (!brickData.rotateFlag) continue
  1142. let gridConfig = brickData.gridConfig
  1143. let deg = brickData.deg
  1144. // 获得旋转的方块网格配置
  1145. for (let count = 1; count <= 3 && !moveFlag; count++) {
  1146. const next = this.nextGridRotate(gridConfig, deg)
  1147. if (this.moveIf(rowIndex, columnIndex, next.gridConfig)) {
  1148. // 复制整体网格,以方块设置网格状态
  1149. const gridList = this.copyGridList()
  1150. next.gridConfig.forEach((gridConfigData) => {
  1151. gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = CellState.FILLED
  1152. })
  1153. // 检查复制的整体网格是否有可消除
  1154. if (this.gridEliminateCheck(gridList).gridEliminateList.length > 0) {
  1155. moveFlag = true
  1156. next.gridConfig.forEach((gridConfigData) => {
  1157. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1158. })
  1159. }
  1160. }
  1161. gridConfig = next.gridConfig
  1162. deg = next.deg
  1163. }
  1164. }
  1165. }
  1166. }
  1167. // 找方块可放置位置
  1168. for (let rowIndex = 0; rowIndex < this.rows && !moveFlag; rowIndex++) {
  1169. for (let columnIndex = 0; columnIndex < this.cols && !moveFlag; columnIndex++) {
  1170. const gridData = this.gridList[rowIndex][columnIndex]
  1171. if (gridData.status !== CellState.EMPTY) continue
  1172. // 方块不旋转检测是否能放
  1173. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1174. const brickData = this.bricksList[brickI]
  1175. if (this.moveIf(rowIndex, columnIndex, brickData.gridConfig)) {
  1176. moveFlag = true
  1177. brickData.gridConfig.forEach((gridConfigData) => {
  1178. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1179. })
  1180. }
  1181. }
  1182. // 方块旋转检测是否能放
  1183. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1184. const brickData = this.bricksList[brickI]
  1185. if (!brickData.rotateFlag) continue
  1186. let gridConfig = brickData.gridConfig
  1187. let deg = brickData.deg
  1188. for (let count = 1; count <= 3 && !moveFlag; count++) {
  1189. const next = this.nextGridRotate(gridConfig, deg)
  1190. if (this.moveIf(rowIndex, columnIndex, next.gridConfig)) {
  1191. moveFlag = true
  1192. next.gridConfig.forEach((gridConfigData) => {
  1193. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1194. })
  1195. }
  1196. gridConfig = next.gridConfig
  1197. deg = next.deg
  1198. }
  1199. }
  1200. }
  1201. }
  1202. if (gridPromptList.length < 1) {
  1203. resolve(false)
  1204. return
  1205. }
  1206. if (!tipFlag) {
  1207. resolve(true)
  1208. return
  1209. }
  1210. // 提示用户(网格变绿)
  1211. gridPromptList.forEach((gridData) => {
  1212. if (gridData.gridNode && gridData.gridNode.children[0]) {
  1213. const sprite = gridData.gridNode.children[0].getComponent(Sprite);
  1214. if (sprite) {
  1215. sprite.color = this.usableColor;
  1216. }
  1217. }
  1218. // 用于恢复格子
  1219. this.gridColorList.push(gridData)
  1220. })
  1221. resolve(true)
  1222. })
  1223. }
  1224. moveIf(row: number, column: number, gridConfig: GridConfigData[]) {
  1225. let moveFlag = true
  1226. for (let i = 0; i < gridConfig.length; i++) {
  1227. const gridConfigData = gridConfig[i]
  1228. const gridI = row + gridConfigData.row
  1229. const gridJ = column + gridConfigData.column
  1230. // 边界判断
  1231. if (
  1232. gridI < 0 ||
  1233. gridI > this.rows - 1 ||
  1234. gridJ < 0 ||
  1235. gridJ > this.cols - 1
  1236. ) {
  1237. moveFlag = false
  1238. break
  1239. }
  1240. // 已用
  1241. else if (this.gridList[gridI][gridJ].status === CellState.FILLED) {
  1242. moveFlag = false
  1243. break
  1244. }
  1245. }
  1246. return moveFlag
  1247. }
  1248. // 复制整体网格
  1249. copyGridList() {
  1250. const gridList: GridData[][] = []
  1251. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1252. gridList.push([])
  1253. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1254. const gridData = this.gridList[rowIndex][columnIndex]
  1255. gridList[rowIndex].push({
  1256. name: gridData.name,
  1257. status: gridData.status,
  1258. gridNode: null,
  1259. row: gridData.row,
  1260. col: gridData.col,
  1261. type: gridData.type,
  1262. })
  1263. }
  1264. }
  1265. return gridList
  1266. }
  1267. gameOver() {
  1268. this.gameState = GameState.GAME_OVER
  1269. this.setGameState(GameState.GAME_OVER)
  1270. console.log("游戏结束")
  1271. oops.gui.open(UIID.GameOver);
  1272. }
  1273. /**
  1274. * 清理网格的子节点
  1275. */
  1276. private clearGridChildren(gridNode: Node): void {
  1277. const children = gridNode.children.slice(); // 创建副本避免遍历时修改问题
  1278. children.forEach(node => node.destroy());
  1279. }
  1280. private setGameState(state: GameState) {
  1281. this.gameState = state;
  1282. switch (state) {
  1283. case GameState.READY:
  1284. break;
  1285. case GameState.PLAYING:
  1286. break;
  1287. case GameState.PAUSED:
  1288. break;
  1289. case GameState.GAME_OVER:
  1290. //打开游戏结束界面
  1291. break;
  1292. }
  1293. }
  1294. //========================打开其他界面和按钮逻辑=======================
  1295. /** 视图对象通过 ecs.Entity.remove(eliminateViewComp) 删除组件是触发组件处理自定义释放逻辑 */
  1296. reset() {
  1297. this.node.destroy();
  1298. }
  1299. //设置按钮
  1300. private btn_setting() {
  1301. oops.gui.open(UIID.Setting);
  1302. }
  1303. //左边微信按钮
  1304. private btn_withdraw() {
  1305. oops.gui.open(UIID.WechatWithdraw);
  1306. }
  1307. //顶部红包按钮
  1308. private btn_award() {
  1309. oops.gui.open(UIID.RedPacketWithdraw);
  1310. }
  1311. //二倍速按钮
  1312. private btn_double() {
  1313. oops.gui.open(UIID.DoubleSpeed);
  1314. }
  1315. //自动按钮
  1316. private btn_auto() {
  1317. //自动放置
  1318. this.autoState = !this.autoState;
  1319. this.initButtonState(this.autoState);
  1320. if (this.autoState) {
  1321. this.gameState = GameState.PLAYING;
  1322. this.executeAutoPlace()
  1323. }
  1324. }
  1325. executeAutoPlace() {
  1326. if (!this.autoState || this.gameState !== GameState.PLAYING || this.editingFlag) {
  1327. return
  1328. }
  1329. console.log("开始自动放置")
  1330. const bestPlacement = this.findBestPlacement()
  1331. if (!bestPlacement) {
  1332. // 所有方块都无法放置,游戏结束
  1333. this.autoState = false
  1334. this.gameOver()
  1335. return
  1336. }
  1337. // 执行放置
  1338. this.placeBrickAtPosition(bestPlacement)
  1339. }
  1340. findBestPlacement() {
  1341. const placements = []
  1342. // 对每个方块计算所有可能的放置位置和分数
  1343. for (let brickIndex = 0; brickIndex < this.bricksList.length; brickIndex++) {
  1344. const brickData = this.bricksList[brickIndex]
  1345. // 检查不同旋转状态
  1346. let gridConfigs = [brickData.gridConfig]
  1347. let degrees = [brickData.deg]
  1348. // 如果可旋转,计算所有旋转状态
  1349. if (brickData.rotateFlag) {
  1350. for (let i = 1; i <= 3; i++) {
  1351. const next = this.nextGridRotate(
  1352. i === 1 ? brickData.gridConfig : gridConfigs[i - 1],
  1353. i === 1 ? brickData.deg : degrees[i - 1]
  1354. )
  1355. gridConfigs.push(next.gridConfig)
  1356. degrees.push(next.deg)
  1357. }
  1358. }
  1359. // 遍历所有网格位置
  1360. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1361. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1362. // 对每个旋转状态检查
  1363. for (let rotateIndex = 0; rotateIndex < gridConfigs.length; rotateIndex++) {
  1364. const currentGridConfig = gridConfigs[rotateIndex]
  1365. const currentDeg = degrees[rotateIndex]
  1366. // 检查是否可以放置
  1367. if (this.moveIf(rowIndex, columnIndex, currentGridConfig)) {
  1368. // 复制网格并模拟放置
  1369. const gridList = this.copyGridList()
  1370. currentGridConfig.forEach((gridConfigData) => {
  1371. const r = gridConfigData.row + rowIndex
  1372. const c = gridConfigData.column + columnIndex
  1373. gridList[r][c].status = CellState.FILLED
  1374. // gridList[r][c].gridColorKey = brickData.gridColorKey
  1375. gridList[r][c].type = brickData.type;
  1376. })
  1377. // 检查是否可以消除,计算分数
  1378. const elimination = this.gridEliminateCheck(gridList)
  1379. let score = 0
  1380. if (elimination.gridEliminateList.length > 0) {
  1381. // 计算消除得分
  1382. for (let i = 1; i <= elimination.eliminateRowNum; i++) {
  1383. score += this.cols * i
  1384. }
  1385. for (let i = 1; i <= elimination.eliminateColumnNum; i++) {
  1386. score += this.rows * i
  1387. }
  1388. }
  1389. // 记录此放置选项
  1390. placements.push({
  1391. brickIndex,
  1392. brickData,
  1393. rowIndex,
  1394. columnIndex,
  1395. gridConfig: currentGridConfig,
  1396. deg: currentDeg,
  1397. score,
  1398. canEliminate: elimination.gridEliminateList.length > 0
  1399. })
  1400. }
  1401. }
  1402. }
  1403. }
  1404. }
  1405. // 按优先级排序:最高分 > 有分数 > 没有分数但可放置
  1406. placements.sort((a, b) => {
  1407. // 首先按分数排序
  1408. if (a.score !== b.score) {
  1409. return b.score - a.score
  1410. }
  1411. // 其次按是否可消除排序
  1412. if (a.canEliminate !== b.canEliminate) {
  1413. return a.canEliminate ? -1 : 1
  1414. }
  1415. // 最后按照方块优先级排序(底部的方块优先)
  1416. return a.brickIndex - b.brickIndex
  1417. })
  1418. return placements.length > 0 ? placements[0] : null
  1419. }
  1420. // ... existing code ...
  1421. placeBrickAtPosition(placement) {
  1422. // 获取方块数据
  1423. const brickData = placement.brickData
  1424. const index = this.bricksList.findIndex(data => data === brickData)
  1425. if (index === -1) {
  1426. console.error("无法找到要放置的方块:", brickData)
  1427. return
  1428. }
  1429. // 从待选区移除方块
  1430. this.editingData.brickData = this.bricksList.splice(index, 1)[0]
  1431. // 如果需要旋转,执行旋转
  1432. if (brickData.deg !== placement.deg) {
  1433. // 更新方块配置和角度
  1434. brickData.gridConfig = placement.gridConfig
  1435. brickData.deg = placement.deg
  1436. // 添加旋转动画
  1437. tween(brickData.brickNode).to(0.1, { angle: placement.deg }).start()
  1438. }
  1439. // 准备网格列表
  1440. this.editingData.gridList = []
  1441. placement.gridConfig.forEach((gridConfigData: GridConfigData) => {
  1442. const r = gridConfigData.row + placement.rowIndex
  1443. const c = gridConfigData.column + placement.columnIndex
  1444. this.editingData.gridList.push(this.gridList[r][c])
  1445. })
  1446. // 计算目标位置 - 使用中间位置作为基准
  1447. let centerPos = new Vec3(0, 0, 0);
  1448. let validGridCount = 0;
  1449. // 计算所有网格的平均位置
  1450. this.editingData.gridList.forEach(grid => {
  1451. if (grid.gridNode) {
  1452. const worldPos = grid.gridNode.getWorldPosition();
  1453. centerPos.add(worldPos);
  1454. validGridCount++;
  1455. }
  1456. });
  1457. // 计算平均位置
  1458. if (validGridCount > 0) {
  1459. centerPos.x /= validGridCount;
  1460. centerPos.y /= validGridCount;
  1461. centerPos.z /= validGridCount;
  1462. } else {
  1463. // 如果没有有效网格,使用第一个网格的位置作为后备
  1464. const targetGridData = this.editingData.gridList[0];
  1465. if (targetGridData && targetGridData.gridNode) {
  1466. centerPos = targetGridData.gridNode.getWorldPosition();
  1467. }
  1468. }
  1469. // 添加到移动节点里进行移动
  1470. const originPos = brickData.brickNode.getWorldPosition()
  1471. brickData.brickNode.setParent(this.moveNode)
  1472. brickData.brickNode.setWorldPosition(originPos)
  1473. // 使用动画移动到目标位置--这里的最终放置有问题
  1474. tween(brickData.brickNode)
  1475. .to(2, { worldPosition: centerPos })
  1476. .call(() => {
  1477. // 动画完成后修改格子状态
  1478. this.editingData.gridList.forEach((gridData) => {
  1479. gridData.status = CellState.FILLED
  1480. gridData.type = this.editingData.brickData.type
  1481. this.generateGrid(gridData)
  1482. })
  1483. // 销毁方块
  1484. this.editingData.brickData.brickNode.destroy()
  1485. // 添加新方块
  1486. this.addBrick(this.editingData.brickData.index)
  1487. // 检查消除和游戏状态
  1488. this.gridEliminate().then(() => {
  1489. this.prompt(false).then((value: unknown) => {
  1490. const promptFlag = value as boolean;
  1491. if (!promptFlag) {
  1492. this.autoState = false
  1493. this.gameOver()
  1494. } else if (this.autoState) {
  1495. // 继续自动放置
  1496. this.scheduleOnce(() => {
  1497. this.executeAutoPlace()
  1498. }, 0.3)
  1499. }
  1500. this.editingFlag = false
  1501. })
  1502. })
  1503. })
  1504. .start()
  1505. }
  1506. doubleSpeedOpenSuccess() {
  1507. this._isDoubleSpeed = true;
  1508. //3分钟后关闭
  1509. this.scheduleOnce(() => {
  1510. this._isDoubleSpeed = false;
  1511. //关闭会自动触发二倍速弹窗,这要带参数
  1512. // oops.gui.open(UIID.DoubleSpeed, { isAutoOpen: true });
  1513. }, 180);
  1514. }
  1515. //重新开始
  1516. private restartGame() {
  1517. if (this.gameState === GameState.READY) return;
  1518. this.initData();
  1519. this.reopenGrid();
  1520. this.initButtonState(this.autoState);
  1521. }
  1522. //重新清除网格
  1523. private reopenGrid() {
  1524. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1525. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1526. this.gridList[rowIndex][columnIndex].status = CellState.EMPTY
  1527. this.generateGrid(this.gridList[rowIndex][columnIndex])
  1528. }
  1529. }
  1530. // 初始化方块
  1531. if (this.brickNode) {
  1532. if (this.brickNode) {
  1533. this.brickNode.children.forEach(node => { node.destroy() });
  1534. }
  1535. }
  1536. this.bricksList.length = 0
  1537. for (let i = 1; i <= this.brickNum; i++) {
  1538. this.addBrick(i)
  1539. }
  1540. // 清除旋转数据
  1541. if (this.rotateNode) {
  1542. this.rotateNode.children.forEach(node => { node.destroy() })
  1543. }
  1544. }
  1545. }