EliminateViewComp.ts 67 KB

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