EliminateViewComp.ts 90 KB

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