Пример #1
0
        public static string Run(string input)
        {
            var sr = new StringReader(input);
            var gridMaxString = sr.ReadLine();

            Parser parser = new Parser();
            var gridMax = parser.MaxPosition(gridMaxString);

            var output = new StringBuilder();

            for (; ; )
            {
                var startAsString = sr.ReadLine();
                var movementsAsString = sr.ReadLine();
                if (string.IsNullOrEmpty(startAsString) || string.IsNullOrEmpty(movementsAsString))
                {
                    break;
                }

                var start = parser.Start(startAsString);
                var movements = parser.Movements(movementsAsString);
                var rover = new Rover(start.Position, start.Direction);
                rover = movements(rover);
                output.AppendFormat("{0}{1}", rover, Environment.NewLine);
            }

            return output.ToString();
        }
Пример #2
0
        public void TestMove(string movements, char direction, int startX, int startY, int finalX, int finalY)
        {
            Grid world = new Grid(10, 10);

            Rover rover = new Rover(startX, startY, direction);

            world.GridCellAt(3, 5).ContainsObstacle = true;
            world.GridCellAt(3, 6).ContainsObstacle = true;
            world.GridCellAt(1, 8).ContainsObstacle = true;
            world.GridCellAt(7, 4).ContainsObstacle = true;
            world.GridCellAt(6, 2).ContainsObstacle = true;

            rover.World = world;

            foreach (char movement in movements)
            {
                if (!rover.Move(movement))
                {
                    break;
                }
            }

            Console.WriteLine("Final Location: " + rover.CurrentLocation.X + " " + rover.CurrentLocation.Y);

            Assert.AreEqual(finalX, rover.CurrentLocation.X);
            Assert.AreEqual(finalY, rover.CurrentLocation.Y);
        }
Пример #3
0
 public void TurnTest()
 {
     var testRover = new Rover("test1", new Position() { X = 0, Y = 0 }, OrientationEnum.E, new MockComModule(),
         new MockTerrain() { Grid = new IRover[5, 5] });
     testRover.Turn(Direction.Left);
     var expectedOrientation = OrientationEnum.N;
     Assert.AreEqual(testRover.Orientation, expectedOrientation);
     testRover.Turn(Direction.Left);
     expectedOrientation = OrientationEnum.W;
     Assert.AreEqual(testRover.Orientation, expectedOrientation);
     testRover.Turn(Direction.Left);
     expectedOrientation = OrientationEnum.S;
     Assert.AreEqual(testRover.Orientation, expectedOrientation);
     testRover.Turn(Direction.Left);
     expectedOrientation = OrientationEnum.E;
     Assert.AreEqual(testRover.Orientation, expectedOrientation);
     testRover.Turn(Direction.Right);
     expectedOrientation = OrientationEnum.S;
     Assert.AreEqual(testRover.Orientation, expectedOrientation);
     testRover.Turn(Direction.Right);
     expectedOrientation = OrientationEnum.W;
     Assert.AreEqual(testRover.Orientation, expectedOrientation);
     testRover.Turn(Direction.Right);
     expectedOrientation = OrientationEnum.N;
     Assert.AreEqual(testRover.Orientation, expectedOrientation);
     testRover.Turn(Direction.Right);
     expectedOrientation = OrientationEnum.E;
     Assert.AreEqual(testRover.Orientation, expectedOrientation);
 }
Пример #4
0
 public void MoveTest()
 {
     Surface MySurface = new Surface(new Size(5, 5));
     Rover Rover1 = new Rover(MySurface, new Point(0, 0), PhysicalObject.Heading.North);
     Rover1.Move();
     Assert.AreEqual(new Point(0, 1), MySurface.GetPosition(Rover1));
 }
Пример #5
0
        private static void MoveRover(IGrid grid, string locationLine, string movesLine)
        {
            IDirectionParser directionParser = (IDirectionParser)container[typeof(IDirectionParser)];
            ILocationParser locationParser = (ILocationParser)container[typeof(ILocationParser)];

            Direction direction = directionParser.GetDirection(locationLine);
            Point location = locationParser.GetLocation(locationLine);
            IMoveSupplier supplier = (IMoveSupplier)container[typeof(IMoveSupplier)];

            supplier.Init(movesLine);
            Rover rover = new Rover(direction, location, grid, supplier);
            try
            {
                rover.ExecuteMoves();
            }
            catch (InvalidLocationException ex)
            {
                Console.WriteLine(MarsRover.IllegalLocation);
            }
            Console.WriteLine(String.Format("{0} {1} {2}", rover.Location.X, rover.Location.Y, rover.Direction));

            container.Release(supplier);
            container.Release(directionParser);
            container.Release(locationParser);
        }
