EliminateViewComp.ts 55 KB

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