public class MakeMap { private var mapParam:MapParam = null; private var types:ArrayCollection = null; //保证取得的数据不被重取 private var flags:ArrayCollection = null; public function MakeMap(param:MapParam):void { mapParam = param; initData(); }
// 初始化必要的数据 private function initData():void { types = new ArrayCollection(); var typeNum:int = Math.floor(mapParam.cols*mapParam.rows/mapParam.numberPerType); for(var i:int=1;i<=typeNum;i++) { for (var j:int=0;j<mapParam.numberPerType;j++) { types.addItem(i); }
}
var yushu:int = mapParam.cols*mapParam.rows - typeNum*mapParam.numberPerType; for (var yI:int = 0; yI<yushu;yI++) { types.addItem(1); } }
//随机生成地图 public function make():Array { flags = new ArrayCollection(); for(var i:int=0;i<types.length;i++){ flags.addItem(i); } var mapData:Array = new Array(); var rowData:Array = null; var col:int = 0;
// 随机取得单个数据 private function getType():int { var ran:int=-1; var ret:int = 0; ran = randomIndex(); var index:int = int(flags.getItemAt(ran)); flags.removeItemAt(ran); ret = int(types.getItemAt(index)); return ret; }
private function randomIndex():int { return Math.random() * (flags.length - 1); } } } 参数类,就是一个bean, package src.ww.llk.map { public class MapParam { public var rows:Number=0; public var cols:Number=0; public var numberPerType:int=4; } } 测试类: public function test():void { var param:MapParam = new MapParam(); param.rows = 6; param.cols = 6; param.numberPerType = 4; var maker:MakeMap = new MakeMap(param); var map:Array = maker.make(); for each(var rowData:Array in map) { var rowStr:String = ""; for each(var cell:int in rowData) { rowStr += cell + " "; } trace(rowStr); } }