package Game{
	import flash.display.*;
	import flash.utils.*;
	
	public class Level extends MovieClip{
		public var Map:LevelMap;
		public var Tiles:Array;
		public var FoodNum:Number = 0;
		public var MapWidth:Number = 0;
		public var MapHeight:Number = 0;
		
		function Level():void{
		}
		
		/**
		 * 
		 * @param	x
		 * @param	y
		 * @param	mc
		 */
		public function replaceTile(nx:Number, ny:Number, mc:MovieClip):void {	
			var Index:Number = getChildIndex(Tiles[nx][ny]);
			removeChild(Tiles[nx][ny]);
			mc.x = nx * 8;
			mc.y = ny * 8;
			Tiles[nx][ny] = mc;			
			addChildAt(Tiles[nx][ny], Index);
		}
		
		/**
		 * Удалить все тайлы
		 */
		public function clearTiles():void {
			for (var i:Number = 0; i < Tiles.length; i++) {
				for (var j:Number = 0; j < Tiles[i].length; j++) {
					removeChild(Tiles[i][j]);
				}
			}
			
			Tiles = new Array();
		}
		
		/** Генерируем изображние самого уровня **/
		public function InitLevel(Lvl: LevelMap):void{
			Map = Lvl;
			Tiles = new Array(Map.Fields.length);
			FoodNum = 0;
			
			MapWidth = Map.Fields.length;
			MapHeight = Map.Fields[0].length;
			
			for(var i:Number = 0; i < Map.Fields.length; i++)
			{
				Tiles[i] = new Array(Map.Fields[i].length);
				
				for(var j:Number = 0; j < Map.Fields[i].length; j++)
				{
					var tile_name:String = 'tile_' + (Map.Fields[i][j]).toString();
					var tile_class:Class = getDefinitionByName(tile_name) as Class;
					var t:MovieClip = new tile_class();
					
					if ((Map.Fields[i][j] == 1) || (Map.Fields[i][j] == 2)) {
						FoodNum++;
					}
					
					t.x = i * 8;
					t.y = j * 8;
					addChildAt(t, 0);
					Tiles[i][j] = t;
				}
			}			
		}
	}
}