EliminateViewComp.ts 83 KB

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