Пример #6
0
        public void PlexisChallenge()
        {
            Surface MySurface = new Surface(new Size(5, 5));

            Rover Spirit = new Rover(MySurface, new Point(1, 2), PhysicalObject.Heading.North);
            Spirit.Rotate(PhysicalObject.Rotation.Left);
            Spirit.Move();
            Spirit.Rotate(PhysicalObject.Rotation.Left);
            Spirit.Move();
            Spirit.Rotate(PhysicalObject.Rotation.Left);
            Spirit.Move();
            Spirit.Rotate(PhysicalObject.Rotation.Left);
            Spirit.Move();
            Spirit.Move();
            Assert.AreEqual(new Point(1, 3), MySurface.GetPosition(Spirit));
            Assert.AreEqual(PhysicalObject.Heading.North, Spirit.Direction);

            Rover Opportunity = new Rover(MySurface, new Point(3, 3), PhysicalObject.Heading.East);
            Opportunity.Move();
            Opportunity.Move();
            Opportunity.Rotate(PhysicalObject.Rotation.Right);
            Opportunity.Move();
            Opportunity.Move();
            Opportunity.Rotate(PhysicalObject.Rotation.Right);
            Opportunity.Move();
            Opportunity.Rotate(PhysicalObject.Rotation.Right);
            Opportunity.Rotate(PhysicalObject.Rotation.Right);
            Opportunity.Move();
            Assert.AreEqual(new Point(5, 1), MySurface.GetPosition(Opportunity));
            Assert.AreEqual(PhysicalObject.Heading.East, Opportunity.Direction);
        }
        /*
         * Bu Sınıfın görevi Program.cs tarafından oluşturulacak olan Rover nesnesinin dışardan verilerini alarak önce RoverValidator sınıfında kontrole
         * göndermek ardından ise veriler doğru ise gerekli atamaları gerekli Propertylere gönderek instance alma işlemini tamamlamak.Eğer yanlış veri girilir ise
         * Validator sınıfı false göndereceği için doğru değer gönderilene ve check değişkeni true olana kadar veri alma işlemeni yapmaya devam edecektir.
         *
         *
         */
        public static MarsRover.Rover RoverCreator(Plateau plateau)
        {
            bool        check            = false;
            List <char> RoverCoordinates = null;

            Console.WriteLine("Rover Parametrelerini Giriniz");
            while (check == false)
            {
                RoverCoordinates = InputSeperator.Seperate(Console.ReadLine());
                check            = RoverValidator.Validate(RoverCoordinates);
            }

            int x = (int)char.GetNumericValue(RoverCoordinates[0]);

            RoverCoordinates.RemoveAt(0);
            int y = (int)char.GetNumericValue(RoverCoordinates[0]);

            RoverCoordinates.RemoveAt(0);

            string direction = Convert.ToString(RoverCoordinates[0]);

            MarsRover.Rover rover = new MarsRover.Rover(x, y, direction, plateau);

            return(rover);
        }
 public void Should_Reset_Rover()
 {
     Rover rover = new Rover(5, 10, Direction.South);
     rover.Reset();
     Assert.AreEqual(new int[] { 0, 0 }, rover.GetLocation());
     Assert.AreEqual(Direction.North, rover.GetDirection());
 }
        public RoverController(Stream stream)
        {
            using (var reader = new StreamReader(stream))
            {
                var firstLine = reader.ReadLine();
                plateau = plateauParser.Parse(firstLine);

                while (!reader.EndOfStream)
                {
                    var roverPositionLine = reader.ReadLine();
                    var roverPosition = roverParser.Parse(roverPositionLine);

                    var roverCommandsLine = reader.ReadLine();
                    var commands = commandParser.Parse(roverCommandsLine);

                    var rover = new Rover(plateau, roverPosition.Coordinate, roverPosition.Direction);

                    foreach (var command in commands)
                    {
                        command.Execute(rover);
                    }

                    rovers.Add(rover);
                }
            }
        }
Пример #10
0
        public void InitialPosition()
        {
            var rover = new Rover(2, 4);

            Assert.AreEqual(2, rover.X);
            Assert.AreEqual(4, rover.Y);
        }
Пример #11
0
        public void isCurrentPositionLengthLower()
        {
            string[]        cPos = { "1", "2" };
            string[]        comm = { "L", "M", "L", "M", "L", "M", "L", "M", "M" };
            MarsRover.Rover r1   = new MarsRover.Rover(cPos, comm);

            Assert.That(r1.ErrCode == 0, r1.ErrDesc);
        }
Пример #12
0
        public void isCurrentPositionFormatFalseNotNESW()
        {
            string[]        cPos = { "1", "2", "Y" };
            string[]        comm = { "L", "M", "L", "M", "L", "M", "L", "M", "M" };
            MarsRover.Rover r1   = new MarsRover.Rover(cPos, comm);

            Assert.That(r1.ErrCode == 0, r1.ErrDesc);
        }
Пример #13
0
        public void CrashLandedTest()
        {
            Surface MySurface = new Surface(new Size(5, 5));
            Rover Rover1 = new Rover(MySurface, new Point(0, 0), PhysicalObject.Heading.North);
            Rover Rover2 = new Rover(MySurface, new Point(0, 0), PhysicalObject.Heading.East);

            Assert.AreEqual(true, Rover2.CrashLanded);
        }
Пример #14
0
 public void TRoverConstructor()
 {
     MarsRover.Plateau plateau = Plateau.FormSize(5, 5);
     string baseLocation = "1 2 N";
     string name = "rover1";
     MarsRover.Rover target = new MarsRover.Rover(plateau, baseLocation, name);
     Assert.AreEqual(target.BaseLocation.ToString(), baseLocation);
 }
Пример #15
0
        public void RoverTakesInStartingPositionAndDirections()
        {
            rover = new Rover(new Coordinate(1, 2), Direction.North, grid);

            Assert.AreEqual(1, rover.Position.X);
            Assert.AreEqual(2, rover.Position.Y);
            Assert.AreEqual(Direction.North, rover.Direction);
        }
Пример #16
0
        public void RoverReadCommandsTest()
        {
            Plateau plateau = new Plateau(5,5);
            Rover rover = new Rover(1, 2, "N", plateau);

            String expected = "N";
            Assert.AreEqual(expected, rover.ReadCommands("LLLL"));
        }
