EliminateViewComp.ts 87 KB

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