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