EliminateViewComp.ts 81 KB

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