EliminateViewComp.ts 80 KB

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