EliminateViewComp.ts 91 KB

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