Пример #17
0
 public void InitRoverWithNegativeYCoordinate()
 {
     Point location = new Point(0, -1);
     Direction direction = Direction.N;
     Rover rover = new Rover(direction, location,null,null);
     Assert.AreEqual(location, rover.Location);
     Assert.AreEqual(direction, rover.Direction);
 }
Пример #18
0
 public void InitRover()
 {
     Point location = new Point(0,0);
     Direction direction = Direction.N;
     Rover rover = new Rover(direction, location,null, null);
     Assert.AreEqual(location, rover.Location);
     Assert.AreEqual(direction, rover.Direction);
 }
Пример #19
0
        public void isInstructionsFormatFalse()
        {
            string[]        cPos = { "1", "2", "N" };
            string[]        comm = { "L", "M", "L", "M", "L", "M", "L", "M", "X" };
            MarsRover.Rover r1   = new MarsRover.Rover(cPos, comm);

            Assert.That(r1.ErrCode == 0, r1.ErrDesc);
        }
Пример #20
0
        public void PDFTestCase2()
        {
            string[]        cPos   = { "3", "3", "E" };
            string[]        comm   = { "M", "M", "R", "M", "M", "R", "M", "R", "R", "M" };
            string[]        result = { "5", "1", "E" };
            MarsRover.Rover r1     = new MarsRover.Rover(cPos, comm);

            Assert.AreEqual(r1.NewPosition, result);
        }
Пример #21
0
        public void Rover_Which_Is_North_When_Asked_To_MoveForward_Should_Move_One_Unit_Vertically()
        {
            Orientation northOrientation = OrientationGenerator.GetOrientation (Direction.North);

            Location location = new Location (new Position (2, 3), northOrientation);
            Location expectedLocation = new Location (new Position (2, 4), northOrientation);
            Rover rover = new Rover (location);
            Location actualLocation = rover.MoveForward ();
            Assert.AreEqual (expectedLocation,actualLocation);
        }
Пример #22
0
        public void Rover_Which_Is_East_When_Asked_To_MoveForward_Should_Move_One_Unit_Horizontally()
        {
            Orientation eastOrientation = OrientationGenerator.GetOrientation (Direction.East);

            Location location = new Location (new Position (2, 3), eastOrientation);
            Location expectedLocation = new Location (new Position (3, 3), eastOrientation);
            Rover rover = new Rover (location);
            Location actualLocation = rover.MoveForward ();
            Assert.AreEqual (expectedLocation,actualLocation);
        }
Пример #23
0
        public void Test_Get_Rover_Directional_Heading()
        {
            Rover rover = new Rover();
            rover.PositionHeading = "N";
            string headingReturned;
            Navigation navigation = new Navigation(rover);
            headingReturned = navigation.GetDirectionalHeading();

            Assert.AreEqual("N", headingReturned);
        }
Пример #24
0
        public void Test_Rover_Left_Turn_West_()
        {
            Rover rover = new Rover();
            rover.PositionHeading = "N";
            Navigation navigation = new Navigation(rover);

            rover.Command_Receiver("L");

            Assert.AreEqual("W", navigation.GetDirectionalHeading());
        }
Пример #25
0
        public void Test_Rover_Turns_North()
        {
            Rover rover = new Rover();
            rover.PositionHeading = "W";
            Navigation navigation = new Navigation(rover);

            rover.Command_Parser("R");

            Assert.AreEqual("N", navigation.GetDirectionalHeading());
        }
Пример #26
0
        public void Rover_When_Facing_North_Should_Turn_To_West_When_Asked_To_TurnLeft()
        {
            Orientation northOrientation = OrientationGenerator.GetOrientation (Direction.North);
            Orientation westOrientation = OrientationGenerator.GetOrientation (Direction.West);

            Location location = new Location (new Position (2, 3), northOrientation);
            Location expectedLocation = new Location (new Position (2, 3), westOrientation);
            Rover rover = new Rover (location);
            Location actualLocation = rover.TurnLeft ();
            Assert.AreEqual (expectedLocation,actualLocation);
        }
Пример #27
0
        public void RoverMovesBackwardFacingEast()
        {
            rover = new Rover(new Coordinate(1, 2), Direction.East, grid);
            var commands = new char[] { Command.Backward };

            rover.Move(commands);

            Assert.AreEqual(0, rover.Position.X);
            Assert.AreEqual(2, rover.Position.Y);
            Assert.AreEqual(Direction.East, rover.Direction);
        }
Пример #28
0
        public void RoverMovesForwardFacingSouth()
        {
            rover = new Rover(new Coordinate(1, 2), Direction.South, grid);
            var commands = new char[] { Command.Forward };

            rover.Move(commands);

            Assert.AreEqual(1, rover.Position.X);
            Assert.AreEqual(1, rover.Position.Y);
            Assert.AreEqual(Direction.South, rover.Direction);
        }
Пример #29
0
        static void Main(string[] args)
        {
            Plateau plateau = new Plateau(5, 5);
            Rover rover = new Rover(1, 2, "N", plateau);
            Rover rover2 = new Rover(3, 3, "E", plateau);
            rover.ReadCommands("LMLMLMLMM");
            rover2.ReadCommands("MMRMMRMRRM");

            Console.WriteLine(rover.toString());
            Console.WriteLine(rover2.toString());
        }
Пример #30
0
        public void Should_Be_Blocked_By_Obstacle()
        {
            bool[,] map = create_map(1,0);
            Rover rover = new Rover(0, 0, Direction.North);

            Assert.False(rover.Move(Command.f, map).IsOperationSucceeded());
            Assert.AreEqual(new int[] { 0, 0 }, rover.GetLocation());

            Assert.True(rover.Move(Command.r, map).IsOperationSucceeded());
            Assert.True(rover.Move(Command.f, map).IsOperationSucceeded());
            Assert.AreEqual(new int[] { 0, 1 }, rover.GetLocation());
        }
