EliminateViewComp.ts 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363
  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-23 16:45:39
  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 { DeviceUtil } from "db://oops-framework/core/utils/DeviceUtil";
  11. import { ecs } from "db://oops-framework/libs/ecs/ECS";
  12. import { LabelChange } from "db://oops-framework/libs/gui/label/LabelChange";
  13. import { CCComp } from "db://oops-framework/module/common/CCComp";
  14. import { GameEvent } from "../common/config/GameEvent";
  15. import { UIID } from "../common/config/GameUIConfig";
  16. import { ServerHandler } from "../common/manager/ServerHandler";
  17. import { smc } from "../common/SingletonModuleComp";
  18. import { Format } from "../utils/Format";
  19. import { DCHandler } from "../common/manager/DCHandler";
  20. const { ccclass, property } = _decorator;
  21. // 游戏状态枚举
  22. enum GameState {
  23. READY, // 准备中
  24. PLAYING, // 游戏中
  25. PAUSED, // 暂停 --进其他界面,广告暂停
  26. GAME_OVER, // 游戏结束
  27. GAME_PASS
  28. }
  29. // 格子状态
  30. enum CellState {
  31. EMPTY, // 空格子
  32. FILLED, // 有方块
  33. HIGHLIGHTED // 高亮(可放置)
  34. }
  35. //网格数据接口
  36. interface GridData {
  37. name: string, // 名称
  38. status: CellState, // 状态
  39. gridNode: Node | null // 网格节点
  40. row: number, // 行
  41. col: number, // 列
  42. type: number, // 类型--gridColorKey
  43. }
  44. interface Grids {
  45. row: number,
  46. column: number,
  47. }
  48. interface EditingData {
  49. brickData: BrickData | null,
  50. gridList: GridData[],
  51. }
  52. //底部方块数据定义
  53. interface BrickData {
  54. index: number,
  55. brickKey: string | null,
  56. rotateFlag: boolean,
  57. gridConfig: Grids[],
  58. deg: number,
  59. brickNode: Node | null,
  60. brickInitPos: Vec3, // 方块初始位置
  61. type: number, // 方块类型--gridColorKey
  62. rotateNode: Node | null,
  63. }
  64. interface GridConfigData {
  65. row: number,
  66. column: number,
  67. }
  68. /** 视图层对象 */
  69. @ccclass('EliminateViewComp')
  70. @ecs.register('EliminateView', false)
  71. export class EliminateViewComp extends CCComp {
  72. @property({ type: LabelChange, displayName: "自动提现金额" })
  73. private lab_wxCoin: LabelChange = null!;
  74. @property({ type: LabelChange, displayName: "额外奖励" })
  75. private lab_hbCoin: LabelChange = null!;
  76. @property({ type: Node, displayName: "tween微信钱Node" })
  77. private tweenWechatNode: Node = null!;
  78. @property({ type: Node, displayName: "tween红包Node" })
  79. private tweenRedNode: Node = null!;
  80. @property({ type: Prefab, displayName: "金币预制体" })
  81. private coinPrefab: Prefab = null!
  82. @property({ type: Prefab, displayName: "红包预制体" })
  83. private redPacketPrefab: Prefab = null!;
  84. @property({ type: Label, displayName: "本局分数" })
  85. private lab_score: Label = null!;
  86. @property({ type: Label, displayName: "目标分数" })
  87. private lab_taget: Label = null!;
  88. @property({ type: Prefab, displayName: "item预制体列表" })
  89. private itemPrefabs: Prefab[] = [];
  90. @property({ type: Node, displayName: "网格Node" })
  91. private gridNode: Node = null!;
  92. @property({ type: Node, displayName: "移动Node" })
  93. private moveNode: Node = null!;
  94. @property({ type: Node, displayName: "旋转Node" })
  95. private rotateNode: Node = null!;
  96. @property({ type: Node, displayName: "方块Node" })
  97. private brickNode: Node = null!;
  98. @property({ type: Prefab, displayName: "旋转预制体" })
  99. private rotatePrefab: Node = null!;
  100. @property({ type: Label, displayName: "累计消除次数" })
  101. private lab_total: Label = null!;
  102. @property({ type: Label, displayName: "每次放置添加的分数" })
  103. private lab_addScore: Label = null!;
  104. @property({ type: Button, displayName: "自动按钮" })
  105. private autoBtn: Button = null!;
  106. //二倍速按钮
  107. @property({ type: Button, displayName: "二倍速按钮" })
  108. private doubleSpeedBtn: Button = null!;
  109. @property({ type: Label, displayName: "第几块金砖" })
  110. private lab_goldNum: Label = null!;
  111. @property({ type: Label, displayName: "二倍速时间" })
  112. private lab_doubleTime: Label = null!;
  113. @property({ type: Node, displayName: "引导层" })
  114. private guideNode: Node = null!;
  115. @property({ type: Node, displayName: "ComboNode" })
  116. private comboNode: Node = null!;
  117. //游戏配置行列
  118. private rows: number = 8; // 行数
  119. private cols: number = 8; // 列数
  120. private itemSize: number = 76.25; // 格子大小
  121. private brickNum: number = 3; // 砖块数量
  122. private yOffset = 100;
  123. private aniBrickRotate = 0
  124. private operateFlag: boolean = false //是否可以操作
  125. private touchStartPos = new Vec2()
  126. private gameState: GameState = GameState.READY;
  127. private score: number = 0; //本局分数
  128. private money: number = 0; //左边金钱
  129. private cash: number = 0; //右边红包钱数
  130. private targetScore: number = 0; //目标分数
  131. private isDoubleSpeed: boolean = false; //是否开启二倍速
  132. private doubleNum: number = 2; //除2就是开启了2倍速,除1就是关闭了2倍速
  133. private callback: Function | null = null; //回调函数
  134. //tween时间控制变量
  135. private autoMoveTime: number = 0.4; //自动移动时间
  136. //再次自动放置间隔时间
  137. private autoPlaceInterval: number = 0.4;
  138. //没使用颜色
  139. notUseColor = new Color(255, 255, 255, 255)
  140. //可用的颜色
  141. usableColor = new Color(0, 255, 0, 100)
  142. //不可用的颜色
  143. unavailableColor = new Color(255, 0, 0, 100)
  144. //旋转容错
  145. rotateFaultTolerant = 10;
  146. isAutoMode: boolean = false;
  147. autoModeInterval: number = 1 // 自动模式的间隔时间(秒)
  148. autoModeTimer: number = 0 // 自动模式计时器
  149. adShowingFlag: boolean = false; // 广告展示标记
  150. //网格列表管理列表
  151. gridList: GridData[][] = [];
  152. //砖块列表
  153. bricksList: BrickData[] = [];
  154. //网格颜色列表
  155. gridColorList: GridData[] = [];
  156. brickConfig: { bricks?: any } = {} //方块配置
  157. editingData: EditingData = {
  158. brickData: null,
  159. gridList: [],
  160. }
  161. //消除区间数组,到时候去这两个中间值,然后消除次数到了就展示翻倍广告
  162. private eliminateInterval: number[] = [];
  163. // 添加新的属性来跟踪是否需要重置消除计数
  164. private shouldResetEliminateCount: boolean = true;
  165. private autoState: boolean = false; //自动状态
  166. private eliminateBaseScore: number = 10; //每行得多少分
  167. private extraGridScore: number = 1; //每个格子占用几分
  168. private placementBaseScore: number = 1; //每个格子占用几分
  169. private currentCombo: number = 0; // 当前连击次数 //这里要记录连击次数就是每次移动能消除就增加,如果不能就归零
  170. //消除总数
  171. private eliminateTotal: number = 0;
  172. //2倍速时间
  173. private doubleSpeedTime: number = 0;
  174. //新手引导
  175. private isGuideMode = false;
  176. private guideStep = 0;
  177. //福利弹窗
  178. private popupType: string = "";
  179. //新人引导提示语
  180. private guideTips: string[] = [
  181. "拖动方块,填满整行可以进行消除",
  182. "当行与列被砖块同时填满,砖块会被消除",
  183. "点击方块可以旋转90°,不限旋转次数哦",
  184. "放置&消除方块得分达成目标获得金砖"
  185. ];
  186. private randomList: number[] = [];
  187. private autoFunction: Function | null = null;
  188. /** 视图层逻辑代码分离演示 */
  189. async start() {
  190. // const entity = this.ent as ecs.Entity; // ecs.Entity 可转为当前模块的具体实体对象
  191. this.setButton();
  192. this.initButtonState(false);
  193. await this.loadConfig();
  194. this.initData();
  195. this.setData();
  196. this.addEventList();
  197. // smc.account.AccountModel.curLevel = 1;
  198. if (this.guideStep === 0 && smc.account.AccountModel.curLevel == 1) {
  199. this.startGuideMode()
  200. } else {
  201. this.guideNode.active = false;
  202. this.initGrid();
  203. }
  204. //更新福利点
  205. this.updateWelfarePoint();
  206. DCHandler.inst.reportData(3000005);
  207. }
  208. addEventList() {
  209. oops.message.on(GameEvent.RestartGame, this.restartGame, this);
  210. oops.message.on(GameEvent.DoubleSpeedOpenSuccess, this.doubleSpeedOpenSuccess, this);
  211. oops.message.on(GameEvent.openView, this.openView, this);
  212. oops.message.on(GameEvent.showCoinAnimation, this.showCoinAnimation, this);
  213. // oops.message.on(GameEvent.Resurrection, this.onResurrection, this);
  214. oops.message.on(GameEvent.updateHbAndWxCoin, this.updateCoin, this);
  215. oops.message.on(GameEvent.StartAutoGame, this.startAutoGame, this);
  216. oops.message.on(GameEvent.updateGameState, this.updateGameState, this);
  217. }
  218. updateGameState(event: string, args: string) {
  219. console.log("更新游戏状态", args);
  220. switch (args) {
  221. case "paused":
  222. this.gameState = GameState.PAUSED;
  223. break;
  224. case "playing":
  225. this.gameState = GameState.PLAYING;
  226. break;
  227. }
  228. }
  229. //初始化网格
  230. private initGrid() {
  231. // 清理现有网格
  232. this.clearExistingGrids();
  233. // 生成网格矩阵
  234. this.createGridMatrix();
  235. }
  236. //初始化按钮状态
  237. private initButtonState(state: boolean) {
  238. //自动按钮默认关闭
  239. if (this.autoBtn) {
  240. //关闭
  241. const on = this.autoBtn.node.getChildByName("on");
  242. on ? on.active = state : null;
  243. const off = this.autoBtn.node.getChildByName("off");
  244. off ? off.active = !state : null;
  245. // this.autoState = state;
  246. }
  247. //第一关隐藏二倍速和自动放置按钮
  248. const curLevel = smc.account.AccountModel.curLevel;
  249. this.autoBtn.node.active = curLevel > 1;
  250. this.doubleSpeedBtn.node.active = curLevel > 1;
  251. }
  252. //初始化数据
  253. private initData() {
  254. // this.gameMode = GameMode.MANUAL;
  255. this.score = 0;
  256. this.targetScore = 0;
  257. this.money = 0;
  258. this.cash = 0;
  259. this.autoState = false;
  260. this.operateFlag = true
  261. this.shouldResetEliminateCount = true;
  262. this.currentCombo = 0;
  263. }
  264. //设置数据
  265. setData() {
  266. if (smc.game.GameModel.curLevelConfig.eliminateScope) {
  267. this.eliminateInterval = smc.game.GameModel.curLevelConfig.eliminateScope || [];
  268. }
  269. this.score = smc.game.GameModel.curScore;
  270. this.money = smc.account.AccountModel.wxCoin;
  271. this.cash = smc.account.AccountModel.hbCoin;
  272. this.targetScore = smc.game.GameModel.targetScore;
  273. this.popupType = smc.game.GameModel.popupType;
  274. this.lab_score.string = this.score.toString();
  275. this.lab_wxCoin.string = Format.formatWxCoin(this.money);
  276. this.lab_hbCoin.string = Format.formatRedPacketCoin(this.cash);
  277. this.lab_taget.string = this.targetScore.toString();
  278. //金砖数量要加1
  279. const num = smc.account.AccountModel.goldCoin
  280. this.lab_goldNum.string = `${num + 1}`;
  281. this.gameState = GameState.PLAYING;
  282. this.randomList = this.getRandomUniqueInts();
  283. }
  284. updateCoin() {
  285. this.money = smc.account.AccountModel.wxCoin;
  286. this.cash = smc.account.AccountModel.hbCoin;
  287. this.lab_wxCoin.string = Format.formatWxCoin(this.money);
  288. this.lab_hbCoin.string = Format.formatRedPacketCoin(this.cash);
  289. }
  290. //开始自动游戏
  291. startAutoGame() {
  292. this.btn_auto();
  293. }
  294. openView(event: string, args: string) {
  295. switch (args) {
  296. case "openRedBagView":
  297. oops.gui.open(UIID.RedPacketWithdraw);
  298. break;
  299. case "openPassView":
  300. oops.gui.open(UIID.GamePass);
  301. break;
  302. case "openDoubleSurprise":
  303. oops.gui.open(UIID.DoubleRewards);
  304. break;
  305. case "openRebateView":
  306. oops.gui.open(UIID.CashRebate);
  307. break;
  308. case "openCashWithdrawalView":
  309. oops.gui.open(UIID.WithSussce); //提现成功
  310. break;
  311. case "openWechatWithdrawalView":
  312. oops.gui.open(UIID.WechatWithdraw); //微信提现页
  313. break;
  314. case "openDoubleSpeedView":
  315. oops.gui.open(UIID.DoubleSpeed);
  316. break;
  317. case "openRecordView":
  318. oops.gui.open(UIID.WithdrawRecord);
  319. break;
  320. }
  321. }
  322. startGuideMode() {
  323. this.isGuideMode = true
  324. this.guideStep = 1
  325. this.guideNode.active = true;
  326. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  327. const currentRow: GridData[] = [];
  328. this.gridList.push(currentRow);
  329. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  330. const gridData = this.createGridData(rowIndex, columnIndex);
  331. currentRow.push(gridData);
  332. this.createGridNode(gridData);
  333. }
  334. }
  335. // 初始化格子状态
  336. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  337. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  338. this.gridList[rowIndex][columnIndex].status = CellState.EMPTY
  339. this.generateGrid(this.gridList[rowIndex][columnIndex])
  340. }
  341. }
  342. // 清除旋转数据
  343. if (this.rotateNode) {
  344. this.rotateNode.destroyAllChildren();
  345. }
  346. this.touchStartPos.set(Vec2.ZERO)
  347. this.setupGuideStep(this.guideStep)
  348. }
  349. setupGuideStep(step: number) {
  350. this.gameState = GameState.PLAYING;
  351. this.operateFlag = true
  352. this.bricksList.length = 0
  353. this.brickNode.destroyAllChildren();
  354. this.clearAllGuideGrids()
  355. this.guideStep = step
  356. const tips_node = this.guideNode.getChildByPath("tips/lab_tips");
  357. if (tips_node) {
  358. const tips = tips_node.getComponent(Label);
  359. if (tips) {
  360. tips.string = this.guideTips[step - 1];
  361. }
  362. }
  363. if (step === 1) {
  364. const emptyIndex = Math.floor(this.cols / 2)
  365. for (let c = 0; c < this.cols; c++) {
  366. if (c !== emptyIndex) {
  367. const g = this.gridList[0][c]
  368. g.status = 1
  369. g.type = 1;
  370. this.generateGrid(g)
  371. }
  372. }
  373. this.createGuideBrick([{ row: 0, column: 0 }], "Brick1", 1, 1)
  374. }
  375. else if (step === 2) {
  376. for (let r = 0; r < this.rows; r++) {
  377. if (r !== 0) {
  378. const g = this.gridList[r][3]
  379. g.status = 1
  380. g.type = 1;
  381. this.generateGrid(g)
  382. }
  383. }
  384. this.createGuideBrick([{ row: 0, column: 0 }], "Brick1", 1, 1)
  385. }
  386. else if (step === 3) {
  387. // 填满前两列,除去 [2][0] 这个位置,制造一个L型缺口
  388. for (let r = 0; r < this.rows; r++) {
  389. for (let c = 3; c < 5; c++) {
  390. if (r === 2 && c === 3) continue
  391. if (r === 1 && c === 3) continue
  392. if (r === 3 && c === 3) continue
  393. if (r === 2 && c === 4) continue
  394. if (r === 1 && c === 4) continue
  395. if (r === 3 && c === 4) continue
  396. const g = this.gridList[r][c]
  397. g.status = 1
  398. g.type = 1;
  399. this.generateGrid(g)
  400. }
  401. }
  402. // 创建一个L型方块,引导玩家旋转后放置
  403. this.createGuideBrick([
  404. { row: 0, column: 0 },
  405. { row: 0, column: 1 },
  406. { row: 0, column: 2 },
  407. { row: 1, column: 0 },
  408. { row: 1, column: 1 },
  409. { row: 1, column: 2 }
  410. ], "BrickII", 1, 1, true) //这要双II
  411. }
  412. else if (step === 4) {
  413. const centerRow = Math.floor(this.rows / 2);
  414. const centerCol = Math.floor(this.cols / 2);
  415. // 遍历整个网格
  416. for (let r = 0; r < this.rows; r++) {
  417. for (let c = 0; c < this.cols; c++) {
  418. const inCenter =
  419. r >= centerRow && r <= centerRow + 1 &&
  420. c >= centerCol && c <= centerCol + 1;
  421. const isCross =
  422. r === centerRow || r === centerRow + 1 || // 中间两行
  423. c === centerCol || c === centerCol + 1; // 中间两列
  424. if (isCross && !inCenter) {
  425. const g = this.gridList[r][c];
  426. g.status = 1;
  427. g.type = 1;
  428. this.generateGrid(g);
  429. }
  430. }
  431. }
  432. this.createGuideBrick([
  433. { row: 0, column: 0 },
  434. { row: 0, column: 1 },
  435. { row: 1, column: 0 },
  436. { row: 1, column: 1 }
  437. ], "BrickO", 1, 1)
  438. }
  439. }
  440. clearAllGuideGrids() {
  441. for (let row = 0; row < this.rows; row++) {
  442. for (let col = 0; col < this.cols; col++) {
  443. const grid = this.gridList[row][col]
  444. grid.status = 0;
  445. grid.type = 0;
  446. this.generateGrid(grid)
  447. }
  448. }
  449. }
  450. // 引导砖块保持底部中间生成
  451. createGuideBrick(gridConfig: GridConfigData[], brickKey: string, colorIndex: number, index: number, rotateFlag = false) {
  452. const brickData = {
  453. index,
  454. brickKey: brickKey,
  455. rotateFlag,
  456. gridConfig,
  457. deg: 0,
  458. brickNode: new Node(),
  459. gridColorKey: "colorKey",
  460. brickInitPos: new Vec3(),
  461. type: colorIndex,
  462. rotateNode: new Node(),
  463. }
  464. console.log("brickKey>>>>>>>>>>", brickKey, colorIndex)
  465. const node = this.generateBrick(brickKey, colorIndex)
  466. this.brickNode.addChild(node);
  467. const transform = this.brickNode.getComponent(UITransform);
  468. if (transform) {
  469. const midX = transform.width / 2;
  470. node.setPosition(0, 0);
  471. brickData.brickNode = node
  472. brickData.brickInitPos = node.getWorldPosition()
  473. this.bricksList.push(brickData)
  474. this.brickAddEvent(brickData)
  475. }
  476. if (brickData.rotateFlag) {
  477. brickData.rotateNode = instantiate(this.rotatePrefab)
  478. this.rotateNode.addChild(brickData.rotateNode);
  479. //先隐藏
  480. brickData.rotateNode.active = false;
  481. brickData.rotateNode.setWorldPosition(this.brickNode.getWorldPosition())
  482. }
  483. }
  484. //显示金币动画 --是否只计算红包
  485. showCoinAnimation(event: string, args: string) {
  486. //计算中间的坐标就好
  487. const lastPos = this.moveNode.getWorldPosition();
  488. const score = this.score;
  489. if (smc.game.GameModel.changeHbCoin > 0) {
  490. this.createCoinFlyAnimation(
  491. this.redPacketPrefab,
  492. lastPos,
  493. this.lab_hbCoin.node.getWorldPosition(),
  494. 5,
  495. () => {
  496. // 显示红包分数增加动画
  497. this.showRedPacketScoreAnimation();
  498. }
  499. );
  500. }
  501. if (smc.game.GameModel.changeWxCoin) {
  502. // 添加回调函数,在金币动画完成后显示微信分数增加
  503. this.createCoinFlyAnimation(
  504. this.coinPrefab,
  505. lastPos,
  506. this.lab_wxCoin.node.getWorldPosition(),
  507. score,
  508. () => {
  509. // 显示微信分数增加动画
  510. this.showWechatScoreAnimation();
  511. }
  512. );
  513. }
  514. }
  515. //初始化网格
  516. private async loadConfig() {
  517. let json_name: string = "gui/eliminate/config/GridConfig";
  518. return new Promise<void>((resolve, reject) => {
  519. oops.res.load(json_name, JsonAsset, (err: Error | null, res: any) => {
  520. if (res) {
  521. this.brickConfig = res.json;
  522. resolve();
  523. } else {
  524. console.log("JSON数据加载失,请检查文件");
  525. reject(err);
  526. }
  527. });
  528. });
  529. }
  530. /**
  531. * @description: 清理现有的网格数据
  532. * @return {*}
  533. */
  534. private clearExistingGrids(): void {
  535. this.gridList = [];
  536. if (this.gridNode) {
  537. this.gridNode.destroyAllChildren();
  538. }
  539. }
  540. /**
  541. * @description: 设置网格容器大小
  542. * @return {*}
  543. */
  544. private createGridMatrix(): void {
  545. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  546. const currentRow: GridData[] = [];
  547. this.gridList.push(currentRow);
  548. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  549. const gridData = this.createGridData(rowIndex, columnIndex);
  550. currentRow.push(gridData);
  551. this.createGridNode(gridData);
  552. }
  553. }
  554. // 初始化格子状态
  555. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  556. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  557. this.gridList[rowIndex][columnIndex].status = CellState.EMPTY
  558. this.generateGrid(this.gridList[rowIndex][columnIndex])
  559. }
  560. }
  561. // 初始化方块
  562. if (this.brickNode) {
  563. this.brickNode.destroyAllChildren();
  564. }
  565. this.bricksList.length = 0
  566. for (let i = 1; i <= this.brickNum; i++) {
  567. this.addBrick(i)
  568. }
  569. // 清除旋转数据
  570. if (this.rotateNode) {
  571. this.rotateNode.destroyAllChildren();
  572. }
  573. this.touchStartPos.set(Vec2.ZERO)
  574. }
  575. /**
  576. * @description: 创建格子数据
  577. * @param {number} row
  578. * @param {number} column
  579. * @return {*}
  580. */
  581. private createGridData(row: number, column: number): GridData {
  582. return {
  583. name: `Grid-${row}-${column}`,
  584. status: CellState.EMPTY,
  585. gridNode: null,
  586. row: row,
  587. col: column,
  588. type: 0
  589. };
  590. }
  591. /**
  592. * @description: 创建网格Node
  593. * @param {GridData} gridData
  594. * @return {*}
  595. */
  596. private createGridNode(gridData: GridData): void {
  597. const gridNode = new Node(gridData.name);
  598. if (this.gridNode) {
  599. this.gridNode.addChild(gridNode);
  600. }
  601. gridData.gridNode = gridNode;
  602. // 设置网格大小
  603. gridNode.addComponent(UITransform).setContentSize(this.itemSize, this.itemSize);
  604. }
  605. /**
  606. * 生成或更新网格
  607. * @param gridData 网格数据
  608. */
  609. private generateGrid(gridData: GridData) {
  610. if (!gridData || !gridData.gridNode) {
  611. console.warn('无效的网格数据');
  612. return;
  613. }
  614. // 清理现有子节点
  615. this.clearGridChildren(gridData.gridNode);
  616. // 获取对应的预制体
  617. const prefab = this.getGridPrefab(gridData);
  618. if (!prefab) {
  619. console.warn('无法获取网格预制体');
  620. return;
  621. }
  622. // 创建并配置新节点
  623. const node = this.createNewGridNode(prefab, gridData);
  624. // 设置节点属性
  625. this.setupGridNode(node, gridData);
  626. }
  627. /**
  628. * 获取对应状态的预制体
  629. */
  630. private getGridPrefab(gridData: GridData): Prefab {
  631. if (gridData.status === CellState.EMPTY) {
  632. if (this.itemPrefabs[0]) {
  633. return this.itemPrefabs[0];
  634. } else {
  635. throw new Error('Grid prefab is not loaded');
  636. }
  637. }
  638. if (gridData.status === CellState.FILLED && gridData.type) {
  639. const type = gridData.type;
  640. return this.itemPrefabs[type];
  641. }
  642. throw new Error('Invalid grid status or missing gridColorKey');
  643. }
  644. /**
  645. * 创建网格节点
  646. */
  647. private createNewGridNode(prefab: Prefab, gridData: GridData): Node {
  648. const node = instantiate(prefab);
  649. if (gridData && gridData.gridNode) {
  650. gridData.gridNode.addChild(node);
  651. return node;
  652. }
  653. return node
  654. }
  655. /**
  656. * 设置网格节点的属性
  657. */
  658. private setupGridNode(node: Node, gridData: GridData): void {
  659. // 设置未使用状态的颜色
  660. if (gridData.status === CellState.EMPTY) {
  661. const sprite = node.getComponent(Sprite);
  662. if (sprite) {
  663. sprite.color = this.notUseColor;
  664. }
  665. }
  666. // 设置节点大小
  667. const transform = node.getComponent(UITransform);
  668. if (transform) {
  669. transform.setContentSize(
  670. this.itemSize,
  671. this.itemSize
  672. );
  673. }
  674. // 设置位置
  675. node.setPosition(Vec3.ZERO);
  676. }
  677. addBrick(index: number) {
  678. if (this.isGuideMode) {
  679. return;
  680. }
  681. const brickKey = Object.keys(this.brickConfig['bricks'])[randomRangeInt(0, Object.keys(this.brickConfig['bricks']).length)];
  682. const brickConfig = this.brickConfig['bricks'][brickKey];
  683. const num = Math.floor(Math.random() * this.randomList.length);
  684. const randomIndex = this.randomList[num];
  685. // const randomIndex = this.randomList[0];
  686. // 生成方块
  687. const brickData: BrickData = {
  688. index,
  689. brickKey: brickKey,
  690. rotateFlag: brickConfig['rotateFlag'],
  691. gridConfig: brickConfig['gridConfig'],
  692. deg: 0,
  693. brickNode: null,
  694. brickInitPos: new Vec3(),
  695. type: randomIndex,
  696. rotateNode: null,
  697. }
  698. this.bricksList.push(brickData)
  699. // 生成方块
  700. const brickNode = this.generateBrick(brickKey, randomIndex);
  701. if (this.brickNode) {
  702. this.brickNode.addChild(brickNode)
  703. }
  704. brickData.brickNode = brickNode;
  705. let offset = 220
  706. if (this.brickNum % 2 === 1) {
  707. const middleNum = Math.floor(this.brickNum / 2) + 1
  708. if (index < middleNum) {
  709. offset = - offset
  710. }
  711. else if (index === middleNum) {
  712. offset = 0
  713. }
  714. }
  715. if (brickData && brickData.brickNode) {
  716. brickData.brickNode.setPosition(offset, 0)
  717. brickData.brickNode.scale_x = 0.6;
  718. brickData.brickNode.scale_y = 0.6;
  719. brickData.brickInitPos = brickData.brickNode.getWorldPosition()
  720. }
  721. if (brickData.rotateFlag) {
  722. brickData.rotateNode = instantiate(this.rotatePrefab)
  723. this.rotateNode.addChild(brickData.rotateNode);
  724. //先隐藏
  725. brickData.rotateNode.active = false;
  726. brickData.rotateNode.setWorldPosition(brickNode.getWorldPosition())
  727. }
  728. this.brickAddEvent(brickData);
  729. }
  730. // 每个item生成独立的方块节点
  731. generateBrick(brickKey: string, randomIndex: number) {
  732. const brickConfig = this.brickConfig['bricks'][brickKey]
  733. let rowMin = 0
  734. let rowMax = 0
  735. let columnMin = 0
  736. let columnMax = 0
  737. brickConfig['gridConfig'].forEach((gridConfigData: GridConfigData) => {
  738. if (gridConfigData.row < rowMin) {
  739. rowMin = gridConfigData.row
  740. }
  741. else if (gridConfigData.row > rowMax) {
  742. rowMax = gridConfigData.row
  743. }
  744. if (gridConfigData.column < columnMin) {
  745. columnMin = gridConfigData.column
  746. }
  747. else if (gridConfigData.column > columnMax) {
  748. columnMax = gridConfigData.column
  749. }
  750. })
  751. const rowNum = (rowMax - rowMin + 1)
  752. const columnNum = (columnMax - columnMin + 1)
  753. // 生成独立的方块节点
  754. const brickNode = new Node()
  755. brickNode.name = brickKey
  756. // 设置方块大小
  757. const transformCom: UITransform = brickNode.addComponent(UITransform)
  758. transformCom.setContentSize(
  759. this.itemSize * columnNum,
  760. this.itemSize * rowNum
  761. )
  762. transformCom.setAnchorPoint(0.5, 0.5)
  763. // 设置方块位置
  764. const gridPrefab = this.itemPrefabs[randomIndex]
  765. //生成对应的配置方块设置地址
  766. brickConfig['gridConfig'].forEach((gridConfigData: GridConfigData) => {
  767. const gridNode = new Node()
  768. gridNode.name = 'grid'
  769. brickNode.addChild(gridNode)
  770. gridNode.addComponent(UITransform).setContentSize(this.itemSize, this.itemSize)
  771. const gridWidget: Widget = gridNode.addComponent(Widget)
  772. gridWidget.isAlignLeft = true
  773. gridWidget.left = this.itemSize * gridConfigData.column - this.itemSize * columnMin
  774. gridWidget.isAlignBottom = true
  775. gridWidget.bottom = this.itemSize * gridConfigData.row - this.itemSize * rowMin
  776. const node = instantiate(gridPrefab)
  777. gridNode.addChild(node)
  778. const uiTransform = node.getComponent(UITransform);
  779. if (uiTransform) {
  780. uiTransform.setContentSize(
  781. this.itemSize,
  782. this.itemSize,
  783. )
  784. }
  785. node.setPosition(Vec3.ZERO)
  786. node.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  787. event.preventSwallow = true;
  788. }, this);
  789. node.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  790. event.preventSwallow = true;
  791. }, this);
  792. node.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
  793. event.preventSwallow = true;
  794. }, this);
  795. })
  796. return brickNode
  797. }
  798. brickAddEvent(brickData: BrickData) {
  799. const brickNode = brickData.brickNode
  800. if (!brickNode) {
  801. console.error("brickNode为空,无法添加事件");
  802. return
  803. }
  804. // 记录初始位置和状态
  805. let startPos = new Vec3();
  806. let originalParent: Node | null = null;
  807. // 触摸开始事件
  808. brickNode.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  809. // 如果正在编辑其他方块,则忽略
  810. if (!this.operateFlag) return;
  811. // 清空编辑中的数据
  812. this.editingData.brickData = null;
  813. this.editingData.gridList.length = 0;
  814. // 记录触摸开始位置和方块原始信息
  815. this.touchStartPos.set(event.getUILocation());
  816. originalParent = brickNode.parent;
  817. startPos = brickNode.getWorldPosition().clone();
  818. // 将方块移到移动层并放大
  819. brickNode.setParent(this.moveNode);
  820. brickNode.setWorldPosition(startPos);
  821. // 从方块列表中移除该方块
  822. const index = this.bricksList.findIndex(item => item === brickData);
  823. if (index > -1) {
  824. this.editingData.brickData = this.bricksList.splice(index, 1)[0];
  825. } else {
  826. console.error("未找到方块数据:", brickData);
  827. }
  828. }, this);
  829. // 触摸移动事件
  830. brickNode.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  831. if (!this.operateFlag) return;
  832. const movePos: Vec2 = event.getUILocation().subtract(this.touchStartPos)
  833. // 挪动很小时,不移动方块组合
  834. if (movePos.length() <= this.rotateFaultTolerant) {
  835. return
  836. }
  837. // 隐藏旋转节点
  838. if (this.editingData.brickData && this.editingData.brickData.rotateFlag) {
  839. if (this.editingData.brickData.rotateNode) {
  840. this.editingData.brickData.rotateNode.active = false
  841. }
  842. }
  843. // 恢复所有网格颜色
  844. this.gridColorRecovery();
  845. // 移动方块
  846. brickNode.setWorldPosition(event.getUILocation().toVec3().add3f(0, this.yOffset, 0))
  847. brickNode.scale_x = 1;
  848. brickNode.scale_y = 1;
  849. // 重置编辑中的网格数据
  850. this.editingData.gridList.length = 0;
  851. // 检查方块每个子网格是否与游戏网格重叠
  852. const tempGridList: GridData[] = [];
  853. let allEmptyGrids: boolean = true; // 标记是否所有网格都为空
  854. brickNode.children.forEach((childNode) => {
  855. const childWorldPos = childNode.getWorldPosition();
  856. // 查找与子网格重叠的游戏网格
  857. let matchedGrid: GridData | null = null;
  858. for (let row = 0; row < this.rows && !matchedGrid; row++) {
  859. for (let col = 0; col < this.cols && !matchedGrid; col++) {
  860. const grid = this.gridList[row][col];
  861. if (!grid || !grid.gridNode) continue;
  862. const gridPos = grid.gridNode.getWorldPosition();
  863. if (Vec3.distance(gridPos, childWorldPos) <= (this.itemSize / 2)) {
  864. matchedGrid = grid;
  865. }
  866. }
  867. }
  868. if (matchedGrid) {
  869. tempGridList.push(matchedGrid);
  870. // 检查是否有非空网格
  871. if (matchedGrid.status !== CellState.EMPTY) {
  872. allEmptyGrids = false;
  873. }
  874. }
  875. });
  876. // 检查是否所有子网格都有对应的游戏网格,且都是空的
  877. let canPlace = tempGridList.length === brickData.gridConfig.length && allEmptyGrids;
  878. // 更新编辑中的网格列表
  879. if (canPlace) {
  880. this.editingData.gridList = [...tempGridList];
  881. }
  882. // 更新网格颜色提示 - 只改变空网格的颜色
  883. tempGridList.forEach(grid => {
  884. // 只处理空网格
  885. if (grid.status === CellState.EMPTY) {
  886. if (grid.gridNode && grid.gridNode.children[0]) {
  887. const sprite = grid.gridNode.children[0].getComponent(Sprite);
  888. if (sprite) {
  889. sprite.color = canPlace ? this.usableColor : this.unavailableColor;
  890. }
  891. }
  892. // 用于后续恢复颜色
  893. this.gridColorList.push(grid);
  894. }
  895. });
  896. }, this);
  897. // 触摸结束或取消事件
  898. const touchEndHandler = (event: EventTouch) => {
  899. if (this.adShowingFlag || !this.operateFlag) return
  900. this.operateFlag = false
  901. // 单击旋转
  902. if (!this.editingData.brickData) {
  903. console.log("没有数据")
  904. return
  905. }
  906. if (
  907. this.editingData.brickData.rotateFlag &&
  908. event.getUILocation().subtract(this.touchStartPos).length() <= this.rotateFaultTolerant
  909. ) {
  910. //旋转
  911. const brickData = this.editingData.brickData
  912. if (brickData && brickData.brickNode) {
  913. this.bricksList.push(brickData)
  914. this.brickNode.addChild(brickData.brickNode)
  915. //显示旋转节点
  916. if (brickData.rotateNode) {
  917. brickData.rotateNode.active = true;
  918. }
  919. brickData.brickNode.setWorldPosition(brickData.brickInitPos)
  920. // 旋转
  921. this.brickGridRotate(brickData).then(() => {
  922. this.operateFlag = true
  923. })
  924. // 隐藏旋转节点
  925. this.scheduleOnce(() => {
  926. if (brickData.rotateNode) {
  927. brickData.rotateNode.active = false;
  928. }
  929. }, 0.4);
  930. //打点
  931. DCHandler.inst.reportData(3000600);
  932. }
  933. } else if (this.editingData.brickData && this.editingData.gridList.length > 0) {
  934. if (this.isGuideMode && this.guideStep > 0) {
  935. const brickData = this.editingData.brickData
  936. const targetGrids = this.editingData.gridList
  937. // 如果格子数量不足,直接视为无效放置
  938. if (!brickData || !targetGrids || targetGrids.length !== brickData.gridConfig.length) {
  939. this.bricksList.push(brickData)
  940. if (brickData.brickNode) {
  941. tween(brickData.brickNode)
  942. .to(0.15, {
  943. worldPosition: brickData.brickInitPos,
  944. scale: new Vec3(0.8, 0.8, 0.8)
  945. })
  946. .call(() => {
  947. if (brickData.brickNode) {
  948. this.operateFlag = true
  949. this.brickNode.addChild(brickData.brickNode)
  950. brickData.brickNode.setWorldPosition(brickData.brickInitPos)
  951. }
  952. })
  953. .start()
  954. }
  955. return
  956. }
  957. // 模拟砖块落下后的状态
  958. const tempGridList = this.copyGridList()
  959. for (let i = 0; i < targetGrids.length; i++) {
  960. const g = targetGrids[i]
  961. tempGridList[g.row][g.col].status = CellState.FILLED
  962. }
  963. const simulateResult = this.gridEliminateCheck(tempGridList)
  964. const canEliminate = simulateResult.gridEliminateList.length > 0
  965. if (!canEliminate) {
  966. this.bricksList.push(brickData);
  967. if (brickData.brickNode) {
  968. tween(brickData.brickNode)
  969. .to(0.15, {
  970. worldPosition: brickData.brickInitPos,
  971. scale: new Vec3(0.8, 0.8, 0.8)
  972. })
  973. .call(() => {
  974. if (brickData.brickNode) {
  975. this.operateFlag = true
  976. this.brickNode.addChild(brickData.brickNode)
  977. brickData.brickNode.setWorldPosition(brickData.brickInitPos)
  978. }
  979. })
  980. .start()
  981. }
  982. return
  983. }
  984. }
  985. // 计算放置的格子数量
  986. const placedGridCount = this.editingData.gridList.length;
  987. // 获取中心位置用于显示分数
  988. let centerPos = new Vec3(0, 0, 0);
  989. if (this.editingData.gridList.length > 0 && this.editingData.gridList[0].gridNode) {
  990. centerPos = this.editingData.gridList[0].gridNode.getWorldPosition().clone();
  991. if (this.editingData.gridList.length > 1) {
  992. // 计算所有格子的平均位置作为中心点
  993. for (let i = 1; i < this.editingData.gridList.length; i++) {
  994. const gridNode = this.editingData.gridList[i].gridNode;
  995. if (gridNode) {
  996. centerPos.add(gridNode.getWorldPosition());
  997. }
  998. }
  999. const validGridCount = this.editingData.gridList.filter(grid => grid.gridNode).length;
  1000. centerPos.x /= validGridCount;
  1001. centerPos.y /= validGridCount;
  1002. }
  1003. }
  1004. // 放置方块到网格
  1005. this.editingData.gridList.forEach(grid => {
  1006. grid.status = CellState.FILLED;
  1007. grid.type = this.editingData.brickData!.type;
  1008. this.generateGrid(grid);
  1009. });
  1010. // 显示放置得分动画(显示一次,包含总格子数)
  1011. this.showScoreAnimation(centerPos, placedGridCount);
  1012. //这里要计算分数,并且计算能消除的分数,然后增加分,这才对
  1013. // 标记需要重置消除计数器
  1014. this.shouldResetEliminateCount = true;
  1015. // 销毁方块节点
  1016. brickNode.destroy();
  1017. // 添加新方块到待选区
  1018. this.addBrick(this.editingData.brickData.index);
  1019. // 检查消除
  1020. this.scheduleOnce(() => {
  1021. this.gridEliminate().then((hasElimination) => {
  1022. // 如果没有消除,确保下次消除会重置计数
  1023. if (!hasElimination) {
  1024. this.shouldResetEliminateCount = true;
  1025. }
  1026. this.operateFlag = true;
  1027. //新手引导
  1028. if (this.isGuideMode) {
  1029. this.scheduleOnce(() => {
  1030. if (this.guideStep < 4) {
  1031. this.setupGuideStep(this.guideStep + 1)
  1032. } else {
  1033. this.isGuideMode = false;
  1034. this.guideNode.active = false;
  1035. this.initGrid();
  1036. }
  1037. }, 0.3)
  1038. } else {
  1039. // 检查游戏是否结束
  1040. this.prompt(false).then(canContinue => {
  1041. if (!canContinue) {
  1042. this.gameOver();
  1043. }
  1044. });
  1045. }
  1046. });
  1047. }, 0.1);
  1048. } else {
  1049. // 无法放置,将方块返回原位置
  1050. const brickData = this.editingData.brickData;
  1051. if (brickData) {
  1052. this.bricksList.push(brickData);
  1053. this.operateFlag = false
  1054. // 添加回弹动画
  1055. tween(brickNode)
  1056. .to(0.2, {
  1057. worldPosition: brickData.brickInitPos,
  1058. scale: new Vec3(0.6, 0.6, 0.6)
  1059. })
  1060. .call(() => {
  1061. if (originalParent) {
  1062. this.operateFlag = true
  1063. brickNode.setParent(originalParent);
  1064. brickNode.setWorldPosition(brickData.brickInitPos);
  1065. }
  1066. })
  1067. .start();
  1068. }
  1069. }
  1070. // 格子颜色恢复
  1071. this.gridColorRecovery()
  1072. };
  1073. brickNode.on(Node.EventType.TOUCH_END, touchEndHandler, this);
  1074. brickNode.on(Node.EventType.TOUCH_CANCEL, touchEndHandler, this);
  1075. }
  1076. //格子颜色恢复
  1077. gridColorRecovery() {
  1078. while (this.gridColorList.length > 0) {
  1079. const gridData = this.gridColorList.pop();
  1080. if (gridData) {
  1081. if (gridData.status === CellState.EMPTY) {
  1082. if (gridData.gridNode) {
  1083. gridData.gridNode.children[0].getComponent(Sprite)!.color = this.notUseColor;
  1084. }
  1085. }
  1086. }
  1087. }
  1088. }
  1089. brickGridRotate(brickData: BrickData) {
  1090. return new Promise((resolve, reject) => {
  1091. const next = this.nextGridRotate(brickData.gridConfig, brickData.deg)
  1092. brickData.deg = next.deg
  1093. brickData.gridConfig = next.gridConfig
  1094. if (brickData.brickNode) {
  1095. tween(brickData.brickNode).to(this.aniBrickRotate, { angle: next.deg }).call(() => {
  1096. resolve(true)
  1097. }).start()
  1098. }
  1099. })
  1100. }
  1101. //下一个旋转
  1102. nextGridRotate(gridConfig: GridConfigData[], deg: number) {
  1103. const newGridConfig: GridConfigData[] = []
  1104. // 顺时针旋转
  1105. let newDeg = deg - 90
  1106. gridConfig.forEach((gridConfigData) => {
  1107. // 例如(1,2) => (-2,1),可以画图分析
  1108. newGridConfig.push({
  1109. row: -gridConfigData.column,
  1110. column: gridConfigData.row
  1111. })
  1112. })
  1113. return { gridConfig: newGridConfig, deg: newDeg }
  1114. }
  1115. // 显示分数增加动画
  1116. showScoreAnimation(position: Vec3, score: number) {
  1117. if (!this.lab_addScore) return;
  1118. // 计算得分(未消除时的得分)
  1119. const calculatedScore = score * this.placementBaseScore;
  1120. // 复制得分Label
  1121. const scoreLabel = instantiate(this.lab_addScore.node);
  1122. scoreLabel.active = true;
  1123. // 设置文本和位置
  1124. const label = scoreLabel.getComponent(Label);
  1125. if (label) {
  1126. label.string = `+${calculatedScore}`;
  1127. }
  1128. // 添加到场景中
  1129. this.node.addChild(scoreLabel);
  1130. scoreLabel.setWorldPosition(position);
  1131. const num = this.isDoubleSpeed ? this.doubleNum : 1;
  1132. // 创建动画效果
  1133. tween(scoreLabel)
  1134. .to(0.5 / num, {
  1135. position: new Vec3(scoreLabel.position.x, scoreLabel.position.y + 50, 0),
  1136. scale: new Vec3(1.2, 1.2, 1.2)
  1137. })
  1138. .to(0.3 / num, { opacity: 0 })
  1139. .call(() => {
  1140. scoreLabel.destroy();
  1141. })
  1142. .start();
  1143. // 更新总分
  1144. this.score += calculatedScore;
  1145. }
  1146. // 显示消除次数动画
  1147. showEliminateCountAnimation(yPosition: number, eliminationCount: number) {
  1148. if (!this.comboNode) return;
  1149. // 如果需要重置计数器,先将计数归零
  1150. if (this.shouldResetEliminateCount) {
  1151. this.currentCombo = 0;
  1152. this.shouldResetEliminateCount = false;
  1153. }
  1154. // 增加累计消除次数
  1155. this.currentCombo += eliminationCount;
  1156. // 复制总次数Label
  1157. const comboNode = instantiate(this.comboNode);
  1158. comboNode.active = true;
  1159. // 设置文本
  1160. const label = comboNode.getChildByName("lab_combo");
  1161. if (label) {
  1162. const labelComponent = label.getComponent(Label);
  1163. if (labelComponent) {
  1164. labelComponent.string = `${this.currentCombo}`;
  1165. }
  1166. }
  1167. // 添加到场景中
  1168. this.node.addChild(comboNode);
  1169. // 计算网格区域的X轴中心位置,Y轴使用传入的消除行位置
  1170. const centerPos = new Vec3();
  1171. if (this.gridNode) {
  1172. // 获取网格区域的X轴中心
  1173. const worldPos = this.gridNode.getWorldPosition();
  1174. centerPos.set(worldPos.x, yPosition, worldPos.z);
  1175. }
  1176. comboNode.setWorldPosition(centerPos);
  1177. // 创建动画效果
  1178. const num = this.isDoubleSpeed ? this.doubleNum : 1;
  1179. tween(comboNode)
  1180. .to(0.3 / num, {
  1181. scale: new Vec3(1.5, 1.5, 1.5),
  1182. opacity: 255
  1183. })
  1184. .delay(0.5 / num) // 停留更长时间
  1185. .to(0.4 / num, {
  1186. scale: new Vec3(1.2, 1.2, 1.2),
  1187. position: new Vec3(comboNode.position.x, comboNode.position.y + 50, 0),
  1188. opacity: 0
  1189. })
  1190. .call(() => {
  1191. comboNode.destroy();
  1192. })
  1193. .start();
  1194. }
  1195. // 修改 gridEliminate 方法来显示消除次数
  1196. gridEliminate() {
  1197. return new Promise<boolean>((resolve, reject) => {
  1198. const d = this.gridEliminateCheck(this.gridList)
  1199. const gridEliminateList = d.gridEliminateList
  1200. const eliminateRowNum = d.eliminateRowNum
  1201. const eliminateColumnNum = d.eliminateColumnNum
  1202. const totalEliminationsInThisRound = eliminateRowNum + eliminateColumnNum
  1203. this.eliminateTotal += totalEliminationsInThisRound;
  1204. console.log("消除总数", this.eliminateTotal)
  1205. if (gridEliminateList.length < 1) {
  1206. // 没有发生消除
  1207. this.updateGameScore();
  1208. this.shouldResetEliminateCount = true; // 下一次消除需要重置计数
  1209. resolve(false);
  1210. return;
  1211. }
  1212. // 如果有消除,计算消除行的平均Y轴位置
  1213. if (gridEliminateList.length > 0) {
  1214. // 计算所有被消除格子的平均Y轴位置
  1215. let totalY = 0;
  1216. let validGrids = 0;
  1217. for (const grid of gridEliminateList) {
  1218. if (grid.gridNode) {
  1219. totalY += grid.gridNode.getWorldPosition().y;
  1220. validGrids++;
  1221. }
  1222. }
  1223. // 计算平均Y位置
  1224. const avgY = validGrids > 0 ? totalY / validGrids : 0;
  1225. // 显示消除次数动画,传入Y轴位置和本次消除的行列总数
  1226. this.showEliminateCountAnimation(avgY, totalEliminationsInThisRound);
  1227. }
  1228. const num = this.isDoubleSpeed ? this.doubleNum : 1;
  1229. gridEliminateList.forEach((gridData) => {
  1230. if (gridData.gridNode?.children[0]) {
  1231. const startPos = gridData.gridNode.getWorldPosition();
  1232. tween(gridData.gridNode.children[0])
  1233. .to(0.2 / num, { scale: new Vec3(0.5, 0.5) })
  1234. .call(() => {
  1235. gridData.status = CellState.EMPTY
  1236. this.generateGrid(gridData)
  1237. })
  1238. .start()
  1239. if (this.coinPrefab && this.lab_wxCoin?.node) {
  1240. this.createCoinFlyAnimation(
  1241. this.coinPrefab,
  1242. startPos,
  1243. this.lab_wxCoin.node.getWorldPosition(),
  1244. 5
  1245. );
  1246. }
  1247. //增加红包
  1248. this.createCoinFlyAnimation(
  1249. this.redPacketPrefab,
  1250. startPos,
  1251. this.lab_hbCoin.node.getWorldPosition(),
  1252. 3
  1253. );
  1254. }
  1255. })
  1256. this.scheduleOnce(() => {
  1257. // 计算分数:每行/列的基础分 + 每个额外格子的分数
  1258. let score = 0;
  1259. // 行消除基础分
  1260. for (let i = 1; i <= eliminateRowNum; i++) {
  1261. score += this.eliminateBaseScore; // 每行基础分
  1262. score += (this.cols - 1) * this.extraGridScore; // 额外格子分
  1263. }
  1264. // 列消除基础分
  1265. for (let i = 1; i <= eliminateColumnNum; i++) {
  1266. score += this.eliminateBaseScore; // 每列基础分
  1267. score += (this.rows - 1) * this.extraGridScore; // 额外格子分
  1268. }
  1269. this.score += score;
  1270. this.updateGameScore();
  1271. if (DeviceUtil.isNative && DeviceUtil.isAndroid) {
  1272. ServerHandler.inst.updateEliminationReward({
  1273. count: totalEliminationsInThisRound,
  1274. score: this.score,
  1275. level: smc.account.AccountModel.curLevel,
  1276. })
  1277. } else {
  1278. //要服务器请求完了出了数据才展示动画
  1279. const lastGrid = gridEliminateList[gridEliminateList.length - 1];
  1280. if (lastGrid?.gridNode && this.coinPrefab && this.lab_wxCoin?.node) {
  1281. const lastPos = lastGrid.gridNode.getWorldPosition();
  1282. // 添加回调函数,在金币动画完成后显示微信分数增加
  1283. this.createCoinFlyAnimation(
  1284. this.coinPrefab,
  1285. lastPos,
  1286. this.lab_wxCoin.node.getWorldPosition(),
  1287. 3,
  1288. () => {
  1289. // 显示微信分数增加动画
  1290. this.showWechatScoreAnimation();
  1291. }
  1292. );
  1293. // 添加回调函数,在红包动画完成后显示红包分数增加
  1294. if (this.cash > 0) {
  1295. this.createCoinFlyAnimation(
  1296. this.redPacketPrefab,
  1297. lastPos,
  1298. this.lab_hbCoin.node.getWorldPosition(),
  1299. 3,
  1300. () => {
  1301. // 显示红包分数增加动画
  1302. this.showRedPacketScoreAnimation();
  1303. }
  1304. );
  1305. }
  1306. }
  1307. }
  1308. // 告诉调用者有消除发生
  1309. resolve(true)
  1310. // 检查是否需要继续消除
  1311. this.scheduleOnce(() => {
  1312. // 递归调用,检查并处理连锁消除
  1313. this.gridEliminate().then(() => {
  1314. if (this.eliminateInterval.length == 0) {
  1315. return;
  1316. }
  1317. const minNum = this.eliminateInterval[0]
  1318. const maxNum = this.eliminateInterval[1]
  1319. const randomNum = randomRangeInt(minNum, maxNum + 1);
  1320. //这个数可以被总消除次数整除那就可以弹广告
  1321. if (this.eliminateTotal % randomNum === 0) {
  1322. // oops.gui.open(UIID.DoubleSpeed);
  1323. //如果有自动就暂停自动
  1324. this.gameState = GameState.PAUSED;
  1325. console.log("弹出翻倍广告");
  1326. ServerHandler.inst.getDoubleSurprise();
  1327. //弹出广告
  1328. }
  1329. });
  1330. }, 0.2);
  1331. }, 0.2)
  1332. })
  1333. }
  1334. gridEliminateCheck(gridList: GridData[][]) {
  1335. const gridEliminateList: GridData[] = []
  1336. let eliminateRowNum = 0
  1337. let eliminateColumnNum = 0
  1338. // 行检查
  1339. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1340. const rowData = gridList[rowIndex]
  1341. if (rowData.every(gridData => gridData.status === CellState.FILLED)) {
  1342. rowData.forEach(gridData => {
  1343. if (gridEliminateList.findIndex(data => data === gridData) < 0) {
  1344. gridEliminateList.push(gridData)
  1345. }
  1346. })
  1347. eliminateRowNum += 1
  1348. }
  1349. }
  1350. // 列检查
  1351. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1352. if (gridList.every(rowData => rowData[columnIndex].status === CellState.FILLED)) {
  1353. gridList.forEach(rowData => {
  1354. const gridData = rowData[columnIndex]
  1355. if (gridEliminateList.findIndex(data => data === gridData) < 0) {
  1356. gridEliminateList.push(gridData)
  1357. }
  1358. })
  1359. eliminateColumnNum += 1
  1360. }
  1361. }
  1362. return {
  1363. gridEliminateList,
  1364. eliminateRowNum,
  1365. eliminateColumnNum,
  1366. }
  1367. }
  1368. // 修改 createCoinFlyAnimation 方法,添加回调
  1369. private createCoinFlyAnimation(prefab: Prefab, startPos: Vec3, endPos: Vec3, count: number, callback?: Function) {
  1370. if (!prefab) return;
  1371. let completedCount = 0;
  1372. const totalCoins = Math.min(count, 5); // 限制最大数量
  1373. for (let i = 0; i < totalCoins; i++) {
  1374. const coin = instantiate(prefab);
  1375. this.node.addChild(coin);
  1376. //设置位置,取舞台中间位置世界坐标
  1377. coin.setWorldPosition(startPos);
  1378. // 创建曲线动画
  1379. const num = this.isDoubleSpeed ? this.doubleNum : 1;
  1380. tween(coin)
  1381. .to(0.2 / num, {
  1382. position: new Vec3(
  1383. coin.position.x,
  1384. coin.position.y,
  1385. 0
  1386. )
  1387. })
  1388. .to(0.5 / num, { worldPosition: endPos })
  1389. .call(() => {
  1390. coin.destroy();
  1391. completedCount++;
  1392. // 所有金币动画完成后执行回调
  1393. if (completedCount === totalCoins && callback) {
  1394. callback();
  1395. }
  1396. })
  1397. .start();
  1398. }
  1399. }
  1400. // 显示微信分数增加动画
  1401. private showWechatScoreAnimation() {
  1402. if (!this.tweenWechatNode) return;
  1403. // 生成随机小数(小于1,保留2位小数)
  1404. const changeNum = smc.game.GameModel.changeWxCoin;
  1405. this.money = smc.account.AccountModel.wxCoin;
  1406. const formattedValue = changeNum;
  1407. console.log("微信币增加数值>>>>>>>>>", changeNum);
  1408. // 获取并设置分数标签
  1409. const scoreLabel = this.tweenWechatNode.getChildByName("lab_num")?.getComponent(Label);
  1410. if (scoreLabel) {
  1411. scoreLabel.string = "+" + Format.formatWxCoinModify(formattedValue);
  1412. }
  1413. // 保存原始位置
  1414. const originalPosition = this.lab_wxCoin.node.worldPosition;
  1415. //设置原始位置
  1416. this.tweenWechatNode.setWorldPosition(originalPosition);
  1417. // 显示节点
  1418. this.tweenWechatNode.active = true;
  1419. // 创建向上移动的动画
  1420. tween(this.tweenWechatNode)
  1421. .to(0.8, {
  1422. worldPosition: new Vec3(
  1423. originalPosition.x,
  1424. originalPosition.y + 50,
  1425. originalPosition.z
  1426. ),
  1427. opacity: 255
  1428. })
  1429. .to(0.2, { opacity: 0 })
  1430. .call(() => {
  1431. //设置位置y-100
  1432. this.tweenWechatNode.setWorldPosition(new Vec3(
  1433. originalPosition.x,
  1434. originalPosition.y,
  1435. originalPosition.z
  1436. ))
  1437. this.tweenWechatNode.active = false;
  1438. // 更新总金额
  1439. if (this.lab_wxCoin) {
  1440. this.lab_wxCoin.string = Format.formatWxCoin(this.money);
  1441. }
  1442. })
  1443. .start();
  1444. }
  1445. // 显示红包分数增加动画
  1446. private showRedPacketScoreAnimation() {
  1447. if (!this.tweenRedNode) return;
  1448. //如果有值就是要那个,没有就是取随机
  1449. const changeNum = smc.game.GameModel.changeHbCoin;
  1450. console.log("红包分数增加动画", changeNum)
  1451. this.cash = smc.account.AccountModel.hbCoin;
  1452. if (!changeNum) return;
  1453. const formattedValue = changeNum;
  1454. // 获取并设置分数标签
  1455. const scoreLabel = this.tweenRedNode.getChildByName("lab_num")?.getComponent(Label);
  1456. if (scoreLabel) {
  1457. scoreLabel.string = "+" + Format.formatRedPacketCoin(formattedValue);
  1458. }
  1459. // 保存原始位置
  1460. const originalPosition = this.lab_hbCoin.node.worldPosition;
  1461. //设置原始位置
  1462. this.tweenRedNode.setWorldPosition(originalPosition);
  1463. // 显示节点
  1464. this.tweenRedNode.active = true;
  1465. // 创建向上移动的动画
  1466. const num = this.isDoubleSpeed ? this.doubleNum : 1;
  1467. tween(this.tweenRedNode)
  1468. .to(0.8 / num, {
  1469. worldPosition: new Vec3(
  1470. originalPosition.x,
  1471. originalPosition.y + 50,
  1472. originalPosition.z
  1473. ),
  1474. opacity: 255
  1475. })
  1476. .to(0.2 / num, { opacity: 0 })
  1477. .call(() => {
  1478. this.tweenRedNode.setWorldPosition(new Vec3(
  1479. originalPosition.x,
  1480. originalPosition.y,
  1481. originalPosition.z
  1482. ))
  1483. this.tweenRedNode.active = false;
  1484. // 更新总红包金额
  1485. if (this.lab_hbCoin) {
  1486. // this.lab_hbCoin.changeTo(0.5, newAmount, () => {
  1487. // })
  1488. this.lab_hbCoin.string = Format.formatRedPacketCoin(this.cash);
  1489. }
  1490. })
  1491. .start();
  1492. }
  1493. // 提示
  1494. prompt(tipFlag = true) {
  1495. return new Promise((resolve, reject) => {
  1496. const gridPromptList: GridData[] = []
  1497. let moveFlag = false
  1498. // 找方块可消除位置
  1499. for (let rowIndex = 0; rowIndex < this.rows && !moveFlag; rowIndex++) {
  1500. for (let columnIndex = 0; columnIndex < this.cols && !moveFlag; columnIndex++) {
  1501. const gridData = this.gridList[rowIndex][columnIndex]
  1502. if (gridData.status !== CellState.EMPTY) continue
  1503. // 方块不旋转检测是否能放
  1504. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1505. const brickData = this.bricksList[brickI]
  1506. if (this.moveIf(rowIndex, columnIndex, brickData.gridConfig)) {
  1507. // 复制整体网格,以方块设置网格状态
  1508. const gridList = this.copyGridList()
  1509. brickData.gridConfig.forEach((gridConfigData) => {
  1510. gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = CellState.FILLED
  1511. })
  1512. // 检查复制的整体网格是否有可消除
  1513. if (this.gridEliminateCheck(gridList).gridEliminateList.length > 0) {
  1514. moveFlag = true
  1515. brickData.gridConfig.forEach((gridConfigData) => {
  1516. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1517. })
  1518. }
  1519. }
  1520. }
  1521. // 方块旋转检测是否能放
  1522. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1523. const brickData = this.bricksList[brickI]
  1524. if (!brickData.rotateFlag) continue
  1525. let gridConfig = brickData.gridConfig
  1526. let deg = brickData.deg
  1527. // 获得旋转的方块网格配置
  1528. for (let count = 1; count <= 3 && !moveFlag; count++) {
  1529. const next = this.nextGridRotate(gridConfig, deg)
  1530. if (this.moveIf(rowIndex, columnIndex, next.gridConfig)) {
  1531. // 复制整体网格,以方块设置网格状态
  1532. const gridList = this.copyGridList()
  1533. next.gridConfig.forEach((gridConfigData) => {
  1534. gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = CellState.FILLED
  1535. })
  1536. // 检查复制的整体网格是否有可消除
  1537. if (this.gridEliminateCheck(gridList).gridEliminateList.length > 0) {
  1538. moveFlag = true
  1539. next.gridConfig.forEach((gridConfigData) => {
  1540. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1541. })
  1542. }
  1543. }
  1544. gridConfig = next.gridConfig
  1545. deg = next.deg
  1546. }
  1547. }
  1548. }
  1549. }
  1550. // 找方块可放置位置
  1551. for (let rowIndex = 0; rowIndex < this.rows && !moveFlag; rowIndex++) {
  1552. for (let columnIndex = 0; columnIndex < this.cols && !moveFlag; columnIndex++) {
  1553. const gridData = this.gridList[rowIndex][columnIndex]
  1554. if (gridData.status !== CellState.EMPTY) continue
  1555. // 方块不旋转检测是否能放
  1556. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1557. const brickData = this.bricksList[brickI]
  1558. if (this.moveIf(rowIndex, columnIndex, brickData.gridConfig)) {
  1559. moveFlag = true
  1560. brickData.gridConfig.forEach((gridConfigData) => {
  1561. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1562. })
  1563. }
  1564. }
  1565. // 方块旋转检测是否能放
  1566. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1567. const brickData = this.bricksList[brickI]
  1568. if (!brickData.rotateFlag) continue
  1569. let gridConfig = brickData.gridConfig
  1570. let deg = brickData.deg
  1571. for (let count = 1; count <= 3 && !moveFlag; count++) {
  1572. const next = this.nextGridRotate(gridConfig, deg)
  1573. if (this.moveIf(rowIndex, columnIndex, next.gridConfig)) {
  1574. moveFlag = true
  1575. next.gridConfig.forEach((gridConfigData) => {
  1576. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1577. })
  1578. }
  1579. gridConfig = next.gridConfig
  1580. deg = next.deg
  1581. }
  1582. }
  1583. }
  1584. }
  1585. if (gridPromptList.length < 1) {
  1586. resolve(false)
  1587. return
  1588. }
  1589. if (!tipFlag) {
  1590. resolve(true)
  1591. return
  1592. }
  1593. // 提示用户(网格变绿)
  1594. gridPromptList.forEach((gridData) => {
  1595. if (gridData.gridNode && gridData.gridNode.children[0]) {
  1596. const sprite = gridData.gridNode.children[0].getComponent(Sprite);
  1597. if (sprite) {
  1598. sprite.color = this.usableColor;
  1599. }
  1600. }
  1601. // 用于恢复格子
  1602. this.gridColorList.push(gridData)
  1603. })
  1604. resolve(true)
  1605. })
  1606. }
  1607. moveIf(row: number, column: number, gridConfig: GridConfigData[]) {
  1608. let moveFlag = true
  1609. for (let i = 0; i < gridConfig.length; i++) {
  1610. const gridConfigData = gridConfig[i]
  1611. const gridI = row + gridConfigData.row
  1612. const gridJ = column + gridConfigData.column
  1613. // 边界判断
  1614. if (
  1615. gridI < 0 ||
  1616. gridI > this.rows - 1 ||
  1617. gridJ < 0 ||
  1618. gridJ > this.cols - 1
  1619. ) {
  1620. moveFlag = false
  1621. break
  1622. }
  1623. // 已用
  1624. else if (this.gridList[gridI][gridJ].status === CellState.FILLED) {
  1625. moveFlag = false
  1626. break
  1627. }
  1628. }
  1629. return moveFlag
  1630. }
  1631. // 复制整体网格
  1632. copyGridList() {
  1633. const gridList: GridData[][] = []
  1634. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1635. gridList.push([])
  1636. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1637. const gridData = this.gridList[rowIndex][columnIndex]
  1638. gridList[rowIndex].push({
  1639. name: gridData.name,
  1640. status: gridData.status,
  1641. gridNode: null,
  1642. row: gridData.row,
  1643. col: gridData.col,
  1644. type: gridData.type,
  1645. })
  1646. }
  1647. }
  1648. return gridList
  1649. }
  1650. gameOver() {
  1651. this.gameState = GameState.GAME_OVER
  1652. this.setGameState(GameState.GAME_OVER)
  1653. console.log("游戏结束")
  1654. smc.game.GameModel.curScore = this.score;
  1655. oops.gui.open(UIID.GameOver);
  1656. //如果有自动就要关闭自动
  1657. if (this.autoFunction) {
  1658. this.unschedule(this.autoFunction);
  1659. this.autoFunction = null;
  1660. this.initButtonState(false);
  1661. this.autoState = false;
  1662. }
  1663. }
  1664. //更新游戏分数
  1665. updateGameScore() {
  1666. this.lab_score.string = this.score.toString();
  1667. if (this.score >= this.targetScore) {
  1668. this.gameState = GameState.GAME_PASS;
  1669. this.setGameState(this.gameState);
  1670. //弹出通关奖励界面
  1671. if (DeviceUtil.isNative && DeviceUtil.isAndroid) {
  1672. ServerHandler.inst.getGameAwardInfo();
  1673. } else {
  1674. oops.gui.open(UIID.GamePass);
  1675. }
  1676. }
  1677. }
  1678. /**
  1679. * 清理网格的子节点
  1680. */
  1681. private clearGridChildren(gridNode: Node): void {
  1682. const children = gridNode.children.slice(); // 创建副本避免遍历时修改问题
  1683. children.forEach(node => node.destroy());
  1684. }
  1685. private setGameState(state: GameState) {
  1686. this.gameState = state;
  1687. switch (state) {
  1688. case GameState.READY:
  1689. break;
  1690. case GameState.PLAYING:
  1691. break;
  1692. case GameState.PAUSED:
  1693. break;
  1694. case GameState.GAME_OVER:
  1695. //打开游戏结束界面
  1696. this.autoState = false;
  1697. this.adShowingFlag = false;
  1698. //自动按钮改为手动
  1699. this.initButtonState(false);
  1700. break;
  1701. }
  1702. }
  1703. //========================打开其他界面和按钮逻辑=======================
  1704. /** 视图对象通过 ecs.Entity.remove(eliminateViewComp) 删除组件是触发组件处理自定义释放逻辑 */
  1705. reset() {
  1706. this.node.destroy();
  1707. }
  1708. //设置按钮
  1709. private btn_setting() {
  1710. oops.gui.open(UIID.Setting);
  1711. this.gameState = GameState.PAUSED;
  1712. DCHandler.inst.reportData(3000011);
  1713. }
  1714. //左边微信按钮
  1715. private btn_withdraw() {
  1716. if (DeviceUtil.isNative && DeviceUtil.isAndroid) {
  1717. ServerHandler.inst.getWechatTxInfo();
  1718. DCHandler.inst.reportData(3000006);
  1719. } else {
  1720. oops.gui.open(UIID.WechatWithdraw);
  1721. }
  1722. this.gameState = GameState.PAUSED;
  1723. }
  1724. //顶部红包按钮
  1725. private btn_award() {
  1726. //oops.gui.open(UIID.RedPacketWithdraw);
  1727. if (DeviceUtil.isNative && DeviceUtil.isAndroid) {
  1728. ServerHandler.inst.getHbTxInfo();
  1729. DCHandler.inst.reportData(3000007);
  1730. } else {
  1731. oops.gui.open(UIID.RedPacketWithdraw);
  1732. }
  1733. this.gameState = GameState.PAUSED;
  1734. }
  1735. //二倍速按钮
  1736. private btn_double() {
  1737. // oops.gui.open(UIID.DoubleSpeed);
  1738. if (DeviceUtil.isNative && DeviceUtil.isAndroid) {
  1739. this.gameState = GameState.PAUSED;
  1740. ServerHandler.inst.getDoubleSpeedTime();
  1741. DCHandler.inst.reportData(3000010);
  1742. } else {
  1743. oops.gui.open(UIID.DoubleSpeed);
  1744. }
  1745. }
  1746. //自动放置
  1747. private btn_auto() {
  1748. if (this.gameState !== GameState.PLAYING) {
  1749. return;
  1750. }
  1751. this.autoState = !this.autoState;
  1752. this.initButtonState(this.autoState);
  1753. if (this.autoState) {
  1754. DCHandler.inst.reportData(3000008);
  1755. this.executeAutoPlace();
  1756. this.autoFunction = this.executeAutoPlace;
  1757. this.schedule(this.autoFunction, 1.5);
  1758. } else {
  1759. //关闭
  1760. if (this.autoFunction) {
  1761. DCHandler.inst.reportData(3000009);
  1762. this.unschedule(this.autoFunction);
  1763. this.autoFunction = null;
  1764. this.initButtonState(false);
  1765. this.autoState = false;
  1766. }
  1767. }
  1768. }
  1769. // 执行自动放置
  1770. executeAutoPlace() {
  1771. if (!this.autoState || this.gameState !== GameState.PLAYING || this.adShowingFlag) {
  1772. return
  1773. }
  1774. const bestPlacement = this.findBestPlacement()
  1775. if (!bestPlacement) {
  1776. // 所有方块都无法放置,游戏结束
  1777. this.autoState = false;
  1778. this.gameState = GameState.GAME_OVER;
  1779. this.gameOver()
  1780. return
  1781. }
  1782. // 执行放置
  1783. this.placeBrickAtPosition(bestPlacement)
  1784. }
  1785. //寻找最佳位置
  1786. findBestPlacement() {
  1787. const placements = []
  1788. // 对每个方块计算所有可能的放置位置和分数
  1789. for (let brickIndex = 0; brickIndex < this.bricksList.length; brickIndex++) {
  1790. const brickData = this.bricksList[brickIndex]
  1791. // 检查不同旋转状态
  1792. let gridConfigs = [brickData.gridConfig]
  1793. let degrees = [brickData.deg]
  1794. // 如果可旋转,计算所有旋转状态
  1795. if (brickData.rotateFlag) {
  1796. for (let i = 1; i <= 3; i++) {
  1797. const next = this.nextGridRotate(
  1798. i === 1 ? brickData.gridConfig : gridConfigs[i - 1],
  1799. i === 1 ? brickData.deg : degrees[i - 1]
  1800. )
  1801. gridConfigs.push(next.gridConfig)
  1802. degrees.push(next.deg)
  1803. }
  1804. }
  1805. // 遍历所有网格位置
  1806. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1807. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1808. // 对每个旋转状态检查
  1809. for (let rotateIndex = 0; rotateIndex < gridConfigs.length; rotateIndex++) {
  1810. const currentGridConfig = gridConfigs[rotateIndex]
  1811. const currentDeg = degrees[rotateIndex]
  1812. // 检查是否可以放置
  1813. if (this.moveIf(rowIndex, columnIndex, currentGridConfig)) {
  1814. // 复制网格并模拟放置
  1815. const gridList = this.copyGridList()
  1816. currentGridConfig.forEach((gridConfigData) => {
  1817. const r = gridConfigData.row + rowIndex
  1818. const c = gridConfigData.column + columnIndex
  1819. gridList[r][c].status = CellState.FILLED
  1820. gridList[r][c].type = brickData.type;
  1821. })
  1822. // 检查是否可以消除,计算分数
  1823. const elimination = this.gridEliminateCheck(gridList)
  1824. let score = 0
  1825. if (elimination.gridEliminateList.length > 0) {
  1826. // 计算消除得分
  1827. for (let i = 1; i <= elimination.eliminateRowNum; i++) {
  1828. score += this.cols * i
  1829. }
  1830. for (let i = 1; i <= elimination.eliminateColumnNum; i++) {
  1831. score += this.rows * i
  1832. }
  1833. }
  1834. // 记录此放置选项
  1835. placements.push({
  1836. brickIndex,
  1837. brickData,
  1838. rowIndex,
  1839. columnIndex,
  1840. gridConfig: currentGridConfig, //这里有问题,拿到的和显示的不对
  1841. deg: currentDeg,
  1842. score,
  1843. canEliminate: elimination.gridEliminateList.length > 0
  1844. })
  1845. }
  1846. }
  1847. }
  1848. }
  1849. }
  1850. // 按优先级排序:最高分 > 有分数 > 没有分数但可放置
  1851. placements.sort((a, b) => {
  1852. // 首先按分数排序
  1853. if (a.score !== b.score) {
  1854. return b.score - a.score
  1855. }
  1856. // 其次按是否可消除排序
  1857. if (a.canEliminate !== b.canEliminate) {
  1858. return a.canEliminate ? -1 : 1
  1859. }
  1860. // 最后按照方块优先级排序(底部的方块优先)
  1861. return a.brickIndex - b.brickIndex
  1862. })
  1863. return placements.length > 0 ? placements[0] : null
  1864. }
  1865. // ... existing code ...
  1866. placeBrickAtPosition(placement: any) {
  1867. const brickData = placement.brickData
  1868. const index = this.bricksList.findIndex(data => data === brickData)
  1869. if (index === -1) {
  1870. console.error("无法找到要放置的方块:", brickData)
  1871. return
  1872. }
  1873. this.editingData.brickData = this.bricksList.splice(index, 1)[0];
  1874. // 应用旋转
  1875. if (brickData.deg !== placement.deg) {
  1876. brickData.gridConfig = placement.gridConfig
  1877. brickData.deg = placement.deg
  1878. tween(brickData.brickNode).to(0.1, { angle: placement.deg }).start()
  1879. }
  1880. // 构建对应网格列表--这里就有问题了,这算位置,有问题
  1881. this.editingData.gridList = [];
  1882. placement.gridConfig.forEach((gridConfigData: GridConfigData) => {
  1883. const r = gridConfigData.row + placement.rowIndex
  1884. const c = gridConfigData.column + placement.columnIndex
  1885. this.editingData.gridList.push(this.gridList[r][c])
  1886. })
  1887. // 计算移动位置(中点)
  1888. let centerPos = new Vec3(0, 0, 0)
  1889. let count = 0
  1890. for (const grid of this.editingData.gridList) {
  1891. if (grid.gridNode) {
  1892. const pos = grid.gridNode.getWorldPosition()
  1893. centerPos.add(pos)
  1894. count++
  1895. }
  1896. }
  1897. if (count > 0) {
  1898. centerPos.x /= count
  1899. centerPos.y /= count
  1900. centerPos.z /= count
  1901. }
  1902. const originPos = brickData.brickNode.getWorldPosition()
  1903. brickData.brickNode.setParent(this.moveNode)
  1904. brickData.brickNode.setWorldPosition(originPos);
  1905. // 动画放置方块
  1906. tween(brickData.brickNode)
  1907. .to(this.autoMoveTime, { worldPosition: centerPos })
  1908. .call(() => {
  1909. // ✅ 更新格子状态(像手动放置那样)
  1910. this.editingData.gridList.forEach(gridData => {
  1911. gridData.status = CellState.FILLED
  1912. gridData.type = brickData.type;
  1913. this.generateGrid(gridData)
  1914. })
  1915. // ✅ 销毁方块节点
  1916. brickData.brickNode.destroy()
  1917. // ✅ 补充新的砖块
  1918. this.addBrick(brickData.index)
  1919. // ✅ 消除检查逻辑保持和手动一致
  1920. this.scheduleOnce(() => {
  1921. this.gridEliminate().then(() => {
  1922. this.prompt(false).then((promptFlag) => {
  1923. if (!promptFlag) {
  1924. this.autoState = false
  1925. this.gameOver()
  1926. }
  1927. })
  1928. })
  1929. })
  1930. })
  1931. .start()
  1932. }
  1933. doubleSpeedOpenSuccess() {
  1934. //2倍速广告展示,页面展示,都会暂停游戏,
  1935. if (this.gameState !== GameState.PLAYING) {
  1936. return
  1937. }
  1938. if (this.callback) {
  1939. this.unschedule(this.callback);
  1940. }
  1941. this.isDoubleSpeed = true;
  1942. this.doubleNum = 2;
  1943. //改变按钮时间
  1944. // let time = smc.game.GameModel.doubleSpeedTime;
  1945. this.doubleSpeedTime = this.doubleSpeedTime + smc.game.GameModel.doubleSpeedTime;
  1946. if (this.doubleSpeedTime <= 0) {
  1947. return
  1948. }
  1949. if (!this.autoState) {
  1950. this.btn_auto();
  1951. //改按钮状态
  1952. this.autoState = true;
  1953. this.initButtonState(this.autoState);
  1954. }
  1955. this.callback = function () {
  1956. if (!this.adShowingFlag && this.gameState === GameState.PLAYING) {
  1957. this.doubleSpeedTime--
  1958. //修改剩余时间,秒格式化成时分10:59
  1959. const minutes = Math.floor(this.doubleSpeedTime / 60);
  1960. const seconds = this.doubleSpeedTime % 60;
  1961. const formattedTime = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  1962. this.lab_doubleTime.string = formattedTime;
  1963. //时间到了
  1964. if (this.doubleSpeedTime <= 0) {
  1965. this.lab_doubleTime.string = "二倍速";
  1966. this.isDoubleSpeed = false;
  1967. this.doubleNum = 1;
  1968. //再打开继续二倍速页面
  1969. this.gameState = GameState.PAUSED;
  1970. oops.gui.open(UIID.KeepSpeed);
  1971. this.unschedule(this.callback);
  1972. }
  1973. }
  1974. }
  1975. this.schedule(this.callback, 1);
  1976. }
  1977. //重新开始
  1978. private restartGame() {
  1979. if (this.gameState === GameState.READY) return;
  1980. this.initData();
  1981. this.setData();
  1982. this.reopenGrid();
  1983. this.initButtonState(this.autoState);
  1984. this.updateWelfarePoint();
  1985. }
  1986. //重新清除网格
  1987. private reopenGrid() {
  1988. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1989. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1990. this.gridList[rowIndex][columnIndex].status = CellState.EMPTY
  1991. this.generateGrid(this.gridList[rowIndex][columnIndex])
  1992. }
  1993. }
  1994. // 初始化方块
  1995. if (this.brickNode) {
  1996. if (this.brickNode) {
  1997. this.brickNode.destroyAllChildren();
  1998. }
  1999. }
  2000. this.bricksList.length = 0
  2001. for (let i = 1; i <= this.brickNum; i++) {
  2002. this.addBrick(i)
  2003. }
  2004. // 清除旋转数据
  2005. if (this.rotateNode) {
  2006. this.rotateNode.destroyAllChildren();
  2007. }
  2008. }
  2009. //===============初始化检查是否要打开福利界面====
  2010. private updateWelfarePoint() {
  2011. switch (this.popupType) {
  2012. case "weal_1":
  2013. oops.gui.open(UIID.WarmReminder);
  2014. ServerHandler.inst.GetGuideInfo();
  2015. break;
  2016. case "weal_2":
  2017. //打开福利二
  2018. oops.gui.open(UIID.WelfareTwo);
  2019. ServerHandler.inst.GetGuideInfo();
  2020. break;
  2021. case "weal_3":
  2022. //打开福利三
  2023. oops.gui.open(UIID.WelfareThree);
  2024. break;
  2025. }
  2026. if (smc.game.GameModel.curLevelConfig) {
  2027. if (smc.game.GameModel.curLevelConfig.eventType && smc.game.GameModel.curLevelConfig.eventType === "SIGN_POINT") {
  2028. //展示提现信息
  2029. oops.gui.open(UIID.ReservePopup);
  2030. }
  2031. }
  2032. }
  2033. btn_text() {
  2034. // const param = {
  2035. // "showReward": [
  2036. // {
  2037. // "propId": "1004",
  2038. // "propNum": 500
  2039. // },
  2040. // {
  2041. // "propId": "1005",
  2042. // "propNum": 200
  2043. // },
  2044. // {
  2045. // "propId": "1006",
  2046. // "propNum": 1
  2047. // }
  2048. // ],
  2049. // "levelProgress": {
  2050. // "nextProgress": 1,
  2051. // "levelInfoList": [
  2052. // {
  2053. // "level": 1,
  2054. // "eventType": "WITHDRAW_POINT",
  2055. // "withdraw": true
  2056. // },
  2057. // {
  2058. // "level": 4,
  2059. // "eventType": "WITHDRAW_POINT",
  2060. // "withdraw": false
  2061. // },
  2062. // {
  2063. // "level": 6,
  2064. // "eventType": "WITHDRAW_POINT",
  2065. // "withdraw": false
  2066. // },
  2067. // {
  2068. // "level": 8,
  2069. // "eventType": "WITHDRAW_POINT",
  2070. // "withdraw": false
  2071. // },
  2072. // {
  2073. // "level": 12,
  2074. // "eventType": "SIGN_POINT",
  2075. // "withdraw": false
  2076. // }
  2077. // ]
  2078. // }
  2079. // }
  2080. // let str = JSON.stringify(param);
  2081. // ServerHandler.inst.onDoubleSurprise(str);
  2082. // ServerHandler.inst.GetGuideInfo();
  2083. }
  2084. getRandomUniqueInts(count: number = 3): number[] {
  2085. let min: number = 0;
  2086. let max: number = 0;
  2087. const curLevel = smc.account.AccountModel.curLevel || 1;
  2088. if (curLevel < 5) {
  2089. return [curLevel]
  2090. } else if (curLevel >= 5 && curLevel <= 7) {
  2091. //三种基础色
  2092. min = 1;
  2093. max = 5;
  2094. } else if (curLevel >= 8 && curLevel <= 11) {
  2095. min = 6;
  2096. max = 12;
  2097. } else {
  2098. min = 1;
  2099. max = 12;
  2100. }
  2101. if (max - min + 1 < count) {
  2102. throw new Error(`区间 [${min}, ${max}] 无法提供 ${count} 个不重复整数`);
  2103. }
  2104. const pool: number[] = [];
  2105. for (let i = min; i <= max; i++) {
  2106. pool.push(i);
  2107. }
  2108. this.shuffle(pool);
  2109. return pool.slice(0, count);
  2110. }
  2111. // 洗牌算法(Fisher-Yates)
  2112. shuffle(arr: number[]) {
  2113. for (let i = arr.length - 1; i > 0; i--) {
  2114. const j = Math.floor(Math.random() * (i + 1));
  2115. [arr[i], arr[j]] = [arr[j], arr[i]];
  2116. }
  2117. }
  2118. }