EliminateViewComp.ts 64 KB

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