Пример #31
0
 public void SetUp()
 {
     List<int[]> obstacles = new List<int[]>()
     {
         new int[] { 4, 4 }, new int[] { 4, 5 }, new int[] { 4, 6 },
         new int[] { 5, 4 }, new int[] { 5, 5 }, new int[] { 5, 6 },
         new int[] { 6, 4 }, new int[] { 6, 5 }, new int[] { 6, 6 },
     };
     mars = new Map(10, 10);
     mars.Obstacles = obstacles;
     marsRover = new Rover(new NorthFacingRover(), mars);
 }
Пример #32
0
 public void XDimensionMoveTest()
 {
     var testRover = new Rover("test1", new Position() { X = 2, Y = 2 }, OrientationEnum.W, new MockComModule(),
         new MockTerrain() { Grid = new IRover[5, 5] });
     testRover.Move();
     var expectedPosition = new Position() { X = 1, Y = 2 };
     Assert.AreEqual(testRover.Position, expectedPosition);
     testRover.Orientation = OrientationEnum.E;
     testRover.Move();
     expectedPosition.X = 2;
     Assert.AreEqual(testRover.Position, expectedPosition);
 }
Пример #33
0
        public void RoverConstructorTest()
        {
            Plateau plateau = new Plateau(5, 5);
            Rover rover = new Rover(1, 2, "N", plateau);

            int expected = 1;
            Assert.AreEqual(expected, rover.PlateauX);
            expected = 2;
            Assert.AreEqual(expected, rover.PlateauY);
            String expected2 = "N";
            Assert.AreEqual(expected2, rover.Direction);
        }
Пример #34
0
        public void Test_Get_Set_The_Grid()
        {
            Rover rover = new Rover();
            rover.PositionHeading = "E";
            rover.PositionY = 4;
            rover.PositionX = 3;

            rover.LandscapeHeight = 3;
            rover.LandscapeWidth = 3;

            Assert.AreEqual(4, rover.PositionY);
            Assert.AreEqual(3, rover.PositionX);
        }
Пример #35
0
        public void RoverReadCommandsTestWithMove()
        {
            Plateau plateau = new Plateau(5, 5);
            Rover rover = new Rover(1, 2, "N", plateau);

            int expectedX = 1;
            int expectedY = 3;
            String expected = "N";
            rover.ReadCommands("LMLMLMLMM");
            Assert.AreEqual(expected, rover.Direction);
            Assert.AreEqual(expectedX, rover.PlateauX);
            Assert.AreEqual(expectedY, rover.PlateauY);
        }
Пример #36
0
 /// <summary>
 /// Creates the URI path for Rover
 /// </summary>
 /// <param name="uri"></param>
 /// <param name="rover"></param>
 /// <returns></returns>
 public string UriRover(string uri, Rover rover)
 {
     return(string.Concat(uri, rover.Name, "/"));
 }
Пример #37
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                int            X             = 0;
                int            Y             = 0;
                string         direction     = "N";
                RoverDirection rd            = RoverDirection.N;
                Position       roverPosition = new Position(X, Y);
                Plateau        marsPlateau   = new Plateau(new Position(X, Y));
                int            platSizeW     = 1;
                int            platSizeL     = 1;
                if (Request["txtPlateauDimension"] != null)
                {
                    if (Request["txtPlateauDimension"] != "")
                    {
                        string   initSize  = Request["txtPlateauDimension"];
                        string[] sizeArray = initSize.Split(' ');
                        if (sizeArray.Length == 2)
                        {
                            int.TryParse(sizeArray[0], out platSizeW);
                            int.TryParse(sizeArray[1], out platSizeL);
                            marsPlateau.PlateauPosition.X = platSizeW;
                            marsPlateau.PlateauPosition.Y = platSizeL;
                        }
                    }
                }
                if (Request["txtInitRover"] != null)
                {
                    if (Request["txtInitRover"] != "")
                    {
                        string   initPos  = Request["txtInitRover"];
                        string[] posArray = initPos.Split(' ');
                        if (posArray.Length == 3)
                        {
                            int.TryParse(posArray[0], out X);
                            int.TryParse(posArray[1], out Y);
                            roverPosition.X = X;
                            roverPosition.Y = Y;
                            switch (posArray[2])
                            {
                            case "N":
                                rd = RoverDirection.N;
                                break;

                            case "E":
                                rd = RoverDirection.E;
                                break;

                            case "S":
                                rd = RoverDirection.S;
                                break;

                            case "W":
                                rd = RoverDirection.W;
                                break;
                            }
                        }
                    }
                }
                Rover  rover  = new Rover(roverPosition, rd, marsPlateau);
                string retval = rover.Process(Request["txtCommands"]);
                Response.Write(retval);
            }
        }
Пример #38
0
 public RoverCommandCenter(Rover rover) : this(rover, Int32.MaxValue)
 {
 }
Пример #39
0
 public void PlaceRover(Rover rover)
 {
     PlacedRovers.Add(rover);
 }
Пример #40
0
 public MovementSystem(Terrain terrain, Rover rover)
 {
     this.terrain = terrain;
     this.rover   = rover;
 }
