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); }
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); }
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; }
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); }
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; }
public Map GenerateMap() { Map map = new Map(); // Generate the layout // Add in start positions return map; }
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; }
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; }
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); } }
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); }
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); }
public override RobotMove NextMove(Map map) { return moves[index++]; ; }
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; }
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; }
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); } }
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; }
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; } }
public abstract RobotMove NextMove(Map map, Vector target, SpecialTargetType type);
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]); }
private void UpdateMap(Map newMap) { if (OnMapUpdate != null) OnMapUpdate(newMap); }
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()); } }
public abstract RobotMove NextMove(Map map);
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); } }
public override RobotMove NextMove(Map map) { return moves[(index++)%moves.Length]; }
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; }
public string GetMapStateAsAscii(Map map) { return new MapSerializer().SerializeMapOnly(map.SkipBorder()).ToString(); }
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); }
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; }