예제 #1
0
 private IEnumerable<Tuple<Vector, SpecialTargetType>> GetSpecial(Map map)
 {
     // Favorite lambdas
     var lambdas = new List<Vector>(map.TotalLambdaCount);
     foreach(var vector in GetElements(map, cell => cell == MapCell.Lambda))
     {
         lambdas.Add(vector);
         yield return new Tuple<Vector, SpecialTargetType>(vector, SpecialTargetType.Favorite);
     }
     //  Kamikadze way
     yield return new Tuple<Vector, SpecialTargetType>(new Vector(1, 1), SpecialTargetType.Kamikadze);
     // Favorite trampolines
     var trampolines = new List<Vector>();
     foreach(var vector in GetElements(map, cell => cell.ToString().StartsWith("Trampoline")))
     {
         trampolines.Add(vector);
         yield return new Tuple<Vector, SpecialTargetType>(vector, SpecialTargetType.Favorite);
     }
     // Banned lambdas
     foreach(var vector in lambdas)
         yield return new Tuple<Vector, SpecialTargetType>(vector, SpecialTargetType.Banned);
     // Banned trampoline
     foreach(var vector in trampolines)
         yield return new Tuple<Vector, SpecialTargetType>(vector, SpecialTargetType.Banned);
 }
예제 #2
0
 private static IEnumerable<Vector> GetElements(Map map, Predicate<MapCell> predicate)
 {
     for(int i = 0; i < map.Width; i++)
         for(int j = 0; j < map.Height; j++)
             if(predicate(map.GetCell(i, j)))
                 yield return new Vector(i, j);
 }
예제 #3
0
 public Map DoMove(RobotMove robotMove, Map map)
 {
     if (map.State != CheckResult.Nothing) return map;
     var resMap = map.Move(robotMove);
     AddMove(robotMove);
     UpdateMap(resMap);
     return resMap;
 }
예제 #4
0
 public virtual Map RunProgram(Map map, IEnumerable<RobotMove> moves)
 {
     foreach (var move in moves)
     {
         map = DoMove(move, map);
         if (map.State != CheckResult.Nothing) break;
     }
     return map;
 }
 public override RobotMove NextMove(Map map)
 {
     if(!isThreadStarted)
     {
         isThreadStarted = true;
         StartThread();
     }
     return backTrackingGreedyBot.NextMove(map);
 }
예제 #6
0
 private static string[] GetTargets(Vector from, Map map)
 {
     Console.WriteLine(map.ToString());
     var waveRun = new WaveRun(map, from);
     Tuple<Vector, Stack<RobotMove>>[] targets = waveRun.EnumerateTargets((lmap, pos, stepNumber) => lmap.GetCell(pos) == MapCell.Lambda).ToArray();
     string[] formattedTargets = targets.Select(FormatTarget).ToArray();
     foreach (var target in formattedTargets)
         Console.WriteLine(target);
     return formattedTargets;
 }
예제 #7
0
        public Map GenerateMap()
        {
            Map map = new Map();

            // Generate the layout

            // Add in start positions

            return map;
        }
예제 #8
0
        public override RobotMove NextMove(Map map)
        {
            if(bestMoves == null)
            {
                CalcSolution(map);
                if(bestMoves == null) return RobotMove.Abort;
            }

            return currentMove <= bestMoves.Length - 1 ? bestMoves[currentMove++] : RobotMove.Abort;
        }
예제 #9
0
 private bool GetItBaby(Map map, Tuple<Vector, SpecialTargetType> special)
 {
     if(StopNow) return true;
     var moves = GetMoves(map, special);
     if(moves == null) return true;
     if(bestScores < moves.Item2)
     {
         bestScores = moves.Item2;
         bestMoves = moves.Item1;
     }
     return false;
 }
예제 #10
0
 public void TestPerformanceOnConcreteMap()
 {
     var map = new Map(Path.Combine(MapsDir, "random20_fl_50.map.txt"));
     var robotMove = RobotMove.Wait;
     var bot = new GreedyBot();
     var botWrapper = new BotWithBestMomentsMemory(bot);
     while (robotMove != RobotMove.Abort && map.State == CheckResult.Nothing)
     {
         robotMove = botWrapper.NextMove(map);
         map = map.Move(robotMove);
         botWrapper.UpdateBestSolution(map);
     }
 }
