示例#1
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();
        }