EliminateViewComp.ts 90 KB

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