예제 #11
0
 private static void Main(string[] args)
 {
     string[] lines = Console.In.ReadToEnd().Split(new[] {Environment.NewLine}, StringSplitOptions.None);
     var map = new Map(lines);
     var bot = new TimeAwaredBackTrackingGreedyBot(140);
     var robotMoves = new List<RobotMove>();
     RobotMove robotMove;
     do
     {
         robotMove = bot.NextMove(map);
         robotMoves.Add(robotMove);
         map = map.Move(robotMove);
     } while(robotMove != RobotMove.Abort && map.State == CheckResult.Nothing);
     string result = robotMoves.Count > 0 ? new string(robotMoves.Select(move => move.ToChar()).ToArray()) : "A";
     Console.Write(result);
 }
예제 #12
0
 private Tuple<RobotMove[], long> GetMoves(Map map, Tuple<Vector, SpecialTargetType> special)
 {
     var moves = new List<RobotMove>();
     var bot = new BotWithBestMomentsMemory(new GreedyBot());
     RobotMove robotMove;
     Map localMap = map;
     do
     {
         if(StopNow) return null;
         robotMove = special != null ? bot.NextMove(localMap, special.Item1, special.Item2) : bot.NextMove(localMap);
         localMap = localMap.Move(robotMove);
         bot.UpdateBestSolution(localMap);
         moves.Add(robotMove);
     } while(robotMove != RobotMove.Abort && localMap.State == CheckResult.Nothing);
     return Tuple.Create(bot.GetBestMovesAsArray(), localMap.State != CheckResult.Fail ? localMap.GetScore() : long.MinValue);
 }
예제 #13
0
 public override RobotMove NextMove(Map map)
 {
     return moves[index++];
     ;
 }
예제 #14
0
파일: Map.cs 프로젝트: xoposhiy/icfpc2012
        private void Update(Map newMap)
        {
            var robotFailed = false;

            var activeMoves = new SortedSet<Tuple<Vector, Vector, MapCell>>(new TupleVectorComparer());
            foreach (var rockPos in activeRocks.Concat(newMap.activeRocks).Distinct())
            {
                var cell = newMap.GetCell(rockPos);
                var rockMove = TryToMoveRock(rockPos, cell, newMap);
                if (rockMove == null) continue;
                var newRockPos = rockPos.Add(rockMove);
                if (cell == MapCell.LambdaRock && newMap.GetCell(newRockPos.Sub(new Vector(0, 1))) != MapCell.Empty)
                    activeMoves.Add(Tuple.Create(rockPos, newRockPos, MapCell.Lambda));
                else
                    activeMoves.Add(Tuple.Create(rockPos, newRockPos, cell));
            }

            newMap.GrowthLeft--;
            if (newMap.GrowthLeft == 0)
            {
                newMap.GrowthLeft = newMap.Growth;
                foreach (var beardPos in newMap.Beard)
                    for (var x = -1; x <= 1; x++)
                        for (var y = -1; y <= 1; y++)
                        {
                            var newBeardPos = beardPos.Add(new Vector(x, y));
                            if (newMap.GetCell(newBeardPos) == MapCell.Empty)
                                activeMoves.Add(Tuple.Create(beardPos, newBeardPos, MapCell.Beard));
                        }
            }

            var newActiveRocks = new SortedSet<Vector>(new VectorComparer());
            foreach (var activeMove in activeMoves)
            {
                var fromPos = activeMove.Item1;
                var toPos = activeMove.Item2;
                var fromCell = newMap.GetCell(fromPos);
                var toCell = newMap.GetCell(toPos);
                if (fromCell.IsRock())
                {
                    if (!toCell.IsRock()) newActiveRocks.Add(toPos);

                    newMap.field = newMap.SetCell(toPos, activeMove.Item3);
                    newMap.field = newMap.SetCell(fromPos, MapCell.Empty);

                    robotFailed |= IsRobotKilledByRock(toPos.X, toPos.Y, newMap);
                    CheckNearRocks(newActiveRocks, fromPos.X, fromPos.Y, newMap);
                    newMap.Beard.Remove(toPos);
                }
                else if(fromCell == MapCell.Beard)
                {
                    newMap.field = newMap.SetCell(toPos, MapCell.Beard);
                    newMap.Beard.Add(toPos);
                }
            }
            newMap.activeRocks = newActiveRocks;

            if (newMap.TotalLambdaCount == newMap.LambdasGathered)
                newMap.field = newMap.SetCell(Lift, MapCell.OpenedLift);

            robotFailed |= IsRobotKilledByFlood(newMap);
            if (robotFailed)
                newMap.State = CheckResult.Fail;
        }
