public void Draw(ITurtle turtle)
 {
     turtle.Up();
     turtle.Move(0.2, 0.5);
     turtle.Down();
     turtle.Move(0.8, 0.5);
 }
Esempio n. 2
0
        public TurtleSetCommandTests()
        {
            ITurtleMoveService turtleMoveService = Mock.Of <TurtleMoveService>();

            _board  = Mock.Of <Board>();
            _turtle = new Turtle(turtleMoveService);
        }
Esempio n. 3
0
        // I used tuples because every related data must be provided together. If I use plain int's it will hard to construct and initialization would be unsafe because of the number of the arguments.
        /// <summary>
        /// Creates Minefield instance
        /// </summary>
        /// <param name="boardSizeXY"></param>
        /// <param name="listOfMines"></param>
        /// <param name="exitPointXY"></param>
        /// <param name="turtle"></param>
        public Minefield(Coordinate boardSizeXY, List <Coordinate> listOfMines, Coordinate exitPointXY, ITurtle turtle)
        {
            // Validations
            if (boardSizeXY.X * boardSizeXY.Y < listOfMines.Count)
            {
                throw new Exception("Number of mines must be less then the minearea cells.");
            }

            if (exitPointXY.X > boardSizeXY.X || exitPointXY.Y > boardSizeXY.Y)
            {
                throw new Exception("Wrong exit point coordinates. Exit point must be within the board.");
            }

            // Creation of the board
            xLength = boardSizeXY.X;
            yLength = boardSizeXY.Y;


            _board = new Dictionary <Coordinate, GameElements>();
            _board.Add(new Coordinate {
                X = exitPointXY.X, Y = exitPointXY.Y
            }, GameElements.Exit);

            foreach (var item in listOfMines)
            {
                _board.Add(new Coordinate {
                    X = item.X, Y = item.Y
                }, GameElements.Mine);
            }

            // Turtle injection
            _turtle = turtle;
        }
Esempio n. 4
0
 public Logic(IBoardSettings settings, ITurtle turtle)
 {
     _settings            = settings;
     _turtle              = turtle;
     _turtle.TurtleMoved += TurtleMoved;
     _turtlePosition      = new Tile(_settings.StartTile);
 }
Esempio n. 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GameBoard"/> class.
        /// </summary>
        /// <param name="turtle">a turtle object</param>
        public GameBoard(ITurtle turtle)
        {
            this.turtle = turtle;
            if (!strategies.ContainsKey(TurtleInstruction.Place))
            {
                strategies.Add(TurtleInstruction.Place, new PlaceCommand());
            }

            if (!strategies.ContainsKey(TurtleInstruction.Move))
            {
                strategies.Add(TurtleInstruction.Move, new MoveCommand());
            }

            if (!strategies.ContainsKey(TurtleInstruction.Left))
            {
                strategies.Add(TurtleInstruction.Left, new LeftCommand());
            }

            if (!strategies.ContainsKey(TurtleInstruction.Right))
            {
                strategies.Add(TurtleInstruction.Right, new RightCommand());
            }

            if (!strategies.ContainsKey(TurtleInstruction.Report))
            {
                strategies.Add(TurtleInstruction.Report, new ReportCommand());
            }

            if (!strategies.ContainsKey(TurtleInstruction.Invalid))
            {
                strategies.Add(TurtleInstruction.Invalid, new InvalidCommand());
            }
        }
Esempio n. 6
0
        public override bool Perform(ITurtle turtle)
        {
            if (turtle == null) return false;

            turtle.Reset();
            return true;
        }
        public void Init(Vector2 boardSize, Vector2 startingPosition, int startingRotation, Vector2 endPosition, List <Vector2> minePositions, List <string> actions)
        {
            _turtle = new Turtle();
            _turtle.Init((int)startingPosition.X, (int)startingPosition.Y, startingRotation);

            _gameBoard = new GameBoard();
            _gameBoard.SetSize((int)boardSize.X, (int)boardSize.Y);

            foreach (Vector2 pos in minePositions)
            {
                _gameBoard.SetTile((int)pos.X, (int)pos.Y, TileType.Mine);
            }

            _gameBoard.SetTile((int)startingPosition.X, (int)startingPosition.Y, TileType.Start);
            _gameBoard.SetTile((int)endPosition.X, (int)endPosition.Y, TileType.End);

            _turtleActions = new List <ITurtleAction>();
            foreach (string action in actions)
            {
                if (action == "L")
                {
                    _turtleActions.Add(new RotateAction(_turtle, RotationDirection.Left, RotationDirection.Right));
                }
                if (action == "R")
                {
                    _turtleActions.Add(new RotateAction(_turtle, RotationDirection.Right, RotationDirection.Left));
                }
                if (action == "M")
                {
                    _turtleActions.Add(new MoveAction(_turtle, _gameBoard));
                }
            }
        }
        public async Task Draw(ITurtle turtle)
        {
            turtle.Up();
            await turtle.Move(0.2, 0.5);

            turtle.Down();
            await turtle.Move(0.8, 0.5);
        }
