EliminateViewComp.ts 68 KB

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