예제 #15
0
파일: Map.cs 프로젝트: xoposhiy/icfpc2012
        private void DoMove(int newRobotX, int newRobotY, Map newMap)
        {
            var newMapCell = GetCell(newRobotX, newRobotY);
            if (newMapCell == MapCell.Lambda)
            {
                newMap.LambdasGathered++;
            }
            else if (newMapCell.IsTrampoline())
            {
                var target = TrampToTarget[newMapCell];
                var targetCoords = Targets[target];
                newRobotX = targetCoords.X;
                newRobotY = targetCoords.Y;
                foreach (var pair in TrampToTarget.Where(a => a.Value == target))
                {
                    var trampolinePos = Trampolines[pair.Key];
                    newMap.field = newMap.SetCell(trampolinePos, MapCell.Empty);
                    CheckNearRocks(newMap.activeRocks, trampolinePos.X, trampolinePos.Y, newMap);
                }
            }
            else if (newMapCell == MapCell.Earth)
            {
            }
            else if (newMapCell == MapCell.Razor)
            {
                newMap.Razors++;
            }
            else if (newMapCell == MapCell.OpenedLift)
            {
                newMap.State = CheckResult.Win;
            }
            else if (newMapCell.IsRock())
            {
                var rockX = newRobotX * 2 - RobotX;
                newMap.field = newMap.SetCell(rockX, newRobotY, newMapCell);
                newMap.activeRocks.Add(new Vector(rockX, newRobotY));
            }
            newMap.field = newMap.SetCell(RobotX, RobotY, MapCell.Empty);
            if (newMapCell != MapCell.OpenedLift)
                newMap.field = newMap.SetCell(newRobotX, newRobotY, MapCell.Robot);

            CheckNearRocks(newMap.activeRocks, RobotX, RobotY, newMap);

            newMap.RobotX = newRobotX;
            newMap.RobotY = newRobotY;
        }
예제 #16
0
파일: Map.cs 프로젝트: xoposhiy/icfpc2012
 private void CutBeard(Map newMap)
 {
     if (Razors == 0) return;
     newMap.Razors--;
     newMap.Beard = new HashSet<Vector>();
     foreach (var b in Beard)
     {
         if(Robot.Distance(b) > 1)
             newMap.Beard.Add(b);
         else
             newMap.field = newMap.SetCell(b, MapCell.Empty);
     }
 }
예제 #17
0
파일: Map.cs 프로젝트: xoposhiy/icfpc2012
 private Map Clone()
 {
     var clone = new Map
     {
         Width = Width,
         Height = Height,
         activeRocks = new SortedSet<Vector>(new VectorComparer()),
         Flooding = Flooding,
         LambdasGathered = LambdasGathered,
         Lift = Lift,
         MovesCount = MovesCount,
         RobotX = RobotX,
         RobotY = RobotY,
         State = State,
         InitialWater = InitialWater,
         StepsToIncreaseWater = StepsToIncreaseWater,
         Targets = new Dictionary<MapCell, Vector>(Targets.Select(kvp => new { kvp.Key, kvp.Value }).ToDictionary(kvp => kvp.Key, kvp => kvp.Value)),
         TotalLambdaCount = TotalLambdaCount,
         TrampToTarget = new Dictionary<MapCell, MapCell>(TrampToTarget.Select(kvp => new { kvp.Key, kvp.Value }).ToDictionary(t => t.Key, t => t.Value)),
         Trampolines = new Dictionary<MapCell, Vector>(Trampolines.Select(kvp => new { kvp.Key, kvp.Value }).ToDictionary(kvp => kvp.Key, kvp => kvp.Value)),
         Water = Water,
         Waterproof = Waterproof,
         WaterproofLeft = WaterproofLeft,
         field = field,
         Beard = new HashSet<Vector>(Beard),
         Growth = Growth,
         GrowthLeft = GrowthLeft,
         Razors = Razors,
     };
     return clone;
 }
