EliminateViewComp.ts 65 KB

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