EliminateViewComp.ts 63 KB

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