EliminateViewComp.ts 84 KB

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