Esempio n. 9
0
        public override bool Perform(ITurtle turtle)
        {
            if (turtle == null) return false;
            if (turtle.PenDown) return false;

            turtle.PenDown = true;
            return true;
        }
Esempio n. 10
0
 public GameValidator(IBoard board, List <ICoordinate> mines, ICoordinate exit, IPosition start, List <List <MoveType> > moves, ITurtle turtle)
 {
     Board         = board;
     Mines         = mines;
     Exit          = exit;
     StartPosition = start;
     Moves         = moves;
     Turtle        = turtle;
 }
Esempio n. 11
0
 public FileInput(ITurtle turtle,
                  Action <string> report,
                  Action clearCommandLine,
                  Func <string, bool> isValidPlaceCommand)  : base(turtle,
                                                                   report,
                                                                   clearCommandLine,
                                                                   isValidPlaceCommand)
 {
 }
Esempio n. 12
0
        public TurtleMoveCommandTests()
        {
            ITurtleMoveService turtleMoveService = Mock.Of <TurtleMoveService>();

            _board  = Mock.Of <Board>();
            _mine   = Mock.Of <Mine>();
            _exit   = Mock.Of <Exit>();
            _turtle = new Turtle(turtleMoveService);
        }
Esempio n. 13
0
        /// <summary>
        /// Place the object on the Table
        /// </summary>
        public void Place(ITurtle turtle, Position position, EDirection direction)
        {
            if (!Map.Contains(position))
            {
                return;
            }

            turtle.Position  = position;
            turtle.Direction = direction;
        }
 public void Draw(ITurtle turtle)
 {
     turtle.Up();
     turtle.Move(0.5 - _side / 2, 0.5 - _side / 2);
     turtle.Down();
     turtle.Move(0.5 - _side / 2, 0.5 + _side / 2);
     turtle.Move(0.5 + _side / 2, 0.5 + _side / 2);
     turtle.Move(0.5 + _side / 2, 0.5 - _side / 2);
     turtle.Move(0.5 - _side / 2, 0.5 - _side / 2);
 }
Esempio n. 15
0
 public StandardInput(ITurtle turtle,
                      Action <string> report,
                      Action clearCommandLine,
                      Func <string, bool> isValidPlaceCommand)
 {
     Turtle              = turtle;
     Report              = report;
     ClearCommandLine    = clearCommandLine;
     IsValidPlaceCommand = isValidPlaceCommand;
 }
Esempio n. 16
0
        public void Draw(ITurtle turtle)
        {
            turtle.Up();
            turtle.Move(0.5, 0.5 + _radius);
            turtle.Down();

            for (double theta = 0.0; theta <= 2 * Math.PI; theta += Math.PI / 20)
            {
                turtle.Move(0.5 + _radius * Math.Sin(theta), 0.5 + _radius * Math.Cos(theta));
            }
        }
Esempio n. 17
0
 public TurtleGameInvoker(IBoard board,
                          IExit exit,
                          ITurtle turtle,
                          IInitializationService <ITurtle, IMine> initializationService)
 {
     _board  = board;
     _mines  = new List <IMine>();
     _exit   = exit;
     _turtle = turtle;
     _initializationService = initializationService;
 }
Esempio n. 18
0
        public void Execute(string userInput, Action <string> writeOutput)
        {
            _turtleFilter.Execute(userInput);

            switch (_turtleFilter.TurtleCommand)
            {
            case TurtleCommand.PLACE:
                if (_turtle != null)
                {
                    throw new InvalidOperationException("Turtle has already been placed and please try other commands.");
                }

                //Turtle is defined and getting placed on the table now
                _turtle = new Turtle(_table, _rotation, _turtleFilter.Position, TurtleMovements.RotationAngle);
                break;

            case TurtleCommand.LEFT:
                if (_turtle == null)
                {
                    throw new InvalidOperationException("Turtle has not been placed and please place before runnig this command.");
                }

                _turtle.Left();
                break;

            case TurtleCommand.RIGHT:
                if (_turtle == null)
                {
                    throw new InvalidOperationException("Turtle has not been placed and please place before runnig this command.");
                }

                _turtle.Right();
                break;

            case TurtleCommand.MOVE:
                if (_turtle == null)
                {
                    throw new InvalidOperationException("Turtle has not been placed and please place before runnig this command.");
                }

                _turtle.Move();
                break;

            case TurtleCommand.REPORT:
                if (_turtle == null)
                {
                    throw new InvalidOperationException("Turtle has not been placed and please place before runnig this command.");
                }

                writeOutput(_turtle.Report());
                break;
            }
        }
