EliminateViewComp.ts 76 KB

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