Пример #41
0
        static void Main(string[] args)
        {
            Console.Write("Enter the plateau's upper-right coordinates (ex. 5 5) :");
            string line = Console.ReadLine();

            Coordinate upperRightCoordinate = MarsRoverCommandHelper.PopulateCoordinate(line);

            if (upperRightCoordinate is default(Coordinate))
            {
                Console.WriteLine("The input is not valid.");
                return;
            }

            // generate the rover and plateau
            Coordinate    lowerLeftCoordinate  = new Coordinate();
            PlateauBounds plateauBounds        = new PlateauBounds(upperRightCoordinate, lowerLeftCoordinate);
            IPlateau      plateau              = new Plateau(plateauBounds);
            Coordinate    roverCurrentPosition = new Coordinate();
            RoverPosition roverPosition        = new RoverPosition(roverCurrentPosition, RoverDirectionEnum.North);
            IRover        rover = new Rover(plateau, roverPosition);

            while (true)
            {
                Console.Clear();
                Console.WriteLine(string.Format("Plateau's bounds are: Upper-Right = ({0},{1}) Lower-Left = ({2},{3})" + Environment.NewLine,
                                                plateau.Bounds.UpperRight.X,
                                                plateau.Bounds.UpperRight.Y,
                                                plateau.Bounds.LowerLeft.X,
                                                plateau.Bounds.LowerLeft.Y));

                Console.Write("Enter the rover's start position (ex. 1 1 N) :");
                line = Console.ReadLine();
                rover.CurrentPosition = MarsRoverCommandHelper.PopulateRoverPosition(line);

                if (rover.CurrentPosition is default(RoverPosition))
                {
                    Console.WriteLine("The input is not valid.");
                    return;
                }

                Console.Write("Enter rover's moving sequence (ex. LMRMRMM) :");
                line = Console.ReadLine();
                IEnumerable <MovingDirectionEnum> movingDirectionList = MarsRoverCommandHelper.PopulateMovingDirectionList(line);

                if (movingDirectionList.Any() == false)
                {
                    Console.WriteLine("The input is not valid.");
                    return;
                }

                foreach (MovingDirectionEnum direction in movingDirectionList)
                {
                    rover.Move(direction);
                }

                Console.WriteLine(string.Format(Environment.NewLine + "Current Position is: {0} {1} {2}", rover.CurrentPosition.Coordinate.X, rover.CurrentPosition.Coordinate.Y, rover.CurrentPosition.Direction));

                Console.Write(Environment.NewLine + "0: Exit \n1: Retry\nSelect :");
                ConsoleKeyInfo key = Console.ReadKey();
                if (key.Key != ConsoleKey.D1 && key.Key != ConsoleKey.NumPad1)
                {
                    return;
                }
            }
        }
        static void Main(string[] args)
        {
            HashSet <Rover> Rovers = new HashSet <Rover>();

            String[] Input;

            Console.WriteLine("Please specify the size of the Mars Plateu:");
            Console.WriteLine("The first number is the width, and the second number is the height.");

            Input = Console.ReadLine().Split(' ');
            Surface MySurface = new Surface(new Size(Convert.ToInt32(Input[0]), Convert.ToInt32(Input[1])));

            while (true)
            {
                Console.WriteLine("");
                Console.WriteLine("Please specify the starting position and direction of the rover:");
                Console.WriteLine("The first number is the horizontal coordinate, the second number is the vertical coordinate");
                Console.WriteLine("The third value is a single character representing a Cardinal Point (N, S, E, or W)");
                Console.WriteLine("Please enter a blank line to indicate you have no more rovers to enter.");

                Input = Console.ReadLine().Split(' ');

                try
                {
                    PhysicalObject.Heading Direction = PhysicalObject.Heading.North;
                    switch (Input[2].ToUpper())
                    {
                    case "N":
                        Direction = PhysicalObject.Heading.North;
                        break;

                    case "E":
                        Direction = PhysicalObject.Heading.East;
                        break;

                    case "S":
                        Direction = PhysicalObject.Heading.South;
                        break;

                    case "W":
                        Direction = PhysicalObject.Heading.West;
                        break;
                    }
                    Rover CurrentRover = new Rover(MySurface, new Point(Convert.ToInt32(Input[0]), Convert.ToInt32(Input[1])), Direction);

                    Console.WriteLine("Please provide a string of directions for the rover to follow.  No spaces are requred.");
                    Console.WriteLine("{ L = Turn Left; R = Turn Right; M = Move 1 unit forward }");

                    String UserInput = Console.ReadLine().Replace(" ", "");

                    foreach (Char character in UserInput.ToUpper())
                    {
                        switch (character)
                        {
                        case 'L':
                            CurrentRover.Rotate(PhysicalObject.Rotation.Left);
                            break;

                        case 'R':
                            CurrentRover.Rotate(PhysicalObject.Rotation.Right);
                            break;

                        case 'M':
                            CurrentRover.Move();
                            break;
                        }
                    }

                    Rovers.Add(CurrentRover);
                }
                catch
                {
                    break;
                }
            }

            Console.WriteLine("These are the resulting location(s) for your rover(s):");

            foreach (Rover TestRover in Rovers)
            {
                String Output = "";
                Output += MySurface.GetPosition(TestRover).X;
                Output += " ";
                Output += MySurface.GetPosition(TestRover).Y;
                Output += " ";

                switch (TestRover.Direction)
                {
                case PhysicalObject.Heading.North:
                    Output += "N";
                    break;

                case PhysicalObject.Heading.East:
                    Output += "E";
                    break;

                case PhysicalObject.Heading.South:
                    Output += "S";
                    break;

                case PhysicalObject.Heading.West:
                    Output += "W";
                    break;
                }

                Console.WriteLine(Output);
            }

            Console.Read();
        }
Пример #43
0
 public Navigation(Rover rover)
 {
     _rover = rover;
 }
