EliminateViewComp.ts 84 KB

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