EliminateViewComp.ts 88 KB

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