Пример #44
0
 public RoverCommandCenter(Rover rover, Planet planet)
 {
     _planet = planet;
     _roverCommandFactory = new RoverCommandFactory();
     Rover = rover;
 }
Пример #45
0
 public Orchastrator()
 {
     _rover = new Rover(_x, _y, _direction);
 }
Пример #46
0
        }                                           //string with ending coordinates and heading of each rover encountered

        public ProcessorState()
        {
            Plateau        = new Plateau();
            Rover          = new Rover();
            RoverEndValues = "";
        }
Пример #47
0
        private string ParseRoverInstructions(string[] instructions)
        {
            StringBuilder output = new StringBuilder();

            for (int i = 1; i < instructions.Length; i += 2)
            {
                var startPosLine = instructions[i];
                if (!IsValidPosition(startPosLine)) // verify the start position is in the valid format
                {
                    output.AppendLine($"Warning: Invalid start position for Rover #{i / 2}. Sipping rover commands.");
                    continue;
                }

                var   startPos = instructions[i].Split(' ');
                Rover rover    = new Rover(int.Parse(startPos[0]), int.Parse(startPos[1]), startPos[2]);

                if (!IsInBounds(rover.Position)) // verify that the given start position is in bounds of the plateau
                {
                    output.AppendLine($"Warning: Invalid start position for Rover #{i / 2}. Sipping rover commands.");
                    continue;
                }

                var commands = instructions[i + 1];

                if (!IsValidCommands(commands)) // verify that the commands are in the valid format
                {
                    output.AppendLine($"Warning: Invalid commands for Rover #{i / 2}. Sipping rover commands.");
                    continue;
                }

                foreach (var command in commands)
                {
                    switch (command)
                    {
                    case 'L':
                    case 'l':
                        rover.RotateLeft();
                        break;

                    case 'R':
                    case 'r':
                        rover.RotateRight();
                        break;

                    case 'M':
                    case 'm':
                        if (IsInBounds(rover.GetNextPosition()))
                        {
                            rover.Position = rover.GetNextPosition();
                        }
                        else
                        {
                            output.AppendLine($"Warning: Cannot move Rover #{i / 2} out of bounds. Move command ignored.");
                        }
                        break;
                    }
                }
                // send updated position back to NASA
                output.AppendLine(rover.ToString());
            }

            return(output.ToString());
        }
Пример #48
0
        /// <summary>
        /// Loads the input orders from an external file
        /// </summary>
        /// <param name="inputOrdersFileName"></param>
        /// <returns></returns>
        public bool LoadOrdersFromFile(string inputOrdersFileName)
        {
            bool plateauSizeFound     = false;
            bool expectingRoverOrders = false;

            string currentInputLine = string.Empty;

            string[] currentInputLineParts = null;

            Rover constructedRover = null;
            int   roverIndex       = 0;


            if (!File.Exists(inputOrdersFileName))
            {
                throw new Exceptions.MissingInputFileException(inputOrdersFileName);
            }

            this.m_Rovers = new RoverCollection();

            StreamReader streamReader = new StreamReader(inputOrdersFileName);

            if (streamReader.Peek() == -1)
            {
                throw new Exceptions.EmptyInputFileException(inputOrdersFileName);
            }

            while (streamReader.Peek() >= 0)
            {
                // Get the whole input line to parse
                currentInputLine = streamReader.ReadLine();


                //
                // Try to match the input line against known line formats (Plateau size, Rover Location, Rover Orders)
                //

                if (Regex.IsMatch(currentInputLine, Constants.INPUT_ORDERS_REGEX_COMMENT))
                {
                    // Ignore any comment lines in the input file
                }
                else if (Regex.IsMatch(currentInputLine, Constants.INPUT_ORDERS_REGEX_ROVER_START_LOCATION))
                {
                    // Current input line is a start location for a rover.
                    constructedRover = new Rover();

                    // Set the starting location of the rover
                    constructedRover.StartLocation = new RoverLocation(currentInputLine);
                    constructedRover.Name          = string.Format("Rover{0}", roverIndex);

                    // The next input line should be a set of orders for the rover
                    expectingRoverOrders = true;
                }
                else if (Regex.IsMatch(currentInputLine, Constants.INPUT_ORDERS_REGEX_ROVER_ORDERS))
                {
                    if (!expectingRoverOrders)
                    {
                        throw new Exceptions.OrdersFileParsingException("The orders file does not seem to be in the correct format, after the plateau definition, there shoud be alternating locations and mission order lines.");
                    }

                    // Current input line is a set of orders for a rover.
                    constructedRover.MissionOrders = currentInputLine;

                    // Add the completed rover to the collection
                    this.m_Rovers.Add(roverIndex, constructedRover);

                    this.AddToEventLog(string.Format("Succesfully created Rover No.{0}, using the base location '{1}' and orders '{2}'", roverIndex, constructedRover.StartLocation, constructedRover.MissionOrders));

                    constructedRover = null;
                    roverIndex++;


                    // Don't expect the next line to be a set of orders, if there are more lines, the next one should be a location+direction for a new Rover.
                    expectingRoverOrders = false;
                }
                else if (Regex.IsMatch(currentInputLine, Constants.INPUT_ORDERS_REGEX_PLATEAU_SIZE))
                {
                    // Check we've not already found a plateau size.
                    if (plateauSizeFound)
                    {
                        throw new Exceptions.OrdersFileParsingException("Apparently two lines determining the plateau size have been detected, you might want to check the input file.");
                    }

                    // Current input line is the Plateau size
                    currentInputLineParts = currentInputLine.Split(' ');

                    // TODO: Check the positioning of the x+y co-ords from the input file
                    this.plateauXDimension = int.Parse(currentInputLineParts[0]);
                    this.plateauYDimension = int.Parse(currentInputLineParts[1]);

                    this.AddToEventLog(string.Format("Succesfully loaded in the Plateau details X:{0} Y:{1}", this.plateauXDimension, this.plateauYDimension));

                    plateauSizeFound = true;
                }
            }

            streamReader.Close();
            streamReader = null;


            return(this.m_Rovers.Count > 0);
        }
