EliminateViewComp.ts 85 KB

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