EliminateViewComp.ts 69 KB

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