EliminateViewComp.ts 55 KB

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