| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777 |
- /*
- * @Author: mojunshou 1637302775@qq.com
- * @Date: 2025-03-11 18:05:45
- * @LastEditors: mojunshou 1637302775@qq.com
- * @LastEditTime: 2025-03-26 15:02:48
- * @Description:
- */
- import { _decorator, Color, EventTouch, instantiate, JsonAsset, Node, Prefab, Sprite, UITransform, Vec3, Widget, tween } from "cc";
- import { oops } from "db://oops-framework/core/Oops";
- import { ecs } from "db://oops-framework/libs/ecs/ECS";
- import { LabelChange } from "db://oops-framework/libs/gui/label/LabelChange";
- import { CCComp } from "db://oops-framework/module/common/CCComp";
- import { GameConfig, GameStatus, GridStatus } from "../../common/config/GameConfig";
- import { UIID } from "../../common/config/GameUIConfig";
- import { randomRangeInt } from "cc";
- import { Vec2 } from "cc";
- import { log } from "console";
- import { Label } from "cc";
- const { ccclass, property } = _decorator;
- // 网格数据接口
- interface GridData {
- name: string,
- status: GridStatus,
- gridNode: Node | null,
- row: number,
- column: number,
- gridColorKey: string | null,
- }
- //网格接口
- interface Grids {
- row: number,
- column: number,
- }
- //底部方块数据定义
- interface BrickData {
- index: number,
- brickKey: string,
- rotateFlag: boolean,
- gridConfig: Grids[],
- deg: number,
- brickNode: Node | null,
- gridColorKey: string,
- brickInitPos: Vec3,
- }
- //可修改的数据
- interface EditingData {
- brickData: BrickData | null,
- gridList: GridData[],
- }
- interface GridConfigData {
- row: number,
- column: number,
- }
- /** 视图层对象 */
- @ccclass('EliminateViewComp')
- @ecs.register('EliminateView', false)
- export class EliminateViewComp extends CCComp {
- @property({ type: LabelChange, displayName: "自动提现金额" })
- private amountLb: LabelChange = null!;
- @property({ type: LabelChange, displayName: "额外奖励" })
- private awardLb: LabelChange = null!;
- @property({ type: Prefab, displayName: "金币预制体" })
- private coinPrefab: Prefab = null!;
- @property({ type: Prefab, displayName: "红包预制体" })
- private redPacketPrefab: Prefab = null!;
- //游戏状态
- game_status: number = GameStatus.None;
- max_row: number = 0;
- max_col: number = 0;
- itemSize: number = 0;
- // itemSpacing: number = 0; //方块间距
- brickNum: number = 0;
- //没使用颜色
- notUseColor = new Color(255, 255, 255, 255)
- //可用的颜色
- usableColor = new Color(0, 255, 0, 100)
- //不可用的颜色
- unavailableColor = new Color(255, 0, 0, 100)
- //旋转容错
- rotateFaultTolerant = 10;
- //游戏变量定义
- _score: number = 0; //分数
- rotateTag: boolean = false; //旋转标记
- gameConfig: { GridType?: any, bricks?: any } = {} //配置数据
- editingFlag = false //编辑状态
- editingData: EditingData = {
- brickData: null,
- gridList: [],
- }
- //旋转标记
- rotateFlag = false
- rotateBrickData: BrickData | null = null;
- //网格列表
- gridList: GridData[][] = [];
- //砖块列表
- bricksList: BrickData[] = [];
- //网格颜色列表
- gridColorList: GridData[] = [];
- gridPrefab: Prefab | null = null;
- rotatePrefab: Prefab | null = null;
- prefabUrlMap: { [key: string]: Prefab } = {}; //预制体url映射
- private _isAutoFunc: (() => void) | null = null
- private readonly GRID_GRAY_COLOR = new Color(128, 128, 128, 255)
- private readonly GRID_GRAY_DELAY = 0.01
- isAutoMode: boolean = false;
- autoModeInterval: number = 1 // 自动模式的间隔时间(秒)
- autoModeTimer: number = 0 // 自动模式计时器
- autoLb: Label | null = null;
- //网格列表
- gridsNode: Node | null = null; //中间网格区域
- itemNode: Node | null = null; //底部三个item块区域
- moveNode: Node | null = null; //移动层Node
- rotateNode: Node | null = null; //旋转Node
- hammerNode: Node | null = null; //锤子节点
- //锤子功能
- hammerMode = false; // 是否在锤子模式
- hammerRange = 2; // 锤子影响范围(以点击位置为中心的方形区域边长)
- hammerPreviewNodes: Node[] = []; // 预览区域的节点列表
- //分数管理
- get score() {
- return this._score
- }
- set score(v: number) {
- this._score = v
- }
- /** 视图层逻辑代码分离演示 */
- async start() {
- // const entity = this.ent as ecs.Entity; // ecs.Entity 可转为当前模块的具体实体对象
- this.setButton();
- this.initBindNode();
- await this.loadBrickConfig(); // 等待 loadBrickConfig 执行完毕
- this.loadPrefabsAsset().then(() => {
- this.scheduleOnce(() => {
- this.initGameData();
- this.initGrids();
- }, 0.1)
- }); // 然后再执行 loadPrefabsAsset
- // 初始化锤子节点
- this.initHammerNode();
- }
- /** 视图对象通过 ecs.Entity.remove(GameViewComp) 删除组件是触发组件处理自定义释放逻辑 */
- reset() {
- this.node.destroy();
- }
- private initBindNode() {
- this.gridsNode = this.node.getChildByPath("Scene/center/GridNode");
- this.itemNode = this.node.getChildByPath("Scene/itemNode");
- this.moveNode = this.node.getChildByPath("Scene/MoveNode");
- this.rotateNode = this.node.getChildByPath("Scene/rotateNode");
- this.hammerNode = this.node.getChildByPath("Scene/hammerNode")
- const autoLbNode = this.node.getChildByPath("Scene/bottom/btn_list/btn_auto/autoLb")
- if (autoLbNode) {
- this.autoLb = autoLbNode.getComponent(Label);
- }
- }
- private btn_setting(event: EventTouch) {
- console.log("点击了设置按钮");
- oops.gui.open(UIID.Setting);
- }
- //初始化游戏数据
- private initGameData() {
- this.max_row = GameConfig.MaxRow;
- this.max_col = GameConfig.MaxCol;
- this.itemSize = GameConfig.ItemSize;
- // this.itemSpacing = GameConfig.Spacing;
- this.brickNum = GameConfig.BlockNum;
- this.rotateFlag = false;
- this.rotateBrickData = null;
- this.setGameStatus(GameStatus.Start);
- if (this.autoLb) {
- this.autoLb.string = "自动:关"
- }
- }
- //初始化网格
- private async loadBrickConfig() {
- let json_name: string = "gui/eliminate/config/GridConfig";
- return new Promise<void>((resolve, reject) => {
- oops.res.load(json_name, JsonAsset, (err: Error | null, res: any) => {
- if (res) {
- this.gameConfig = res.json;
- resolve();
- } else {
- console.log("JSON数据加载失,请检查文件");
- reject(err);
- }
- });
- });
- }
- //加载预制体资源
- private async loadPrefabsAsset() {
- const loadMap = {
- gridPrefab: "gui/eliminate/prefabs/Grid",
- rotatePrefab: "gui/eliminate/prefabs/Rotation",
- coinPrefab: "gui/eliminate/prefabs/Coin", // 添加金币预制体路径
- redPacketPrefab: "gui/eliminate/prefabs/RedPacket" // 添加红包预制体路径
- };
- Object.keys(loadMap).forEach(key => {
- let path = loadMap[key as keyof typeof loadMap];
- const keyTyped = key as 'gridPrefab' | 'rotatePrefab' | 'coinPrefab' | 'redPacketPrefab';
- new Promise((resolve, reject) => {
- oops.res.load(path, Prefab, (err: Error | null, res: any) => {
- if (err) {
- reject(err);
- return;
- }
- if (res) {
- this[keyTyped] = res;
- resolve(0);
- }
- });
- })
- });
- const prefabUrls: string[] = [];
- const typeList = this.gameConfig['GridType'];
- Object.keys(typeList).forEach(key => {
- let path = typeList[key]['prefabUrl'];
- prefabUrls.push(path);
- });
- prefabUrls.forEach(path => {
- new Promise((resolve, reject) => {
- oops.res.load(path, Prefab, (err: Error | null, res: any) => {
- if (err) {
- reject(err);
- return;
- }
- if (res) {
- this.prefabUrlMap[path] = res;
- resolve(0);
- }
- });
- })
- });
- }
- private initGrids() {
- // 清理现有网格
- this.clearExistingGrids();
- // 设置网格容器大小
- this.setupGridsContainer();
- // 生成网格矩阵
- this.createGridMatrix();
- }
- //设置游戏状态
- /**
- * @description: 设置游戏状态
- * @param {GameStatus} status
- * @return {*}
- */
- private setGameStatus(status: GameStatus) {
- this.game_status = status;
- switch (status) {
- case GameStatus.None:
- break;
- case GameStatus.Start:
- break;
- case GameStatus.Over:
- break;
- default:
- break;
- }
- }
- /**
- * @description: 清理现有的网格数据
- * @return {*}
- */
- private clearExistingGrids(): void {
- this.gridList = [];
- if (this.gridsNode) {
- this.gridsNode.children.forEach(node => node.destroy());
- }
- }
- /**
- * @description: 设置网格大小
- * @return {*}
- */
- private setupGridsContainer(): void {
- const containerSize = {
- width: this.itemSize * this.max_col,
- height: this.itemSize * this.max_row
- };
- if (this.gridsNode) {
- const uiTransform = this.gridsNode.getComponent(UITransform);
- if (uiTransform) {
- uiTransform.setContentSize(
- containerSize.width,
- containerSize.height
- );
- }
- }
- }
- /**
- * @description: 设置网格容器大小
- * @return {*}
- */
- private createGridMatrix(): void {
- for (let rowIndex = 0; rowIndex < this.max_row; rowIndex++) {
- const currentRow: GridData[] = [];
- this.gridList.push(currentRow);
- for (let columnIndex = 0; columnIndex < this.max_col; columnIndex++) {
- const gridData = this.createGridData(rowIndex, columnIndex);
- currentRow.push(gridData);
- this.createGridNode(gridData);
- }
- }
- // 初始化格子状态
- for (let rowIndex = 0; rowIndex < this.max_row; rowIndex++) {
- for (let columnIndex = 0; columnIndex < this.max_col; columnIndex++) {
- this.gridList[rowIndex][columnIndex].status = GridStatus.NotUse
- this.generateGrid(this.gridList[rowIndex][columnIndex])
- }
- }
- // 初始化方块
- if (this.itemNode) {
- if (this.itemNode) {
- this.itemNode.children.forEach(node => { node.destroy() });
- }
- }
- this.bricksList.length = 0
- for (let i = 1; i <= this.brickNum; i++) {
- this.addBrick(i)
- }
- // 清除旋转数据
- if (this.rotateNode) {
- this.rotateNode.children.forEach(node => { node.destroy() })
- }
- }
- /**
- * @description: 创建格子数据
- * @param {number} row
- * @param {number} column
- * @return {*}
- */
- private createGridData(row: number, column: number): GridData {
- return {
- name: `Grid-${row}-${column}`,
- status: GridStatus.NotUse,
- gridNode: null,
- row: row,
- column: column,
- gridColorKey: null,
- };
- }
- /**
- * @description: 创建网格Node
- * @param {GridData} gridData
- * @return {*}
- */
- private createGridNode(gridData: GridData): void {
- const gridNode = new Node(gridData.name);
- if (this.gridsNode) {
- this.gridsNode.addChild(gridNode);
- }
- gridData.gridNode = gridNode;
- // 设置网格大小
- gridNode.addComponent(UITransform).setContentSize(this.itemSize, this.itemSize);
- // 设置网格位置约束
- // this.setupGridWidget(gridNode, gridData.row, gridData.column);
- }
- /**
- * @description: 设置网格约束
- * @param {Node} gridNode
- * @param {number} row
- * @param {number} column
- * @return {*}
- */
- // private setupGridWidget(gridNode: Node, row: number, column: number): void {
- // const gridWidget = gridNode.addComponent(Widget);
- // gridWidget.isAlignLeft = true;
- // gridWidget.left = this.itemSize * column;
- // gridWidget.isAlignBottom = true;
- // gridWidget.bottom = this.itemSize * row;
- // }
- /**
- * 生成或更新网格
- * @param gridData 网格数据
- */
- private generateGrid(gridData: GridData) {
- if (!gridData || !gridData.gridNode) {
- console.warn('无效的网格数据');
- return;
- }
- // 清理现有子节点
- this.clearGridChildren(gridData.gridNode);
- // 获取对应的预制体
- const prefab = this.getGridPrefab(gridData);
- if (!prefab) {
- console.warn('无法获取网格预制体');
- return;
- }
- // 创建并配置新节点
- const node = this.createNewGridNode(prefab, gridData);
- // 设置节点属性
- this.setupGridNode(node, gridData);
- }
- /**
- * 清理网格的子节点
- */
- private clearGridChildren(gridNode: Node): void {
- const children = gridNode.children.slice(); // 创建副本避免遍历时修改问题
- children.forEach(node => node.destroy());
- }
- /**
- * 获取对应状态的预制体
- */
- private getGridPrefab(gridData: GridData): Prefab {
- if (gridData.status === GridStatus.NotUse) {
- if (this.gridPrefab) {
- return this.gridPrefab;
- } else {
- throw new Error('Grid prefab is not loaded');
- }
- }
- if (gridData.status === GridStatus.Used && gridData.gridColorKey) {
- const prefabUrl = this.gameConfig['GridType']?.[gridData.gridColorKey]?.['prefabUrl'];
- return this.prefabUrlMap[prefabUrl];
- }
- throw new Error('Invalid grid status or missing gridColorKey');
- }
- /**
- * 创建网格节点
- */
- private createNewGridNode(prefab: Prefab, gridData: GridData): Node {
- const node = instantiate(prefab);
- if (gridData && gridData.gridNode) {
- gridData.gridNode.addChild(node);
- return node;
- }
- return node
- }
- /**
- * 设置网格节点的属性
- */
- private setupGridNode(node: Node, gridData: GridData): void {
- // 设置未使用状态的颜色
- if (gridData.status === GridStatus.NotUse) {
- const sprite = node.getComponent(Sprite);
- if (sprite) {
- sprite.color = this.notUseColor;
- }
- }
- // 设置节点大小
- const transform = node.getComponent(UITransform);
- if (transform) {
- transform.setContentSize(
- this.itemSize,
- this.itemSize
- );
- }
- // 设置位置
- node.setPosition(Vec3.ZERO);
- }
- //底部增加方块
- addBrick(index: number) {
- const brickKey = Object.keys(this.gameConfig['bricks'])[randomRangeInt(0, Object.keys(this.gameConfig['bricks']).length)]
- const gridColorKey = Object.keys(this.gameConfig['GridType'])[randomRangeInt(0, Object.keys(this.gameConfig['GridType']).length)]
- const brickConfig = this.gameConfig['bricks'][brickKey]
- const brickData: BrickData = {
- index,
- brickKey,
- rotateFlag: brickConfig['rotateFlag'],
- gridConfig: brickConfig['gridConfig'],
- deg: 0,
- brickNode: null,
- gridColorKey,
- brickInitPos: new Vec3(),
- }
- this.bricksList.push(brickData)
- // 生成方块
- const brickNode = this.generateBrick(brickKey, gridColorKey);
- if (this.itemNode) {
- this.itemNode.addChild(brickNode)
- }
- brickData.brickNode = brickNode
- // 方块间隔
- let offset = 220
- if (this.brickNum % 2 === 1) {
- const middleNum = Math.floor(this.brickNum / 2) + 1
- if (index < middleNum) {
- offset = - offset
- }
- else if (index === middleNum) {
- offset = 0
- }
- }
- if (brickData && brickData.brickNode) {
- let width = 0;
- if (this.itemNode) {
- width = this.itemNode.getComponent(UITransform)!.width;
- }
- brickData.brickNode.setPosition(offset, 0)
- brickData.brickNode.scale_x = 0.6;
- brickData.brickNode.scale_y = 0.6;
- brickData.brickInitPos = brickData.brickNode.getWorldPosition()
- this.brickAddEvent(brickData);
- }
- }
- touchStartLocation = new Vec2()
- touchStartFlag = false
- //方块添加监听事件
- brickAddEvent(brickData: BrickData) {
- const brickNode = brickData.brickNode
- if (!brickNode) {
- console.log("打印进这里来了")
- return
- }
- brickNode.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
- // if (this.adShowingFlag) return
- // 未操作完时不能操作下一个方块
- if (this.editingFlag) return
- this.touchStartFlag = true
- this.editingFlag = true
- this.editingData.brickData = null
- this.editingData.gridList.length = 0
- // 隐藏游戏提示
- // this.gameTipNode.active = false
- // 记录开始触摸的位置,用于结束触摸时,判断位置是否是单击
- this.touchStartLocation.set(event.getUILocation())
- // 添加到移动节点里进行移动
- const pos = brickNode.getWorldPosition()
- brickNode.setParent(this.moveNode)
- brickNode.setWorldPosition(pos)
- // 添加放大动画
- tween(brickNode)
- .to(0.2, { scale: new Vec3(1, 1, 1) })
- .start()
- const index = this.bricksList.findIndex(data => data === brickData)
- if (index > -1) {
- this.editingData.brickData = this.bricksList.splice(index, 1)[0]
- } else {
- console.error("bricksList not find brickData:", brickData)
- }
- // 清除旋转数据
- if (this.rotateFlag && this.rotateBrickData !== this.editingData.brickData) {
- this.rotateFlag = false
- this.rotateBrickData = null
- if (this.rotateNode) {
- this.rotateNode.children.forEach(node => { node.destroy() })
- }
- }
- })
- // 触摸移动时
- brickNode.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
- // 防止如放回方块回弹动画时,已经触摸在另一个方块上面,从而导致异常错误
- if (this.editingData.brickData !== brickData) return
- // 清除旋转数据
- if (event.getUILocation().subtract(this.touchStartLocation).length() >= this.rotateFaultTolerant) {
- this.rotateFlag = false
- this.rotateBrickData = null
- if (this.rotateNode) {
- this.rotateNode.children.forEach(node => { node.destroy() })
- }
- }
- // 格子颜色恢复
- this.gridColorRecovery()
- // 移动
- brickNode.setWorldPosition(brickNode.getWorldPosition().add(event.getUIDelta().toVec3()))
- // 每次移动重置数据
- this.editingData.gridList.length = 0
- // 实时获取方块位置判断在哪个格子上
- const tempGridList: GridData[] = []
- brickNode.children.forEach((brickGridNode) => {
- const brickGridPos = brickGridNode.getWorldPosition()
- let gridData: GridData | null = null
- for (let rowIndex = 0; rowIndex < this.max_row && gridData === null; rowIndex++) {
- for (let columnIndex = 0; columnIndex < this.max_col && gridData === null; columnIndex++) {
- const nowGridData = this.gridList[rowIndex][columnIndex];
- if (nowGridData && nowGridData.gridNode) {
- const gridPos = nowGridData.gridNode.getWorldPosition()
- if (Vec3.distance(gridPos, brickGridPos) <= (this.itemSize / 2)) {
- gridData = nowGridData
- }
- }
- }
- }
- if (gridData === null) {
- return;
- }
- tempGridList.push(gridData)
- })
- // 检查整体情况
- let checkFlag = false
- if (
- tempGridList.length === brickData.gridConfig.length &&
- tempGridList.filter(d => d.status === GridStatus.NotUse).length === brickData.gridConfig.length
- ) {
- checkFlag = true
- tempGridList.forEach((gridData) => {
- this.editingData.gridList.push(gridData)
- })
- }
- // 格子给用户提示
- tempGridList.forEach((gridData) => {
- if (gridData.status !== GridStatus.NotUse) {
- return;
- }
- if (gridData.gridNode) {
- const children = gridData.gridNode.children[0];
- if (children) {
- children.getComponent(Sprite)!.color = checkFlag ? this.usableColor : this.unavailableColor
- }
- }
- // 用于恢复格子
- this.gridColorList.push(gridData)
- })
- })
- // 触摸结束
- brickNode.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
- console.log("移动结束数据查看", this.editingData.gridList.length);
- console.log("brickData数据查看", this.editingData.brickData);
- // 当连击很快时,会出现1次start,2次end情况,为了避免所以通过标志位表示是一个连贯操作
- if (!this.touchStartFlag) return
- this.touchStartFlag = false
- // console.log("TOUCH_END", this.editingFlag, this.editingData.brickData.index)
- // 防止如放回方块回弹动画时,已经触摸在另一个方块上面,从而导致异常错误
- if (this.editingData.brickData !== brickData) return
- // 第二次单击,旋转
- if (this.rotateFlag) {
- const brickData = this.editingData.brickData
- this.brickGridRotate(brickData)
- // 方块放回待选区
- this.bricksList.push(brickData)
- if (this.itemNode && brickData.brickNode) {
- this.itemNode.addChild(brickData.brickNode)
- // brickData.brickNode.setWorldPosition(brickData.brickInitPos)
- tween(brickData.brickNode)
- .to(0.2, {
- worldPosition: brickData.brickInitPos,
- scale: new Vec3(0.8, 0.8, 0.8)
- })
- .start()
- }
- this.editingFlag = false
- }
- // 方块到格子
- else if (this.editingData.brickData && this.editingData.gridList.length > 0) {
- // 修改格子
- this.editingData.gridList.forEach((gridData) => {
- gridData.status = GridStatus.Used
- if (this.editingData.brickData) {
- gridData.gridColorKey = this.editingData.brickData.gridColorKey;
- }
- this.generateGrid(gridData)
- })
- // 销毁方块--这增加动画
- if (this.editingData.brickData && this.editingData.brickData.brickNode) {
- this.editingData.brickData.brickNode.destroy();
- }
- // 新增方块
- this.addBrick(this.editingData.brickData.index);
- this.scheduleOnce(() => {
- // 格子消除
- this.gridEliminate().then(() => {
- // 检查方块是否还能消除格子
- this.prompt(false).then((promptFlag) => {
- if (!promptFlag) {
- this.gameOver()
- }
- this.editingFlag = false
- })
- })
- })
- }
- // 方块回到待选区
- else {
- console.log("返回带待选区域")
- const brickData = this.editingData.brickData
- this.bricksList.push(brickData)
- // this.audioManager.playMoveFail()
- // 回弹动画
- if (brickData.brickNode) {
- tween(brickData.brickNode)
- .to(0.15, {
- worldPosition: this.editingData.brickData.brickInitPos,
- scale: new Vec3(0.8, 0.8, 0.8)
- })
- .call(() => {
- if (this.itemNode && brickData.brickNode) {
- this.itemNode.addChild(brickData.brickNode);
- brickData.brickNode.setWorldPosition(brickData.brickInitPos);
- }
- this.editingFlag = false;
- })
- .start();
- }
- }
- // 旋转标志位
- if (
- !this.rotateFlag &&
- this.editingData.brickData.rotateFlag &&
- event.getUILocation().subtract(this.touchStartLocation).length() < this.rotateFaultTolerant
- ) {
- //方块可以旋转了
- this.rotateFlag = true
- this.rotateBrickData = this.editingData.brickData;
- if (this.rotateBrickData.brickNode) {
- const prosition = this.rotateBrickData.brickNode.getWorldPosition()
- const rotateNode = instantiate(this.rotatePrefab)
- if (this.rotateNode && rotateNode) {
- const instantiatedRotateNode = instantiate(rotateNode);
- this.rotateNode.addChild(instantiatedRotateNode);
- instantiatedRotateNode.setWorldPosition(prosition)
- }
- }
- }
- // 格子颜色恢复
- this.gridColorRecovery();
- })
- }
- // 提示
- prompt(tipFlag = true) {
- return new Promise((resolve, reject) => {
- const gridPromptList: GridData[] = []
- let moveFlag = false
- // 找方块可消除位置
- for (let rowIndex = 0; rowIndex < this.max_row && !moveFlag; rowIndex++) {
- for (let columnIndex = 0; columnIndex < this.max_col && !moveFlag; columnIndex++) {
- const gridData = this.gridList[rowIndex][columnIndex]
- if (gridData.status !== GridStatus.NotUse) continue
- // 方块不旋转检测是否能放
- for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
- const brickData = this.bricksList[brickI]
- if (this.moveIf(rowIndex, columnIndex, brickData.gridConfig)) {
- // 复制整体网格,以方块设置网格状态
- const gridList = this.copyGridList()
- brickData.gridConfig.forEach((gridConfigData) => {
- gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = GridStatus.Used
- })
- // 检查复制的整体网格是否有可消除
- if (this.gridEliminateCheck(gridList).gridEliminateList.length > 0) {
- moveFlag = true
- brickData.gridConfig.forEach((gridConfigData) => {
- gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
- })
- }
- }
- }
- // 方块旋转检测是否能放
- for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
- const brickData = this.bricksList[brickI]
- if (!brickData.rotateFlag) continue
- let gridConfig = brickData.gridConfig
- let deg = brickData.deg
- // 获得旋转的方块网格配置
- for (let count = 1; count <= 3 && !moveFlag; count++) {
- const next = this.nextGridRotate(gridConfig, deg)
- if (this.moveIf(rowIndex, columnIndex, next.gridConfig)) {
- // 复制整体网格,以方块设置网格状态
- const gridList = this.copyGridList()
- next.gridConfig.forEach((gridConfigData) => {
- gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = GridStatus.Used
- })
- // 检查复制的整体网格是否有可消除
- if (this.gridEliminateCheck(gridList).gridEliminateList.length > 0) {
- moveFlag = true
- next.gridConfig.forEach((gridConfigData) => {
- gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
- })
- }
- }
- gridConfig = next.gridConfig
- deg = next.deg
- }
- }
- }
- }
- // 找方块可放置位置
- for (let rowIndex = 0; rowIndex < this.max_row && !moveFlag; rowIndex++) {
- for (let columnIndex = 0; columnIndex < this.max_col && !moveFlag; columnIndex++) {
- const gridData = this.gridList[rowIndex][columnIndex]
- if (gridData.status !== GridStatus.NotUse) continue
- // 方块不旋转检测是否能放
- for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
- const brickData = this.bricksList[brickI]
- if (this.moveIf(rowIndex, columnIndex, brickData.gridConfig)) {
- moveFlag = true
- brickData.gridConfig.forEach((gridConfigData) => {
- gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
- })
- }
- }
- // 方块旋转检测是否能放
- for (let brickI = 0; brickI < this.bricksList.length && !moveFlag; brickI++) {
- const brickData = this.bricksList[brickI]
- if (!brickData.rotateFlag) continue
- let gridConfig = brickData.gridConfig
- let deg = brickData.deg
- for (let count = 1; count <= 3 && !moveFlag; count++) {
- const next = this.nextGridRotate(gridConfig, deg)
- if (this.moveIf(rowIndex, columnIndex, next.gridConfig)) {
- moveFlag = true
- next.gridConfig.forEach((gridConfigData) => {
- gridPromptList.push(this.gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex])
- })
- }
- gridConfig = next.gridConfig
- deg = next.deg
- }
- }
- }
- }
- if (gridPromptList.length < 1) {
- resolve(false)
- return
- }
- if (!tipFlag) {
- resolve(true)
- return
- }
- // 提示用户(网格变绿)
- gridPromptList.forEach((gridData) => {
- if (gridData.gridNode && gridData.gridNode.children[0]) {
- const sprite = gridData.gridNode.children[0].getComponent(Sprite);
- if (sprite) {
- sprite.color = this.usableColor;
- }
- }
- // 用于恢复格子
- this.gridColorList.push(gridData)
- })
- resolve(true)
- })
- }
- // 复制整体网格
- copyGridList() {
- const gridList: GridData[][] = []
- for (let rowIndex = 0; rowIndex < this.max_row; rowIndex++) {
- gridList.push([])
- for (let columnIndex = 0; columnIndex < this.max_col; columnIndex++) {
- const gridData = this.gridList[rowIndex][columnIndex]
- gridList[rowIndex].push({
- name: gridData.name,
- status: gridData.status,
- gridNode: null,
- row: gridData.row,
- column: gridData.column,
- gridColorKey: gridData.gridColorKey,
- })
- }
- }
- return gridList
- }
- // 检查是否能放置方块
- moveIf(row: number, column: number, gridConfig: GridConfigData[]) {
- let moveFlag = true
- for (let i = 0; i < gridConfig.length; i++) {
- const gridConfigData = gridConfig[i]
- const gridI = row + gridConfigData.row
- const gridJ = column + gridConfigData.column
- // 边界判断
- if (
- gridI < 0 ||
- gridI > this.max_row - 1 ||
- gridJ < 0 ||
- gridJ > this.max_col - 1
- ) {
- moveFlag = false
- break
- }
- // 已用
- else if (this.gridList[gridI][gridJ].status === GridStatus.Used) {
- moveFlag = false
- break
- }
- }
- return moveFlag
- }
- brickGridRotate(brickData: BrickData) {
- const next = this.nextGridRotate(brickData.gridConfig, brickData.deg)
- brickData.deg = next.deg
- brickData.gridConfig = next.gridConfig;
- if (brickData.brickNode) {
- tween(brickData.brickNode).to(0.1, { angle: next.deg }).start();
- }
- // this.audioManager.playRotate()
- }
- //下一个旋转
- nextGridRotate(gridConfig: GridConfigData[], deg: number) {
- const newGridConfig: GridConfigData[] = []
- // 顺时针旋转
- let newDeg = deg - 90
- gridConfig.forEach((gridConfigData) => {
- // 例如(1,2) => (-2,1),可以画图分析
- newGridConfig.push({
- row: -gridConfigData.column,
- column: gridConfigData.row
- })
- })
- return { gridConfig: newGridConfig, deg: newDeg }
- }
- //格子颜色恢复
- gridColorRecovery() {
- while (this.gridColorList.length > 0) {
- const gridData = this.gridColorList.pop();
- if (gridData) {
- if (gridData.status === GridStatus.NotUse) {
- if (gridData.gridNode) {
- gridData.gridNode.children[0].getComponent(Sprite)!.color = this.notUseColor;
- }
- }
- }
- }
- }
- // 生成独立的方块节点
- generateBrick(brickKey: string, gridColorKey: string) {
- const brickConfig = this.gameConfig['bricks'][brickKey]
- let rowMin = 0
- let rowMax = 0
- let columnMin = 0
- let columnMax = 0
- brickConfig['gridConfig'].forEach((gridConfigData: GridConfigData) => {
- if (gridConfigData.row < rowMin) {
- rowMin = gridConfigData.row
- }
- else if (gridConfigData.row > rowMax) {
- rowMax = gridConfigData.row
- }
- if (gridConfigData.column < columnMin) {
- columnMin = gridConfigData.column
- }
- else if (gridConfigData.column > columnMax) {
- columnMax = gridConfigData.column
- }
- })
- const rowNum = (rowMax - rowMin + 1)
- const columnNum = (columnMax - columnMin + 1)
- // 生成独立的方块节点
- const brickNode = new Node()
- brickNode.name = brickKey
- const transformCom: UITransform = brickNode.addComponent(UITransform)
- transformCom.setContentSize(
- this.itemSize * columnNum,
- this.itemSize * rowNum
- )
- transformCom.setAnchorPoint(0.5, 0.5)
- const gridPrefab = this.prefabUrlMap[this.gameConfig['GridType'][gridColorKey]['prefabUrl']]
- //生成对应的配置方块
- brickConfig['gridConfig'].forEach((gridConfigData: GridConfigData) => {
- const gridNode = new Node()
- gridNode.name = 'grid'
- brickNode.addChild(gridNode)
- gridNode.addComponent(UITransform).setContentSize(this.itemSize, this.itemSize)
- const gridWidget: Widget = gridNode.addComponent(Widget)
- gridWidget.isAlignLeft = true
- gridWidget.left = this.itemSize * gridConfigData.column - this.itemSize * columnMin
- gridWidget.isAlignBottom = true
- gridWidget.bottom = this.itemSize * gridConfigData.row - this.itemSize * rowMin
- const node = instantiate(gridPrefab)
- gridNode.addChild(node)
- const uiTransform = node.getComponent(UITransform);
- if (uiTransform) {
- uiTransform.setContentSize(
- this.itemSize,
- this.itemSize,
- )
- }
- node.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
- event.propagationStopped = false
- })
- node.setPosition(Vec3.ZERO)
- })
- return brickNode
- }
- // 消除,这里增加飞的动画
- gridEliminate() {
- return new Promise((resolve, reject) => {
- const d = this.gridEliminateCheck(this.gridList)
- const gridEliminateList = d.gridEliminateList
- const eliminateRowNum = d.eliminateRowNum
- const eliminateColumnNum = d.eliminateColumnNum
- if (gridEliminateList.length < 1) {
- resolve(false)
- return
- }
- gridEliminateList.forEach((gridData) => {
- if (gridData.gridNode?.children[0]) {
- const startPos = gridData.gridNode.getWorldPosition();
- tween(gridData.gridNode.children[0])
- .to(0.2, { scale: new Vec3(0.5, 0.5) })
- .call(() => {
- gridData.status = GridStatus.NotUse
- this.generateGrid(gridData)
- })
- .start()
- if (this.coinPrefab && this.amountLb?.node) {
- this.createCoinFlyAnimation(
- this.coinPrefab,
- startPos,
- this.amountLb.node.getWorldPosition(),
- 5
- );
- }
- //增加红包
- this.createCoinFlyAnimation(
- this.redPacketPrefab,
- startPos,
- this.awardLb.node.getWorldPosition(),
- 5
- );
- }
- })
- this.scheduleOnce(() => {
- let score = 0
- for (let i = 1; i <= eliminateRowNum; i++) {
- score += this.max_col * i
- }
- for (let i = 1; i <= eliminateColumnNum; i++) {
- score += this.max_row * i
- }
- this.score += score
- const lastGrid = gridEliminateList[gridEliminateList.length - 1];
- if (lastGrid?.gridNode && this.coinPrefab && this.amountLb?.node) {
- const lastPos = lastGrid.gridNode.getWorldPosition();
- this.createCoinFlyAnimation(
- this.coinPrefab,
- lastPos,
- this.amountLb.node.getWorldPosition(),
- score
- );
- }
- resolve(true)
- }, 0.2)
- })
- }
- // 检查消除
- gridEliminateCheck(gridList: GridData[][]) {
- const gridEliminateList: GridData[] = []
- let eliminateRowNum = 0
- let eliminateColumnNum = 0
- // 行检查
- for (let rowIndex = 0; rowIndex < this.max_row; rowIndex++) {
- const rowData = gridList[rowIndex]
- if (rowData.every(gridData => gridData.status === GridStatus.Used)) {
- rowData.forEach(gridData => {
- if (gridEliminateList.findIndex(data => data === gridData) < 0) {
- gridEliminateList.push(gridData)
- }
- })
- eliminateRowNum += 1
- }
- }
- // 列检查
- for (let columnIndex = 0; columnIndex < this.max_col; columnIndex++) {
- if (gridList.every(rowData => rowData[columnIndex].status === GridStatus.Used)) {
- gridList.forEach(rowData => {
- const gridData = rowData[columnIndex]
- if (gridEliminateList.findIndex(data => data === gridData) < 0) {
- gridEliminateList.push(gridData)
- }
- })
- eliminateColumnNum += 1
- }
- }
- return {
- gridEliminateList,
- eliminateRowNum,
- eliminateColumnNum,
- }
- }
- async gameOver() {
- // 先禁用所有操作
- this.isAutoMode = false
- this.editingFlag = true // 防止操作
- // 执行格子变灰动画
- await this.playGameOverGridAnimation()
- // 播放游戏结束音效
- // this.audioManager.playGameOver()
- // 设置游戏状态
- this.setGameStatus(GameStatus.Over)
- // 恢复操作标志
- this.editingFlag = false
- oops.gui.open(UIID.GameOver);
- }
- private async playGameOverGridAnimation(): Promise<void> {
- // 按行从左到右收集所有已使用的格子
- const usedGrids: GridData[] = []
- for (let row = 0; row < this.max_row; row++) {
- for (let col = 0; col < this.max_col; col++) {
- const grid = this.gridList[row][col]
- if (grid.status === GridStatus.Used) {
- usedGrids.push(grid)
- }
- }
- }
- // 执行变灰动画
- return new Promise<void>((resolve) => {
- let completedCount = 0
- usedGrids.forEach((grid, index) => {
- this.scheduleOnce(() => {
- // 获取格子的 Sprite 组件
- if (grid.gridNode) {
- const gridSprite = grid.gridNode.children[0].getComponent(Sprite)
- // 创建变灰动画
- if (!gridSprite) {
- return
- }
- tween(gridSprite)
- .to(0.2, { color: this.GRID_GRAY_COLOR })
- .call(() => {
- completedCount++
- if (completedCount === usedGrids.length) {
- resolve()
- }
- })
- .start()
- }
- }, index * this.GRID_GRAY_DELAY)
- })
- // 如果没有已使用的格子,直接完成
- if (usedGrids.length === 0) {
- resolve()
- }
- })
- }
- // //刷新按钮
- btn_refresh() {
- if (
- this.game_status !== GameStatus.Start
- ) return
- // 清除方块重新获取
- if (this.itemNode) {
- this.itemNode.children.forEach(node => { node.destroy() });
- }
- this.bricksList.length = 0
- for (let i = 1; i <= this.brickNum; i++) {
- this.addBrick(i)
- }
- // 清除旋转数据
- if (this.rotateNode) {
- this.rotateNode.children.forEach(node => { node.destroy() })
- }
- this.rotateFlag = false
- this.rotateBrickData = null
- // 恢复格子颜色
- this.gridColorRecovery()
- }
- //提示按钮
- btn_hint() {
- if (
- this.game_status !== GameStatus.Start
- ) return
- // 先检查是否死局
- this.prompt(false).then((flag) => {
- if (!flag) {
- this.gameOver()
- return
- }
- this.gridColorRecovery()
- this.prompt()
- })
- }
- //继续按钮
- onContinueBtnClick() {
- this.setGameStatus(GameStatus.Start);
- }
- // ... 修改 autoPlaceBrick 方法
- async autoPlaceBrick() {
- if (!this.isAutoMode) return;
- if (this.bricksList.length === 0) return
- // 遍历所有方块,找到一个可以放置的方块
- let bestMove = null;
- let selectedBrickIndex = -1;
- for (let i = 0; i < this.bricksList.length; i++) {
- const move = this.findBestPosition(this.bricksList[i]);
- if (move) {
- // 优先选择可以消除的位置
- if (move.score > 0) {
- bestMove = move;
- selectedBrickIndex = i;
- break;
- } else if (bestMove === null) {
- // 如果还没有找到任何可放置的位置,保存这个位置
- bestMove = move;
- selectedBrickIndex = i;
- }
- }
- }
- // 如果所有方块都没有可放置的位置,游戏结束
- if (!bestMove || selectedBrickIndex === -1) {
- console.log('所有方块都没有可放置的位置,游戏结束');
- this.isAutoMode = false;
- if (this._isAutoFunc) {
- this.unschedule(this._isAutoFunc);
- this._isAutoFunc = null;
- }
- this.gameOver();
- return;
- }
- // 获取选中的方块
- const brickData = this.bricksList[selectedBrickIndex];
- // 从列表中移除方块
- this.bricksList.splice(selectedBrickIndex, 1);
- // 保存方块的初始位置(从待选区开始)
- const startPos = brickData.brickInitPos.clone();
- // 设置方块到移动层并确保位置精确
- if (brickData.brickNode) {
- brickData.brickNode.setParent(this.moveNode);
- brickData.brickNode.setWorldPosition(startPos);
- }
- // this.guideNode.active = true;
- // this.guideNode.setWorldPosition(
- // startPos.x,
- // startPos.y + brickData.brickNode.getComponent(UITransform).height / 2,
- // startPos.z
- // );
- // 如果需要旋转,先旋转到正确的角度
- if (brickData.rotateFlag && bestMove.rotation && bestMove.rotation.deg !== brickData.deg) {
- await new Promise<void>((resolve) => {
- if (brickData.brickNode) {
- tween(brickData.brickNode)
- .to(0.2, { angle: bestMove.rotation ? bestMove.rotation.deg : 0 })
- .call(() => {
- if (bestMove.rotation) {
- brickData.gridConfig = bestMove.rotation.gridConfig;
- brickData.deg = bestMove.rotation.deg;
- }
- resolve();
- })
- .start();
- }
- });
- }
- // 获取目标位置,有些目标位置获取有问题需要修改
- const targetGrid = this.gridList[bestMove.position.row][bestMove.position.column];
- if (!targetGrid.gridNode) {
- console.error('targetGrid.gridNode is null');
- return;
- }
- const targetWorldPos = targetGrid.gridNode.getWorldPosition().clone();
- // 创建平滑的移动动画
- await new Promise<void>((resolve) => {
- if (brickData.brickNode) {
- tween(brickData.brickNode)
- .to(0.3, {
- worldPosition: targetWorldPos,
- }, {
- easing: 'cubicOut'
- })
- .call(() => {
- if (brickData.brickNode) {
- brickData.brickNode.setWorldPosition(targetWorldPos);
- // 放置方块
- if (bestMove.rotation) {
- bestMove.rotation.gridConfig.forEach((gridConfigData) => {
- const gridData = this.gridList[bestMove.position.row + gridConfigData.row][bestMove.position.column + gridConfigData.column];
- gridData.status = GridStatus.Used;
- gridData.gridColorKey = brickData.gridColorKey;
- this.generateGrid(gridData);
- });
- }
- // 销毁方块
- brickData.brickNode.destroy();
- // 添加新方块
- this.addBrick(brickData.index);
- }
- resolve();
- })
- .start();
- }
- });
- // 检查并执行消除
- await this.gridEliminate();
- // 检查是否还有任何方块可以放置
- let hasValidMove = false;
- for (const brick of this.bricksList) {
- if (this.findBestPosition(brick)) {
- hasValidMove = true;
- break;
- }
- }
- if (!hasValidMove) {
- console.log('没有方块可以放置,游戏结束');
- this.isAutoMode = false;
- if (this._isAutoFunc) {
- this.unschedule(this._isAutoFunc);
- this._isAutoFunc = null;
- }
- this.gameOver();
- }
- }
- // ... 修改 findBestPosition 方法,这个方法有问题,需要修改
- findBestPosition(brickData: BrickData) {
- let bestScore = -1
- let bestPosition = null
- let bestRotation = null
- let fallbackPosition = null
- let fallbackRotation = null
- // 遍历所有可能的位置
- for (let rowIndex = 0; rowIndex < this.max_row; rowIndex++) {
- for (let columnIndex = 0; columnIndex < this.max_col; columnIndex++) {
- // 检查当前位置的所有可能旋转
- let currentGridConfig = brickData.gridConfig
- let currentDeg = brickData.deg
- // 最多旋转4次(0°, 90°, 180°, 270°)
- for (let rotation = 0; rotation < 4; rotation++) {
- if (this.moveIf(rowIndex, columnIndex, currentGridConfig)) {
- // 如果还没有找到后备位置,保存第一个可放置的位置
- if (fallbackPosition === null) {
- fallbackPosition = { row: rowIndex, column: columnIndex }
- fallbackRotation = { gridConfig: currentGridConfig, deg: currentDeg }
- }
- // 模拟放置并计算得分
- const gridList = this.copyGridList()
- currentGridConfig.forEach((gridConfigData) => {
- gridList[gridConfigData.row + rowIndex][gridConfigData.column + columnIndex].status = GridStatus.Used
- })
- // 计算这个位置的得分
- const eliminateCheck = this.gridEliminateCheck(gridList)
- let positionScore = eliminateCheck.gridEliminateList.length
- // 如果这个位置比之前找到的更好
- if (positionScore > bestScore) {
- bestScore = positionScore
- bestPosition = { row: rowIndex, column: columnIndex }
- bestRotation = { gridConfig: currentGridConfig, deg: currentDeg }
- }
- }
- // 如果方块可以旋转,计算下一个旋转状态
- if (brickData.rotateFlag && rotation < 3) {
- const next = this.nextGridRotate(currentGridConfig, currentDeg)
- currentGridConfig = next.gridConfig
- currentDeg = next.deg
- } else {
- break
- }
- }
- }
- }
- // 如果找到了最佳得分位置,返回它
- if (bestPosition !== null) {
- return {
- position: bestPosition,
- rotation: bestRotation,
- score: bestScore
- }
- }
- // 如果没有找到可消除的位置但有可放置的位置,返回第一个可放置的位置
- if (fallbackPosition !== null) {
- return {
- position: fallbackPosition,
- rotation: fallbackRotation,
- score: 0
- }
- }
- // 如果真的没有任何可放置的位置,返回null
- return null
- }
- //重新开始-这样正常要接广告
- private btn_reopen() {
- console.log("重新开始");
- if (this.game_status === GameStatus.None) return
- this.initGameData();
- this.reopenGrid();
- }
- private reopenGrid() {
- for (let rowIndex = 0; rowIndex < this.max_row; rowIndex++) {
- for (let columnIndex = 0; columnIndex < this.max_col; columnIndex++) {
- this.gridList[rowIndex][columnIndex].status = GridStatus.NotUse
- this.generateGrid(this.gridList[rowIndex][columnIndex])
- }
- }
- // 初始化方块
- if (this.itemNode) {
- if (this.itemNode) {
- this.itemNode.children.forEach(node => { node.destroy() });
- }
- }
- this.bricksList.length = 0
- for (let i = 1; i <= this.brickNum; i++) {
- this.addBrick(i)
- }
- // 清除旋转数据
- if (this.rotateNode) {
- this.rotateNode.children.forEach(node => { node.destroy() })
- }
- }
- //=================自动模式逻辑=================
- //自动模式
- private btn_auto() {
- // if (
- // this.game_status !== GameStatus.Start ||
- // this.editingFlag
- // ) return
- // 切换自动模式状态
- this.isAutoMode = !this.isAutoMode
- if (this.isAutoMode) {
- this._isAutoFunc = () => {
- this.autoPlaceBrick()
- }
- this.schedule(this._isAutoFunc, this.autoModeInterval)
- if (this.autoLb) {
- this.autoLb.string = "自动:开"
- }
- } else {
- if (this._isAutoFunc) {
- this.unschedule(this._isAutoFunc)
- this._isAutoFunc = null
- }
- if (this.autoLb) {
- this.autoLb.string = "自动:关"
- }
- }
- }
- // 修改 createCoinFlyAnimation 方法为公共方法,扩展参数列表
- public createCoinFlyAnimation(prefab: Prefab, startPos: Vec3, endPos: Vec3, score: number, parent: Node = this.node) {
- const coinNum = Math.min(Math.max(Math.floor(score / 10), 1), 10);
- for (let i = 0; i < coinNum; i++) {
- if (!prefab) {
- console.warn('金币预制体未加载');
- return;
- }
- const coin = instantiate(prefab);
- parent.addChild(coin);
- const randomOffset = new Vec3(
- (Math.random() - 0.5) * 50,
- (Math.random() - 0.5) * 50,
- 0
- );
- const startPosition = startPos.clone().add(randomOffset);
- coin.setWorldPosition(startPosition);
- const controlPoint = new Vec3(
- (startPosition.x + endPos.x) / 2 + (Math.random() - 0.5) * 100,
- (startPosition.y + endPos.y) / 2 + Math.random() * 100,
- 0
- );
- this.scheduleOnce(() => {
- tween(coin)
- .parallel(
- tween().to(0.2, { scale: new Vec3(1.2, 1.2, 1.2) })
- .to(0.1, { scale: new Vec3(1, 1, 1) }),
- tween().by(0.3, { angle: 360 })
- )
- .start();
- const bezierCurve = (target: Node | undefined, ratio?: number) => {
- if (!target || ratio === undefined) return;
- const t = ratio;
- const pos = new Vec3();
- Vec3.multiplyScalar(pos, startPosition, (1 - t) * (1 - t));
- Vec3.scaleAndAdd(pos, pos, controlPoint, 2 * (1 - t) * t);
- Vec3.scaleAndAdd(pos, pos, endPos, t * t);
- target.setWorldPosition(pos);
- };
- tween(coin)
- .to(0.8, {
- worldPosition: endPos
- }, {
- easing: 'cubicIn',
- onUpdate: bezierCurve
- })
- .call(() => {
- tween(coin)
- .to(0.1, { scale: new Vec3(0.7, 0.7, 0.7) })
- .call(() => {
- coin.destroy();
- })
- .start();
- })
- .start();
- }, i * 0.1);
- }
- }
- //======================拓展功能==锤子玩法==========
- private btn_hammer(): void {
- if (
- this.game_status !== GameStatus.Start ||
- this.editingFlag ||
- this.isAutoMode
- )
- return
- // 随机选择一片区域的方块进行清除
- this.performRandomHammerSmash();
- }
- // 添加初始化锤子节点的方法
- private initHammerNode(): void {
- if (!this.hammerNode) {
- console.warn('锤子节点未找到');
- return;
- }
- // 默认隐藏锤子节点
- this.hammerNode.active = false;
- }
- // 实现随机锤子敲击效果 - 清除周围少量方块
- private performRandomHammerSmash(): void {
- // 收集所有已放置的方块
- const placedBlocks: GridData[] = [];
- for (let row = 0; row < this.max_row; row++) {
- for (let col = 0; col < this.max_col; col++) {
- const gridData = this.gridList[row][col];
- if (gridData.status === GridStatus.Used && gridData.gridNode) {
- placedBlocks.push(gridData);
- }
- }
- }
- // 如果没有已放置的方块,直接返回
- if (placedBlocks.length === 0) {
- console.log('没有可清除的方块');
- return;
- }
- // 随机选择一个方块作为中心点
- const randomIndex = randomRangeInt(0, placedBlocks.length);
- const centerBlock = placedBlocks[randomIndex];
- if (!centerBlock.gridNode) return;
- // 获取中心方块的位置
- const centerPosition = centerBlock.gridNode.getWorldPosition();
- // 要清除的方块列表
- const blocksToSmash: GridData[] = [];
- // 首先添加中心块
- blocksToSmash.push(centerBlock);
- // 确定要消除的总方块数量 (3-6个方块)
- const totalBlockCount = randomRangeInt(3, 7);
- // 设置最大曼哈顿距离,限制只选择锤子附近的方块
- const MAX_DISTANCE = 2; // 最多选择周围2格内的方块
- // 收集锤子周围符合距离要求的方块
- const nearbyBlocks: GridData[] = [];
- for (let row = Math.max(0, centerBlock.row - MAX_DISTANCE);
- row <= Math.min(this.max_row - 1, centerBlock.row + MAX_DISTANCE);
- row++) {
- for (let col = Math.max(0, centerBlock.column - MAX_DISTANCE);
- col <= Math.min(this.max_col - 1, centerBlock.column + MAX_DISTANCE);
- col++) {
- // 跳过中心块自身
- if (row === centerBlock.row && col === centerBlock.column) continue;
- const currentBlock = this.gridList[row][col];
- // 只考虑已放置的方块
- if (currentBlock.status === GridStatus.Used && currentBlock.gridNode) {
- // 计算与中心块的曼哈顿距离
- const distance = Math.abs(row - centerBlock.row) + Math.abs(col - centerBlock.column);
- // 只添加在指定距离内的方块
- if (distance <= MAX_DISTANCE) {
- nearbyBlocks.push(currentBlock);
- }
- }
- }
- }
- // 如果周围没有足够的方块,就用现有的所有方块
- const extraBlocksToSelect = Math.min(totalBlockCount - 1, nearbyBlocks.length);
- // 随机选择周围的方块,但保持锤子范围内的聚集效果
- for (let i = 0; i < extraBlocksToSelect; i++) {
- if (nearbyBlocks.length === 0) break;
- // 随机选择一个附近的方块
- const selectedIndex = randomRangeInt(0, nearbyBlocks.length);
- blocksToSmash.push(nearbyBlocks[selectedIndex]);
- // 从列表中移除已选方块,避免重复选择
- nearbyBlocks.splice(selectedIndex, 1);
- }
- // 如果没有足够的方块可清除,直接返回
- if (blocksToSmash.length < 2) {
- oops.gui.toast('附近没有足够的方块可清除')
- return;
- }
- // 显示锤子并设置在中心方块上方
- if (this.hammerNode) {
- this.hammerNode.active = true;
- const hammerPosition = centerPosition.clone();
- hammerPosition.y += 50; // 设置在方块上方一定距离
- this.hammerNode.setWorldPosition(hammerPosition);
- // 播放锤子敲击动画,并清除选择的方块
- this.playHammerSmashAnimation(blocksToSmash);
- }
- }
- // 添加锤子敲击动画,并清除目标区域内所有方块
- private playHammerSmashAnimation(blocksToSmash: GridData[]): void {
- if (!this.hammerNode) return;
- // 创建敲击动画
- tween(this.hammerNode)
- .to(0.1, { angle: -30 }) // 锤子抬起
- .to(0.1, { angle: 30 }) // 锤子落下
- .call(() => {
- // 添加更强的震动效果
- tween(this.node)
- .to(0.05, { position: new Vec3(8, 0, 0) })
- .to(0.05, { position: new Vec3(-8, 0, 0) })
- .to(0.05, { position: new Vec3(5, 5, 0) })
- .to(0.05, { position: new Vec3(-5, -5, 0) })
- .to(0.05, { position: new Vec3(0, 0, 0) })
- .start();
- // 播放敲击音效(如果有的话)
- // this.audioManager.playHammerSmash();
- // 依次执行方块消除动画,让消除有先后顺序
- blocksToSmash.forEach((targetBlock, index) => {
- if (targetBlock.gridNode?.children[0]) {
- this.scheduleOnce(() => {
- tween(targetBlock.gridNode!.children[0])
- .to(0.2, { scale: new Vec3(0.5, 0.5) })
- .call(() => {
- // 更新格子状态
- targetBlock.status = GridStatus.NotUse;
- targetBlock.gridColorKey = null;
- this.generateGrid(targetBlock);
- })
- .start();
- }, index * 0.05); // 添加少量延迟,创造波纹式消除效果
- }
- });
- // 延迟一段时间后隐藏锤子
- this.scheduleOnce(() => {
- if (this.hammerNode) {
- this.hammerNode.active = false;
- }
- }, 0.5); // 增加时间以完成全部消除动画
- })
- .start();
- }
- //点击进入提现页面
- }
|