EliminateViewComp.ts 82 KB

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