EliminateViewComp.ts 81 KB

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