EliminateViewComp.ts 88 KB

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