EliminateViewComp.ts 86 KB

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