EliminateViewComp.ts 67 KB

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