EliminateViewComp.ts 67 KB

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