Esempio n. 19
0
        public Game(IBoard board, List <ICoordinate> mines, ICoordinate exit, IPosition start, List <List <MoveType> > moves, ITurtle turtle, IGameValidator validator)
        {
            //Validate game settings
            validator.Validate();

            Board         = board;
            Mines         = mines;
            Exit          = exit;
            StartPosition = start;
            Moves         = moves;
            Turtle        = turtle;
        }
Esempio n. 20
0
        /// <summary>
        /// Gets the output for REPORT command
        /// </summary>
        /// <param name="turtle">turtle class instance</param>
        /// <param name="isSuccess">boolean representing a successful execution</param>
        /// <returns>command output</returns>
        private string GetReport(ITurtle turtle, out bool isSuccess)
        {
            if (turtle != null && turtle.Report() != null)
            {
                TurtleState currentState = turtle.Report();
                isSuccess = true;
                return(string.Format("{0}, {1}, {2}", currentState.X, currentState.Y, currentState.FacingDirection.ToString().ToUpper()));
            }

            isSuccess = false;
            return("Please place the turtle on the board before trying to get its current state.");
        }
Esempio n. 21
0
        public void Draw(ITurtle turtle)
        {
            double height = Math.Cos(Math.PI / 6) * _base;
            double centre = _base * Math.Tan(Math.PI / 6) / 2;

            turtle.Up();
            turtle.Move(0.5 - _base / 2, 0.5 + centre);
            turtle.Down();
            turtle.Move(0.5 + _base / 2, 0.5 + centre);
            turtle.Move(0.5, 0.5 + centre - height);
            turtle.Move(0.5 - _base / 2, 0.5 + centre);
        }
Esempio n. 22
0
 public void Interpret(ITurtle turtle, IEnumerable modules)
 {
     this.Turtle = turtle;
     foreach (var module in modules)
     {
         Action <object> action = null;
         if (this.registeredTypes.TryGetValue(module.GetType(), out action))
         {
             action(module);
         }
     }
     this.Turtle = null;
 }
        public async Task Draw(ITurtle turtle)
        {
            turtle.Up();
            await turtle.Move(0.5 - _side / 2, 0.5 - _side / 2);

            turtle.Down();
            await turtle.Move(0.5 - _side / 2, 0.5 + _side / 2);

            await turtle.Move(0.5 + _side / 2, 0.5 + _side / 2);

            await turtle.Move(0.5 + _side / 2, 0.5 - _side / 2);

            await turtle.Move(0.5 - _side / 2, 0.5 - _side / 2);
        }
Esempio n. 24
0
        private static void DoAction(ITurtle turtle, MovementSteps m)
        {
            switch (m)
            {
            case MovementSteps.Move:
                turtle.Move();
                break;

            case MovementSteps.Rotate:
                turtle.Rotate();
                break;

            default:
                throw new ArgumentException($"Unsupported movement type {m}");
            }
        }
Esempio n. 25
0
        /// <summary>
        ///     Execute RIGHT command
        /// </summary>
        /// <param name="turtle">turtle instance</param>
        /// <param name="arguments">NOT REQUIRED</param>
        /// <param name="message">message after command execution result</param>
        /// <returns>command execution result</returns>
        public bool DoExecution(ITurtle turtle, string[] arguments, out string message)
        {
            bool isSuccess;

            if (turtle.Right())
            {
                isSuccess = true;
                message   = MessageConstants.DoneMsg;
            }
            else
            {
                isSuccess = false;
                message   = turtle.GetErrorMessage();
            }

            return(isSuccess);
        }
