EliminateViewComp.ts 65 KB

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