EliminateViewComp.ts 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346
  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 11:13:27
  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. /** 视图层逻辑代码分离演示 */
  187. async start() {
  188. // const entity = this.ent as ecs.Entity; // ecs.Entity 可转为当前模块的具体实体对象
  189. this.setButton();
  190. this.initButtonState(false);
  191. await this.loadConfig();
  192. this.initData();
  193. this.setData();
  194. this.addEventList();
  195. // smc.account.AccountModel.curLevel = 1;
  196. if (this.guideStep === 0 && smc.account.AccountModel.curLevel == 1) {
  197. this.startGuideMode()
  198. } else {
  199. this.guideNode.active = false;
  200. this.initGrid();
  201. }
  202. //更新福利点
  203. this.updateWelfarePoint();
  204. }
  205. addEventList() {
  206. oops.message.on(GameEvent.RestartGame, this.restartGame, this);
  207. oops.message.on(GameEvent.DoubleSpeedOpenSuccess, this.doubleSpeedOpenSuccess, this);
  208. oops.message.on(GameEvent.openView, this.openView, this);
  209. oops.message.on(GameEvent.showCoinAnimation, this.showCoinAnimation, this);
  210. // oops.message.on(GameEvent.Resurrection, this.onResurrection, this);
  211. oops.message.on(GameEvent.updateHbAndWxCoin, this.updateCoin, this);
  212. oops.message.on(GameEvent.StartAutoGame, this.startAutoGame, this);
  213. oops.message.on(GameEvent.updateGameState, this.updateGameState, this);
  214. }
  215. updateGameState(event: string, args: string) {
  216. console.log("更新游戏状态", args);
  217. switch (args) {
  218. case "paused":
  219. this.gameState = GameState.PAUSED;
  220. break;
  221. case "playing":
  222. this.gameState = GameState.PLAYING;
  223. break;
  224. }
  225. }
  226. //初始化网格
  227. private initGrid() {
  228. // 清理现有网格
  229. this.clearExistingGrids();
  230. // 生成网格矩阵
  231. this.createGridMatrix();
  232. }
  233. //初始化按钮状态
  234. private initButtonState(state: boolean) {
  235. //自动按钮默认关闭
  236. if (this.autoBtn) {
  237. //关闭
  238. const on = this.autoBtn.node.getChildByName("on");
  239. on ? on.active = state : null;
  240. const off = this.autoBtn.node.getChildByName("off");
  241. off ? off.active = !state : null;
  242. // this.autoState = state;
  243. }
  244. //第一关隐藏二倍速和自动放置按钮
  245. const curLevel = smc.account.AccountModel.curLevel;
  246. this.autoBtn.node.active = curLevel > 1;
  247. this.doubleSpeedBtn.node.active = curLevel > 1;
  248. }
  249. //初始化数据
  250. private initData() {
  251. // this.gameMode = GameMode.MANUAL;
  252. this.score = 0;
  253. this.targetScore = 0;
  254. this.money = 0;
  255. this.cash = 0;
  256. this.autoState = false;
  257. this.operateFlag = true
  258. this.shouldResetEliminateCount = true;
  259. this.currentCombo = 0;
  260. }
  261. //设置数据
  262. setData() {
  263. if (smc.game.GameModel.curLevelConfig.eliminateScope) {
  264. this.eliminateInterval = smc.game.GameModel.curLevelConfig.eliminateScope || [];
  265. }
  266. this.score = smc.game.GameModel.curScore;
  267. this.money = smc.account.AccountModel.wxCoin;
  268. this.cash = smc.account.AccountModel.hbCoin;
  269. // this.targetScore = smc.game.GameModel.targetScore;
  270. this.targetScore = 200;
  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. this.updateGameScore();
  513. }
  514. //初始化网格
  515. private async loadConfig() {
  516. let json_name: string = "gui/eliminate/config/GridConfig";
  517. return new Promise<void>((resolve, reject) => {
  518. oops.res.load(json_name, JsonAsset, (err: Error | null, res: any) => {
  519. if (res) {
  520. this.brickConfig = res.json;
  521. resolve();
  522. } else {
  523. console.log("JSON数据加载失,请检查文件");
  524. reject(err);
  525. }
  526. });
  527. });
  528. }
  529. /**
  530. * @description: 清理现有的网格数据
  531. * @return {*}
  532. */
  533. private clearExistingGrids(): void {
  534. this.gridList = [];
  535. if (this.gridNode) {
  536. this.gridNode.destroyAllChildren();
  537. }
  538. }
  539. /**
  540. * @description: 设置网格容器大小
  541. * @return {*}
  542. */
  543. private createGridMatrix(): void {
  544. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  545. const currentRow: GridData[] = [];
  546. this.gridList.push(currentRow);
  547. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  548. const gridData = this.createGridData(rowIndex, columnIndex);
  549. currentRow.push(gridData);
  550. this.createGridNode(gridData);
  551. }
  552. }
  553. // 初始化格子状态
  554. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  555. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  556. this.gridList[rowIndex][columnIndex].status = CellState.EMPTY
  557. this.generateGrid(this.gridList[rowIndex][columnIndex])
  558. }
  559. }
  560. // 初始化方块
  561. if (this.brickNode) {
  562. this.brickNode.destroyAllChildren();
  563. }
  564. this.bricksList.length = 0
  565. for (let i = 1; i <= this.brickNum; i++) {
  566. this.addBrick(i)
  567. }
  568. // 清除旋转数据
  569. if (this.rotateNode) {
  570. this.rotateNode.destroyAllChildren();
  571. }
  572. this.touchStartPos.set(Vec2.ZERO)
  573. }
  574. /**
  575. * @description: 创建格子数据
  576. * @param {number} row
  577. * @param {number} column
  578. * @return {*}
  579. */
  580. private createGridData(row: number, column: number): GridData {
  581. return {
  582. name: `Grid-${row}-${column}`,
  583. status: CellState.EMPTY,
  584. gridNode: null,
  585. row: row,
  586. col: column,
  587. type: 0
  588. };
  589. }
  590. /**
  591. * @description: 创建网格Node
  592. * @param {GridData} gridData
  593. * @return {*}
  594. */
  595. private createGridNode(gridData: GridData): void {
  596. const gridNode = new Node(gridData.name);
  597. if (this.gridNode) {
  598. this.gridNode.addChild(gridNode);
  599. }
  600. gridData.gridNode = gridNode;
  601. // 设置网格大小
  602. gridNode.addComponent(UITransform).setContentSize(this.itemSize, this.itemSize);
  603. }
  604. /**
  605. * 生成或更新网格
  606. * @param gridData 网格数据
  607. */
  608. private generateGrid(gridData: GridData) {
  609. if (!gridData || !gridData.gridNode) {
  610. console.warn('无效的网格数据');
  611. return;
  612. }
  613. // 清理现有子节点
  614. this.clearGridChildren(gridData.gridNode);
  615. // 获取对应的预制体
  616. const prefab = this.getGridPrefab(gridData);
  617. if (!prefab) {
  618. console.warn('无法获取网格预制体');
  619. return;
  620. }
  621. // 创建并配置新节点
  622. const node = this.createNewGridNode(prefab, gridData);
  623. // 设置节点属性
  624. this.setupGridNode(node, gridData);
  625. }
  626. /**
  627. * 获取对应状态的预制体
  628. */
  629. private getGridPrefab(gridData: GridData): Prefab {
  630. if (gridData.status === CellState.EMPTY) {
  631. if (this.itemPrefabs[0]) {
  632. return this.itemPrefabs[0];
  633. } else {
  634. throw new Error('Grid prefab is not loaded');
  635. }
  636. }
  637. if (gridData.status === CellState.FILLED && gridData.type) {
  638. const type = gridData.type;
  639. return this.itemPrefabs[type];
  640. }
  641. throw new Error('Invalid grid status or missing gridColorKey');
  642. }
  643. /**
  644. * 创建网格节点
  645. */
  646. private createNewGridNode(prefab: Prefab, gridData: GridData): Node {
  647. const node = instantiate(prefab);
  648. if (gridData && gridData.gridNode) {
  649. gridData.gridNode.addChild(node);
  650. return node;
  651. }
  652. return node
  653. }
  654. /**
  655. * 设置网格节点的属性
  656. */
  657. private setupGridNode(node: Node, gridData: GridData): void {
  658. // 设置未使用状态的颜色
  659. if (gridData.status === CellState.EMPTY) {
  660. const sprite = node.getComponent(Sprite);
  661. if (sprite) {
  662. sprite.color = this.notUseColor;
  663. }
  664. }
  665. // 设置节点大小
  666. const transform = node.getComponent(UITransform);
  667. if (transform) {
  668. transform.setContentSize(
  669. this.itemSize,
  670. this.itemSize
  671. );
  672. }
  673. // 设置位置
  674. node.setPosition(Vec3.ZERO);
  675. }
  676. addBrick(index: number) {
  677. if (this.isGuideMode) {
  678. return;
  679. }
  680. const brickKey = Object.keys(this.brickConfig['bricks'])[randomRangeInt(0, Object.keys(this.brickConfig['bricks']).length)];
  681. const brickConfig = this.brickConfig['bricks'][brickKey];
  682. const num = Math.floor(Math.random() * this.randomList.length);
  683. const randomIndex = this.randomList[num];
  684. // const randomIndex = this.randomList[0];
  685. // 生成方块
  686. const brickData: BrickData = {
  687. index,
  688. brickKey: brickKey,
  689. rotateFlag: brickConfig['rotateFlag'],
  690. gridConfig: brickConfig['gridConfig'],
  691. deg: 0,
  692. brickNode: null,
  693. brickInitPos: new Vec3(),
  694. type: randomIndex,
  695. rotateNode: null,
  696. }
  697. this.bricksList.push(brickData)
  698. // 生成方块
  699. const brickNode = this.generateBrick(brickKey, randomIndex);
  700. if (this.brickNode) {
  701. this.brickNode.addChild(brickNode)
  702. }
  703. brickData.brickNode = brickNode;
  704. let offset = 220
  705. if (this.brickNum % 2 === 1) {
  706. const middleNum = Math.floor(this.brickNum / 2) + 1
  707. if (index < middleNum) {
  708. offset = - offset
  709. }
  710. else if (index === middleNum) {
  711. offset = 0
  712. }
  713. }
  714. if (brickData && brickData.brickNode) {
  715. brickData.brickNode.setPosition(offset, 0)
  716. brickData.brickNode.scale_x = 0.6;
  717. brickData.brickNode.scale_y = 0.6;
  718. brickData.brickInitPos = brickData.brickNode.getWorldPosition()
  719. }
  720. if (brickData.rotateFlag) {
  721. brickData.rotateNode = instantiate(this.rotatePrefab)
  722. this.rotateNode.addChild(brickData.rotateNode);
  723. //先隐藏
  724. brickData.rotateNode.active = false;
  725. brickData.rotateNode.setWorldPosition(brickNode.getWorldPosition())
  726. }
  727. this.brickAddEvent(brickData);
  728. }
  729. // 每个item生成独立的方块节点
  730. generateBrick(brickKey: string, randomIndex: number) {
  731. const brickConfig = this.brickConfig['bricks'][brickKey]
  732. let rowMin = 0
  733. let rowMax = 0
  734. let columnMin = 0
  735. let columnMax = 0
  736. brickConfig['gridConfig'].forEach((gridConfigData: GridConfigData) => {
  737. if (gridConfigData.row < rowMin) {
  738. rowMin = gridConfigData.row
  739. }
  740. else if (gridConfigData.row > rowMax) {
  741. rowMax = gridConfigData.row
  742. }
  743. if (gridConfigData.column < columnMin) {
  744. columnMin = gridConfigData.column
  745. }
  746. else if (gridConfigData.column > columnMax) {
  747. columnMax = gridConfigData.column
  748. }
  749. })
  750. const rowNum = (rowMax - rowMin + 1)
  751. const columnNum = (columnMax - columnMin + 1)
  752. // 生成独立的方块节点
  753. const brickNode = new Node()
  754. brickNode.name = brickKey
  755. // 设置方块大小
  756. const transformCom: UITransform = brickNode.addComponent(UITransform)
  757. transformCom.setContentSize(
  758. this.itemSize * columnNum,
  759. this.itemSize * rowNum
  760. )
  761. transformCom.setAnchorPoint(0.5, 0.5)
  762. // 设置方块位置
  763. const gridPrefab = this.itemPrefabs[randomIndex]
  764. //生成对应的配置方块设置地址
  765. brickConfig['gridConfig'].forEach((gridConfigData: GridConfigData) => {
  766. const gridNode = new Node()
  767. gridNode.name = 'grid'
  768. brickNode.addChild(gridNode)
  769. gridNode.addComponent(UITransform).setContentSize(this.itemSize, this.itemSize)
  770. const gridWidget: Widget = gridNode.addComponent(Widget)
  771. gridWidget.isAlignLeft = true
  772. gridWidget.left = this.itemSize * gridConfigData.column - this.itemSize * columnMin
  773. gridWidget.isAlignBottom = true
  774. gridWidget.bottom = this.itemSize * gridConfigData.row - this.itemSize * rowMin
  775. const node = instantiate(gridPrefab)
  776. gridNode.addChild(node)
  777. const uiTransform = node.getComponent(UITransform);
  778. if (uiTransform) {
  779. uiTransform.setContentSize(
  780. this.itemSize,
  781. this.itemSize,
  782. )
  783. }
  784. node.setPosition(Vec3.ZERO)
  785. node.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  786. event.preventSwallow = true;
  787. }, this);
  788. node.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  789. event.preventSwallow = true;
  790. }, this);
  791. node.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
  792. event.preventSwallow = true;
  793. }, this);
  794. })
  795. return brickNode
  796. }
  797. brickAddEvent(brickData: BrickData) {
  798. const brickNode = brickData.brickNode
  799. if (!brickNode) {
  800. console.error("brickNode为空,无法添加事件");
  801. return
  802. }
  803. // 记录初始位置和状态
  804. let startPos = new Vec3();
  805. let originalParent: Node | null = null;
  806. // 触摸开始事件
  807. brickNode.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  808. // 如果正在编辑其他方块,则忽略
  809. if (!this.operateFlag) return;
  810. // 清空编辑中的数据
  811. this.editingData.brickData = null;
  812. this.editingData.gridList.length = 0;
  813. // 记录触摸开始位置和方块原始信息
  814. this.touchStartPos.set(event.getUILocation());
  815. originalParent = brickNode.parent;
  816. startPos = brickNode.getWorldPosition().clone();
  817. // 将方块移到移动层并放大
  818. brickNode.setParent(this.moveNode);
  819. brickNode.setWorldPosition(startPos);
  820. // 从方块列表中移除该方块
  821. const index = this.bricksList.findIndex(item => item === brickData);
  822. if (index > -1) {
  823. this.editingData.brickData = this.bricksList.splice(index, 1)[0];
  824. } else {
  825. console.error("未找到方块数据:", brickData);
  826. }
  827. }, this);
  828. // 触摸移动事件
  829. brickNode.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  830. if (!this.operateFlag) return;
  831. const movePos: Vec2 = event.getUILocation().subtract(this.touchStartPos)
  832. // 挪动很小时,不移动方块组合
  833. if (movePos.length() <= this.rotateFaultTolerant) {
  834. return
  835. }
  836. // 隐藏旋转节点
  837. if (this.editingData.brickData && this.editingData.brickData.rotateFlag) {
  838. if (this.editingData.brickData.rotateNode) {
  839. this.editingData.brickData.rotateNode.active = false
  840. }
  841. }
  842. // 恢复所有网格颜色
  843. this.gridColorRecovery();
  844. // 移动方块
  845. brickNode.setWorldPosition(event.getUILocation().toVec3().add3f(0, this.yOffset, 0))
  846. brickNode.scale_x = 1;
  847. brickNode.scale_y = 1;
  848. // 重置编辑中的网格数据
  849. this.editingData.gridList.length = 0;
  850. // 检查方块每个子网格是否与游戏网格重叠
  851. const tempGridList: GridData[] = [];
  852. let allEmptyGrids: boolean = true; // 标记是否所有网格都为空
  853. brickNode.children.forEach((childNode) => {
  854. const childWorldPos = childNode.getWorldPosition();
  855. // 查找与子网格重叠的游戏网格
  856. let matchedGrid: GridData | null = null;
  857. for (let row = 0; row < this.rows && !matchedGrid; row++) {
  858. for (let col = 0; col < this.cols && !matchedGrid; col++) {
  859. const grid = this.gridList[row][col];
  860. if (!grid || !grid.gridNode) continue;
  861. const gridPos = grid.gridNode.getWorldPosition();
  862. if (Vec3.distance(gridPos, childWorldPos) <= (this.itemSize / 2)) {
  863. matchedGrid = grid;
  864. }
  865. }
  866. }
  867. if (matchedGrid) {
  868. tempGridList.push(matchedGrid);
  869. // 检查是否有非空网格
  870. if (matchedGrid.status !== CellState.EMPTY) {
  871. allEmptyGrids = false;
  872. }
  873. }
  874. });
  875. // 检查是否所有子网格都有对应的游戏网格,且都是空的
  876. let canPlace = tempGridList.length === brickData.gridConfig.length && allEmptyGrids;
  877. // 更新编辑中的网格列表
  878. if (canPlace) {
  879. this.editingData.gridList = [...tempGridList];
  880. }
  881. // 更新网格颜色提示 - 只改变空网格的颜色
  882. tempGridList.forEach(grid => {
  883. // 只处理空网格
  884. if (grid.status === CellState.EMPTY) {
  885. if (grid.gridNode && grid.gridNode.children[0]) {
  886. const sprite = grid.gridNode.children[0].getComponent(Sprite);
  887. if (sprite) {
  888. sprite.color = canPlace ? this.usableColor : this.unavailableColor;
  889. }
  890. }
  891. // 用于后续恢复颜色
  892. this.gridColorList.push(grid);
  893. }
  894. });
  895. }, this);
  896. // 触摸结束或取消事件
  897. const touchEndHandler = (event: EventTouch) => {
  898. if (this.adShowingFlag || !this.operateFlag) return
  899. this.operateFlag = false
  900. // 单击旋转
  901. if (!this.editingData.brickData) {
  902. console.log("没有数据")
  903. return
  904. }
  905. if (
  906. this.editingData.brickData.rotateFlag &&
  907. event.getUILocation().subtract(this.touchStartPos).length() <= this.rotateFaultTolerant
  908. ) {
  909. //旋转
  910. const brickData = this.editingData.brickData
  911. if (brickData && brickData.brickNode) {
  912. this.bricksList.push(brickData)
  913. this.brickNode.addChild(brickData.brickNode)
  914. //显示旋转节点
  915. if (brickData.rotateNode) {
  916. brickData.rotateNode.active = true;
  917. }
  918. brickData.brickNode.setWorldPosition(brickData.brickInitPos)
  919. // 旋转
  920. this.brickGridRotate(brickData).then(() => {
  921. this.operateFlag = true
  922. })
  923. // 隐藏旋转节点
  924. this.scheduleOnce(() => {
  925. if (brickData.rotateNode) {
  926. brickData.rotateNode.active = false;
  927. }
  928. }, 0.4);
  929. }
  930. } else if (this.editingData.brickData && this.editingData.gridList.length > 0) {
  931. if (this.isGuideMode && this.guideStep > 0) {
  932. const brickData = this.editingData.brickData
  933. const targetGrids = this.editingData.gridList
  934. // 如果格子数量不足,直接视为无效放置
  935. if (!brickData || !targetGrids || targetGrids.length !== brickData.gridConfig.length) {
  936. this.bricksList.push(brickData)
  937. if (brickData.brickNode) {
  938. tween(brickData.brickNode)
  939. .to(0.15, {
  940. worldPosition: brickData.brickInitPos,
  941. scale: new Vec3(0.8, 0.8, 0.8)
  942. })
  943. .call(() => {
  944. if (brickData.brickNode) {
  945. this.operateFlag = true
  946. this.brickNode.addChild(brickData.brickNode)
  947. brickData.brickNode.setWorldPosition(brickData.brickInitPos)
  948. }
  949. })
  950. .start()
  951. }
  952. return
  953. }
  954. // 模拟砖块落下后的状态
  955. const tempGridList = this.copyGridList()
  956. for (let i = 0; i < targetGrids.length; i++) {
  957. const g = targetGrids[i]
  958. tempGridList[g.row][g.col].status = CellState.FILLED
  959. }
  960. const simulateResult = this.gridEliminateCheck(tempGridList)
  961. const canEliminate = simulateResult.gridEliminateList.length > 0
  962. if (!canEliminate) {
  963. this.bricksList.push(brickData);
  964. if (brickData.brickNode) {
  965. tween(brickData.brickNode)
  966. .to(0.15, {
  967. worldPosition: brickData.brickInitPos,
  968. scale: new Vec3(0.8, 0.8, 0.8)
  969. })
  970. .call(() => {
  971. if (brickData.brickNode) {
  972. this.operateFlag = true
  973. this.brickNode.addChild(brickData.brickNode)
  974. brickData.brickNode.setWorldPosition(brickData.brickInitPos)
  975. }
  976. })
  977. .start()
  978. }
  979. return
  980. }
  981. }
  982. // 计算放置的格子数量
  983. const placedGridCount = this.editingData.gridList.length;
  984. // 获取中心位置用于显示分数
  985. let centerPos = new Vec3(0, 0, 0);
  986. if (this.editingData.gridList.length > 0 && this.editingData.gridList[0].gridNode) {
  987. centerPos = this.editingData.gridList[0].gridNode.getWorldPosition().clone();
  988. if (this.editingData.gridList.length > 1) {
  989. // 计算所有格子的平均位置作为中心点
  990. for (let i = 1; i < this.editingData.gridList.length; i++) {
  991. const gridNode = this.editingData.gridList[i].gridNode;
  992. if (gridNode) {
  993. centerPos.add(gridNode.getWorldPosition());
  994. }
  995. }
  996. const validGridCount = this.editingData.gridList.filter(grid => grid.gridNode).length;
  997. centerPos.x /= validGridCount;
  998. centerPos.y /= validGridCount;
  999. }
  1000. }
  1001. // 放置方块到网格
  1002. this.editingData.gridList.forEach(grid => {
  1003. grid.status = CellState.FILLED;
  1004. grid.type = this.editingData.brickData!.type;
  1005. this.generateGrid(grid);
  1006. });
  1007. // 显示放置得分动画(显示一次,包含总格子数)
  1008. this.showScoreAnimation(centerPos, placedGridCount);
  1009. //这里要计算分数,并且计算能消除的分数,然后增加分,这才对
  1010. // 标记需要重置消除计数器
  1011. this.shouldResetEliminateCount = true;
  1012. // 销毁方块节点
  1013. brickNode.destroy();
  1014. // 添加新方块到待选区
  1015. this.addBrick(this.editingData.brickData.index);
  1016. // 检查消除
  1017. this.scheduleOnce(() => {
  1018. this.gridEliminate().then((hasElimination) => {
  1019. // 如果没有消除,确保下次消除会重置计数
  1020. if (!hasElimination) {
  1021. this.shouldResetEliminateCount = true;
  1022. }
  1023. this.operateFlag = true;
  1024. //新手引导
  1025. if (this.isGuideMode) {
  1026. this.scheduleOnce(() => {
  1027. if (this.guideStep < 4) {
  1028. this.setupGuideStep(this.guideStep + 1)
  1029. } else {
  1030. this.isGuideMode = false;
  1031. this.guideNode.active = false;
  1032. this.initGrid();
  1033. }
  1034. }, 0.3)
  1035. } else {
  1036. // 检查游戏是否结束
  1037. this.prompt(false).then(canContinue => {
  1038. if (!canContinue) {
  1039. this.gameOver();
  1040. }
  1041. });
  1042. }
  1043. });
  1044. }, 0.1);
  1045. } else {
  1046. // 无法放置,将方块返回原位置
  1047. const brickData = this.editingData.brickData;
  1048. if (brickData) {
  1049. this.bricksList.push(brickData);
  1050. this.operateFlag = false
  1051. // 添加回弹动画
  1052. tween(brickNode)
  1053. .to(0.2, {
  1054. worldPosition: brickData.brickInitPos,
  1055. scale: new Vec3(0.6, 0.6, 0.6)
  1056. })
  1057. .call(() => {
  1058. if (originalParent) {
  1059. this.operateFlag = true
  1060. brickNode.setParent(originalParent);
  1061. brickNode.setWorldPosition(brickData.brickInitPos);
  1062. }
  1063. })
  1064. .start();
  1065. }
  1066. }
  1067. // 格子颜色恢复
  1068. this.gridColorRecovery()
  1069. };
  1070. brickNode.on(Node.EventType.TOUCH_END, touchEndHandler, this);
  1071. brickNode.on(Node.EventType.TOUCH_CANCEL, touchEndHandler, this);
  1072. }
  1073. //格子颜色恢复
  1074. gridColorRecovery() {
  1075. while (this.gridColorList.length > 0) {
  1076. const gridData = this.gridColorList.pop();
  1077. if (gridData) {
  1078. if (gridData.status === CellState.EMPTY) {
  1079. if (gridData.gridNode) {
  1080. gridData.gridNode.children[0].getComponent(Sprite)!.color = this.notUseColor;
  1081. }
  1082. }
  1083. }
  1084. }
  1085. }
  1086. brickGridRotate(brickData: BrickData) {
  1087. return new Promise((resolve, reject) => {
  1088. const next = this.nextGridRotate(brickData.gridConfig, brickData.deg)
  1089. brickData.deg = next.deg
  1090. brickData.gridConfig = next.gridConfig
  1091. if (brickData.brickNode) {
  1092. tween(brickData.brickNode).to(this.aniBrickRotate, { angle: next.deg }).call(() => {
  1093. resolve(true)
  1094. }).start()
  1095. }
  1096. })
  1097. }
  1098. //下一个旋转
  1099. nextGridRotate(gridConfig: GridConfigData[], deg: number) {
  1100. const newGridConfig: GridConfigData[] = []
  1101. // 顺时针旋转
  1102. let newDeg = deg - 90
  1103. gridConfig.forEach((gridConfigData) => {
  1104. // 例如(1,2) => (-2,1),可以画图分析
  1105. newGridConfig.push({
  1106. row: -gridConfigData.column,
  1107. column: gridConfigData.row
  1108. })
  1109. })
  1110. return { gridConfig: newGridConfig, deg: newDeg }
  1111. }
  1112. // 显示分数增加动画
  1113. showScoreAnimation(position: Vec3, score: number) {
  1114. if (!this.lab_addScore) return;
  1115. // 计算得分(未消除时的得分)
  1116. const calculatedScore = score * this.placementBaseScore;
  1117. // 复制得分Label
  1118. const scoreLabel = instantiate(this.lab_addScore.node);
  1119. scoreLabel.active = true;
  1120. // 设置文本和位置
  1121. const label = scoreLabel.getComponent(Label);
  1122. if (label) {
  1123. label.string = `+${calculatedScore}`;
  1124. }
  1125. // 添加到场景中
  1126. this.node.addChild(scoreLabel);
  1127. scoreLabel.setWorldPosition(position);
  1128. const num = this.isDoubleSpeed ? this.doubleNum : 1;
  1129. // 创建动画效果
  1130. tween(scoreLabel)
  1131. .to(0.5 / num, {
  1132. position: new Vec3(scoreLabel.position.x, scoreLabel.position.y + 50, 0),
  1133. scale: new Vec3(1.2, 1.2, 1.2)
  1134. })
  1135. .to(0.3 / num, { opacity: 0 })
  1136. .call(() => {
  1137. scoreLabel.destroy();
  1138. })
  1139. .start();
  1140. // 更新总分
  1141. this.score += calculatedScore;
  1142. }
  1143. // 显示消除次数动画
  1144. showEliminateCountAnimation(yPosition: number, eliminationCount: number) {
  1145. if (!this.comboNode) return;
  1146. // 如果需要重置计数器,先将计数归零
  1147. if (this.shouldResetEliminateCount) {
  1148. this.currentCombo = 0;
  1149. this.shouldResetEliminateCount = false;
  1150. }
  1151. // 增加累计消除次数
  1152. this.currentCombo += eliminationCount;
  1153. // 复制总次数Label
  1154. const comboNode = instantiate(this.comboNode);
  1155. comboNode.active = true;
  1156. // 设置文本
  1157. const label = comboNode.getChildByName("lab_combo");
  1158. if (label) {
  1159. const labelComponent = label.getComponent(Label);
  1160. if (labelComponent) {
  1161. labelComponent.string = `${this.currentCombo}`;
  1162. }
  1163. }
  1164. // 添加到场景中
  1165. this.node.addChild(comboNode);
  1166. // 计算网格区域的X轴中心位置,Y轴使用传入的消除行位置
  1167. const centerPos = new Vec3();
  1168. if (this.gridNode) {
  1169. // 获取网格区域的X轴中心
  1170. const worldPos = this.gridNode.getWorldPosition();
  1171. centerPos.set(worldPos.x, yPosition, worldPos.z);
  1172. }
  1173. comboNode.setWorldPosition(centerPos);
  1174. // 创建动画效果
  1175. const num = this.isDoubleSpeed ? this.doubleNum : 1;
  1176. tween(comboNode)
  1177. .to(0.3 / num, {
  1178. scale: new Vec3(1.5, 1.5, 1.5),
  1179. opacity: 255
  1180. })
  1181. .delay(0.5 / num) // 停留更长时间
  1182. .to(0.4 / num, {
  1183. scale: new Vec3(1.2, 1.2, 1.2),
  1184. position: new Vec3(comboNode.position.x, comboNode.position.y + 50, 0),
  1185. opacity: 0
  1186. })
  1187. .call(() => {
  1188. comboNode.destroy();
  1189. })
  1190. .start();
  1191. }
  1192. // 修改 gridEliminate 方法来显示消除次数
  1193. gridEliminate() {
  1194. return new Promise<boolean>((resolve, reject) => {
  1195. const d = this.gridEliminateCheck(this.gridList)
  1196. const gridEliminateList = d.gridEliminateList
  1197. const eliminateRowNum = d.eliminateRowNum
  1198. const eliminateColumnNum = d.eliminateColumnNum
  1199. const totalEliminationsInThisRound = eliminateRowNum + eliminateColumnNum
  1200. this.eliminateTotal += totalEliminationsInThisRound;
  1201. console.log("消除总数", this.eliminateTotal)
  1202. if (gridEliminateList.length < 1) {
  1203. // 没有发生消除
  1204. this.updateGameScore();
  1205. this.shouldResetEliminateCount = true; // 下一次消除需要重置计数
  1206. resolve(false);
  1207. return;
  1208. }
  1209. // 如果有消除,计算消除行的平均Y轴位置
  1210. if (gridEliminateList.length > 0) {
  1211. // 计算所有被消除格子的平均Y轴位置
  1212. let totalY = 0;
  1213. let validGrids = 0;
  1214. for (const grid of gridEliminateList) {
  1215. if (grid.gridNode) {
  1216. totalY += grid.gridNode.getWorldPosition().y;
  1217. validGrids++;
  1218. }
  1219. }
  1220. // 计算平均Y位置
  1221. const avgY = validGrids > 0 ? totalY / validGrids : 0;
  1222. // 显示消除次数动画,传入Y轴位置和本次消除的行列总数
  1223. this.showEliminateCountAnimation(avgY, totalEliminationsInThisRound);
  1224. }
  1225. const num = this.isDoubleSpeed ? this.doubleNum : 1;
  1226. gridEliminateList.forEach((gridData) => {
  1227. if (gridData.gridNode?.children[0]) {
  1228. const startPos = gridData.gridNode.getWorldPosition();
  1229. tween(gridData.gridNode.children[0])
  1230. .to(0.2 / num, { scale: new Vec3(0.5, 0.5) })
  1231. .call(() => {
  1232. gridData.status = CellState.EMPTY
  1233. this.generateGrid(gridData)
  1234. })
  1235. .start()
  1236. if (this.coinPrefab && this.lab_wxCoin?.node) {
  1237. this.createCoinFlyAnimation(
  1238. this.coinPrefab,
  1239. startPos,
  1240. this.lab_wxCoin.node.getWorldPosition(),
  1241. 5
  1242. );
  1243. }
  1244. //增加红包
  1245. this.createCoinFlyAnimation(
  1246. this.redPacketPrefab,
  1247. startPos,
  1248. this.lab_hbCoin.node.getWorldPosition(),
  1249. 3
  1250. );
  1251. }
  1252. })
  1253. this.scheduleOnce(() => {
  1254. // 计算分数:每行/列的基础分 + 每个额外格子的分数
  1255. let score = 0;
  1256. // 行消除基础分
  1257. for (let i = 1; i <= eliminateRowNum; i++) {
  1258. score += this.eliminateBaseScore; // 每行基础分
  1259. score += (this.cols - 1) * this.extraGridScore; // 额外格子分
  1260. }
  1261. // 列消除基础分
  1262. for (let i = 1; i <= eliminateColumnNum; i++) {
  1263. score += this.eliminateBaseScore; // 每列基础分
  1264. score += (this.rows - 1) * this.extraGridScore; // 额外格子分
  1265. }
  1266. this.score += score;
  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. //更新游戏分数
  1659. updateGameScore() {
  1660. this.lab_score.string = this.score.toString();
  1661. if (this.score >= this.targetScore) {
  1662. this.gameState = GameState.GAME_PASS;
  1663. this.setGameState(this.gameState);
  1664. //弹出通关奖励界面
  1665. if (DeviceUtil.isNative && DeviceUtil.isAndroid) {
  1666. ServerHandler.inst.getGameAwardInfo();
  1667. } else {
  1668. oops.gui.open(UIID.GamePass);
  1669. }
  1670. }
  1671. }
  1672. /**
  1673. * 清理网格的子节点
  1674. */
  1675. private clearGridChildren(gridNode: Node): void {
  1676. const children = gridNode.children.slice(); // 创建副本避免遍历时修改问题
  1677. children.forEach(node => node.destroy());
  1678. }
  1679. private setGameState(state: GameState) {
  1680. this.gameState = state;
  1681. switch (state) {
  1682. case GameState.READY:
  1683. break;
  1684. case GameState.PLAYING:
  1685. break;
  1686. case GameState.PAUSED:
  1687. break;
  1688. case GameState.GAME_OVER:
  1689. //打开游戏结束界面
  1690. this.autoState = false;
  1691. this.adShowingFlag = false;
  1692. //自动按钮改为手动
  1693. this.initButtonState(false);
  1694. break;
  1695. }
  1696. }
  1697. //========================打开其他界面和按钮逻辑=======================
  1698. /** 视图对象通过 ecs.Entity.remove(eliminateViewComp) 删除组件是触发组件处理自定义释放逻辑 */
  1699. reset() {
  1700. this.node.destroy();
  1701. }
  1702. //设置按钮
  1703. private btn_setting() {
  1704. oops.gui.open(UIID.Setting);
  1705. }
  1706. //左边微信按钮
  1707. private btn_withdraw() {
  1708. if (DeviceUtil.isNative && DeviceUtil.isAndroid) {
  1709. ServerHandler.inst.getWechatTxInfo();
  1710. } else {
  1711. oops.gui.open(UIID.WechatWithdraw);
  1712. }
  1713. }
  1714. //顶部红包按钮
  1715. private btn_award() {
  1716. //oops.gui.open(UIID.RedPacketWithdraw);
  1717. if (DeviceUtil.isNative && DeviceUtil.isAndroid) {
  1718. ServerHandler.inst.getHbTxInfo();
  1719. } else {
  1720. oops.gui.open(UIID.RedPacketWithdraw);
  1721. }
  1722. }
  1723. //二倍速按钮
  1724. private btn_double() {
  1725. // oops.gui.open(UIID.DoubleSpeed);
  1726. if (DeviceUtil.isNative && DeviceUtil.isAndroid) {
  1727. ServerHandler.inst.getDoubleSpeedTime();
  1728. } else {
  1729. oops.gui.open(UIID.DoubleSpeed);
  1730. }
  1731. }
  1732. //自动放置
  1733. private btn_auto() {
  1734. if (this.gameState !== GameState.PLAYING) {
  1735. return;
  1736. }
  1737. this.autoState = !this.autoState;
  1738. this.initButtonState(this.autoState);
  1739. if (this.autoState) {
  1740. this.executeAutoPlace();
  1741. }
  1742. }
  1743. // 执行自动放置
  1744. executeAutoPlace() {
  1745. if (!this.autoState || this.gameState !== GameState.PLAYING || this.adShowingFlag) {
  1746. return
  1747. }
  1748. const bestPlacement = this.findBestPlacement()
  1749. if (!bestPlacement) {
  1750. // 所有方块都无法放置,游戏结束
  1751. this.autoState = false;
  1752. this.gameState = GameState.GAME_OVER;
  1753. this.gameOver()
  1754. return
  1755. }
  1756. // 执行放置
  1757. this.placeBrickAtPosition(bestPlacement)
  1758. }
  1759. //寻找最佳位置
  1760. findBestPlacement() {
  1761. const placements = []
  1762. // 对每个方块计算所有可能的放置位置和分数
  1763. for (let brickIndex = 0; brickIndex < this.bricksList.length; brickIndex++) {
  1764. const brickData = this.bricksList[brickIndex]
  1765. // 检查不同旋转状态
  1766. let gridConfigs = [brickData.gridConfig]
  1767. let degrees = [brickData.deg]
  1768. // 如果可旋转,计算所有旋转状态
  1769. if (brickData.rotateFlag) {
  1770. for (let i = 1; i <= 3; i++) {
  1771. const next = this.nextGridRotate(
  1772. i === 1 ? brickData.gridConfig : gridConfigs[i - 1],
  1773. i === 1 ? brickData.deg : degrees[i - 1]
  1774. )
  1775. gridConfigs.push(next.gridConfig)
  1776. degrees.push(next.deg)
  1777. }
  1778. }
  1779. // 遍历所有网格位置
  1780. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1781. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1782. // 对每个旋转状态检查
  1783. for (let rotateIndex = 0; rotateIndex < gridConfigs.length; rotateIndex++) {
  1784. const currentGridConfig = gridConfigs[rotateIndex]
  1785. const currentDeg = degrees[rotateIndex]
  1786. // 检查是否可以放置
  1787. if (this.moveIf(rowIndex, columnIndex, currentGridConfig)) {
  1788. // 复制网格并模拟放置
  1789. const gridList = this.copyGridList()
  1790. currentGridConfig.forEach((gridConfigData) => {
  1791. const r = gridConfigData.row + rowIndex
  1792. const c = gridConfigData.column + columnIndex
  1793. gridList[r][c].status = CellState.FILLED
  1794. gridList[r][c].type = brickData.type;
  1795. })
  1796. // 检查是否可以消除,计算分数
  1797. const elimination = this.gridEliminateCheck(gridList)
  1798. let score = 0
  1799. if (elimination.gridEliminateList.length > 0) {
  1800. // 计算消除得分
  1801. for (let i = 1; i <= elimination.eliminateRowNum; i++) {
  1802. score += this.cols * i
  1803. }
  1804. for (let i = 1; i <= elimination.eliminateColumnNum; i++) {
  1805. score += this.rows * i
  1806. }
  1807. }
  1808. // 记录此放置选项
  1809. placements.push({
  1810. brickIndex,
  1811. brickData,
  1812. rowIndex,
  1813. columnIndex,
  1814. gridConfig: currentGridConfig, //这里有问题,拿到的和显示的不对
  1815. deg: currentDeg,
  1816. score,
  1817. canEliminate: elimination.gridEliminateList.length > 0
  1818. })
  1819. }
  1820. }
  1821. }
  1822. }
  1823. }
  1824. // 按优先级排序:最高分 > 有分数 > 没有分数但可放置
  1825. placements.sort((a, b) => {
  1826. // 首先按分数排序
  1827. if (a.score !== b.score) {
  1828. return b.score - a.score
  1829. }
  1830. // 其次按是否可消除排序
  1831. if (a.canEliminate !== b.canEliminate) {
  1832. return a.canEliminate ? -1 : 1
  1833. }
  1834. // 最后按照方块优先级排序(底部的方块优先)
  1835. return a.brickIndex - b.brickIndex
  1836. })
  1837. return placements.length > 0 ? placements[0] : null
  1838. }
  1839. // ... existing code ...
  1840. placeBrickAtPosition(placement: any) {
  1841. const brickData = placement.brickData
  1842. const index = this.bricksList.findIndex(data => data === brickData)
  1843. if (index === -1) {
  1844. console.error("无法找到要放置的方块:", brickData)
  1845. return
  1846. }
  1847. this.editingData.brickData = this.bricksList.splice(index, 1)[0];
  1848. // 应用旋转
  1849. if (brickData.deg !== placement.deg) {
  1850. brickData.gridConfig = placement.gridConfig
  1851. brickData.deg = placement.deg
  1852. tween(brickData.brickNode).to(0.1, { angle: placement.deg }).start()
  1853. }
  1854. // 构建对应网格列表--这里就有问题了,这算位置,有问题
  1855. this.editingData.gridList = [];
  1856. placement.gridConfig.forEach((gridConfigData: GridConfigData) => {
  1857. const r = gridConfigData.row + placement.rowIndex
  1858. const c = gridConfigData.column + placement.columnIndex
  1859. this.editingData.gridList.push(this.gridList[r][c])
  1860. })
  1861. // 计算移动位置(中点)
  1862. let centerPos = new Vec3(0, 0, 0)
  1863. let count = 0
  1864. for (const grid of this.editingData.gridList) {
  1865. if (grid.gridNode) {
  1866. const pos = grid.gridNode.getWorldPosition()
  1867. centerPos.add(pos)
  1868. count++
  1869. }
  1870. }
  1871. if (count > 0) {
  1872. centerPos.x /= count
  1873. centerPos.y /= count
  1874. centerPos.z /= count
  1875. }
  1876. const originPos = brickData.brickNode.getWorldPosition()
  1877. brickData.brickNode.setParent(this.moveNode)
  1878. brickData.brickNode.setWorldPosition(originPos);
  1879. // 动画放置方块
  1880. tween(brickData.brickNode)
  1881. .to(this.autoMoveTime, { worldPosition: centerPos })
  1882. .call(() => {
  1883. // ✅ 更新格子状态(像手动放置那样)
  1884. this.editingData.gridList.forEach(gridData => {
  1885. gridData.status = CellState.FILLED
  1886. gridData.type = brickData.type;
  1887. this.generateGrid(gridData)
  1888. })
  1889. // ✅ 销毁方块节点
  1890. brickData.brickNode.destroy()
  1891. // ✅ 补充新的砖块
  1892. this.addBrick(brickData.index)
  1893. // ✅ 消除检查逻辑保持和手动一致
  1894. this.scheduleOnce(() => {
  1895. this.gridEliminate().then(() => {
  1896. this.prompt(false).then((promptFlag) => {
  1897. if (!promptFlag) {
  1898. this.autoState = false
  1899. this.gameOver()
  1900. } else if (this.autoState) {
  1901. // 继续自动放置
  1902. this.scheduleOnce(() => {
  1903. this.executeAutoPlace()
  1904. }, this.autoPlaceInterval)
  1905. }
  1906. })
  1907. })
  1908. })
  1909. })
  1910. .start()
  1911. }
  1912. doubleSpeedOpenSuccess() {
  1913. //2倍速广告展示,页面展示,都会暂停游戏,
  1914. if (this.gameState !== GameState.PLAYING) {
  1915. return
  1916. }
  1917. if (this.callback) {
  1918. this.unschedule(this.callback);
  1919. }
  1920. this.isDoubleSpeed = true;
  1921. this.doubleNum = 2;
  1922. //改变按钮时间
  1923. // let time = smc.game.GameModel.doubleSpeedTime;
  1924. this.doubleSpeedTime = smc.game.GameModel.doubleSpeedTime;
  1925. let time = 15;
  1926. if (time <= 0) {
  1927. return
  1928. }
  1929. console.log("二倍速时间", time);
  1930. if (!this.autoState) {
  1931. this.btn_auto();
  1932. //改按钮状态
  1933. this.autoState = true;
  1934. this.initButtonState(this.autoState);
  1935. }
  1936. this.callback = function () {
  1937. if (!this.adShowingFlag && this.gameState === GameState.PLAYING) {
  1938. time--
  1939. //修改剩余时间,秒格式化成时分10:59
  1940. const minutes = Math.floor(time / 60);
  1941. const seconds = time % 60;
  1942. const formattedTime = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  1943. this.lab_doubleTime.string = formattedTime;
  1944. //时间到了
  1945. if (time <= 0) {
  1946. this.lab_doubleTime.string = "二倍速";
  1947. this.isDoubleSpeed = false;
  1948. this.doubleNum = 1;
  1949. //再打开继续二倍速页面
  1950. oops.gui.open(UIID.KeepSpeed);
  1951. this.unschedule(this.callback);
  1952. }
  1953. }
  1954. }
  1955. this.schedule(this.callback, 1);
  1956. }
  1957. //重新开始
  1958. private restartGame() {
  1959. if (this.gameState === GameState.READY) return;
  1960. this.initData();
  1961. this.setData();
  1962. this.reopenGrid();
  1963. this.initButtonState(this.autoState);
  1964. this.updateWelfarePoint();
  1965. }
  1966. //重新清除网格
  1967. private reopenGrid() {
  1968. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1969. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1970. this.gridList[rowIndex][columnIndex].status = CellState.EMPTY
  1971. this.generateGrid(this.gridList[rowIndex][columnIndex])
  1972. }
  1973. }
  1974. // 初始化方块
  1975. if (this.brickNode) {
  1976. if (this.brickNode) {
  1977. this.brickNode.destroyAllChildren();
  1978. }
  1979. }
  1980. this.bricksList.length = 0
  1981. for (let i = 1; i <= this.brickNum; i++) {
  1982. this.addBrick(i)
  1983. }
  1984. // 清除旋转数据
  1985. if (this.rotateNode) {
  1986. this.rotateNode.destroyAllChildren();
  1987. }
  1988. }
  1989. //===============初始化检查是否要打开福利界面====
  1990. private updateWelfarePoint() {
  1991. switch (this.popupType) {
  1992. case "weal_1":
  1993. oops.gui.open(UIID.WarmReminder);
  1994. ServerHandler.inst.GetGuideInfo();
  1995. break;
  1996. case "weal_2":
  1997. //打开福利二
  1998. oops.gui.open(UIID.WelfareTwo);
  1999. ServerHandler.inst.GetGuideInfo();
  2000. break;
  2001. case "weal_3":
  2002. //打开福利三
  2003. oops.gui.open(UIID.WelfareThree);
  2004. break;
  2005. }
  2006. if (smc.game.GameModel.curLevelConfig) {
  2007. if (smc.game.GameModel.curLevelConfig.eventType && smc.game.GameModel.curLevelConfig.eventType === "SIGN_POINT") {
  2008. //展示提现信息
  2009. oops.gui.open(UIID.ReservePopup);
  2010. }
  2011. }
  2012. }
  2013. btn_text() {
  2014. // const param = {
  2015. // "showReward": [
  2016. // {
  2017. // "propId": "1004",
  2018. // "propNum": 500
  2019. // },
  2020. // {
  2021. // "propId": "1005",
  2022. // "propNum": 200
  2023. // },
  2024. // {
  2025. // "propId": "1006",
  2026. // "propNum": 1
  2027. // }
  2028. // ],
  2029. // "levelProgress": {
  2030. // "nextProgress": 1,
  2031. // "levelInfoList": [
  2032. // {
  2033. // "level": 1,
  2034. // "eventType": "WITHDRAW_POINT",
  2035. // "withdraw": true
  2036. // },
  2037. // {
  2038. // "level": 4,
  2039. // "eventType": "WITHDRAW_POINT",
  2040. // "withdraw": false
  2041. // },
  2042. // {
  2043. // "level": 6,
  2044. // "eventType": "WITHDRAW_POINT",
  2045. // "withdraw": false
  2046. // },
  2047. // {
  2048. // "level": 8,
  2049. // "eventType": "WITHDRAW_POINT",
  2050. // "withdraw": false
  2051. // },
  2052. // {
  2053. // "level": 12,
  2054. // "eventType": "SIGN_POINT",
  2055. // "withdraw": false
  2056. // }
  2057. // ]
  2058. // }
  2059. // }
  2060. // let str = JSON.stringify(param);
  2061. // ServerHandler.inst.onDoubleSurprise(str);
  2062. // ServerHandler.inst.GetGuideInfo();
  2063. }
  2064. getRandomUniqueInts(count: number = 3): number[] {
  2065. let min: number = 0;
  2066. let max: number = 0;
  2067. const curLevel = smc.account.AccountModel.curLevel || 1;
  2068. if (curLevel < 5) {
  2069. return [curLevel]
  2070. } else if (curLevel >= 5 && curLevel <= 7) {
  2071. //三种基础色
  2072. min = 1;
  2073. max = 5;
  2074. } else if (curLevel >= 8 && curLevel <= 11) {
  2075. min = 6;
  2076. max = 12;
  2077. } else {
  2078. min = 1;
  2079. max = 12;
  2080. }
  2081. if (max - min + 1 < count) {
  2082. throw new Error(`区间 [${min}, ${max}] 无法提供 ${count} 个不重复整数`);
  2083. }
  2084. const pool: number[] = [];
  2085. for (let i = min; i <= max; i++) {
  2086. pool.push(i);
  2087. }
  2088. this.shuffle(pool);
  2089. return pool.slice(0, count);
  2090. }
  2091. // 洗牌算法(Fisher-Yates)
  2092. shuffle(arr: number[]) {
  2093. for (let i = arr.length - 1; i > 0; i--) {
  2094. const j = Math.floor(Math.random() * (i + 1));
  2095. [arr[i], arr[j]] = [arr[j], arr[i]];
  2096. }
  2097. }
  2098. }