Esempio n. 26
0
        private void Draw(PathGeometry geometry, string expression, ITurtle turtle, LSystem system, int currentLevel)
        {
            if (geometry.Figures.Count == 0)
            {
                geometry.Figures.Add(new PathFigure()
                {
                    Segments = { new PolyLineSegment() }, StartPoint = turtle.CurrentPosition.Point, IsClosed = System.IsClosed, IsFilled = System.IsFilled
                });
            }
            for (var i = 0; i < expression.Length; i++)
            {
                var chr = expression[i];
                if (currentLevel < system.Interation &&
                    ((ExpressionCollection)system.Expressions).TryGetValue(chr, out LExpression childExpression))
                {
                    Draw(geometry, childExpression.To, turtle, system, currentLevel + 1);
                }
                else if (system.Operations.TryGetValue(chr, out LOperation operation))
                {
                    TurtlePosition position;
                    switch (operation.Action)
                    {
                    case TurtleAction.Forward:
                        position = turtle.Forward(operation.Value);
                        ((PolyLineSegment)geometry.Figures[geometry.Figures.Count - 1].Segments[0]).Points.Add(position.Point);
                        break;

                    case TurtleAction.Turn:
                        turtle.Turn(operation.Value);
                        break;

                    case TurtleAction.Save:
                        turtle.SaveAngle();
                        break;

                    case TurtleAction.Restore:
                        position = turtle.RestoreAngle();
                        geometry.Figures.Add(new PathFigure()
                        {
                            Segments = { new PolyLineSegment() }, StartPoint = position.Point, IsClosed = System.IsClosed, IsFilled = System.IsFilled
                        });
                        break;
                    }
                }
            }
        }
Esempio n. 27
0
        /// <summary>
        ///     Execute REPORT command
        /// </summary>
        /// <param name="turtle">turtle instance</param>
        /// <param name="arguments">NOT REQUIRED</param>
        /// <param name="message">message after command execution result</param>
        /// <returns>command execution result</returns>
        public bool DoExecution(ITurtle turtle, string[] arguments, out string message)
        {
            bool isSuccess;

            if (turtle != null && turtle.Report() != null)
            {
                TurtleState currentState = turtle.Report();
                isSuccess = true;
                message   = string.Format("{0}, {1}, {2}", currentState.X, currentState.Y, currentState.FacingDirection.ToString().ToUpper());
            }
            else
            {
                isSuccess = false;
                message   = MessageConstants.InvalidStateMsg;
            }

            return(isSuccess);
        }