Пример #49
0
 public Landscape(Rover rover)
 {
     _rover = rover;
 }
Пример #50
0
        /// <summary>
        /// Builds Inputs from the file using Stream reader.
        /// </summary>
        /// <param name="args"></param>
        public static void readFromfile(string[] args)
        {
            StreamReader streamReader = null;
            string       line         = " ";
            int          firstline    = 0;

            try
            {
                streamReader = new StreamReader(args[0]);
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine("File Not Found" + e.Message);
                Environment.Exit(-1);
            }
            try
            {
                while ((line = streamReader.ReadLine()) != null)
                {
                    if (firstline == 0)
                    {
                        string[] maxXY   = line.Split(' ');
                        int      maxX    = Convert.ToInt32(maxXY[0]);
                        int      maxY    = Convert.ToInt32(maxXY[1]);
                        Plateau  plateau = null;
                        if (maxX > 0 && maxY > 0)
                        {
                            plateau = new Plateau(maxX, maxY);
                        }
                        else
                        {
                            Console.WriteLine("Invalid Upper Right Co-ordinates");
                            Environment.Exit(-1);
                        }
                    }
                    else if ((firstline % 2) != 0)
                    {
                        Rover rover = buildRover(line);
                        roverQueue.Enqueue(rover);
                    }
                    else
                    {
                        string     controllerInput = line;
                        Controller controller      = null;
                        int        count           = 0;
                        foreach (char ch in controllerInput)
                        {
                            if (ch == 'L' || ch == 'R' || ch == 'M')
                            {
                                count++;
                            }
                        }
                        if (count == controllerInput.Length)
                        {
                            controller = new Controller(line);
                            controllerQueue.Enqueue(controller);
                        }
                        else
                        {
                            Console.WriteLine("Invalid Controller Input");
                            Environment.Exit(-1);
                        }
                    }
                    firstline++;
                }
            }
            catch (IOException e)
            {
                Console.WriteLine("Error reading Input" + e.Message);
                Environment.Exit(-1);
            }
        }
Пример #51
0
        private static void TestMoveRover()
        {
            //test null case
            MarsRover = new Rover(3, 3, "N");
            MoveRover(null);

            Debug.Assert(MarsRover.XAxis == 3);
            Debug.Assert(MarsRover.YAxis == 3);
            Debug.Assert(MarsRover.Direction.Equals("N"));

            //test empty case
            MarsRover = new Rover(3, 3, "N");
            MoveRover("");

            Debug.Assert(MarsRover.XAxis == 3);
            Debug.Assert(MarsRover.YAxis == 3);
            Debug.Assert(MarsRover.Direction.Equals("N"));

            //test wrong format case
            MarsRover = new Rover(3, 3, "N");
            MoveRover("12345@!#$");

            Debug.Assert(MarsRover.XAxis == 3);
            Debug.Assert(MarsRover.YAxis == 3);
            Debug.Assert(MarsRover.Direction.Equals("N"));

            //test out of bound case
            MarsRover = new Rover(3, 3, "N");
            InitialPlateau(new List <string>()
            {
                "3 3"
            });

            MoveRover("LMMMMMLMMMMMLMMMMMLMMMMM");
            Debug.Assert(MarsRover.XAxis == 3);
            Debug.Assert(MarsRover.YAxis == 3);
            Debug.Assert(MarsRover.Direction.Equals("N"));

            //test normal case
            MarsRover = new Rover(1, 2, "N");
            InitialPlateau(new List <string>()
            {
                "5 5"
            });

            MoveRover("LMLMLMLMM");
            Debug.Assert(MarsRover.XAxis == 1);
            Debug.Assert(MarsRover.YAxis == 3);
            Debug.Assert(MarsRover.Direction.Equals("N"));

            //test normal case
            MarsRover = new Rover(3, 3, "E");
            InitialPlateau(new List <string>()
            {
                "5 5"
            });

            MoveRover("MMrMMrmRRM");
            Debug.Assert(MarsRover.XAxis == 5);
            Debug.Assert(MarsRover.YAxis == 1);
            Debug.Assert(MarsRover.Direction.Equals("E"));
        }
