MazeRunner/Bobo.System.Maze.Bot/SimplerBot.cs

87 lines
3.3 KiB
C#

using Bobo.System.Maze.Bot.Interface;
using HightechICT.Amazeing.Client.Rest;
using Microsoft.Extensions.Logging;
namespace Bobo.System.Maze.Bot
{
public class SimplerBot : BaseBot
{
public SimplerBot(AmazeingClient mazeClient, ILogger logger) : base(mazeClient, logger)
{ }
public override async Task<int> Run(MazeInfo maze)
{
if (MazeClient == null)
throw new ArgumentException(nameof(MazeClient));
if (string.IsNullOrWhiteSpace(maze.Name))
throw new ArgumentException(nameof(maze.Name));
Random random = new Random();
Logger.Log(LogLevel.Information, "Entering maze '{MazeName}'", maze.Name);
PossibleActionsAndCurrentScore result = await MazeClient.EnterMaze(maze.Name);
Stack<Direction> directions = new Stack<Direction>();
int collected = 0;
do
{
if (result.PossibleMoveActions.All(m => m.HasBeenVisited))
{
Logger.Log(LogLevel.Debug, "All adjacent tiles have been visited! Going back.");
Direction direction = directions.Pop();
switch (direction)
{
case Direction.Left:
direction = Direction.Right;
break;
case Direction.Right:
direction = Direction.Left;
break;
case Direction.Up:
direction = Direction.Down;
break;
case Direction.Down:
direction = Direction.Up;
break;
}
Logger.Log(LogLevel.Debug, "Moving {Direction}, I have been here.", direction);
result = await MazeClient.Move(direction);
}
else
{
MoveAction[] notVisited = result.PossibleMoveActions.Where(m => !m.HasBeenVisited).ToArray();
Logger.Log(LogLevel.Debug, $"{string.Join(", ", notVisited.Select(m => m.Direction.ToString()))} have not been visited, selecting next move.");
int selected = random.Next(notVisited.Length - 1);
MoveAction moveAction = notVisited[selected];
Logger.Log(LogLevel.Debug, $"Moving {moveAction.Direction}, I have {(!moveAction.HasBeenVisited ? "not" : string.Empty)} been here.");
result = await MazeClient.Move(moveAction.Direction);
directions.Push(moveAction.Direction);
}
if (result.CanCollectScoreHere && result.CurrentScoreInHand > 0)
{
collected += result.CurrentScoreInHand;
await MazeClient.CollectScore();
}
Logger.Log(LogLevel.Debug, $"New tile has {(!result.CanExitMazeHere ? "no" : string.Empty)} exit.");
} while (!result.CanExitMazeHere);
await MazeClient.ExitMaze();
Logger.Log(LogLevel.Information, "Collected {Collected}!", collected);
Logger.Log(LogLevel.Information, "Exited maze {MazeName}!", maze.Name);
return collected;
}
}
}