Esempio n. 28
0
        public void Draw(ITurtle turtle)
        {
            if (InvokeRequired)
            {
                Invoke(_draw, turtle);
                return;
            }

            if (turtle == null) return;

            Image buffer = turtle.Image;

            Graphics graphics = null;
            // get existing drawing surface
            Bitmap bitmap = (Bitmap)pictureTurtle.Image;
            // if surface exists, then test size
            if (bitmap != null)
            {
                if ((bitmap.Width < buffer.Width + 16) || (bitmap.Height < buffer.Height + 16))
                {
                    bitmap.Dispose();
                    bitmap = null;
                }
            }
            // if new image needed, then create
            if (bitmap == null) bitmap = new Bitmap(buffer.Width + 16, buffer.Height + 16, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            graphics = Graphics.FromImage(bitmap);
            graphics.Clear(pictureTurtle.BackColor);
            graphics.DrawImageUnscaled(buffer, 8, 8, buffer.Width, buffer.Height);
            graphics.DrawImage(Properties.Resources.Turtle, turtle.Location.X, turtle.Location.Y);

            // cleanup memory
            graphics.Dispose();
            graphics = null;

            pictureTurtle.Image = bitmap;

            // ensure form is large enough to accomodate image.
            if (Width < bitmap.Width + 21) Width = bitmap.Width + 21;
            if (Height < bitmap.Height + 92) Height = bitmap.Height + 92;
            Application.DoEvents();
        }
Esempio n. 29
0
        /// <summary>
        /// Move the turtle one unit forward
        /// in the direction it is currently facing
        /// </summary>
        public void Move(ITurtle turtle)
        {
            if (turtle.Direction == EDirection.NONE)
            {
                return;
            }

            Position position = turtle.Position;

            switch (turtle.Direction)
            {
            case EDirection.NORTH:
                position.Y += 1;
                break;

            case EDirection.EAST:
                position.X += 1;
                break;

            case EDirection.SOUTH:
                position.Y -= 1;
                break;

            case EDirection.WEST:
                position.X -= 1;
                break;

            default:
                break;
            }

            if (Map.Contains(position))
            {
                turtle.Position = position;
            }
        }
Esempio n. 30
0
 public virtual bool Perform(ITurtle turtle)
 {
     return false;
 }
Esempio n. 31
0
 public override bool Perform(ITurtle turtle)
 {
     Thread.Sleep(_timeout);
     return true;
 }
Esempio n. 32
0
 /// <summary>
 /// Set
 /// </summary>
 /// <param name="turtle">Turtle</param>
 /// <param name="mines">Mines collections</param>
 /// <param name="exit">Exit</param>
 public void Set(ITurtle turtle, IEnumerable <IMine> mines, IExit exit)
 {
     _turtle = turtle;
     _mines  = mines;
     _exit   = exit;
 }
Esempio n. 33
0
        /// <summary>
        ///     Execute PLACE command
        /// </summary>
        /// <param name="turtle">turtle instance</param>
        /// <param name="arguments">X, Y, F arguments</param>
        /// <param name="message">message after command execution result</param>
        /// <returns>command execution result</returns>
        public bool DoExecution(ITurtle turtle, string[] arguments, out string message)
        {
            TurtleInstruction instruction;

            if (arguments == null)
            {
                message = MessageConstants.MissingXYFArgsMsg;
                return(false);
            }

            if (Enum.TryParse <TurtleInstruction>(arguments[0], true, out instruction))
            {
                int             x = 0, y = 0;
                FacingDirection direction = FacingDirection.North;

                string[] place_args = arguments[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToArray();

                if (place_args.Length != 3)
                {
                    message = MessageConstants.InvalidXYFArgsMsg;
                    return(false);
                }

                if (instruction == TurtleInstruction.Place)
                {
                    if (!int.TryParse(place_args[0], out x))
                    {
                        message = MessageConstants.InvalidXNonIntMsg;
                        return(false);
                    }
                    else
                    {
                        if (x < 0 || x >= turtle.BoardSizeX())
                        {
                            message = MessageConstants.InvalidXUnboundMsg + turtle.BoardSizeX();
                            return(false);
                        }
                    }

                    if (!int.TryParse(place_args[1], out y))
                    {
                        message = MessageConstants.InvalidYNonIntMsg;
                        return(false);
                    }
                    else
                    {
                        if (y < 0 || y >= turtle.BoardSizeY())
                        {
                            message = MessageConstants.InvalidYUnboundMsg + turtle.BoardSizeY();
                            return(false);
                        }
                    }

                    if (!Enum.TryParse(place_args[2], true, out direction))
                    {
                        message = MessageConstants.InvalidFArgsMsg;
                        return(false);
                    }

                    bool isPlacedSuccessfull = turtle.Place(new TurtleState()
                    {
                        X = x,
                        Y = y,
                        FacingDirection = direction
                    });

                    if (isPlacedSuccessfull)
                    {
                        message = MessageConstants.DoneMsg;
                        return(true);
                    }
                    else
                    {
                        message = MessageConstants.InvalidCommandMsg;
                        return(false);
                    }
                }
                else
                {
                    message = MessageConstants.InvalidCommandMsg;
                    return(false);
                }
            }
            else
            {
                message = MessageConstants.InvalidCommandMsg;
                return(false);
            }
        }
Esempio n. 34
0
        public void ExecuteMovements()
        {
            var sequenceCounter = 0;

            try
            {
                foreach (var sequence in _sequences)
                {
                    //for each move sequence we need to:
                    //1) reset the currentTile
                    //2) reset Turtle's initial position
                    //3) reset won status
                    //4) increate the sequence counter by 1

                    var currentTile = TileType.Safe;
                    Turtle = new Turtle(_gameSettings);
                    _won   = false;
                    sequenceCounter++;

                    foreach (var action in sequence)
                    {
                        switch (action)
                        {
                        case ActionType.Move:
                            Turtle.Move();
                            break;

                        case ActionType.Rotate:
                            Turtle.Rotate();
                            break;

                        case ActionType.None:
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                        }

                        currentTile = Board.GetTileTypeForPoint(Turtle.Position);

                        if (currentTile == TileType.Safe)
                        {
                            continue;
                        }

                        if (currentTile == TileType.Mine)
                        {
                            Console.WriteLine($"Sequence {sequenceCounter}: Mine hit!");
                            break;
                        }

                        if (currentTile == TileType.Exit)
                        {
                            _won = true;
                            Console.WriteLine($"Sequence {sequenceCounter}: Success!");
                            break;
                        }
                    }

                    //if we finished all moves and didn't win and didn't hit a mine then we are still in danger!!
                    if (!_won && currentTile == TileType.Safe)
                    {
                        Console.WriteLine($"Sequence {sequenceCounter}: Still in danger!");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"There was an error - Message: {ex.Message}");
            }
        }
Esempio n. 35
0
 /// <summary>
 ///     Execute any unsupported command
 /// </summary>
 /// <param name="turtle">turtle instance</param>
 /// <param name="arguments">NOT REQUIRED</param>
 /// <param name="message">message after command execution result</param>
 /// <returns>command execution result</returns>
 public bool DoExecution(ITurtle turtle, string[] arguments, out string message)
 {
     message = MessageConstants.InvalidCommandMsg;
     return(false);
 }