EliminateViewComp.ts 67 KB

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