EliminateViewComp.ts 90 KB

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