public static bool ValidateCommand(string inputCommand, out ToyArgs inputArgs) { bool isValidCommand = false; inputArgs = null; if (!string.IsNullOrEmpty(inputCommand)) { inputCommand = inputCommand.ToLower().Trim(); var commandData = inputCommand.Split(placeCommandSeparator); if (commandData.Length == 2) { return ValidatePlaceCommand(commandData, out inputArgs); } else if(commandData.Length == 1) { ToyActions toyAction; inputArgs = new ToyArgs(); isValidCommand = ValidateOtherCommand(inputCommand, out toyAction); if (isValidCommand) { inputArgs.ActionArg = toyAction; } return isValidCommand; } } return isValidCommand; }
private static bool ValidatePlaceCommand(string[] placeCommandData, out ToyArgs inputArgs) { bool isValidCommand = false; inputArgs = new ToyArgs(); MoveDirection moveDirection; if (string.Equals(placeCommandData[0], ToyActions.Place.ToString(), StringComparison.CurrentCultureIgnoreCase)) { int x, y; var placeArgs = placeCommandData[1].Split(placeCommandArgSeprator); if (placeArgs.Length == 3 && int.TryParse(placeArgs[0], out x) && int.TryParse(placeArgs[1], out y) && ValidateMoveDirection(placeArgs[2], out moveDirection)) { inputArgs.PositionArg.X = x; inputArgs.PositionArg.Y = y; inputArgs.MoveDirectionArg = moveDirection; inputArgs.ActionArg = ToyActions.Place; isValidCommand = true; } } return isValidCommand; }
private static void ProcessCommand_1(string inputCommand, Toy robot, ToyArgs inputArgs) { try { if (CommandValidations.ValidateCommand(inputCommand, out inputArgs)) { ToyCommand toyCommand = null; CommandInvoker commandInvoker = null; switch (inputArgs.ActionArg) { case ToyActions.Invalid: Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid command"); return; case ToyActions.Place: { toyCommand = new PlaceCommand(robot, inputArgs.PositionArg, inputArgs.MoveDirectionArg); commandInvoker = new CommandInvoker(toyCommand); } break; case ToyActions.Move: { toyCommand = new MoveCommand(robot); commandInvoker = new CommandInvoker(toyCommand); } break; case ToyActions.Right: { toyCommand = new TurnCommand(robot, TurnDirection.Right); commandInvoker = new CommandInvoker(toyCommand); } break; case ToyActions.Left: { toyCommand = new TurnCommand(robot, TurnDirection.Left); commandInvoker = new CommandInvoker(toyCommand); } break; case ToyActions.Report: { toyCommand = new ReportCommand(robot); commandInvoker = new CommandInvoker(toyCommand); } break; default: Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid command"); return; } if (commandInvoker != null && commandInvoker.ExecuteCommand()) { Console.ForegroundColor = ConsoleColor.Green; } else { Console.ForegroundColor = ConsoleColor.Yellow; } Console.WriteLine(robot.Message); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid command"); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Exception Occured: " + ex.Message); } Console.ResetColor(); }