예제 #18
0
 public bool AssertEngineState(Map actualMap)
 {
     try
     {
         CheckResult checkResult = actualMap.State;
         if (checkResult == CheckResult.Abort) checkResult = CheckResult.Nothing; //Специфика загружалки результатов валидатора
         Assert.AreEqual(Result, checkResult, this.ToString());
         Assert.AreEqual(Score, actualMap.GetScore(), this.ToString());
         var mapStateAsAscii = GetMapStateAsAscii(actualMap);
         string actualMap1 = Regex.Replace(mapStateAsAscii, "[A-I]", "T"); //Специфика вывода валидатора
         string actualMap2 = Regex.Replace(actualMap1, "[1-9]", "t"); //Специфика вывода валидатора
         Assert.AreEqual(FinalMapState, actualMap2, string.Format("{0}\r\nactual map state:\r\n{1}", this.ToString(), actualMap2));
         return true;
     }
     catch (AssertionException ex)
     {
         Console.WriteLine(ex.Message);
         return false;
     }
 }
예제 #19
0
 public abstract RobotMove NextMove(Map map, Vector target, SpecialTargetType type);
예제 #20
0
 public static RobotAI Create(Type robotType, Map map)
 {
     ConstructorInfo constructorInfo = robotType.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, new Type[0], null);
     return (RobotAI) constructorInfo.Invoke(new object[0]);
 }
예제 #21
0
 private void UpdateMap(Map newMap)
 {
     if (OnMapUpdate != null) OnMapUpdate(newMap);
 }
예제 #22
0
        private void TestBrains(Func<RobotAI> botFactory, string dir)
        {
            var now = DateTime.Now;
            var typeBot = botFactory();
            string botName = typeBot.GetType().Name;
            using (var writer = new StreamWriter(Path.Combine(TestsDir, botName + "_" + now.ToString("yyyy-MM-dd_HH-mm-ss") + ".txt")))
            {
                long sum = 0;
                WriteLineAndShow(writer, botName + " " + now.ToString("yyyy-MM-dd HH:mm:ss"));
                WriteLineAndShow(writer);
                WriteLineAndShow(writer, "\t  score: [W|N|A] <SCORE> (W - win, N - nothing, A - Abort)");
                WriteLineAndShow(writer);

                WriteLineAndShow(writer,
                    "map".PadRight(FilenamePadding)
                    + "ms".PadRight(ValuePadding)
                    + "ch?".PadRight(ValuePadding)
                    + "curScore".PadRight(ValuePadding)
                    + "prevScores    ...   moves");
                foreach (var file in Directory.GetFiles(dir, "*.map.txt"))
                {
                    string mapName = Path.GetFileNameWithoutExtension(file) ?? "NA";
                    var lines = File.ReadAllLines(file);
                    var bot = botFactory();
                    var map = new Map(lines);

                    var robotMove = RobotMove.Wait;

                    var timer = Stopwatch.StartNew();
                    var botWrapper = new BotWithBestMomentsMemory(bot);
                    while(robotMove != RobotMove.Abort && map.State == CheckResult.Nothing)
                    {
                        robotMove = (timer.Elapsed.TotalSeconds < 150) ? botWrapper.NextMove(map) : RobotMove.Abort;

                        map = map.Move(robotMove);
                        botWrapper.UpdateBestSolution(map);
                    }
                    string[] history = LoadHistory(dir, mapName, botName);
                    string result = botWrapper.BestMovesEndState.ToString()[0] + " " + botWrapper.BestScore.ToString();
                    bool resultChanged = result != history.FirstOrDefault();
                    WriteLineAndShow(writer,
                        mapName.PadRight(FilenamePadding)
                        + timer.ElapsedMilliseconds.ToString().PadRight(ValuePadding)
                        + (resultChanged ? "*" : "").PadRight(ValuePadding)
                        + result.PadRight(ValuePadding)
                        + String.Join(" ", history.Take(10)) + "  "
                        + botWrapper.GetBestMoves());
                    if (resultChanged)
                        history = new[] {result}.Concat(history).ToArray();
                    File.WriteAllLines(GetHistoryFilename(dir, mapName, botName), history);
                    sum += botWrapper.BestScore;
                }
                WriteLineAndShow(writer, sum.ToString());
            }
        }
