直接上代码
//随机地图const { ccclass, property } = cc._decorator;@ccclass
export default class NewClass extends cc.Component {@property(cc.Node)mapItem: cc.Node = null;@property(cc.Node)mapContent: cc.Node = null;private mapArr: any = [];onLoad() {}start() {}ranstatr() {let mapData = this.creatMap(10, 10);this.brushMap(mapData);}rand(min: number, max: number) {let num = Math.random() * (max + 1 - min) + min;num = parseInt(num.toString());return num}creatMap(r: number, c: number) {this.mapArr = [];let notAccessed = [];let accessed = [];for (let i = 0; i < r * 2 + 1; ++i) {let arr = [];for (let n = 0; n < c * 2 + 1; ++n) {if ((n ^ (n - 1)) == 1 && (i ^ (i - 1)) == 1) {arr.push(0); // 0 表示路notAccessed.push(0);}else {arr.push(1); // 1 表示墙}}this.mapArr.push(arr);}let count = r * c;let cur = this.rand(0, count);let offs = [-c, c, -1, 1]; // 四周顶点在notAccessed的偏移量let offr = [-1, 1, 0, 0]; // 四周顶点在arr的纵向偏移量let offc = [0, 0, -1, 1]; // 四周顶点在arr的横向偏移量accessed.push(cur);notAccessed[cur] = 1;while (accessed.length < count) {let tr = parseInt((cur / c).toString());let tc = parseInt((cur % c).toString());let num = 0;let off = -1;// 遍历上下左右顶点while (++num < 5) {let around = this.rand(0, 4),nr = tr + offr[around],nc = tc + offc[around];if (nr >= 0 && nc >= 0 && nr < r && nc < c && notAccessed[cur + offs[around]] == 0) {off = around;break;}}// 四周顶点均被访问,则从已访问的顶点中随机抽取一个为curif (off < 0) {cur = accessed[this.rand(0, accessed.length)];}else {tr = 2 * tr + 1;tc = 2 * tc + 1;this.mapArr[tr + offr[off]][tc + offc[off]] = 0;cur = cur + offs[off];notAccessed[cur] = 1;accessed.push(cur);// cc.log(accessed.length)}}return this.mapArr;}brushMap(map) {for (let i = 0; i < 21; i++) {for (let n = 0; n < 21; n++) {let node = this.instantiateMap(i, n);if (map[i][n] == 1) {var color1 = new cc.Color(255, 0, 0, 255);node.color = color1;}}}}instantiateMap(i, n) {let node = cc.instantiate(this.mapItem);node.parent = this.mapContent;node.setPosition(new cc.Vec2(i * 10, n * 10));return node;}
}