EliminateViewComp.ts 66 KB

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