EliminateViewComp.ts 66 KB

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