Пример #52
0
        private static void DeployRover(Canvas canvas)
        {
            var rover = new Rover(canvas);

            var roverDropSuccess = false;

            do
            {
                Console.WriteLine();
                Console.WriteLine("Enter Rover's drop off point.");

                try
                {
                    string dropPosition = Console.ReadLine();
                    rover.DropAt(dropPosition);
                    roverDropSuccess = true;
                }
                catch (MyCustomException ex)
                {
                    Console.WriteLine();
                    Console.WriteLine(ex.Message);
                    Console.WriteLine("Please try again to drop your Rover.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("!! Exception !!");
                }
            }while (!roverDropSuccess);



            Console.WriteLine();
            Console.WriteLine("Enter Rover's path to explore.");

            var roverExploreSuccess = false;

            do
            {
                try
                {
                    string explorationPath = Console.ReadLine();
                    rover.Explore(explorationPath);
                    Console.WriteLine();
                    Console.WriteLine(string.Format("Rover Position - {0}", rover.Position.ToString()));

                    roverExploreSuccess = true;
                }
                catch (OutOfBoundException ex)
                {
                    Console.WriteLine();
                    Console.WriteLine("Ooops !! Rover went too far from the Canvas. It is on the ledge");
                    Console.WriteLine(string.Format("Rover Position - {0}", rover.Position.ToString()));
                    roverExploreSuccess = true;
                }
                catch (MyCustomException ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine("Rover couldn't explore. Try again.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("!! Exception !!");
                }
            }while (!roverExploreSuccess);
        }
Пример #53
0
 public Rover(Rover rover) : this(rover.RoverPosition.X, rover.RoverPosition.Y, rover.RoverOrientation)
 {
 }
Пример #54
0
 //Adds current rover coordinates and heading to RoverEndValues
 public void UpdateRoverEndValues()
 {
     RoverEndValues += Rover.ToString();
     RoverEndValues += "\n";
 }
Пример #55
0
 public Interpreter(Rover rover)
 {
     MarsRover = rover;
 }
Пример #56
0
 public RoverCommandCenter(Rover rover, int limit) : this(rover, new Planet(limit, new List <Position>()))
 {
 }
Пример #57
0
 private static string[] InstructionsFromFile(string[] args, Rover marsRover, Interpreter interpreter)
 {
     string[] lines = File.ReadAllLines(args[0]);
     return(interpreter.InterpretLines(lines));
 }
        //sir ka emthod to remove if else id to create a lsit of fucntions to be accessed after the condition checking.
        //then add tryparse.

        public InstructionProcessor(Rover rover)
        {
            this.Instructions = new List <Instruction>();
        }
Пример #59
0
        private static void ParseAndValidateInitialRoverData(List <string> initialRoverPosition, Rover rover)
        {
            if (initialRoverPosition.Count == 3)
            {
                //Parses and validates initial rover's X coordinate input
                if (!int.TryParse(initialRoverPosition[0], out int xPosition))
                {
                    throw new Exception(
                              $"Invalid initial X position for rover (Invalid data: {initialRoverPosition[0]}). Position value must be an integer.");
                }

                //Parses and validates initial rover's Y coordinate input
                if (!int.TryParse(initialRoverPosition[1], out int yPosition))
                {
                    throw new Exception(
                              $"Invalid initial Y position for rover (Invalid data: {initialRoverPosition[1]}). Position value must be an integer.");
                }

                //Parses and validates initial rover's direction input.
                Directions direction;
                if (!Regex.IsMatch(initialRoverPosition[2], @"^[a-zA-Z]+$"))
                {
                    throw new Exception(
                              $"Invalid initial direction for rover (Invalid data: {initialRoverPosition[2]}). Valid direction values are (N,E,S,W)");
                }

                //Parses and validates initial rover's direction input is valid direction type.
                if (!Enum.TryParse(initialRoverPosition[2], true, out direction))
                {
                    throw new Exception(
                              $"Invalid initial direction for rover (Invalid data: {initialRoverPosition[2]}). Valid direction values are (N,E,S,W)");
                }

                rover.X         = xPosition;
                rover.Y         = yPosition;
                rover.Direction = direction;
            }
            else
            {
                throw new Exception(
                          $"Invalid initial directions for rover. Valid direction values must include X,Y coordinates and initial direction(N,E,S,W). Eg.(1 2 N)");
            }
        }
Пример #60
0
        static void Main(string[] args)
        {
            List <Rover> roverList        = new List <Rover>();
            List <int>   terrainMaxPoints = new List <int>();

            //Gets the instructions from  .txt file located under application base directory.
            var commandlines = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + @"\\roverCommands.txt").Where(x => !string.IsNullOrWhiteSpace(x)).ToList();

            if (commandlines.Count < 3)
            {
                throw new Exception(
                          $"Insufficient information provided. Information must include terrain max cooridnates. At least one rover's initial positions and movement information");
            }

            var terrainPointsInput = commandlines[0].Trim().Split(' ').ToList();

            //Parses and validates the gathered information for terrain data.
            ParseAndValidateTerrainData(terrainPointsInput, terrainMaxPoints);

            for (int i = 1; i < commandlines.Count; i += 2)
            {
                Rover rover = new Rover();
                var   initialRoverPosition = commandlines[i].Trim().Split(' ').ToList();

                //Parses and validates the gathered information for mars rover.
                ParseAndValidateInitialRoverData(initialRoverPosition, rover);

                //Checks if initial rover placement location is occupied by another rover.
                CheckLocationAvailability(roverList, rover, terrainMaxPoints);

                //Checks if any move information exists.
                if (commandlines.Count == i + 1)
                {
                    throw new Exception($"Rover#{roverList.Count + 1} movement terminated. Missing move information");
                }

                //Gets the rover's move command(s).
                var moves = commandlines[i + 1].ToUpper().Trim().Replace(" ", "").ToCharArray();

                try
                {
                    //Starts rover's movement.
                    rover.StartMoving(terrainMaxPoints, moves, roverList);
                    roverList.Add(rover);
                    Console.WriteLine($"Rover#{roverList.Count} moved successfully to target location ({rover.X},{rover.Y} {rover.Direction.ToString()})");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Rover#{roverList.Count + 1} movement terminated.");
                    throw e;
                }
            }

            //Successful Output.
            foreach (var rover in roverList)
            {
                Console.WriteLine($"{rover.X} {rover.Y} {rover.Direction.ToString()}");
            }

            Console.ReadLine();
        }