EliminateViewComp.ts 56 KB

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