EliminateViewComp.ts 65 KB

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