EliminateViewComp.ts 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701
  1. /*
  2. * @Author: mojunshou 1637302775@qq.com
  3. * @Date: 2025-03-20 15:01:09
  4. * @LastEditors: mojunshou 1637302775@qq.com
  5. * @LastEditTime: 2025-03-28 17:23:57
  6. * @Description: 消除游戏主场景
  7. */
  8. import { _decorator, Color, EventTouch, instantiate, JsonAsset, Label, Node, Prefab, randomRangeInt, Sprite, Toggle, tween, UITransform, Vec2, Vec3, Widget } from "cc";
  9. import { RandomManager } from "db://oops-framework/core/common/random/RandomManager";
  10. import { oops } from "db://oops-framework/core/Oops";
  11. import { ecs } from "db://oops-framework/libs/ecs/ECS";
  12. import { LabelChange } from "db://oops-framework/libs/gui/label/LabelChange";
  13. import { CCComp } from "db://oops-framework/module/common/CCComp";
  14. import { GameEvent } from "../../common/config/GameEvent";
  15. import { UIID } from "../../common/config/GameUIConfig";
  16. import { BlockItemView } from "./BlockItemView";
  17. const { ccclass, property } = _decorator;
  18. // 游戏状态枚举
  19. enum GameState {
  20. READY, // 准备中
  21. PLAYING, // 游戏中
  22. PAUSED, // 暂停
  23. GAME_OVER // 游戏结束
  24. }
  25. // 游戏模式枚举
  26. enum GameMode {
  27. MANUAL, // 手动模式
  28. AUTO // 自动模式
  29. }
  30. // 格子状态
  31. enum CellState {
  32. EMPTY, // 空格子
  33. FILLED, // 有方块
  34. HIGHLIGHTED // 高亮(可放置)
  35. }
  36. // 新手引导步骤
  37. enum TutorialStep {
  38. NONE, // 无引导
  39. ROW_ELIMINATION, // 行消除引导
  40. COLUMN_ELIMINATION, // 列消除引导
  41. ROTATION, // 旋转引导
  42. FINAL_ELIMINATION // 最终消除引导
  43. }
  44. //网格数据接口
  45. interface GridData {
  46. name: string, // 名称
  47. status: CellState, // 状态
  48. gridNode: Node | null // 网格节点
  49. row: number, // 行
  50. col: number, // 列
  51. gridColorKey: string | null,
  52. type: number, // 类型--gridColorKey
  53. }
  54. interface Grids {
  55. row: number,
  56. column: number,
  57. }
  58. interface EditingData {
  59. brickData: BrickData | null,
  60. gridList: GridData[],
  61. }
  62. //底部方块数据定义
  63. interface BrickData {
  64. index: number,
  65. brickKey: string | null,
  66. rotateTag: boolean,
  67. rotateFlag: boolean,
  68. gridConfig: Grids[],
  69. deg: number,
  70. brickNode: Node | null,
  71. gridColorKey: string | null,
  72. brickInitPos: Vec3, // 方块初始位置
  73. type: number, // 方块类型--gridColorKey
  74. }
  75. interface GridConfigData {
  76. row: number,
  77. column: number,
  78. }
  79. /** 视图层对象 */
  80. @ccclass('EliminateViewComp')
  81. @ecs.register('EliminateView', false)
  82. export class EliminateViewComp extends CCComp {
  83. @property({ type: LabelChange, displayName: "自动提现金额" })
  84. private amountLb: LabelChange = null!;
  85. @property({ type: LabelChange, displayName: "额外奖励" })
  86. private awardLb: LabelChange = null!;
  87. @property({ type: Prefab, displayName: "金币预制体" })
  88. private coinPrefab: Prefab = null!;
  89. @property({ type: Prefab, displayName: "红包预制体" })
  90. private redPacketPrefab: Prefab = null!;
  91. @property({ type: Label, displayName: "本局分数" })
  92. private lab_score: Label = null!;
  93. @property({ type: Prefab, displayName: "item预制体列表" })
  94. private itemPrefabs: Prefab[] = [];
  95. @property({ type: Node, displayName: "网格Node" })
  96. private gridNode: Node = null!;
  97. @property({ type: Node, displayName: "移动Node" })
  98. private moveNode: Node = null!;
  99. @property({ type: Node, displayName: "旋转Node" })
  100. private rotateNode: Node = null!;
  101. @property({ type: Node, displayName: "方块Node" })
  102. private brickNode: Node = null!;
  103. @property({ type: Prefab, displayName: "旋转预制体" })
  104. private rotatePrefab: Node = null!;
  105. @property({ type: Label, displayName: "累计消除次数" })
  106. private lab_total: Label = null!;
  107. @property({ type: Label, displayName: "每次放置添加的分数" })
  108. private lab_addScore: Label = null!;
  109. private lab_speed: Label = null!;
  110. private winthdrawNode: Node = null!;
  111. private awardNode: Node = null!;
  112. private autoOnToggle: Toggle = null!;
  113. //游戏配置行列
  114. private rows: number = 8; // 行数
  115. private cols: number = 8; // 列数
  116. private itemSize: number = 82; // 格子大小
  117. private brickNum: number = 3; // 砖块数量
  118. //按钮状态
  119. private autoClick: boolean = false;
  120. private gameState: GameState = GameState.READY;
  121. private gameMode: GameMode = GameMode.MANUAL;
  122. private rotateTag: boolean = false; // 旋转标志
  123. private score: number = 0; //本局分数
  124. private money: number = 0; //左边金钱
  125. private cash: number = 0; //右边红包钱数
  126. private totalNum: number = 0; //累计消除次数,断了就是又从0开始
  127. //网格列表
  128. // gridsNode: Node | null = null; //中间网格区域
  129. // brickNode: Node | null = null; //底部三个item块区域
  130. // moveNode: Node | null = null; //移动层Node
  131. // rotateNode: Node | null = null; //旋转Node吧
  132. //没使用颜色
  133. notUseColor = new Color(255, 255, 255, 255)
  134. //可用的颜色
  135. usableColor = new Color(0, 255, 0, 100)
  136. //不可用的颜色
  137. unavailableColor = new Color(255, 0, 0, 100)
  138. //旋转容错
  139. rotateFaultTolerant = 10;
  140. private _isAutoFunc: (() => void) | null = null;
  141. isAutoMode: boolean = false;
  142. autoModeInterval: number = 1 // 自动模式的间隔时间(秒)
  143. autoModeTimer: number = 0 // 自动模式计时器
  144. //网格列表管理列表
  145. gridList: GridData[][] = [];
  146. //砖块列表
  147. bricksList: BrickData[] = [];
  148. //网格颜色列表
  149. gridColorList: GridData[] = [];
  150. brickConfig: { bricks?: any } = {} //方块配置
  151. editingFlag = false //编辑状态
  152. editingData: EditingData = {
  153. brickData: null,
  154. gridList: [],
  155. }
  156. //旋转标记
  157. rotateFlag = false
  158. rotateBrickData: BrickData | null = null;
  159. // 网格相关
  160. private grid: CellState[][] = []; //数组管理网格状态
  161. private gridBlocks: (BlockItemView | null)[][] = []; // 存储网格中的方块脚本引用
  162. private gridCells: Node[][] = [];
  163. // 方块数据保存数组,生成后就保存起来
  164. private brickList: BrickData[] = [];
  165. // 添加新的属性来跟踪是否需要重置消除计数
  166. private shouldResetEliminateCount: boolean = true;
  167. private consecutiveEliminations: boolean = false;
  168. /** 视图层逻辑代码分离演示 */
  169. async start() {
  170. // const entity = this.ent as ecs.Entity; // ecs.Entity 可转为当前模块的具体实体对象
  171. this.setButton();
  172. this.initComponents();
  173. this.initButtonState();
  174. await this.loadConfig();
  175. this.initGrid();
  176. this.initData();
  177. this.addEventList();
  178. }
  179. addEventList() {
  180. oops.message.on(GameEvent.RestartGame, this.restartGame, this);
  181. // oops.message.on(GameEvent.Resurrection, this.resurrection, this);
  182. }
  183. //增加一个新人新手引导
  184. private addNewPlayerGuide() {
  185. // 获取当前引导步骤
  186. // const currentStep = this.getTutorialStep();
  187. }
  188. private initComponents() {
  189. // this.winthdrawNode = this.node.getChildByPath("Scene/Top/btn_withdraw")!;
  190. // this.awardNode = this.node.getChildByPath("Scene/Top/btn_award")!;
  191. const toggle = this.node.getChildByPath("Scene/Bottom/btn_auto/auto_Toggle/Off")!;
  192. this.autoOnToggle = toggle.getComponent(Toggle)!;
  193. this.lab_speed = this.node.getChildByPath("Scene/Bottom/btn_double/lab_time")!.uiLabel;
  194. this.lab_speed.string = "二倍速"
  195. // this.brickNode.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  196. // const touch = event.touch;
  197. // console.log("iiiiii", touch)
  198. // }, this);
  199. // this.brickNode.on(Node.EventType.TOUCH_MOVE, () => {
  200. // console.log("22222")
  201. // }, this);
  202. // this.brickNode.on(Node.EventType.TOUCH_END, () => {
  203. // console.log("333333")
  204. // }, this);
  205. }
  206. //初始化网格
  207. private initGrid() {
  208. // 清理现有网格
  209. this.clearExistingGrids();
  210. // 生成网格矩阵
  211. this.createGridMatrix();
  212. }
  213. //初始化按钮状态
  214. private initButtonState() {
  215. //自动按钮默认关闭
  216. if (this.autoOnToggle) {
  217. console.log("自动按钮状态:", this.autoOnToggle.isChecked);
  218. this.autoOnToggle.isChecked = true;
  219. }
  220. }
  221. //初始化数据
  222. private initData() {
  223. this.gameMode = GameMode.MANUAL;
  224. this.score = 0;
  225. this.money = 0;
  226. this.cash = 0;
  227. this.totalNum = 0;
  228. this.shouldResetEliminateCount = true;
  229. this.consecutiveEliminations = false;
  230. this.lab_score.string = this.score.toString();
  231. this.amountLb.string = this.money.toString();
  232. this.awardLb.string = this.cash.toString();
  233. }
  234. //初始化网格
  235. private async loadConfig() {
  236. let json_name: string = "gui/eliminate/config/GridConfig";
  237. return new Promise<void>((resolve, reject) => {
  238. oops.res.load(json_name, JsonAsset, (err: Error | null, res: any) => {
  239. if (res) {
  240. this.brickConfig = res.json;
  241. resolve();
  242. } else {
  243. console.log("JSON数据加载失,请检查文件");
  244. reject(err);
  245. }
  246. });
  247. });
  248. }
  249. /**
  250. * @description: 清理现有的网格数据
  251. * @return {*}
  252. */
  253. private clearExistingGrids(): void {
  254. this.gridList = [];
  255. if (this.gridNode) {
  256. this.gridNode.children.forEach(node => node.destroy());
  257. }
  258. }
  259. /**
  260. * @description: 设置网格容器大小
  261. * @return {*}
  262. */
  263. private createGridMatrix(): void {
  264. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  265. const currentRow: GridData[] = [];
  266. this.gridList.push(currentRow);
  267. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  268. const gridData = this.createGridData(rowIndex, columnIndex);
  269. currentRow.push(gridData);
  270. this.createGridNode(gridData);
  271. }
  272. }
  273. // 初始化格子状态
  274. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  275. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  276. this.gridList[rowIndex][columnIndex].status = CellState.EMPTY
  277. this.generateGrid(this.gridList[rowIndex][columnIndex])
  278. }
  279. }
  280. // 初始化方块
  281. if (this.brickNode) {
  282. if (this.brickNode) {
  283. this.brickNode.children.forEach(node => { node.destroy() });
  284. }
  285. }
  286. this.bricksList.length = 0
  287. for (let i = 1; i <= this.brickNum; i++) {
  288. this.addBrick(i)
  289. }
  290. // 清除旋转数据
  291. if (this.rotateNode) {
  292. this.rotateNode.children.forEach(node => { node.destroy() })
  293. }
  294. }
  295. /**
  296. * @description: 创建格子数据
  297. * @param {number} row
  298. * @param {number} column
  299. * @return {*}
  300. */
  301. private createGridData(row: number, column: number): GridData {
  302. return {
  303. name: `Grid-${row}-${column}`,
  304. status: CellState.EMPTY,
  305. gridNode: null,
  306. row: row,
  307. col: column,
  308. gridColorKey: null,
  309. type: 0
  310. };
  311. }
  312. /**
  313. * @description: 创建网格Node
  314. * @param {GridData} gridData
  315. * @return {*}
  316. */
  317. private createGridNode(gridData: GridData): void {
  318. const gridNode = new Node(gridData.name);
  319. if (this.gridNode) {
  320. this.gridNode.addChild(gridNode);
  321. }
  322. gridData.gridNode = gridNode;
  323. // 设置网格大小
  324. gridNode.addComponent(UITransform).setContentSize(this.itemSize, this.itemSize);
  325. }
  326. /**
  327. * 生成或更新网格
  328. * @param gridData 网格数据
  329. */
  330. private generateGrid(gridData: GridData) {
  331. if (!gridData || !gridData.gridNode) {
  332. console.warn('无效的网格数据');
  333. return;
  334. }
  335. // 清理现有子节点
  336. this.clearGridChildren(gridData.gridNode);
  337. // 获取对应的预制体
  338. const prefab = this.getGridPrefab(gridData);
  339. if (!prefab) {
  340. console.warn('无法获取网格预制体');
  341. return;
  342. }
  343. // 创建并配置新节点
  344. const node = this.createNewGridNode(prefab, gridData);
  345. // 设置节点属性
  346. this.setupGridNode(node, gridData);
  347. }
  348. /**
  349. * 获取对应状态的预制体
  350. */
  351. private getGridPrefab(gridData: GridData): Prefab {
  352. if (gridData.status === CellState.EMPTY) {
  353. if (this.itemPrefabs[0]) {
  354. return this.itemPrefabs[0];
  355. } else {
  356. throw new Error('Grid prefab is not loaded');
  357. }
  358. }
  359. if (gridData.status === CellState.FILLED && gridData.gridColorKey) {
  360. console.log("gridData.type>>>>>", gridData.type)
  361. const type = gridData.type;
  362. return this.itemPrefabs[type];
  363. }
  364. throw new Error('Invalid grid status or missing gridColorKey');
  365. }
  366. /**
  367. * 创建网格节点
  368. */
  369. private createNewGridNode(prefab: Prefab, gridData: GridData): Node {
  370. const node = instantiate(prefab);
  371. if (gridData && gridData.gridNode) {
  372. gridData.gridNode.addChild(node);
  373. return node;
  374. }
  375. return node
  376. }
  377. /**
  378. * 设置网格节点的属性
  379. */
  380. private setupGridNode(node: Node, gridData: GridData): void {
  381. // 设置未使用状态的颜色
  382. if (gridData.status === CellState.EMPTY) {
  383. const sprite = node.getComponent(Sprite);
  384. if (sprite) {
  385. sprite.color = this.notUseColor;
  386. }
  387. }
  388. // 设置节点大小
  389. const transform = node.getComponent(UITransform);
  390. if (transform) {
  391. transform.setContentSize(
  392. this.itemSize,
  393. this.itemSize
  394. );
  395. }
  396. // 设置位置
  397. node.setPosition(Vec3.ZERO);
  398. }
  399. addBrick(index: number) {
  400. //随机名字
  401. const brickKey = Object.keys(this.brickConfig['bricks'])[randomRangeInt(0, Object.keys(this.brickConfig['bricks']).length)]
  402. // // console.log("brickKey>>>>>", brickKey)
  403. // //随机颜色-一个颜色出来
  404. // const gridColorKey = Object.keys(this.brickConfig['GridType'])[randomRangeInt(0, Object.keys(this.brickConfig['GridType']).length)]
  405. // // console.log("gridColorKey>>>>>", gridColorKey)
  406. // //随机配置-通过名字拿到那个配置
  407. const brickConfig = this.brickConfig['bricks'][brickKey];
  408. // console.log("brickConfig>>>>>", brickConfig)
  409. const randomIndex = RandomManager.instance.getRandomInt(1, 5, 2);
  410. console.log("随机颜色>>>>>", randomIndex)
  411. // 生成方块
  412. const brickData: BrickData = {
  413. index,
  414. brickKey: brickKey,
  415. rotateFlag: brickConfig['rotateFlag'],
  416. gridConfig: brickConfig['gridConfig'],
  417. deg: 0,
  418. brickNode: null,
  419. gridColorKey: randomIndex.toString(),
  420. brickInitPos: new Vec3(),
  421. rotateTag: false,
  422. type: randomIndex,
  423. }
  424. this.bricksList.push(brickData)
  425. // 生成方块
  426. const brickNode = this.generateBrick(brickKey, randomIndex);
  427. if (this.brickNode) {
  428. this.brickNode.addChild(brickNode)
  429. }
  430. brickData.brickNode = brickNode;
  431. // 方块间隔
  432. //这里修改一下,分别放到3个Node中,然后
  433. let offset = 220
  434. if (this.brickNum % 2 === 1) {
  435. const middleNum = Math.floor(this.brickNum / 2) + 1
  436. if (index < middleNum) {
  437. offset = - offset
  438. }
  439. else if (index === middleNum) {
  440. offset = 0
  441. }
  442. }
  443. if (brickData && brickData.brickNode) {
  444. brickData.brickNode.setPosition(offset, 0)
  445. brickData.brickNode.scale_x = 0.6;
  446. brickData.brickNode.scale_y = 0.6;
  447. brickData.brickInitPos = brickData.brickNode.getWorldPosition()
  448. }
  449. this.brickAddEvent(brickData);
  450. }
  451. // 每个item生成独立的方块节点
  452. generateBrick(brickKey: string, randomIndex: number) {
  453. const brickConfig = this.brickConfig['bricks'][brickKey]
  454. let rowMin = 0
  455. let rowMax = 0
  456. let columnMin = 0
  457. let columnMax = 0
  458. brickConfig['gridConfig'].forEach((gridConfigData: GridConfigData) => {
  459. if (gridConfigData.row < rowMin) {
  460. rowMin = gridConfigData.row
  461. }
  462. else if (gridConfigData.row > rowMax) {
  463. rowMax = gridConfigData.row
  464. }
  465. if (gridConfigData.column < columnMin) {
  466. columnMin = gridConfigData.column
  467. }
  468. else if (gridConfigData.column > columnMax) {
  469. columnMax = gridConfigData.column
  470. }
  471. })
  472. const rowNum = (rowMax - rowMin + 1)
  473. const columnNum = (columnMax - columnMin + 1)
  474. // 生成独立的方块节点
  475. const brickNode = new Node()
  476. brickNode.name = brickKey
  477. // 设置方块大小
  478. const transformCom: UITransform = brickNode.addComponent(UITransform)
  479. transformCom.setContentSize(
  480. this.itemSize * columnNum,
  481. this.itemSize * rowNum
  482. )
  483. transformCom.setAnchorPoint(0.5, 0.5)
  484. // 设置方块位置
  485. const gridPrefab = this.itemPrefabs[randomIndex]
  486. //生成对应的配置方块设置地址
  487. brickConfig['gridConfig'].forEach((gridConfigData: GridConfigData) => {
  488. const gridNode = new Node()
  489. gridNode.name = 'grid'
  490. brickNode.addChild(gridNode)
  491. gridNode.addComponent(UITransform).setContentSize(this.itemSize, this.itemSize)
  492. const gridWidget: Widget = gridNode.addComponent(Widget)
  493. gridWidget.isAlignLeft = true
  494. gridWidget.left = this.itemSize * gridConfigData.column - this.itemSize * columnMin
  495. gridWidget.isAlignBottom = true
  496. gridWidget.bottom = this.itemSize * gridConfigData.row - this.itemSize * rowMin
  497. const node = instantiate(gridPrefab)
  498. gridNode.addChild(node)
  499. const uiTransform = node.getComponent(UITransform);
  500. if (uiTransform) {
  501. uiTransform.setContentSize(
  502. this.itemSize,
  503. this.itemSize,
  504. )
  505. }
  506. node.setPosition(Vec3.ZERO)
  507. node.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  508. event.preventSwallow = true;
  509. }, this);
  510. node.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  511. event.preventSwallow = true;
  512. }, this);
  513. node.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
  514. event.preventSwallow = true;
  515. }, this);
  516. })
  517. return brickNode
  518. }
  519. touchStartLocation = new Vec2()
  520. touchStartFlag = false
  521. brickAddEvent(brickData: BrickData) {
  522. const brickNode = brickData.brickNode
  523. if (!brickNode) {
  524. console.error("brickNode为空,无法添加事件");
  525. return
  526. }
  527. // 确保节点可交互
  528. brickNode.active = true;
  529. // 移除可能存在的旧事件监听器
  530. brickNode.off(Node.EventType.TOUCH_START);
  531. brickNode.off(Node.EventType.TOUCH_MOVE);
  532. brickNode.off(Node.EventType.TOUCH_END);
  533. brickNode.off(Node.EventType.TOUCH_CANCEL);
  534. // 记录初始位置和状态
  535. let startPos = new Vec3();
  536. let originalParent: Node | null = null;
  537. let isDragging = false;
  538. // 触摸开始事件
  539. brickNode.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
  540. // 如果正在编辑其他方块,则忽略
  541. if (this.editingFlag) return;
  542. // 设置编辑状态
  543. this.editingFlag = true;
  544. isDragging = true;
  545. this.touchStartFlag = true;
  546. // 清空编辑中的数据
  547. this.editingData.brickData = null;
  548. this.editingData.gridList.length = 0;
  549. // 记录触摸开始位置和方块原始信息
  550. this.touchStartLocation.set(event.getUILocation());
  551. originalParent = brickNode.parent;
  552. startPos = brickNode.getWorldPosition().clone();
  553. // 将方块移到移动层并放大
  554. brickNode.setParent(this.moveNode);
  555. brickNode.setWorldPosition(startPos);
  556. tween(brickNode)
  557. .to(0.2, { scale: new Vec3(1, 1, 1) })
  558. .start();
  559. // 从方块列表中移除该方块
  560. const index = this.bricksList.findIndex(item => item === brickData);
  561. if (index > -1) {
  562. this.editingData.brickData = this.bricksList.splice(index, 1)[0];
  563. } else {
  564. console.error("未找到方块数据:", brickData);
  565. this.editingData.brickData = brickData;
  566. }
  567. // 清除旋转数据
  568. if (this.rotateFlag && this.rotateBrickData !== this.editingData.brickData) {
  569. this.rotateFlag = false;
  570. this.rotateBrickData = null;
  571. if (this.rotateNode) {
  572. this.rotateNode.children.forEach(node => { node.destroy() });
  573. }
  574. }
  575. }, this);
  576. // 触摸移动事件
  577. brickNode.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
  578. if (!isDragging || !this.editingData.brickData) return;
  579. // 清除旋转数据
  580. if (event.getUILocation().subtract(this.touchStartLocation).length() >= this.rotateFaultTolerant) {
  581. this.rotateFlag = false;
  582. this.rotateBrickData = null;
  583. if (this.rotateNode) {
  584. this.rotateNode.children.forEach(node => { node.destroy() });
  585. }
  586. }
  587. // 恢复所有网格颜色
  588. this.gridColorRecovery();
  589. // 移动方块
  590. brickNode.setWorldPosition(brickNode.getWorldPosition().add(event.getUIDelta().toVec3()));
  591. // 重置编辑中的网格数据
  592. this.editingData.gridList.length = 0;
  593. // 检查方块每个子网格是否与游戏网格重叠
  594. const tempGridList: GridData[] = [];
  595. let allEmptyGrids: boolean = true; // 标记是否所有网格都为空
  596. brickNode.children.forEach((childNode) => {
  597. const childWorldPos = childNode.getWorldPosition();
  598. // 查找与子网格重叠的游戏网格
  599. let matchedGrid: GridData | null = null;
  600. for (let row = 0; row < this.rows && !matchedGrid; row++) {
  601. for (let col = 0; col < this.cols && !matchedGrid; col++) {
  602. const grid = this.gridList[row][col];
  603. if (!grid || !grid.gridNode) continue;
  604. const gridPos = grid.gridNode.getWorldPosition();
  605. if (Vec3.distance(gridPos, childWorldPos) <= (this.itemSize / 2)) {
  606. matchedGrid = grid;
  607. }
  608. }
  609. }
  610. if (matchedGrid) {
  611. tempGridList.push(matchedGrid);
  612. // 检查是否有非空网格
  613. if (matchedGrid.status !== CellState.EMPTY) {
  614. allEmptyGrids = false;
  615. }
  616. }
  617. });
  618. // 检查是否所有子网格都有对应的游戏网格,且都是空的
  619. let canPlace = tempGridList.length === brickData.gridConfig.length && allEmptyGrids;
  620. // 更新编辑中的网格列表
  621. if (canPlace) {
  622. this.editingData.gridList = [...tempGridList];
  623. }
  624. // 更新网格颜色提示 - 只改变空网格的颜色
  625. tempGridList.forEach(grid => {
  626. // 只处理空网格
  627. if (grid.status === CellState.EMPTY) {
  628. if (grid.gridNode && grid.gridNode.children[0]) {
  629. const sprite = grid.gridNode.children[0].getComponent(Sprite);
  630. if (sprite) {
  631. sprite.color = canPlace ? this.usableColor : this.unavailableColor;
  632. }
  633. }
  634. // 用于后续恢复颜色
  635. this.gridColorList.push(grid);
  636. }
  637. });
  638. }, this);
  639. // 触摸结束或取消事件
  640. const touchEndHandler = (event: EventTouch) => {
  641. if (!isDragging) return;
  642. isDragging = false;
  643. this.touchStartFlag = false;
  644. // 恢复网格颜色
  645. this.gridColorRecovery();
  646. // 防止如放回方块回弹动画时,已经触摸在另一个方块上面
  647. if (this.editingData.brickData !== brickData) return;
  648. // 检查是否可以放置
  649. if (this.editingData.brickData && this.editingData.gridList.length > 0) {
  650. // 计算放置的格子数量
  651. const placedGridCount = this.editingData.gridList.length;
  652. // 获取中心位置用于显示分数
  653. let centerPos = new Vec3(0, 0, 0);
  654. if (this.editingData.gridList.length > 0 && this.editingData.gridList[0].gridNode) {
  655. centerPos = this.editingData.gridList[0].gridNode.getWorldPosition().clone();
  656. if (this.editingData.gridList.length > 1) {
  657. // 计算所有格子的平均位置作为中心点
  658. for (let i = 1; i < this.editingData.gridList.length; i++) {
  659. const gridNode = this.editingData.gridList[i].gridNode;
  660. if (gridNode) {
  661. centerPos.add(gridNode.getWorldPosition());
  662. }
  663. }
  664. const validGridCount = this.editingData.gridList.filter(grid => grid.gridNode).length;
  665. centerPos.x /= validGridCount;
  666. centerPos.y /= validGridCount;
  667. }
  668. }
  669. // 放置方块到网格
  670. this.editingData.gridList.forEach(grid => {
  671. grid.status = CellState.FILLED;
  672. grid.gridColorKey = this.editingData.brickData!.gridColorKey;
  673. grid.type = this.editingData.brickData!.type;
  674. this.generateGrid(grid);
  675. });
  676. // 显示放置得分动画(显示一次,包含总格子数)
  677. this.showScoreAnimation(centerPos, placedGridCount);
  678. // 标记需要重置消除计数器
  679. this.shouldResetEliminateCount = true;
  680. this.consecutiveEliminations = true;
  681. // 销毁方块节点
  682. brickNode.destroy();
  683. // 添加新方块到待选区
  684. this.addBrick(this.editingData.brickData.index);
  685. // 检查消除
  686. this.scheduleOnce(() => {
  687. this.gridEliminate().then((hasElimination) => {
  688. // 如果没有消除,确保下次消除会重置计数
  689. if (!hasElimination) {
  690. this.shouldResetEliminateCount = true;
  691. }
  692. // 检查游戏是否结束
  693. this.prompt(false).then(canContinue => {
  694. if (!canContinue) {
  695. this.gameOver();
  696. }
  697. this.editingFlag = false;
  698. });
  699. });
  700. }, 0.1);
  701. } else if (this.rotateFlag) {
  702. // 旋转方块
  703. const brickData = this.editingData.brickData;
  704. this.brickGridRotate(brickData);
  705. // 方块放回待选区
  706. this.bricksList.push(brickData);
  707. if (this.brickNode && brickData.brickNode) {
  708. this.brickNode.addChild(brickData.brickNode);
  709. tween(brickData.brickNode)
  710. .to(0.2, {
  711. worldPosition: brickData.brickInitPos,
  712. scale: new Vec3(0.6, 0.6, 0.6)
  713. })
  714. .start();
  715. }
  716. this.editingFlag = false;
  717. } else {
  718. // 无法放置,将方块返回原位置
  719. const brickData = this.editingData.brickData;
  720. if (brickData) {
  721. this.bricksList.push(brickData);
  722. // 添加回弹动画
  723. tween(brickNode)
  724. .to(0.2, {
  725. worldPosition: brickData.brickInitPos,
  726. scale: new Vec3(0.6, 0.6, 0.6)
  727. })
  728. .call(() => {
  729. if (originalParent) {
  730. brickNode.setParent(originalParent);
  731. brickNode.setWorldPosition(brickData.brickInitPos);
  732. }
  733. this.editingFlag = false;
  734. })
  735. .start();
  736. } else {
  737. this.editingFlag = false;
  738. }
  739. }
  740. // 检查是否需要处理旋转(短距离移动视为点击)
  741. if (!this.rotateFlag &&
  742. this.editingData.brickData &&
  743. this.editingData.brickData.rotateFlag &&
  744. event.getUILocation().subtract(this.touchStartLocation).length() < this.rotateFaultTolerant) {
  745. this.rotateFlag = true;
  746. this.rotateBrickData = this.editingData.brickData;
  747. // 显示旋转提示
  748. if (this.rotatePrefab && this.rotateNode && brickNode) {
  749. const rotateIndicator = instantiate(this.rotatePrefab);
  750. this.rotateNode.addChild(rotateIndicator);
  751. rotateIndicator.setWorldPosition(brickNode.getWorldPosition());
  752. }
  753. }
  754. };
  755. brickNode.on(Node.EventType.TOUCH_END, touchEndHandler, this);
  756. brickNode.on(Node.EventType.TOUCH_CANCEL, touchEndHandler, this);
  757. }
  758. //格子颜色恢复
  759. gridColorRecovery() {
  760. while (this.gridColorList.length > 0) {
  761. const gridData = this.gridColorList.pop();
  762. if (gridData) {
  763. if (gridData.status === CellState.EMPTY) {
  764. if (gridData.gridNode) {
  765. gridData.gridNode.children[0].getComponent(Sprite)!.color = this.notUseColor;
  766. }
  767. }
  768. }
  769. }
  770. }
  771. brickGridRotate(brickData: BrickData) {
  772. const next = this.nextGridRotate(brickData.gridConfig, brickData.deg)
  773. brickData.deg = next.deg
  774. brickData.gridConfig = next.gridConfig;
  775. if (brickData.brickNode) {
  776. tween(brickData.brickNode).to(0.1, { angle: next.deg }).start();
  777. }
  778. // this.audioManager.playRotate()
  779. }
  780. //下一个旋转
  781. nextGridRotate(gridConfig: GridConfigData[], deg: number) {
  782. const newGridConfig: GridConfigData[] = []
  783. // 顺时针旋转
  784. let newDeg = deg - 90
  785. gridConfig.forEach((gridConfigData) => {
  786. // 例如(1,2) => (-2,1),可以画图分析
  787. newGridConfig.push({
  788. row: -gridConfigData.column,
  789. column: gridConfigData.row
  790. })
  791. })
  792. return { gridConfig: newGridConfig, deg: newDeg }
  793. }
  794. // 显示分数增加动画
  795. showScoreAnimation(position: Vec3, score: number) {
  796. if (!this.lab_addScore) return;
  797. // 复制得分Label
  798. const scoreLabel = instantiate(this.lab_addScore.node);
  799. scoreLabel.active = true;
  800. // 设置文本和位置
  801. const label = scoreLabel.getComponent(Label);
  802. if (label) {
  803. label.string = `+${score}`;
  804. }
  805. // 添加到场景中
  806. this.node.addChild(scoreLabel);
  807. scoreLabel.setWorldPosition(position);
  808. // 创建动画效果
  809. tween(scoreLabel)
  810. .to(0.5, {
  811. position: new Vec3(scoreLabel.position.x, scoreLabel.position.y + 50, 0),
  812. scale: new Vec3(1.2, 1.2, 1.2)
  813. })
  814. .to(0.3, { opacity: 0 })
  815. .call(() => {
  816. scoreLabel.destroy();
  817. })
  818. .start();
  819. // 更新总分
  820. this.score += score;
  821. this.lab_score.string = this.score.toString();
  822. }
  823. // 显示消除次数动画
  824. showEliminateCountAnimation(yPosition: number) {
  825. if (!this.lab_total) return;
  826. // 如果需要重置计数器,先将计数归零
  827. if (this.shouldResetEliminateCount) {
  828. this.totalNum = 0;
  829. this.shouldResetEliminateCount = false;
  830. }
  831. // 增加累计消除次数
  832. this.totalNum++;
  833. // 复制总次数Label
  834. const totalLabel = instantiate(this.lab_total.node);
  835. totalLabel.active = true;
  836. // 设置文本
  837. const label = totalLabel.getComponent(Label);
  838. if (label) {
  839. label.string = `Combo${this.totalNum}`;
  840. }
  841. // 添加到场景中
  842. this.node.addChild(totalLabel);
  843. // 计算网格区域的X轴中心位置,Y轴使用传入的消除行位置
  844. const centerPos = new Vec3();
  845. if (this.gridNode) {
  846. // 获取网格区域的X轴中心
  847. const worldPos = this.gridNode.getWorldPosition();
  848. centerPos.set(worldPos.x, yPosition, worldPos.z);
  849. }
  850. totalLabel.setWorldPosition(centerPos);
  851. // 创建动画效果
  852. tween(totalLabel)
  853. .to(0.3, {
  854. scale: new Vec3(1.5, 1.5, 1.5),
  855. opacity: 255
  856. })
  857. .delay(0.5) // 停留更长时间
  858. .to(0.4, {
  859. scale: new Vec3(1.2, 1.2, 1.2),
  860. position: new Vec3(totalLabel.position.x, totalLabel.position.y + 50, 0),
  861. opacity: 0
  862. })
  863. .call(() => {
  864. totalLabel.destroy();
  865. })
  866. .start();
  867. }
  868. // 修改 gridEliminate 方法来显示消除次数
  869. gridEliminate() {
  870. return new Promise<boolean>((resolve, reject) => {
  871. const d = this.gridEliminateCheck(this.gridList)
  872. const gridEliminateList = d.gridEliminateList
  873. const eliminateRowNum = d.eliminateRowNum
  874. const eliminateColumnNum = d.eliminateColumnNum
  875. if (gridEliminateList.length < 1) {
  876. // 没有发生消除
  877. this.shouldResetEliminateCount = true; // 下一次消除需要重置计数
  878. this.consecutiveEliminations = false; // 不是连续消除
  879. resolve(false);
  880. return;
  881. }
  882. // 如果有消除,计算消除行的平均Y轴位置
  883. if (gridEliminateList.length > 0) {
  884. // 计算所有被消除格子的平均Y轴位置
  885. let totalY = 0;
  886. let validGrids = 0;
  887. for (const grid of gridEliminateList) {
  888. if (grid.gridNode) {
  889. totalY += grid.gridNode.getWorldPosition().y;
  890. validGrids++;
  891. }
  892. }
  893. // 计算平均Y位置
  894. const avgY = validGrids > 0 ? totalY / validGrids : 0;
  895. // 标记为连续消除
  896. this.consecutiveEliminations = true;
  897. // 显示消除次数动画,传入Y轴位置
  898. this.showEliminateCountAnimation(avgY);
  899. }
  900. gridEliminateList.forEach((gridData) => {
  901. if (gridData.gridNode?.children[0]) {
  902. const startPos = gridData.gridNode.getWorldPosition();
  903. tween(gridData.gridNode.children[0])
  904. .to(0.2, { scale: new Vec3(0.5, 0.5) })
  905. .call(() => {
  906. gridData.status = CellState.EMPTY
  907. this.generateGrid(gridData)
  908. })
  909. .start()
  910. if (this.coinPrefab && this.amountLb?.node) {
  911. this.createCoinFlyAnimation(
  912. this.coinPrefab,
  913. startPos,
  914. this.amountLb.node.getWorldPosition(),
  915. 5
  916. );
  917. }
  918. //增加红包
  919. this.createCoinFlyAnimation(
  920. this.redPacketPrefab,
  921. startPos,
  922. this.awardLb.node.getWorldPosition(),
  923. 5
  924. );
  925. }
  926. })
  927. this.scheduleOnce(() => {
  928. let score = 0
  929. for (let i = 1; i <= eliminateRowNum; i++) {
  930. score += this.cols * i
  931. }
  932. for (let i = 1; i <= eliminateColumnNum; i++) {
  933. score += this.rows * i
  934. }
  935. this.score += score
  936. this.lab_score.string = this.score.toString();
  937. const lastGrid = gridEliminateList[gridEliminateList.length - 1];
  938. if (lastGrid?.gridNode && this.coinPrefab && this.amountLb?.node) {
  939. const lastPos = lastGrid.gridNode.getWorldPosition();
  940. this.createCoinFlyAnimation(
  941. this.coinPrefab,
  942. lastPos,
  943. this.amountLb.node.getWorldPosition(),
  944. score
  945. );
  946. }
  947. // 告诉调用者有消除发生
  948. resolve(true)
  949. // 检查是否需要继续消除
  950. this.scheduleOnce(() => {
  951. // 递归调用,检查并处理连锁消除
  952. this.gridEliminate().then(() => {
  953. // 连锁消除结束,不做额外处理
  954. });
  955. }, 0.2);
  956. }, 0.2)
  957. })
  958. }
  959. gridEliminateCheck(gridList: GridData[][]) {
  960. const gridEliminateList: GridData[] = []
  961. let eliminateRowNum = 0
  962. let eliminateColumnNum = 0
  963. // 行检查
  964. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  965. const rowData = gridList[rowIndex]
  966. if (rowData.every(gridData => gridData.status === CellState.FILLED)) {
  967. rowData.forEach(gridData => {
  968. if (gridEliminateList.findIndex(data => data === gridData) < 0) {
  969. gridEliminateList.push(gridData)
  970. }
  971. })
  972. eliminateRowNum += 1
  973. }
  974. }
  975. // 列检查
  976. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  977. if (gridList.every(rowData => rowData[columnIndex].status === CellState.FILLED)) {
  978. gridList.forEach(rowData => {
  979. const gridData = rowData[columnIndex]
  980. if (gridEliminateList.findIndex(data => data === gridData) < 0) {
  981. gridEliminateList.push(gridData)
  982. }
  983. })
  984. eliminateColumnNum += 1
  985. }
  986. }
  987. return {
  988. gridEliminateList,
  989. eliminateRowNum,
  990. eliminateColumnNum,
  991. }
  992. }
  993. // 修改 createCoinFlyAnimation 方法为公共方法,扩展参数列表
  994. public createCoinFlyAnimation(prefab: Prefab, startPos: Vec3, endPos: Vec3, score: number, parent: Node = this.node) {
  995. const coinNum = Math.min(Math.max(Math.floor(score / 10), 1), 10);
  996. for (let i = 0; i < coinNum; i++) {
  997. if (!prefab) {
  998. console.warn('金币预制体未加载');
  999. return;
  1000. }
  1001. const coin = instantiate(prefab);
  1002. parent.addChild(coin);
  1003. const randomOffset = new Vec3(
  1004. (Math.random() - 0.5) * 50,
  1005. (Math.random() - 0.5) * 50,
  1006. 0
  1007. );
  1008. const startPosition = startPos.clone().add(randomOffset);
  1009. coin.setWorldPosition(startPosition);
  1010. const controlPoint = new Vec3(
  1011. (startPosition.x + endPos.x) / 2 + (Math.random() - 0.5) * 100,
  1012. (startPosition.y + endPos.y) / 2 + Math.random() * 100,
  1013. 0
  1014. );
  1015. this.scheduleOnce(() => {
  1016. tween(coin)
  1017. .parallel(
  1018. tween().to(0.2, { scale: new Vec3(1.2, 1.2, 1.2) })
  1019. .to(0.1, { scale: new Vec3(1, 1, 1) }),
  1020. tween().by(0.3, { angle: 360 })
  1021. )
  1022. .start();
  1023. const bezierCurve = (target: Node | undefined, ratio?: number) => {
  1024. if (!target || ratio === undefined) return;
  1025. const t = ratio;
  1026. const pos = new Vec3();
  1027. Vec3.multiplyScalar(pos, startPosition, (1 - t) * (1 - t));
  1028. Vec3.scaleAndAdd(pos, pos, controlPoint, 2 * (1 - t) * t);
  1029. Vec3.scaleAndAdd(pos, pos, endPos, t * t);
  1030. target.setWorldPosition(pos);
  1031. };
  1032. tween(coin)
  1033. .to(0.8, {
  1034. worldPosition: endPos
  1035. }, {
  1036. easing: 'cubicIn',
  1037. onUpdate: bezierCurve
  1038. })
  1039. .call(() => {
  1040. tween(coin)
  1041. .to(0.1, { scale: new Vec3(0.7, 0.7, 0.7) })
  1042. .call(() => {
  1043. coin.destroy();
  1044. })
  1045. .start();
  1046. })
  1047. .start();
  1048. //需要有个金币飘的icon和文字动画,在两边,然后最后展示最新的数字
  1049. }, i * 0.1);
  1050. }
  1051. }
  1052. // 提示
  1053. prompt(tipFlag = true) {
  1054. return new Promise((resolve, reject) => {
  1055. const gridPromptList: GridData[] = []
  1056. let moveFlag = false
  1057. // 找方块可消除位置
  1058. for (let rowIndex = 0; rowIndex < this.rows && !moveFlag; rowIndex++) {
  1059. for (let columnIndex = 0; columnIndex < this.cols && !moveFlag; columnIndex++) {
  1060. const gridData = this.gridList[rowIndex][columnIndex]
  1061. if (gridData.status !== CellState.EMPTY) continue
  1062. // 方块不旋转检测是否能放
  1063. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1064. const brickData = this.bricksList[brickI]
  1065. if (this.moveIf(rowIndex, columnIndex, brickData.gridConfig)) {
  1066. // 复制整体网格,以方块设置网格状态
  1067. const gridList = this.copyGridList()
  1068. brickData.gridConfig.forEach((gridConfigData) => {
  1069. gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = CellState.FILLED
  1070. })
  1071. // 检查复制的整体网格是否有可消除
  1072. if (this.gridEliminateCheck(gridList).gridEliminateList.length > 0) {
  1073. moveFlag = true
  1074. brickData.gridConfig.forEach((gridConfigData) => {
  1075. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1076. })
  1077. }
  1078. }
  1079. }
  1080. // 方块旋转检测是否能放
  1081. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1082. const brickData = this.bricksList[brickI]
  1083. if (!brickData.rotateFlag) continue
  1084. let gridConfig = brickData.gridConfig
  1085. let deg = brickData.deg
  1086. // 获得旋转的方块网格配置
  1087. for (let count = 1; count <= 3 && !moveFlag; count++) {
  1088. const next = this.nextGridRotate(gridConfig, deg)
  1089. if (this.moveIf(rowIndex, columnIndex, next.gridConfig)) {
  1090. // 复制整体网格,以方块设置网格状态
  1091. const gridList = this.copyGridList()
  1092. next.gridConfig.forEach((gridConfigData) => {
  1093. gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = CellState.FILLED
  1094. })
  1095. // 检查复制的整体网格是否有可消除
  1096. if (this.gridEliminateCheck(gridList).gridEliminateList.length > 0) {
  1097. moveFlag = true
  1098. next.gridConfig.forEach((gridConfigData) => {
  1099. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1100. })
  1101. }
  1102. }
  1103. gridConfig = next.gridConfig
  1104. deg = next.deg
  1105. }
  1106. }
  1107. }
  1108. }
  1109. // 找方块可放置位置
  1110. for (let rowIndex = 0; rowIndex < this.rows && !moveFlag; rowIndex++) {
  1111. for (let columnIndex = 0; columnIndex < this.cols && !moveFlag; columnIndex++) {
  1112. const gridData = this.gridList[rowIndex][columnIndex]
  1113. if (gridData.status !== CellState.EMPTY) continue
  1114. // 方块不旋转检测是否能放
  1115. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1116. const brickData = this.bricksList[brickI]
  1117. if (this.moveIf(rowIndex, columnIndex, brickData.gridConfig)) {
  1118. moveFlag = true
  1119. brickData.gridConfig.forEach((gridConfigData) => {
  1120. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1121. })
  1122. }
  1123. }
  1124. // 方块旋转检测是否能放
  1125. for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
  1126. const brickData = this.bricksList[brickI]
  1127. if (!brickData.rotateFlag) continue
  1128. let gridConfig = brickData.gridConfig
  1129. let deg = brickData.deg
  1130. for (let count = 1; count <= 3 && !moveFlag; count++) {
  1131. const next = this.nextGridRotate(gridConfig, deg)
  1132. if (this.moveIf(rowIndex, columnIndex, next.gridConfig)) {
  1133. moveFlag = true
  1134. next.gridConfig.forEach((gridConfigData) => {
  1135. gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
  1136. })
  1137. }
  1138. gridConfig = next.gridConfig
  1139. deg = next.deg
  1140. }
  1141. }
  1142. }
  1143. }
  1144. if (gridPromptList.length < 1) {
  1145. resolve(false)
  1146. return
  1147. }
  1148. if (!tipFlag) {
  1149. resolve(true)
  1150. return
  1151. }
  1152. // 提示用户(网格变绿)
  1153. gridPromptList.forEach((gridData) => {
  1154. if (gridData.gridNode && gridData.gridNode.children[0]) {
  1155. const sprite = gridData.gridNode.children[0].getComponent(Sprite);
  1156. if (sprite) {
  1157. sprite.color = this.usableColor;
  1158. }
  1159. }
  1160. // 用于恢复格子
  1161. this.gridColorList.push(gridData)
  1162. })
  1163. resolve(true)
  1164. })
  1165. }
  1166. moveIf(row: number, column: number, gridConfig: GridConfigData[]) {
  1167. let moveFlag = true
  1168. for (let i = 0; i < gridConfig.length; i++) {
  1169. const gridConfigData = gridConfig[i]
  1170. const gridI = row + gridConfigData.row
  1171. const gridJ = column + gridConfigData.column
  1172. // 边界判断
  1173. if (
  1174. gridI < 0 ||
  1175. gridI > this.rows - 1 ||
  1176. gridJ < 0 ||
  1177. gridJ > this.cols - 1
  1178. ) {
  1179. moveFlag = false
  1180. break
  1181. }
  1182. // 已用
  1183. else if (this.gridList[gridI][gridJ].status === CellState.FILLED) {
  1184. moveFlag = false
  1185. break
  1186. }
  1187. }
  1188. return moveFlag
  1189. }
  1190. // 复制整体网格
  1191. copyGridList() {
  1192. const gridList: GridData[][] = []
  1193. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1194. gridList.push([])
  1195. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1196. const gridData = this.gridList[rowIndex][columnIndex]
  1197. gridList[rowIndex].push({
  1198. name: gridData.name,
  1199. status: gridData.status,
  1200. gridNode: null,
  1201. row: gridData.row,
  1202. col: gridData.col,
  1203. gridColorKey: gridData.gridColorKey,
  1204. type: gridData.type,
  1205. })
  1206. }
  1207. }
  1208. return gridList
  1209. }
  1210. gameOver() {
  1211. this.gameState = GameState.GAME_OVER
  1212. this.setGameState(GameState.GAME_OVER)
  1213. console.log("游戏结束")
  1214. oops.gui.open(UIID.GameOver);
  1215. }
  1216. /**
  1217. * 清理网格的子节点
  1218. */
  1219. private clearGridChildren(gridNode: Node): void {
  1220. const children = gridNode.children.slice(); // 创建副本避免遍历时修改问题
  1221. children.forEach(node => node.destroy());
  1222. }
  1223. private setGameState(state: GameState) {
  1224. this.gameState = state;
  1225. switch (state) {
  1226. case GameState.READY:
  1227. break;
  1228. case GameState.PLAYING:
  1229. break;
  1230. case GameState.PAUSED:
  1231. break;
  1232. case GameState.GAME_OVER:
  1233. //打开游戏结束界面
  1234. break;
  1235. }
  1236. }
  1237. // ... 修改 autoPlaceBrick 方法
  1238. async autoPlaceBrick() {
  1239. if (!this.isAutoMode) return;
  1240. if (this.bricksList.length === 0) return
  1241. // 遍历所有方块,找到一个可以放置的方块
  1242. let bestMove = null;
  1243. let selectedBrickIndex = -1;
  1244. for (let i = 0; i < this.bricksList.length; i++) {
  1245. const move = this.findBestPosition(this.bricksList[i]);
  1246. if (move) {
  1247. // 优先选择可以消除的位置
  1248. if (move.score > 0) {
  1249. bestMove = move;
  1250. selectedBrickIndex = i;
  1251. break;
  1252. } else if (bestMove === null) {
  1253. // 如果还没有找到任何可放置的位置,保存这个位置
  1254. bestMove = move;
  1255. selectedBrickIndex = i;
  1256. }
  1257. }
  1258. }
  1259. // 如果所有方块都没有可放置的位置,游戏结束
  1260. if (!bestMove || selectedBrickIndex === -1) {
  1261. console.log('所有方块都没有可放置的位置,游戏结束');
  1262. this.isAutoMode = false;
  1263. if (this._isAutoFunc) {
  1264. this.unschedule(this._isAutoFunc);
  1265. this._isAutoFunc = null;
  1266. }
  1267. this.gameOver();
  1268. return;
  1269. }
  1270. // 获取选中的方块
  1271. const brickData = this.bricksList[selectedBrickIndex];
  1272. // 从列表中移除方块
  1273. this.bricksList.splice(selectedBrickIndex, 1);
  1274. // 保存方块的初始位置(从待选区开始)
  1275. const startPos = brickData.brickInitPos.clone();
  1276. // 设置方块到移动层并确保位置精确
  1277. if (brickData.brickNode) {
  1278. brickData.brickNode.setParent(this.moveNode);
  1279. brickData.brickNode.setWorldPosition(startPos);
  1280. }
  1281. // this.guideNode.active = true;
  1282. // this.guideNode.setWorldPosition(
  1283. // startPos.x,
  1284. // startPos.y + brickData.brickNode.getComponent(UITransform).height / 2,
  1285. // startPos.z
  1286. // );
  1287. // 如果需要旋转,先旋转到正确的角度
  1288. if (brickData.rotateFlag && bestMove.rotation && bestMove.rotation.deg !== brickData.deg) {
  1289. await new Promise<void>((resolve) => {
  1290. if (brickData.brickNode) {
  1291. tween(brickData.brickNode)
  1292. .to(0.2, { angle: bestMove.rotation ? bestMove.rotation.deg : 0 })
  1293. .call(() => {
  1294. if (bestMove.rotation) {
  1295. brickData.gridConfig = bestMove.rotation.gridConfig;
  1296. brickData.deg = bestMove.rotation.deg;
  1297. }
  1298. resolve();
  1299. })
  1300. .start();
  1301. }
  1302. });
  1303. }
  1304. // 获取目标位置,有些目标位置获取有问题需要修改
  1305. const targetGrid = this.gridList[bestMove.position.row][bestMove.position.column];
  1306. if (!targetGrid.gridNode) {
  1307. console.error('targetGrid.gridNode is null');
  1308. return;
  1309. }
  1310. const targetWorldPos = targetGrid.gridNode.getWorldPosition().clone();
  1311. // 创建平滑的移动动画
  1312. await new Promise<void>((resolve) => {
  1313. if (brickData.brickNode) {
  1314. tween(brickData.brickNode)
  1315. .to(0.3, {
  1316. worldPosition: targetWorldPos,
  1317. }, {
  1318. easing: 'cubicOut'
  1319. })
  1320. .call(() => {
  1321. if (brickData.brickNode) {
  1322. brickData.brickNode.setWorldPosition(targetWorldPos);
  1323. // 放置方块
  1324. if (bestMove.rotation) {
  1325. bestMove.rotation.gridConfig.forEach((gridConfigData) => {
  1326. const gridData = this.gridList[bestMove.position.row + gridConfigData.row][bestMove.position.column + gridConfigData.column];
  1327. gridData.status = CellState.FILLED;
  1328. gridData.gridColorKey = brickData.gridColorKey;
  1329. gridData.type = brickData.type;
  1330. this.generateGrid(gridData);
  1331. });
  1332. }
  1333. // 销毁方块
  1334. brickData.brickNode.destroy();
  1335. // 添加新方块
  1336. this.addBrick(brickData.index);
  1337. }
  1338. resolve();
  1339. })
  1340. .start();
  1341. }
  1342. });
  1343. // 检查并执行消除
  1344. await this.gridEliminate();
  1345. // 检查是否还有任何方块可以放置
  1346. let hasValidMove = false;
  1347. for (const brick of this.bricksList) {
  1348. if (this.findBestPosition(brick)) {
  1349. hasValidMove = true;
  1350. break;
  1351. }
  1352. }
  1353. if (!hasValidMove) {
  1354. console.log('没有方块可以放置,游戏结束');
  1355. this.isAutoMode = false;
  1356. if (this._isAutoFunc) {
  1357. this.unschedule(this._isAutoFunc);
  1358. this._isAutoFunc = null;
  1359. }
  1360. this.gameOver();
  1361. }
  1362. }
  1363. // ... 修改 findBestPosition 方法,这个方法有问题,需要修改
  1364. findBestPosition(brickData: BrickData) {
  1365. let bestScore = -1
  1366. let bestPosition = null
  1367. let bestRotation = null
  1368. let fallbackPosition = null
  1369. let fallbackRotation = null
  1370. // 遍历所有可能的位置
  1371. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1372. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1373. // 检查当前位置的所有可能旋转
  1374. let currentGridConfig = brickData.gridConfig
  1375. let currentDeg = brickData.deg
  1376. // 最多旋转4次(0°, 90°, 180°, 270°)
  1377. for (let rotation = 0; rotation < 4; rotation++) {
  1378. if (this.moveIf(rowIndex, columnIndex, currentGridConfig)) {
  1379. // 如果还没有找到后备位置,保存第一个可放置的位置
  1380. if (fallbackPosition === null) {
  1381. fallbackPosition = { row: rowIndex, column: columnIndex }
  1382. fallbackRotation = { gridConfig: currentGridConfig, deg: currentDeg }
  1383. }
  1384. // 模拟放置并计算得分
  1385. const gridList = this.copyGridList()
  1386. currentGridConfig.forEach((gridConfigData) => {
  1387. gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = CellState.FILLED
  1388. })
  1389. // 计算这个位置的得分
  1390. const eliminateCheck = this.gridEliminateCheck(gridList)
  1391. let positionScore = eliminateCheck.gridEliminateList.length
  1392. // 如果这个位置比之前找到的更好
  1393. if (positionScore > bestScore) {
  1394. bestScore = positionScore
  1395. bestPosition = { row: rowIndex, column: columnIndex }
  1396. bestRotation = { gridConfig: currentGridConfig, deg: currentDeg }
  1397. }
  1398. }
  1399. // 如果方块可以旋转,计算下一个旋转状态
  1400. if (brickData.rotateFlag && rotation < 3) {
  1401. const next = this.nextGridRotate(currentGridConfig, currentDeg)
  1402. currentGridConfig = next.gridConfig
  1403. currentDeg = next.deg
  1404. } else {
  1405. break
  1406. }
  1407. }
  1408. }
  1409. }
  1410. // 如果找到了最佳得分位置,返回它
  1411. if (bestPosition !== null) {
  1412. return {
  1413. position: bestPosition,
  1414. rotation: bestRotation,
  1415. score: bestScore
  1416. }
  1417. }
  1418. // 如果没有找到可消除的位置但有可放置的位置,返回第一个可放置的位置
  1419. if (fallbackPosition !== null) {
  1420. return {
  1421. position: fallbackPosition,
  1422. rotation: fallbackRotation,
  1423. score: 0
  1424. }
  1425. }
  1426. // 如果真的没有任何可放置的位置,返回null
  1427. return null
  1428. }
  1429. //========================打开其他界面和按钮逻辑=======================
  1430. /** 视图对象通过 ecs.Entity.remove(eliminateViewComp) 删除组件是触发组件处理自定义释放逻辑 */
  1431. reset() {
  1432. this.node.destroy();
  1433. }
  1434. private onToggleContainerAutoClick(toggle: Toggle) {
  1435. switch (toggle.node.name) {
  1436. case "On":
  1437. this.autoClick = true;
  1438. break;
  1439. case "Off":
  1440. this.autoClick = false;
  1441. break;
  1442. }
  1443. this.startAutoMode();
  1444. }
  1445. private startAutoMode() {
  1446. if (
  1447. this.gameState !== GameState.READY ||
  1448. this.editingFlag
  1449. ) return
  1450. // 切换自动模式状态
  1451. this.isAutoMode = this.autoClick;
  1452. if (this.isAutoMode) {
  1453. this._isAutoFunc = () => {
  1454. this.autoPlaceBrick()
  1455. }
  1456. this.schedule(this._isAutoFunc, this.autoModeInterval)
  1457. } else {
  1458. if (this._isAutoFunc) {
  1459. this.unschedule(this._isAutoFunc)
  1460. this._isAutoFunc = null
  1461. }
  1462. }
  1463. }
  1464. private btn_setting() {
  1465. oops.gui.open(UIID.Setting);
  1466. }
  1467. private btn_withdraw() {
  1468. oops.gui.open(UIID.WechatWithdraw);
  1469. }
  1470. private btn_award() {
  1471. oops.gui.open(UIID.RedPacketWithdraw);
  1472. }
  1473. //重新开始
  1474. private restartGame() {
  1475. if (this.gameState === GameState.READY) return;
  1476. this.initData();
  1477. this.reopenGrid();
  1478. }
  1479. private reopenGrid() {
  1480. for (let rowIndex = 0; rowIndex < this.rows; rowIndex++) {
  1481. for (let columnIndex = 0; columnIndex < this.cols; columnIndex++) {
  1482. this.gridList[rowIndex][columnIndex].status = CellState.EMPTY
  1483. this.generateGrid(this.gridList[rowIndex][columnIndex])
  1484. }
  1485. }
  1486. // 初始化方块
  1487. if (this.brickNode) {
  1488. if (this.brickNode) {
  1489. this.brickNode.children.forEach(node => { node.destroy() });
  1490. }
  1491. }
  1492. this.bricksList.length = 0
  1493. for (let i = 1; i <= this.brickNum; i++) {
  1494. this.addBrick(i)
  1495. }
  1496. // 清除旋转数据
  1497. if (this.rotateNode) {
  1498. this.rotateNode.children.forEach(node => { node.destroy() })
  1499. }
  1500. }
  1501. }