/JTacticalSim.Console/BaseConsoleIOHandler.cs
C# | 498 lines | 380 code | 97 blank | 21 comment | 50 complexity | 497f200ec1aa8c102efc523258f79088 MD5 | raw file
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using JTacticalSim.API;
- using JTacticalSim.API.Component;
- using JTacticalSim.API.DTO;
- using JTacticalSim.API.Game;
- using JTacticalSim.API.Service;
- using JTacticalSim.Utility;
- namespace JTacticalSim.Console
- {
- public abstract class BaseConsoleIOHandler
- {
- protected ParsedCommandArgs _commandArgs;
- protected bool _inputError = false;
- protected IGame _theGame { get; set; }
- protected BaseConsoleIOHandler(IGame theGame)
- {
- _theGame = theGame;
- }
- #region Public Virtual Methods
- public virtual void SetInputError(string error)
- {
- _inputError = true;
- _theGame.Renderer.HandleErrorUI(error, null);
- }
- public virtual void RenderBoard()
- {
- // Enter main game sate
- // The statechanged event handler will call the state renderer (board in this case)
- _theGame.StateSystem.ChangeState(StateType.GAME_IN_PLAY);
- }
-
- public virtual void RefreshScreen()
- {
- _theGame.StateSystem.Render();
- }
- public virtual void GetCommandInput(ICommandInterface ci)
- { throw new NotImplementedException();}
- #endregion
- protected virtual void DrawLine()
- {
- System.Console.Write("________________________________________________________");
- }
- protected virtual void RunCommand(ICommandInterface ci)
- {
- _inputError = false;
- var commands = CommandInterface.GetInputCommandMethods(_theGame.StateSystem.CurrentStateType);
- // Allow for the name and alias
- var dictItem = commands.SingleOrDefault(kvp => (kvp.Key.CommandName.ToLowerInvariant() == _commandArgs.Command.ToLowerInvariant()) ||
- kvp.Key.Alias.ToLowerInvariant() == _commandArgs.Command.ToLowerInvariant());
-
-
- // We found the command
- if (dictItem.Key != null && dictItem.Value != null)
- {
- dictItem.Value.Invoke(ci, null);
- if (dictItem.Key.RefreshScreen && !_inputError)
- RefreshScreen();
- return;
- }
- // No command found
- System.Console.ForegroundColor = ConsoleColor.Red;
- System.Console.WriteLine("Command not recognized");
- System.Console.ResetColor();
-
- }
- protected virtual void ParseCommandArgs(string command)
- {
- // Get all args. Skip the command text
- string[] tmp = command.Split(' ').ToArray();
- _commandArgs.Command = tmp.First();
- _commandArgs.Args = tmp.Skip(1).Where(arg => !arg.Contains("--")).ToArray();
- _commandArgs.Switches = tmp.Skip(1).Where(arg => arg.Contains("--")).ToList();
- _commandArgs.Cancel = (tmp.Any(i => i.ToLowerInvariant() == "cancel"));
- _commandArgs.Switches.ForEach(arg => arg.ToLowerInvariant());
- }
- protected virtual bool IsValidRow(string input)
- {
- int intVal;
- if (!CommandLineUtil.ConsoleUtils.IsValidateNumericInput(input))
- {
- SetInputError("Row must be a positive numeric value.");
- return false;
- }
- intVal = Convert.ToInt32(input);
- if (intVal > _theGame.GameBoard.DefaultAttributes.Height - 1 || intVal < 0)
- {
- SetInputError("Row must be between 0 and {0}".F(_theGame.GameBoard.DefaultAttributes.Height - 1));
- return false;
- }
- _inputError = false;
- return true;
- }
- protected virtual bool IsValidColumn(string input)
- {
- int intVal;
- if (!CommandLineUtil.ConsoleUtils.IsValidateNumericInput(input))
- {
- SetInputError("Column must be a positive numeric value.");
- return false;
- }
- intVal = Convert.ToInt32(input);
- if (intVal > _theGame.GameBoard.DefaultAttributes.Width - 1 || intVal < 0)
- {
- SetInputError("Column must be between 0 and {0}".F(_theGame.GameBoard.DefaultAttributes.Width - 1));
- return false;
- }
- _inputError = false;
- return true;
- }
- protected virtual bool IsValidLocationEntered()
- {
- if (_commandArgs.Args.Length < 2)
- {
- SetInputError("Command requires a Column and Row value.");
- return false;
- }
- _inputError = false;
- return (IsValidRow(_commandArgs.Args[1]) && IsValidColumn(_commandArgs.Args[0]));
- }
- protected virtual IResult<bool> IsValidScenarioTitleEntered(string input)
- {
- var Result = _theGame.JTSServices.RulesService.ScenarioTitleIsValid(input);
- var r = Result.ConvertServiceResultData(_theGame.JTSServices);
- return r;
- }
- protected virtual IResult<bool> IsValidGameTitleEntered(string input)
- {
- var sResult = _theGame.JTSServices.RulesService.GameTitleIsValid(input);
- var r = sResult.ConvertServiceResultData(_theGame.JTSServices);
- return r;
- }
- protected virtual MouseButton GetValidMouseButtonClick(string input)
- {
- // if no input default is left click
- if (input == null) return MouseButton.LEFT;
- var validButtonClicks = new List<string>
- {
- "l", "left", "r", "right", "m", "middle"
- };
- _inputError = false;
- switch (input.ToLowerInvariant())
- {
- case ("l") :
- case ("left") :
- return MouseButton.LEFT;
- case ("ll") :
- return MouseButton.DOUBLELEFT;
- case("r") :
- case ("right") :
- return MouseButton.RIGHT;
- case("rr") :
- return MouseButton.DOUBLERIGHT;
- case ("m") :
- case ("middle") :
- return MouseButton.MIDDLE;
- default :
- return MouseButton.LEFT;
- }
- }
- protected virtual string GetValidUnitName()
- {
- string unitName;
- //Restrict to 16 characters to not f-up the board
- System.Console.Write("Unit Name : ");
- unitName = CommandLineUtil.ConsoleUtils.GetInputWithCancel();
- //unitName = Interaction.InputBox("Enter a valid unit name [16 chrs or less] : ", "Unit Name", "", 100, 100);
- while ((unitName.Length > 16 || unitName.Length == 0) && !_commandArgs.Cancel)
- {
- System.Console.ForegroundColor = ConsoleColor.Red;
- System.Console.Write("Enter a valid unit name [16 chrs or less] : ");
- System.Console.ResetColor();
- unitName = CommandLineUtil.ConsoleUtils.GetInputWithCancel();
- //unitName = Interaction.InputBox("Enter a valid unit name [16 chrs or less] : ", "Unit Name", "", 100, 100);
- }
- while (!_theGame.JTSServices.RulesService.UnitNameIsUnique(unitName).Result && !_commandArgs.Cancel)
- {
- System.Console.ForegroundColor = ConsoleColor.Red;
- System.Console.Write("Unit name in use : ");
- System.Console.ResetColor();
- unitName = CommandLineUtil.ConsoleUtils.GetInputWithCancel();
- //unitName = Interaction.InputBox("Unit name in use. Enter a valid unit name [16 chrs or less] : ", "Unit Name", "", 100, 100);
- }
- return unitName;
- }
- protected virtual IUnit GetValidReinforcementUnit(string unitName)
- {
- IUnit unit = GetValidUnit(unitName);
-
- while (!_theGame.CurrentTurn.Player.UnplacedReinforcements.Contains(unit))
- {
- System.Console.ForegroundColor = ConsoleColor.Red;
- System.Console.Write("{0} is not a currently unplaced unit. Unit Name : ".F(unitName));
- System.Console.ResetColor();
- unitName = CommandLineUtil.ConsoleUtils.GetInputWithCancel().ToLowerInvariant();
- unit = GetValidUnit(unitName);
- }
- return unit;
- }
- protected virtual IUnit GetValidUnit(string unitName)
- {
- IUnit unit;
- // Get and validate unit to move
- if (string.IsNullOrWhiteSpace(unitName))
- {
- System.Console.Write("Unit Name : ");
- unitName = CommandLineUtil.ConsoleUtils.GetInputWithCancel().ToLowerInvariant();
- //unitName = Interaction.InputBox("Unit Name [16 chrs or less] : ", "Unit Name", "", 100, 100);
- }
-
- try
- {
- unit = _theGame.JTSServices.GenericComponentService.GetByName<IUnit, IUnitDTO>(unitName);
- }
- catch (ComponentNotFoundException)
- {
- unit = null;
- }
-
-
- while (unit == null && !_commandArgs.Cancel)
- {
- System.Console.ForegroundColor = ConsoleColor.Red;
- System.Console.Write("Enter a valid unit name : ");
- System.Console.ResetColor();
- unitName = CommandLineUtil.ConsoleUtils.GetInputWithCancel().ToLowerInvariant();
- //unitName = unitName = Interaction.InputBox("Enter a valid unit name [16 chrs or less] : ", "Unit Name", "", 100, 100);
- try
- {
- unit = _theGame.JTSServices.GenericComponentService.GetByName<IUnit, IUnitDTO>(unitName);
- }
- catch (ComponentNotFoundException)
- {
- unit = null;
- }
- }
- while (unit == null || !unit.Country.Equals(_theGame.CurrentTurn.Player.Country))
- {
- System.Console.ForegroundColor = ConsoleColor.Red;
- System.Console.Write("Select a unit from your country : ");
- System.Console.ResetColor();
- unitName = CommandLineUtil.ConsoleUtils.GetInputWithCancel().ToLowerInvariant();
- //unitName = unitName = Interaction.InputBox("Enter a valid unit name [16 chrs or less] : ", "Unit Name", "", 100, 100);
- try
- {
- unit = _theGame.JTSServices.GenericComponentService.GetByName<IUnit, IUnitDTO>(unitName);
- }
- catch (ComponentNotFoundException)
- {
- unit = null;
- }
- }
- return unit;
- }
- protected virtual IUnitType GetValidUnitType(bool forCurrentTile)
- {
- var options = "";
- if (forCurrentTile)
- {
- var UnitTypes = _theGame.JTSServices.UnitService.GetUnitTypesAllowableForTile(_theGame.GameBoard.SelectedNode.DefaultTile());
- options = GetCommandInputOptions(UnitTypes);
- }
- System.Console.Write("Unit Type {0} : ", options);
- var name = CommandLineUtil.ConsoleUtils.GetInputWithCancel().ToLowerInvariant();
- IUnitType unitType;
- try
- {
- unitType = _theGame.JTSServices.UnitService.GetUnitTypeByName(name);
- }
- catch (ComponentNotFoundException)
- {
- unitType = null;
- }
- while (unitType == null && !_commandArgs.Cancel)
- {
- System.Console.ForegroundColor = ConsoleColor.Red;
- System.Console.Write("Enter a valid Unit Type {0} : ", options);
- System.Console.ResetColor();
- name = CommandLineUtil.ConsoleUtils.GetInputWithCancel().ToLowerInvariant();
- //country = Interaction.InputBox(string.Format("Faction not valid. Faction [{0}] ", sb.ToString()), "Faction by Country", "", 100, 100);
-
- try
- {
- unitType = _theGame.JTSServices.UnitService.GetUnitTypeByName(name);
- }
- catch (ComponentNotFoundException)
- {
- unitType = null;
- }
- }
- return unitType;
- }
- protected virtual IUnitClass GetValidUnitClass(IUnitType unitType)
- {
- // Get available unit classes
- var ids = _theGame.JTSServices.DataService.LookupAllowableUnitClassesByUnitBaseType(unitType.BaseType.ID);
- var unitClasses = _theGame.JTSServices.UnitService.GetUnitClassesByIDs(ids).Result;
- string options = GetCommandInputOptions(unitClasses);
- System.Console.Write("Unit Class {0} : ", options);
- var name = CommandLineUtil.ConsoleUtils.GetInputWithCancel().ToLowerInvariant();
- //country = Interaction.InputBox(String.Format("Faction [{0}] : ", sb.ToString()), "Faction by Country", "", 100, 100);
- IUnitClass unitClass;
-
- try
- {
- unitClass = _theGame.JTSServices.UnitService.GetUnitClassByName(name);
- }
- catch (ComponentNotFoundException)
- {
- unitClass = null;
- }
- while (unitClass == null && !_commandArgs.Cancel)
- {
- System.Console.ForegroundColor = ConsoleColor.Red;
- System.Console.Write("Enter a valid Unit Class {0} : ", options);
- System.Console.ResetColor();
- name = CommandLineUtil.ConsoleUtils.GetInputWithCancel().ToLowerInvariant();
- //country = Interaction.InputBox(string.Format("Faction not valid. Faction [{0}] ", sb.ToString()), "Faction by Country", "", 100, 100);
-
- try
- {
- unitClass = _theGame.JTSServices.UnitService.GetUnitClassByName(name);
- }
- catch (ComponentNotFoundException)
- {
- unitClass = null;
- }
- }
- return unitClass;
- }
- protected virtual IUnitGroupType GetValidUnitGroupType()
- {
- var sb = new StringBuilder();
- string options = GetCommandInputOptions<IUnitGroupType, IUnitGroupTypeDTO>();
- System.Console.Write("Unit Group Type {0} : ", options);
- var name = CommandLineUtil.ConsoleUtils.GetInputWithCancel().ToLowerInvariant();
- //country = Interaction.InputBox(String.Format("Faction [{0}] : ", sb.ToString()), "Faction by Country", "", 100, 100);
- IUnitGroupType unitGroupType;
- try
- {
- unitGroupType = _theGame.JTSServices.UnitService.GetUnitGroupTypeByName(name);
- }
- catch (ComponentNotFoundException)
- {
- unitGroupType = null;
- }
- while (unitGroupType == null && !_commandArgs.Cancel)
- {
- System.Console.ForegroundColor = ConsoleColor.Red;
- System.Console.Write("Enter a valid Unit Group Type {0} : ", options);
- System.Console.ResetColor();
- name = CommandLineUtil.ConsoleUtils.GetInputWithCancel().ToLowerInvariant();
- //country = Interaction.InputBox(string.Format("Faction not valid. Faction [{0}] ", sb.ToString()), "Faction by Country", "", 100, 100);
-
- try
- {
- unitGroupType = _theGame.JTSServices.UnitService.GetUnitGroupTypeByName(name);
- }
- catch (ComponentNotFoundException)
- {
- unitGroupType = null;
- }
- }
- return unitGroupType;
- }
-
- protected virtual INode GetSelectedNode()
- {
- if (_theGame.GameBoard.SelectedNode == null)
- {
- SetInputError("You must select a location first.");
- return null;
- }
-
- return _theGame.GameBoard.SelectedNode;
- }
- protected virtual bool MoveUnitToSelectedNode(IUnit unit)
- {
- var sourceNode = _theGame.JTSServices.NodeService.GetNodeAt(unit.Location);
- var targetNode = _theGame.GameBoard.SelectedNode;
- if (targetNode == null)
- return false;
-
- var r = unit.MoveToLocation(targetNode, sourceNode);
-
- if (r.Status != ResultStatus.SUCCESS)
- {
- SetInputError(r.Message);
- return false;
- }
- return true;
- }
- protected virtual string GetCommandInputOptions<T, dtoT>()
- where T : IBaseComponent
- where dtoT : IBaseGameComponentDTO
- {
- StringBuilder sb = new StringBuilder();
- sb.Append("[ ");
-
- var table = _theGame.JTSServices.GenericComponentService.GetComponentTable<T, dtoT>();
- table.Records.ToList().ForEach(t => sb.Append("{0} ".F(t.Name)));
- sb.Append("]");
- return sb.ToString();
- }
- protected virtual string GetCommandInputOptions<T>(IEnumerable<T> components)
- where T : IBaseComponent
- {
- StringBuilder sb = new StringBuilder();
- sb.Append("[ ");
- components.ToList().ForEach(t => sb.Append("{0} ".F(t.Name)));
- sb.Append("]");
- return sb.ToString();
- }
- }
- }