예제 #23
0
 public abstract RobotMove NextMove(Map map);
예제 #24
0
파일: Map.cs 프로젝트: xoposhiy/icfpc2012
 private static void CheckNearRocks(SortedSet<Vector> updateableRocks, int x, int y, Map mapToUse)
 {
     for (var rockX = x - 1; rockX <= x + 1; rockX++)
         for (var rockY = y; rockY <= y + 1; rockY++)
         {
             var rockPos = new Vector(rockX, rockY);
             if (TryToMoveRock(rockPos, mapToUse.GetCell(rockPos), mapToUse) != null)
                 updateableRocks.Add(rockPos);
         }
 }
예제 #25
0
 public override RobotMove NextMove(Map map)
 {
     return moves[(index++)%moves.Length];
 }
예제 #26
0
파일: Map.cs 프로젝트: xoposhiy/icfpc2012
 private static bool IsRobotKilledByFlood(Map newMap)
 {
     if (newMap.Water >= newMap.RobotY) newMap.WaterproofLeft--;
     else newMap.WaterproofLeft = newMap.Waterproof;
     if (newMap.Flooding > 0)
     {
         newMap.StepsToIncreaseWater--;
         if (newMap.StepsToIncreaseWater == 0)
         {
             newMap.Water++;
             newMap.StepsToIncreaseWater = newMap.Flooding;
         }
     }
     return newMap.WaterproofLeft < 0;
 }
예제 #27
0
 public string GetMapStateAsAscii(Map map)
 {
     return new MapSerializer().SerializeMapOnly(map.SkipBorder()).ToString();
 }
예제 #28
0
파일: Map.cs 프로젝트: xoposhiy/icfpc2012
 private static bool IsRobotKilledByRock(int x, int y, Map mapToUse)
 {
     return mapToUse.GetCell(x, y - 1) == MapCell.Robot;
 }
 public override RobotMove NextMove(Map map, Vector target, SpecialTargetType type)
 {
     return NextMove(map);
 }
예제 #30
0
파일: Map.cs 프로젝트: xoposhiy/icfpc2012
 private static Vector TryToMoveRock(Vector p, MapCell xyCell, Map mapToUse)
 {
     int x = p.X;
     int y = p.Y;
     if (xyCell.IsRock())
     {
         var upCell = mapToUse.GetCell(x, y - 1);
         if (upCell == MapCell.Empty)
         {
             return new Vector(0, -1);
         }
         if (upCell.IsRock()
             && mapToUse.GetCell(x + 1, y) == MapCell.Empty && mapToUse.GetCell(x + 1, y - 1) == MapCell.Empty)
         {
             return new Vector(1, -1);
         }
         if (upCell.IsRock()
             && (mapToUse.GetCell(x + 1, y) != MapCell.Empty || mapToUse.GetCell(x + 1, y - 1) != MapCell.Empty)
             && mapToUse.GetCell(x - 1, y) == MapCell.Empty && mapToUse.GetCell(x - 1, y - 1) == MapCell.Empty)
         {
             return new Vector(-1, -1);
         }
         if (upCell == MapCell.Lambda
             && mapToUse.GetCell(x + 1, y) == MapCell.Empty && mapToUse.GetCell(x + 1, y - 1) == MapCell.Empty)
         {
             return new Vector(1, -1);
         }
     }
     return null;
 }