EliminateViewComp.ts 69 KB

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