cover_image

100关推箱子游戏

小工 一枚小工
2019年08月07日 10:44

实现原理

1.创建游戏场景,通过读取配置文件,取到地图数据并保存,核心逻辑如下:

this.allLevelConfig = {};cc.loader.loadRes('levelConfig.json', function (err, object) {    if (err) {        console.log(err);        return;    }    this.allLevelConfig = object.json.level;    this.allLevelCount = object.json.levelCount;    this.loadingTxt.active = false;    this.startBtn.getComponent(cc.Button).interactable = true;
//加载完配置后,直接创建关卡元素 this.createLavelItem();}.bind(this));


2.地图采用定宽原则,先计算出地图方块的尺寸,再计算每个方块的偏移量就可以设置游戏的每块地图的坐标,核心逻辑如下:

//计算方块大小this.boxW = this.allWidth / this.allCol;this.boxH = this.boxW;
//计算起始坐标let sPosX = -(this.allWidth / 2) + (this.boxW / 2);let sPosY = (this.allWidth / 2) - (this.boxW / 2);
//计算坐标的偏移量,运算规则(宽铺满,设置高的坐标)let offset = 0;if(this.allRow > this.allCol){ offset = ((this.allRow - this.allCol) * this.boxH) / 2;}else{ offset = ((this.allRow - this.allCol) * this.boxH) / 2;}


3.人物运动,玩家点哪游戏人物就走到哪,通过递归查找,并保留最短路线,如果目标点不可达,则人物不移动,核心逻辑如下:

//curPos记录当前坐标,step记录步数getPath : function(curPos, step, result){    //判断是否到达终点    if((curPos.row == this.end.row) && (curPos.col == this.end.col)){        if(step < this.minPath){            this.bestMap = [];            for(let i = 0; i < result.length; i++){                this.bestMap.push(result[i]);            }            this.minPath = step; //如果当前抵达步数比最小值小,则修改最小值            result = [];        }    }
//递归 for(let i = (curPos.row - 1); i <= (curPos.row + 1); i++){ for(let j = (curPos.col - 1); j <= (curPos.col + 1); j++){ //越界跳过 if((i < 0) || (i >= this.allRow) || (j < 0) || (j >= this.allCol)){ continue; } if((i != curPos.row) && (j != curPos.col)){//忽略斜角 continue; } else if(this.palace[i][j] && ((this.palace[i][j] == boxType.LAND) || (this.palace[i][j] == boxType.BODY))){ let tmp = this.palace[i][j]; this.palace[i][j] = boxType.WALL; //标记为不可走
//保存路线 let r = {}; r.row = i; r.col = j; result.push(r);
this.getPath(r, step + 1, result); this.palace[i][j] = tmp; //尝试结束,取消标记 result.pop(); } } }},


4.路线计算好后,玩家移动,若玩家点击的是箱子区域,先检测箱子前方是否有障碍物,若没有则推动箱子,通过切换地图的图片和修改位置类型达到推动箱子的效果。


5.游戏结束判定,若达成目标的箱子数量和配置的箱子数量相等,则游戏过关。


以下是游戏中的效果图

图片


游戏源码

(关注公众号,发送消息“推箱子”获取源码)

图片

【体验游戏,请点击】阅读原文

继续滑动看下一个
一枚小工
向上滑动看下一个