EliminateViewComp.ts 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518
  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-01 15:42:00
  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. import { Button } from "cc";
  18. const { ccclass, property } = _decorator;
  19. // 游戏状态枚举
  20. enum GameState {
  21. READY, // 准备中
  22. PLAYING, // 游戏中
  23. PAUSED, // 暂停
  24. GAME_OVER // 游戏结束
  25. }
  26. // 游戏模式枚举
  27. enum GameMode {
  28. MANUAL, // 手动模式
  29. AUTO // 自动模式
  30. }
  31. // 格子状态
  32. enum CellState {
  33. EMPTY, // 空格子
  34. FILLED, // 有方块
  35. HIGHLIGHTED // 高亮(可放置)
  36. }
  37. // 新手引导步骤
  38. enum TutorialStep {
  39. NONE, // 无引导
  40. ROW_ELIMINATION, // 行消除引导
  41. COLUMN_ELIMINATION, // 列消除引导
  42. ROTATION, // 旋转引导
  43. FINAL_ELIMINATION // 最终消除引导
  44. }
  45. //网格数据接口
  46. interface GridData {
  47. name: string, // 名称
  48. status: CellState, // 状态
  49. gridNode: Node | null // 网格节点
  50. row: number, // 行
  51. col: number, // 列
  52. gridColorKey: string | null,
  53. type: number, // 类型--gridColorKey
  54. }
  55. interface Grids {
  56. row: number,
  57. column: number,
  58. }
  59. interface EditingData {
  60. brickData: BrickData | null,
  61. gridList: GridData[],
  62. }
  63. //底部方块数据定义
  64. interface BrickData {
  65. index: number,
  66. brickKey: string | null,
  67. rotateTag: boolean,
  68. rotateFlag: boolean,
  69. gridConfig: Grids[],
  70. deg: number,
  71. brickNode: Node | null,
  72. gridColorKey: string | null,
  73. brickInitPos: Vec3, // 方块初始位置
  74. type: number, // 方块类型--gridColorKey
  75. }
  76. interface GridConfigData {
  77. row: number,
  78. column: number,
  79. }
  80. /** 视图层对象 */
  81. @ccclass('EliminateViewComp')
  82. @ecs.register('EliminateView', false)
  83. export class EliminateViewComp extends CCComp {
  84. @property({ type: LabelChange, displayName: "自动提现金额" })
  85. private amountLb: LabelChange = null!;
  86. @property({ type: LabelChange, displayName: "额外奖励" })
  87. private awardLb: LabelChange = null!;
  88. @property({ type: Node, displayName: "tween微信钱Node" })
  89. private tweenWechatNode: Node = null!;
  90. @property({ type: Node, displayName: "tween红包Node" })
  91. private tweenRedNode: Node = null!;
  92. @property({ type: Prefab, displayName: "金币预制体" })
  93. private coinPrefab: Prefab = null!;
  94. @property({ type: Prefab, displayName: "红包预制体" })
  95. private redPacketPrefab: Prefab = null!;
  96. @property({ type: Label, displayName: "本局分数" })
  97. private lab_score: Label = null!;
  98. @property({ type: Prefab, displayName: "item预制体列表" })
  99. private itemPrefabs: Prefab[] = [];
  100. @property({ type: Node, displayName: "网格Node" })
  101. private gridNode: Node = null!;
  102. @property({ type: Node, displayName: "移动Node" })
  103. private moveNode: Node = null!;
  104. @property({ type: Node, displayName: "旋转Node" })
  105. private rotateNode: Node = null!;
  106. @property({ type: Node, displayName: "方块Node" })
  107. private brickNode: Node = null!;
  108. @property({ type: Prefab, displayName: "旋转预制体" })
  109. private rotatePrefab: Node = null!;
  110. @property({ type: Label, displayName: "累计消除次数" })
  111. private lab_total: Label = null!;
  112. @property({ type: Label, displayName: "每次放置添加的分数" })
  113. private lab_addScore: Label = null!;
  114. @property({ type: Button, displayName: "自动按钮" })
  115. private autoBtn: Button = null!;
  116. //游戏配置行列
  117. private rows: number = 8; // 行数
  118. private cols: number = 8; // 列数
  119. private itemSize: number = 82; // 格子大小
  120. private brickNum: number = 3; // 砖块数量
  121. private gameState: GameState = GameState.READY;
  122. private score: number = 0; //本局分数
  123. private money: number = 0; //左边金钱
  124. private cash: number = 0; //右边红包钱数
  125. private totalNum: number = 0; //累计消除次数,断了就是又从0开始
  126. //网格列表
  127. // gridsNode: Node | null = null; //中间网格区域
  128. // brickNode: Node | null = null; //底部三个item块区域
  129. // moveNode: Node | null = null; //移动层Node
  130. // rotateNode: Node | null = null; //旋转Node吧
  131. //没使用颜色
  132. notUseColor = new Color(255, 255, 255, 255)
  133. //可用的颜色
  134. usableColor = new Color(0, 255, 0, 100)
  135. //不可用的颜色
  136. unavailableColor = new Color(255, 0, 0, 100)
  137. //旋转容错
  138. rotateFaultTolerant = 10;
  139. private _isAutoFunc: (() => void) | null = null;
  140. isAutoMode: boolean = false;
  141. autoModeInterval: number = 1 // 自动模式的间隔时间(秒)
  142. autoModeTimer: number = 0 // 自动模式计时器
  143. //网格列表管理列表
  144. gridList: GridData[][] = [];
  145. //砖块列表
  146. bricksList: BrickData[] = [];
  147. //网格颜色列表
  148. gridColorList: GridData[] = [];
  149. brickConfig: { bricks?: any } = {} //方块配置
  150. editingFlag = false //编辑状态
  151. editingData: EditingData = {
  152. brickData: null,
  153. gridList: [],
  154. }
  155. //旋转标记
  156. rotateFlag = false
  157. rotateBrickData: BrickData | null = null
  158. // 添加新的属性来跟踪是否需要重置消除计数
  159. private shouldResetEliminateCount: boolean = true;
  160. private consecutiveEliminations: boolean = false;
  161. // 添加配置属性 - 消除基础分
  162. @property({ displayName: "消除一行/列基础分" })
  163. private eliminateBaseScore: number = 10;
  164. //当前局数
  165. private curGameNum: number = 0;
  166. //第一通关开始新人模式
  167. //第二局开始马上播放新的弹窗
  168. //往后根据每局需要弹窗就弹窗
  169. //通关一局算一块金砖
  170. //通关比例算金砖比例
  171. private autoState: boolean = false; //自动状态
  172. /** 视图层逻辑代码分离演示 */
  173. async start() {
  174. // const entity = this.ent as ecs.Entity; // ecs.Entity 可转为当前模块的具体实体对象
  175. this.setButton();
  176. this.initComponents();
  177. this.initButtonState(false);
  178. await this.loadConfig();
  179. this.initGrid();
  180. this.initData();
  181. this.addEventList();
  182. }
  183. addEventList() {
  184. oops.message.on(GameEvent.RestartGame, this.restartGame, this);
  185. }
  186. private initComponents() {
  187. }
  188. //初始化网格
  189. private initGrid() {
  190. // 清理现有网格
  191. this.clearExistingGrids();
  192. // 生成网格矩阵
  193. this.createGridMatrix();
  194. }
  195. //初始化按钮状态
  196. private initButtonState(state: boolean) {
  197. //自动按钮默认关闭
  198. if (this.autoBtn) {
  199. //关闭
  200. const on = this.autoBtn.node.getChildByName("on");
  201. on ? on.active = state : null;
  202. const off = this.autoBtn.node.getChildByName("off");
  203. off ? off.active = !state : null;
  204. // this.autoState = state;
  205. }
  206. }
  207. //初始化数据
  208. private initData() {
  209. // this.gameMode = GameMode.MANUAL;
  210. this.score = 0;
  211. this.money = 0;
  212. this.cash = 0;
  213. this.totalNum = 0;
  214. this.autoState = false;
  215. this.shouldResetEliminateCount = true;
  216. this.consecutiveEliminations = false;
  217. this.lab_score.string = this.score.toString();
  218. this.amountLb.string = this.money.toString();
  219. this.awardLb.string = this.cash.toString();
  220. }
  221. //初始化网格
  222. private async loadConfig() {
  223. let json_name: string = "gui/eliminate/config/GridConfig";
  224. return new Promise<void>((resolve, reject) => {
  225. oops.res.load(json_name, JsonAsset, (err: Error | null, res: any) => {
  226. if (res) {
  227. this.brickConfig = res.json;
  228. resolve();
  229. } else {
  230. console.log("JSON数据加载失,请检查文件");
  231. reject(err);
  232. }
  233. });
  234. });
  235. }
  236. /**
  237. * @description: 清理现有的网格数据
  238. * @return {*}
  239. */
  240. private clearExistingGrids(): void {
  241. this.gridList = [];
  242. if (this.gridNode) {
  243. this.gridNode.children.forEach(node => node.destroy());
  244. }
  245. }
  246. /**
  247. * @description: 设置网格容器大小
  248. * @return {*}
  249. */
  250. private createGridMatrix(): void {
  251. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  252. const currentRow: GridData[] = [];
  253. this.gridList.push(currentRow);
  254. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  255. const gridData = this.createGridData(rowIndex, columnIndex);
  256. currentRow.push(gridData);
  257. this.createGridNode(gridData);
  258. }
  259. }
  260. // 初始化格子状态
  261. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  262. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  263. this.gridList[rowIndex][columnIndex].status = CellState.EMPTY
  264. this.generateGrid(this.gridList[rowIndex][columnIndex])
  265. }
  266. }
  267. // 初始化方块
  268. if (this.brickNode) {
  269. if (this.brickNode) {
  270. this.brickNode.children.forEach(node => { node.destroy() });
  271. }
  272. }
  273. this.bricksList.length = 0
  274. for (let i = 1; i <= this.brickNum; i++) {
  275. this.addBrick(i)
  276. }
  277. // 清除旋转数据
  278. if (this.rotateNode) {
  279. this.rotateNode.children.forEach(node => { node.destroy() })
  280. }
  281. }
  282. /**
  283. * @description: 创建格子数据
  284. * @param {number} row
  285. * @param {number} column
  286. * @return {*}
  287. */
  288. private createGridData(row: number, column: number): GridData {
  289. return {
  290. name: `Grid-${row}-${column}`,
  291. status: CellState.EMPTY,
  292. gridNode: null,
  293. row: row,
  294. col: column,
  295. gridColorKey: null,
  296. type: 0
  297. };
  298. }
  299. /**
  300. * @description: 创建网格Node
  301. * @param {GridData} gridData
  302. * @return {*}
  303. */
  304. private createGridNode(gridData: GridData): void {
  305. const gridNode = new Node(gridData.name);
  306. if (this.gridNode) {
  307. this.gridNode.addChild(gridNode);
  308. }
  309. gridData.gridNode = gridNode;
  310. // 设置网格大小
  311. gridNode.addComponent(UITransform).setContentSize(this.itemSize, this.itemSize);
  312. }
  313. /**
  314. * 生成或更新网格
  315. * @param gridData 网格数据
  316. */
  317. private generateGrid(gridData: GridData) {
  318. if (!gridData || !gridData.gridNode) {
  319. console.warn('无效的网格数据');
  320. return;
  321. }
  322. // 清理现有子节点
  323. this.clearGridChildren(gridData.gridNode);
  324. // 获取对应的预制体
  325. const prefab = this.getGridPrefab(gridData);
  326. if (!prefab) {
  327. console.warn('无法获取网格预制体');
  328. return;
  329. }
  330. // 创建并配置新节点
  331. const node = this.createNewGridNode(prefab, gridData);
  332. // 设置节点属性
  333. this.setupGridNode(node, gridData);
  334. }
  335. /**
  336. * 获取对应状态的预制体
  337. */
  338. private getGridPrefab(gridData: GridData): Prefab {
  339. if (gridData.status === CellState.EMPTY) {
  340. if (this.itemPrefabs[0]) {
  341. return this.itemPrefabs[0];
  342. } else {
  343. throw new Error('Grid prefab is not loaded');
  344. }
  345. }
  346. if (gridData.status === CellState.FILLED && gridData.type) {
  347. const type = gridData.type;
  348. return this.itemPrefabs[type];
  349. }
  350. throw new Error('Invalid grid status or missing gridColorKey');
  351. }
  352. /**
  353. * 创建网格节点
  354. */
  355. private createNewGridNode(prefab: Prefab, gridData: GridData): Node {
  356. const node = instantiate(prefab);
  357. if (gridData && gridData.gridNode) {
  358. gridData.gridNode.addChild(node);
  359. return node;
  360. }
  361. return node
  362. }
  363. /**
  364. * 设置网格节点的属性
  365. */
  366. private setupGridNode(node: Node, gridData: GridData): void {
  367. // 设置未使用状态的颜色
  368. if (gridData.status === CellState.EMPTY) {
  369. const sprite = node.getComponent(Sprite);
  370. if (sprite) {
  371. sprite.color = this.notUseColor;
  372. }
  373. }
  374. // 设置节点大小
  375. const transform = node.getComponent(UITransform);
  376. if (transform) {
  377. transform.setContentSize(
  378. this.itemSize,
  379. this.itemSize
  380. );
  381. }
  382. // 设置位置
  383. node.setPosition(Vec3.ZERO);
  384. }
  385. addBrick(index: number) {
  386. //随机名字
  387. const brickKey = Object.keys(this.brickConfig['bricks'])[randomRangeInt(0, Object.keys(this.brickConfig['bricks']).length)]
  388. const brickConfig = this.brickConfig['bricks'][brickKey];
  389. const randomIndex = oops.random.getRandomInt(1, 5);
  390. // 生成方块
  391. const brickData: BrickData = {
  392. index,
  393. brickKey: brickKey,
  394. rotateFlag: brickConfig['rotateFlag'],
  395. gridConfig: brickConfig['gridConfig'],
  396. deg: 0,
  397. brickNode: null,
  398. gridColorKey: randomIndex.toString(),
  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. }
  428. // 每个item生成独立的方块节点
  429. generateBrick(brickKey: string, randomIndex: number) {
  430. const brickConfig = this.brickConfig['bricks'][brickKey]
  431. let rowMin = 0
  432. let rowMax = 0
  433. let columnMin = 0
  434. let columnMax = 0
  435. brickConfig['gridConfig'].forEach((gridConfigData: GridConfigData) => {
  436. if (gridConfigData.row < rowMin) {
  437. rowMin = gridConfigData.row
  438. }
  439. else if (gridConfigData.row > rowMax) {
  440. rowMax = gridConfigData.row
  441. }
  442. if (gridConfigData.column < columnMin) {
  443. columnMin = gridConfigData.column
  444. }
  445. else if (gridConfigData.column > columnMax) {
  446. columnMax = gridConfigData.column
  447. }
  448. })
  449. const rowNum = (rowMax - rowMin + 1)
  450. const columnNum = (columnMax - columnMin + 1)
  451. // 生成独立的方块节点
  452. const brickNode = new Node()
  453. brickNode.name = brickKey
  454. // 设置方块大小
  455. const transformCom: UITransform = brickNode.addComponent(UITransform)
  456. transformCom.setContentSize(
  457. this.itemSize * columnNum,
  458. this.itemSize * rowNum
  459. )
  460. transformCom.setAnchorPoint(0.5, 0.5)
  461. // 设置方块位置
  462. const gridPrefab = this.itemPrefabs[randomIndex]
  463. //生成对应的配置方块设置地址
  464. brickConfig['gridConfig'].forEach((gridConfigData: GridConfigData) => {
  465. const gridNode = new Node()
  466. gridNode.name = 'grid'
  467. brickNode.addChild(gridNode)
  468. gridNode.addComponent(UITransform).setContentSize(this.itemSize, this.itemSize)
  469. const gridWidget: Widget = gridNode.addComponent(Widget)
  470. gridWidget.isAlignLeft = true
  471. gridWidget.left = this.itemSize * gridConfigData.column - this.itemSize * columnMin
  472. gridWidget.isAlignBottom = true
  473. gridWidget.bottom = this.itemSize * gridConfigData.row - this.itemSize * rowMin
  474. const node = instantiate(gridPrefab)
  475. gridNode.addChild(node)
  476. const uiTransform = node.getComponent(UITransform);
  477. if (uiTransform) {
  478. uiTransform.setContentSize(
  479. this.itemSize,
  480. this.itemSize,
  481. )
  482. }
  483. node.setPosition(Vec3.ZERO)
  484. node.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  485. event.preventSwallow = true;
  486. }, this);
  487. node.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  488. event.preventSwallow = true;
  489. }, this);
  490. node.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
  491. event.preventSwallow = true;
  492. }, this);
  493. })
  494. return brickNode
  495. }
  496. touchStartLocation = new Vec2()
  497. touchStartFlag = false
  498. brickAddEvent(brickData: BrickData) {
  499. const brickNode = brickData.brickNode
  500. if (!brickNode) {
  501. console.error("brickNode为空,无法添加事件");
  502. return
  503. }
  504. // 确保节点可交互
  505. brickNode.active = true;
  506. // 移除可能存在的旧事件监听器
  507. brickNode.off(Node.EventType.TOUCH_START);
  508. brickNode.off(Node.EventType.TOUCH_MOVE);
  509. brickNode.off(Node.EventType.TOUCH_END);
  510. brickNode.off(Node.EventType.TOUCH_CANCEL);
  511. // 记录初始位置和状态
  512. let startPos = new Vec3();
  513. let originalParent: Node | null = null;
  514. let isDragging = false;
  515. // 触摸开始事件
  516. brickNode.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  517. // 如果正在编辑其他方块,则忽略
  518. if (this.editingFlag) return;
  519. // 设置编辑状态
  520. this.editingFlag = true;
  521. isDragging = true;
  522. this.touchStartFlag = true;
  523. // 清空编辑中的数据
  524. this.editingData.brickData = null;
  525. this.editingData.gridList.length = 0;
  526. // 记录触摸开始位置和方块原始信息
  527. this.touchStartLocation.set(event.getUILocation());
  528. originalParent = brickNode.parent;
  529. startPos = brickNode.getWorldPosition().clone();
  530. // 将方块移到移动层并放大
  531. brickNode.setParent(this.moveNode);
  532. brickNode.setWorldPosition(startPos);
  533. tween(brickNode)
  534. .to(0.2, { scale: new Vec3(1, 1, 1) })
  535. .start();
  536. // 从方块列表中移除该方块
  537. const index = this.bricksList.findIndex(item => item === brickData);
  538. if (index > -1) {
  539. this.editingData.brickData = this.bricksList.splice(index, 1)[0];
  540. } else {
  541. console.error("未找到方块数据:", brickData);
  542. this.editingData.brickData = brickData;
  543. }
  544. // 清除旋转数据
  545. if (this.rotateFlag && this.rotateBrickData !== this.editingData.brickData) {
  546. this.rotateFlag = false;
  547. this.rotateBrickData = null;
  548. if (this.rotateNode) {
  549. this.rotateNode.children.forEach(node => { node.destroy() });
  550. }
  551. }
  552. }, this);
  553. // 触摸移动事件
  554. brickNode.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  555. if (!isDragging || !this.editingData.brickData) return;
  556. // 清除旋转数据
  557. if (event.getUILocation().subtract(this.touchStartLocation).length() >= this.rotateFaultTolerant) {
  558. this.rotateFlag = false;
  559. this.rotateBrickData = null;
  560. if (this.rotateNode) {
  561. this.rotateNode.children.forEach(node => { node.destroy() });
  562. }
  563. }
  564. // 恢复所有网格颜色
  565. this.gridColorRecovery();
  566. // 移动方块
  567. brickNode.setWorldPosition(brickNode.getWorldPosition().add(event.getUIDelta().toVec3()));
  568. // 重置编辑中的网格数据
  569. this.editingData.gridList.length = 0;
  570. // 检查方块每个子网格是否与游戏网格重叠
  571. const tempGridList: GridData[] = [];
  572. let allEmptyGrids: boolean = true; // 标记是否所有网格都为空
  573. brickNode.children.forEach((childNode) => {
  574. const childWorldPos = childNode.getWorldPosition();
  575. // 查找与子网格重叠的游戏网格
  576. let matchedGrid: GridData | null = null;
  577. for (let row = 0; row < this.rows && !matchedGrid; row++) {
  578. for (let col = 0; col < this.cols && !matchedGrid; col++) {
  579. const grid = this.gridList[row][col];
  580. if (!grid || !grid.gridNode) continue;
  581. const gridPos = grid.gridNode.getWorldPosition();
  582. if (Vec3.distance(gridPos, childWorldPos) <= (this.itemSize / 2)) {
  583. matchedGrid = grid;
  584. }
  585. }
  586. }
  587. if (matchedGrid) {
  588. tempGridList.push(matchedGrid);
  589. // 检查是否有非空网格
  590. if (matchedGrid.status !== CellState.EMPTY) {
  591. allEmptyGrids = false;
  592. }
  593. }
  594. });
  595. // 检查是否所有子网格都有对应的游戏网格,且都是空的
  596. let canPlace = tempGridList.length === brickData.gridConfig.length && allEmptyGrids;
  597. // 更新编辑中的网格列表
  598. if (canPlace) {
  599. this.editingData.gridList = [...tempGridList];
  600. }
  601. // 更新网格颜色提示 - 只改变空网格的颜色
  602. tempGridList.forEach(grid => {
  603. // 只处理空网格
  604. if (grid.status === CellState.EMPTY) {
  605. if (grid.gridNode && grid.gridNode.children[0]) {
  606. const sprite = grid.gridNode.children[0].getComponent(Sprite);
  607. if (sprite) {
  608. sprite.color = canPlace ? this.usableColor : this.unavailableColor;
  609. }
  610. }
  611. // 用于后续恢复颜色
  612. this.gridColorList.push(grid);
  613. }
  614. });
  615. }, this);
  616. // 触摸结束或取消事件
  617. const touchEndHandler = (event: EventTouch) => {
  618. if (!isDragging) return;
  619. isDragging = false;
  620. this.touchStartFlag = false;
  621. // 恢复网格颜色
  622. this.gridColorRecovery();
  623. // 防止如放回方块回弹动画时,已经触摸在另一个方块上面
  624. if (this.editingData.brickData !== brickData) return;
  625. // 检查是否可以放置
  626. if (this.editingData.brickData && this.editingData.gridList.length > 0) {
  627. // 计算放置的格子数量
  628. const placedGridCount = this.editingData.gridList.length;
  629. // 获取中心位置用于显示分数
  630. let centerPos = new Vec3(0, 0, 0);
  631. if (this.editingData.gridList.length > 0 && this.editingData.gridList[0].gridNode) {
  632. centerPos = this.editingData.gridList[0].gridNode.getWorldPosition().clone();
  633. if (this.editingData.gridList.length > 1) {
  634. // 计算所有格子的平均位置作为中心点
  635. for (let i = 1; i < this.editingData.gridList.length; i++) {
  636. const gridNode = this.editingData.gridList[i].gridNode;
  637. if (gridNode) {
  638. centerPos.add(gridNode.getWorldPosition());
  639. }
  640. }
  641. const validGridCount = this.editingData.gridList.filter(grid => grid.gridNode).length;
  642. centerPos.x /= validGridCount;
  643. centerPos.y /= validGridCount;
  644. }
  645. }
  646. // 放置方块到网格
  647. this.editingData.gridList.forEach(grid => {
  648. grid.status = CellState.FILLED;
  649. grid.gridColorKey = this.editingData.brickData!.gridColorKey;
  650. grid.type = this.editingData.brickData!.type;
  651. this.generateGrid(grid);
  652. });
  653. // 显示放置得分动画(显示一次,包含总格子数)
  654. this.showScoreAnimation(centerPos, placedGridCount);
  655. // 标记需要重置消除计数器
  656. this.shouldResetEliminateCount = true;
  657. this.consecutiveEliminations = true;
  658. // 销毁方块节点
  659. brickNode.destroy();
  660. // 添加新方块到待选区
  661. this.addBrick(this.editingData.brickData.index);
  662. // 检查消除
  663. this.scheduleOnce(() => {
  664. this.gridEliminate().then((hasElimination) => {
  665. // 如果没有消除,确保下次消除会重置计数
  666. if (!hasElimination) {
  667. this.shouldResetEliminateCount = true;
  668. }
  669. // 检查游戏是否结束
  670. this.prompt(false).then(canContinue => {
  671. if (!canContinue) {
  672. this.gameOver();
  673. }
  674. this.editingFlag = false;
  675. });
  676. });
  677. }, 0.1);
  678. } else if (this.rotateFlag) {
  679. // 旋转方块
  680. const brickData = this.editingData.brickData;
  681. this.brickGridRotate(brickData);
  682. // 方块放回待选区
  683. this.bricksList.push(brickData);
  684. if (this.brickNode && brickData.brickNode) {
  685. this.brickNode.addChild(brickData.brickNode);
  686. tween(brickData.brickNode)
  687. .to(0.2, {
  688. worldPosition: brickData.brickInitPos,
  689. scale: new Vec3(0.6, 0.6, 0.6)
  690. })
  691. .start();
  692. }
  693. this.editingFlag = false;
  694. } else {
  695. // 无法放置,将方块返回原位置
  696. const brickData = this.editingData.brickData;
  697. if (brickData) {
  698. this.bricksList.push(brickData);
  699. // 添加回弹动画
  700. tween(brickNode)
  701. .to(0.2, {
  702. worldPosition: brickData.brickInitPos,
  703. scale: new Vec3(0.6, 0.6, 0.6)
  704. })
  705. .call(() => {
  706. if (originalParent) {
  707. brickNode.setParent(originalParent);
  708. brickNode.setWorldPosition(brickData.brickInitPos);
  709. }
  710. this.editingFlag = false;
  711. })
  712. .start();
  713. } else {
  714. this.editingFlag = false;
  715. }
  716. }
  717. // 检查是否需要处理旋转(短距离移动视为点击)
  718. if (!this.rotateFlag &&
  719. this.editingData.brickData &&
  720. this.editingData.brickData.rotateFlag &&
  721. event.getUILocation().subtract(this.touchStartLocation).length() < this.rotateFaultTolerant) {
  722. this.rotateFlag = true;
  723. this.rotateBrickData = this.editingData.brickData;
  724. // 显示旋转提示
  725. if (this.rotatePrefab && this.rotateNode && brickNode) {
  726. const rotateIndicator = instantiate(this.rotatePrefab);
  727. this.rotateNode.addChild(rotateIndicator);
  728. rotateIndicator.setWorldPosition(brickNode.getWorldPosition());
  729. }
  730. }
  731. };
  732. brickNode.on(Node.EventType.TOUCH_END, touchEndHandler, this);
  733. brickNode.on(Node.EventType.TOUCH_CANCEL, touchEndHandler, this);
  734. }
  735. //格子颜色恢复
  736. gridColorRecovery() {
  737. while (this.gridColorList.length > 0) {
  738. const gridData = this.gridColorList.pop();
  739. if (gridData) {
  740. if (gridData.status === CellState.EMPTY) {
  741. if (gridData.gridNode) {
  742. gridData.gridNode.children[0].getComponent(Sprite)!.color = this.notUseColor;
  743. }
  744. }
  745. }
  746. }
  747. }
  748. brickGridRotate(brickData: BrickData) {
  749. const next = this.nextGridRotate(brickData.gridConfig, brickData.deg)
  750. brickData.deg = next.deg
  751. brickData.gridConfig = next.gridConfig;
  752. if (brickData.brickNode) {
  753. tween(brickData.brickNode).to(0.1, { angle: next.deg }).start();
  754. }
  755. // this.audioManager.playRotate()
  756. }
  757. //下一个旋转
  758. nextGridRotate(gridConfig: GridConfigData[], deg: number) {
  759. const newGridConfig: GridConfigData[] = []
  760. // 顺时针旋转
  761. let newDeg = deg - 90
  762. gridConfig.forEach((gridConfigData) => {
  763. // 例如(1,2) => (-2,1),可以画图分析
  764. newGridConfig.push({
  765. row: -gridConfigData.column,
  766. column: gridConfigData.row
  767. })
  768. })
  769. return { gridConfig: newGridConfig, deg: newDeg }
  770. }
  771. // 显示分数增加动画
  772. showScoreAnimation(position: Vec3, score: number) {
  773. if (!this.lab_addScore) return;
  774. // 复制得分Label
  775. const scoreLabel = instantiate(this.lab_addScore.node);
  776. scoreLabel.active = true;
  777. // 设置文本和位置
  778. const label = scoreLabel.getComponent(Label);
  779. if (label) {
  780. label.string = `+${score}`;
  781. }
  782. // 添加到场景中
  783. this.node.addChild(scoreLabel);
  784. scoreLabel.setWorldPosition(position);
  785. // 创建动画效果
  786. tween(scoreLabel)
  787. .to(0.5, {
  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, { 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. showEliminateCountAnimation(yPosition: number) {
  802. if (!this.lab_total) return;
  803. // 如果需要重置计数器,先将计数归零
  804. if (this.shouldResetEliminateCount) {
  805. this.totalNum = 0;
  806. this.shouldResetEliminateCount = false;
  807. }
  808. // 增加累计消除次数
  809. this.totalNum++;
  810. // 复制总次数Label
  811. const totalLabel = instantiate(this.lab_total.node);
  812. totalLabel.active = true;
  813. // 设置文本
  814. const label = totalLabel.getComponent(Label);
  815. if (label) {
  816. label.string = `Combo${this.totalNum}`;
  817. }
  818. // 添加到场景中
  819. this.node.addChild(totalLabel);
  820. // 计算网格区域的X轴中心位置,Y轴使用传入的消除行位置
  821. const centerPos = new Vec3();
  822. if (this.gridNode) {
  823. // 获取网格区域的X轴中心
  824. const worldPos = this.gridNode.getWorldPosition();
  825. centerPos.set(worldPos.x, yPosition, worldPos.z);
  826. }
  827. totalLabel.setWorldPosition(centerPos);
  828. // 创建动画效果
  829. tween(totalLabel)
  830. .to(0.3, {
  831. scale: new Vec3(1.5, 1.5, 1.5),
  832. opacity: 255
  833. })
  834. .delay(0.5) // 停留更长时间
  835. .to(0.4, {
  836. scale: new Vec3(1.2, 1.2, 1.2),
  837. position: new Vec3(totalLabel.position.x, totalLabel.position.y + 50, 0),
  838. opacity: 0
  839. })
  840. .call(() => {
  841. totalLabel.destroy();
  842. })
  843. .start();
  844. }
  845. // 修改 gridEliminate 方法来显示消除次数
  846. gridEliminate() {
  847. return new Promise<boolean>((resolve, reject) => {
  848. const d = this.gridEliminateCheck(this.gridList)
  849. const gridEliminateList = d.gridEliminateList
  850. const eliminateRowNum = d.eliminateRowNum
  851. const eliminateColumnNum = d.eliminateColumnNum
  852. if (gridEliminateList.length < 1) {
  853. // 没有发生消除
  854. this.shouldResetEliminateCount = true; // 下一次消除需要重置计数
  855. this.consecutiveEliminations = false; // 不是连续消除
  856. resolve(false);
  857. return;
  858. }
  859. // 如果有消除,计算消除行的平均Y轴位置
  860. if (gridEliminateList.length > 0) {
  861. // 计算所有被消除格子的平均Y轴位置
  862. let totalY = 0;
  863. let validGrids = 0;
  864. for (const grid of gridEliminateList) {
  865. if (grid.gridNode) {
  866. totalY += grid.gridNode.getWorldPosition().y;
  867. validGrids++;
  868. }
  869. }
  870. // 计算平均Y位置
  871. const avgY = validGrids > 0 ? totalY / validGrids : 0;
  872. // 标记为连续消除
  873. this.consecutiveEliminations = true;
  874. // 显示消除次数动画,传入Y轴位置
  875. this.showEliminateCountAnimation(avgY);
  876. }
  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, { 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. tween(coin)
  1003. .to(0.2, {
  1004. position: new Vec3(
  1005. coin.position.x + randomOffset.x,
  1006. coin.position.y + randomOffset.y,
  1007. 0
  1008. )
  1009. })
  1010. .to(0.5, { worldPosition: endPos })
  1011. .call(() => {
  1012. coin.destroy();
  1013. completedCount++;
  1014. // 所有金币动画完成后执行回调
  1015. if (completedCount === totalCoins && callback) {
  1016. callback();
  1017. }
  1018. })
  1019. .start();
  1020. }
  1021. }
  1022. // 显示微信分数增加动画
  1023. private showWechatScoreAnimation() {
  1024. if (!this.tweenWechatNode) return;
  1025. // 生成随机小数(小于1,保留2位小数)
  1026. const randomValue = Math.random() * 0.99;
  1027. const formattedValue = randomValue.toFixed(2);
  1028. // 获取并设置分数标签
  1029. const scoreLabel = this.tweenWechatNode.getChildByName("lab_num")?.getComponent(Label);
  1030. if (scoreLabel) {
  1031. scoreLabel.string = "+" + formattedValue;
  1032. }
  1033. // 保存原始位置
  1034. const originalPosition = this.tweenWechatNode.position.clone();
  1035. // 显示节点
  1036. this.tweenWechatNode.active = true;
  1037. // 创建向上移动的动画
  1038. tween(this.tweenWechatNode)
  1039. .to(0.8, {
  1040. position: new Vec3(
  1041. originalPosition.x,
  1042. originalPosition.y + 80,
  1043. originalPosition.z
  1044. ),
  1045. opacity: 255
  1046. })
  1047. .to(0.2, { opacity: 0 })
  1048. .call(() => {
  1049. // 重置位置
  1050. this.tweenWechatNode.setPosition(originalPosition);
  1051. this.tweenWechatNode.active = false;
  1052. // 更新总金额
  1053. if (this.amountLb) {
  1054. const currentAmount = parseFloat(this.amountLb.string);
  1055. const newAmount = currentAmount + parseFloat(formattedValue);
  1056. this.money = newAmount;
  1057. this.amountLb.string = newAmount.toFixed(2);
  1058. }
  1059. })
  1060. .start();
  1061. }
  1062. // 显示红包分数增加动画
  1063. private showRedPacketScoreAnimation() {
  1064. if (!this.tweenRedNode) return;
  1065. // 生成随机小数(小于1,保留2位小数)
  1066. const randomValue = Math.random() * 0.99;
  1067. const formattedValue = randomValue.toFixed(2);
  1068. // 获取并设置分数标签
  1069. const scoreLabel = this.tweenRedNode.getChildByName("lab_num")?.getComponent(Label);
  1070. if (scoreLabel) {
  1071. scoreLabel.string = "+" + formattedValue;
  1072. }
  1073. // 保存原始位置
  1074. const originalPosition = this.tweenRedNode.position.clone();
  1075. // 显示节点
  1076. this.tweenRedNode.active = true;
  1077. // 创建向上移动的动画
  1078. tween(this.tweenRedNode)
  1079. .to(0.8, {
  1080. position: new Vec3(
  1081. originalPosition.x,
  1082. originalPosition.y + 80,
  1083. originalPosition.z
  1084. ),
  1085. opacity: 255
  1086. })
  1087. .to(0.2, { opacity: 0 })
  1088. .call(() => {
  1089. // 重置位置
  1090. this.tweenRedNode.setPosition(originalPosition);
  1091. this.tweenRedNode.active = false;
  1092. // 更新总红包金额
  1093. if (this.awardLb) {
  1094. const currentAmount = parseFloat(this.awardLb.string);
  1095. const newAmount = currentAmount + parseFloat(formattedValue);
  1096. this.cash = newAmount;
  1097. this.awardLb.string = newAmount.toFixed(2);
  1098. }
  1099. })
  1100. .start();
  1101. }
  1102. // 提示
  1103. prompt(tipFlag = true) {
  1104. return new Promise((resolve, reject) => {
  1105. const gridPromptList: GridData[] = []
  1106. let moveFlag = false
  1107. // 找方块可消除位置
  1108. for (let rowIndex = 0; rowIndex < this.rows && !moveFlag; rowIndex++) {
  1109. for (let columnIndex = 0; columnIndex < this.cols && !moveFlag; columnIndex++) {
  1110. const gridData = this.gridList[rowIndex][columnIndex]
  1111. if (gridData.status !== CellState.EMPTY) continue
  1112. // 方块不旋转检测是否能放
  1113. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1114. const brickData = this.bricksList[brickI]
  1115. if (this.moveIf(rowIndex, columnIndex, brickData.gridConfig)) {
  1116. // 复制整体网格,以方块设置网格状态
  1117. const gridList = this.copyGridList()
  1118. brickData.gridConfig.forEach((gridConfigData) => {
  1119. gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = CellState.FILLED
  1120. })
  1121. // 检查复制的整体网格是否有可消除
  1122. if (this.gridEliminateCheck(gridList).gridEliminateList.length > 0) {
  1123. moveFlag = true
  1124. brickData.gridConfig.forEach((gridConfigData) => {
  1125. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1126. })
  1127. }
  1128. }
  1129. }
  1130. // 方块旋转检测是否能放
  1131. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1132. const brickData = this.bricksList[brickI]
  1133. if (!brickData.rotateFlag) continue
  1134. let gridConfig = brickData.gridConfig
  1135. let deg = brickData.deg
  1136. // 获得旋转的方块网格配置
  1137. for (let count = 1; count <= 3 && !moveFlag; count++) {
  1138. const next = this.nextGridRotate(gridConfig, deg)
  1139. if (this.moveIf(rowIndex, columnIndex, next.gridConfig)) {
  1140. // 复制整体网格,以方块设置网格状态
  1141. const gridList = this.copyGridList()
  1142. next.gridConfig.forEach((gridConfigData) => {
  1143. gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = CellState.FILLED
  1144. })
  1145. // 检查复制的整体网格是否有可消除
  1146. if (this.gridEliminateCheck(gridList).gridEliminateList.length > 0) {
  1147. moveFlag = true
  1148. next.gridConfig.forEach((gridConfigData) => {
  1149. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1150. })
  1151. }
  1152. }
  1153. gridConfig = next.gridConfig
  1154. deg = next.deg
  1155. }
  1156. }
  1157. }
  1158. }
  1159. // 找方块可放置位置
  1160. for (let rowIndex = 0; rowIndex < this.rows && !moveFlag; rowIndex++) {
  1161. for (let columnIndex = 0; columnIndex < this.cols && !moveFlag; columnIndex++) {
  1162. const gridData = this.gridList[rowIndex][columnIndex]
  1163. if (gridData.status !== CellState.EMPTY) continue
  1164. // 方块不旋转检测是否能放
  1165. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1166. const brickData = this.bricksList[brickI]
  1167. if (this.moveIf(rowIndex, columnIndex, brickData.gridConfig)) {
  1168. moveFlag = true
  1169. brickData.gridConfig.forEach((gridConfigData) => {
  1170. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1171. })
  1172. }
  1173. }
  1174. // 方块旋转检测是否能放
  1175. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1176. const brickData = this.bricksList[brickI]
  1177. if (!brickData.rotateFlag) continue
  1178. let gridConfig = brickData.gridConfig
  1179. let deg = brickData.deg
  1180. for (let count = 1; count <= 3 && !moveFlag; count++) {
  1181. const next = this.nextGridRotate(gridConfig, deg)
  1182. if (this.moveIf(rowIndex, columnIndex, next.gridConfig)) {
  1183. moveFlag = true
  1184. next.gridConfig.forEach((gridConfigData) => {
  1185. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1186. })
  1187. }
  1188. gridConfig = next.gridConfig
  1189. deg = next.deg
  1190. }
  1191. }
  1192. }
  1193. }
  1194. if (gridPromptList.length < 1) {
  1195. resolve(false)
  1196. return
  1197. }
  1198. if (!tipFlag) {
  1199. resolve(true)
  1200. return
  1201. }
  1202. // 提示用户(网格变绿)
  1203. gridPromptList.forEach((gridData) => {
  1204. if (gridData.gridNode && gridData.gridNode.children[0]) {
  1205. const sprite = gridData.gridNode.children[0].getComponent(Sprite);
  1206. if (sprite) {
  1207. sprite.color = this.usableColor;
  1208. }
  1209. }
  1210. // 用于恢复格子
  1211. this.gridColorList.push(gridData)
  1212. })
  1213. resolve(true)
  1214. })
  1215. }
  1216. moveIf(row: number, column: number, gridConfig: GridConfigData[]) {
  1217. let moveFlag = true
  1218. for (let i = 0; i < gridConfig.length; i++) {
  1219. const gridConfigData = gridConfig[i]
  1220. const gridI = row + gridConfigData.row
  1221. const gridJ = column + gridConfigData.column
  1222. // 边界判断
  1223. if (
  1224. gridI < 0 ||
  1225. gridI > this.rows - 1 ||
  1226. gridJ < 0 ||
  1227. gridJ > this.cols - 1
  1228. ) {
  1229. moveFlag = false
  1230. break
  1231. }
  1232. // 已用
  1233. else if (this.gridList[gridI][gridJ].status === CellState.FILLED) {
  1234. moveFlag = false
  1235. break
  1236. }
  1237. }
  1238. return moveFlag
  1239. }
  1240. // 复制整体网格
  1241. copyGridList() {
  1242. const gridList: GridData[][] = []
  1243. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1244. gridList.push([])
  1245. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1246. const gridData = this.gridList[rowIndex][columnIndex]
  1247. gridList[rowIndex].push({
  1248. name: gridData.name,
  1249. status: gridData.status,
  1250. gridNode: null,
  1251. row: gridData.row,
  1252. col: gridData.col,
  1253. gridColorKey: gridData.gridColorKey,
  1254. type: gridData.type,
  1255. })
  1256. }
  1257. }
  1258. return gridList
  1259. }
  1260. gameOver() {
  1261. this.gameState = GameState.GAME_OVER
  1262. this.setGameState(GameState.GAME_OVER)
  1263. console.log("游戏结束")
  1264. oops.gui.open(UIID.GameOver);
  1265. }
  1266. /**
  1267. * 清理网格的子节点
  1268. */
  1269. private clearGridChildren(gridNode: Node): void {
  1270. const children = gridNode.children.slice(); // 创建副本避免遍历时修改问题
  1271. children.forEach(node => node.destroy());
  1272. }
  1273. private setGameState(state: GameState) {
  1274. this.gameState = state;
  1275. switch (state) {
  1276. case GameState.READY:
  1277. break;
  1278. case GameState.PLAYING:
  1279. break;
  1280. case GameState.PAUSED:
  1281. break;
  1282. case GameState.GAME_OVER:
  1283. //打开游戏结束界面
  1284. break;
  1285. }
  1286. }
  1287. //========================打开其他界面和按钮逻辑=======================
  1288. /** 视图对象通过 ecs.Entity.remove(eliminateViewComp) 删除组件是触发组件处理自定义释放逻辑 */
  1289. reset() {
  1290. this.node.destroy();
  1291. }
  1292. private btn_setting() {
  1293. oops.gui.open(UIID.Setting);
  1294. }
  1295. private btn_withdraw() {
  1296. oops.gui.open(UIID.WechatWithdraw);
  1297. }
  1298. private btn_award() {
  1299. oops.gui.open(UIID.RedPacketWithdraw);
  1300. }
  1301. private btn_auto() {
  1302. //自动放置
  1303. this.autoState = !this.autoState;
  1304. this.initButtonState(this.autoState);
  1305. }
  1306. //重新开始
  1307. private restartGame() {
  1308. if (this.gameState === GameState.READY) return;
  1309. this.initData();
  1310. this.reopenGrid();
  1311. this.initButtonState(this.autoState);
  1312. }
  1313. //重新清除网格
  1314. private reopenGrid() {
  1315. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1316. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1317. this.gridList[rowIndex][columnIndex].status = CellState.EMPTY
  1318. this.generateGrid(this.gridList[rowIndex][columnIndex])
  1319. }
  1320. }
  1321. // 初始化方块
  1322. if (this.brickNode) {
  1323. if (this.brickNode) {
  1324. this.brickNode.children.forEach(node => { node.destroy() });
  1325. }
  1326. }
  1327. this.bricksList.length = 0
  1328. for (let i = 1; i <= this.brickNum; i++) {
  1329. this.addBrick(i)
  1330. }
  1331. // 清除旋转数据
  1332. if (this.rotateNode) {
  1333. this.rotateNode.children.forEach(node => { node.destroy() })
  1334. }
  1335. }
  1336. }