/// <summary> /// Transfer objects/persons/animals depends on the the user answer /// </summary> /// <param name="tranferDescr"></param> public virtual void TransferObjectsByFerry(string tranferDescr) { try { //get the list of objects for transferring ICollection <FarmerPazle_ObjectToTransfer> objForTr = GetListOfObjectsToTransfer(tranferDescr); if (objForTr == default(ICollection <FarmerPazle_ObjectToTransfer>)) //check if there are some objects for transferring { return; } //get current direction for transferring FarmerPazle_Direction direction = GetDirectionForTransfer(tranferDescr); objForTr.ToList().ForEach(obj => { switch (direction) //depends on the direction of transferring { case FarmerPazle_Direction.there: FromBank.Remove(obj); //remove object from first bank ToBank.Add(obj); //add object to destination bank break; case FarmerPazle_Direction.back: ToBank.Remove(obj); //remove object from destination bank FromBank.Add(obj); //add object to opposite bank break; } }); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
/// <summary> /// Get current direction for transferring /// </summary> /// <param name="tranferDescr"></param> /// <returns></returns> public virtual FarmerPazle_Direction GetDirectionForTransfer(string tranferDescr) { try { //check if input string arg is null or empty if (string.IsNullOrEmpty(tranferDescr)) { return(default(FarmerPazle_Direction)); } //split the current user answer by ' ' string[] posVariants = tranferDescr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); //check if the type of direction is defined ('there', 'back', etc...) in user answer if (posVariants.Any(x => Enum.IsDefined(typeof(FarmerPazle_Direction), x.ToLower()))) { //return the type of direction whitch is cast to the FarmerPazle_Direction enum return(posVariants .Where(x => Enum.IsDefined(typeof(FarmerPazle_Direction), x.ToLower())) .First() .ToEnumButFirstlyTryParse <FarmerPazle_Direction>()); } return(default(FarmerPazle_Direction)); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(default(FarmerPazle_Direction));; }
public virtual bool RunAndContinue() { try { StringBuilder consoleLog = new StringBuilder(); Console.Clear(); ConsoleIO.WriteColorTextNewLine(_header, ConsoleColor.Cyan); consoleLog.AppendLine(_header); ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); consoleLog.AppendLine(string.Format("{0}{1}{0}", ConsoleIO.ConsoleRowSeparator, "\n")); string answer = string.Format("{0}{1}{2}", new string(ReplaceToSymbol, GetTypedValue("first", ref consoleLog)), Delimiter, new string(ReplaceToSymbol, GetTypedValue("second", ref consoleLog))); Console.Clear(); ConsoleIO.WriteColorText(consoleLog); ConsoleIO.WriteColorTextNewLine("\n-!Well Done! You've made a great thing! Now your PC is trying to process it!-\n", ConsoleColor.Green); DoMathOperation(answer);//, ExpressionType.SubtractChecked); ConsoleIO.Console_ToMainMenu(); return(true); } catch (Exception ex) { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(false); }
public virtual bool RunAndContinue() { try { StringBuilder consoleLog = new StringBuilder(); Console.Clear(); ConsoleIO.WriteColorTextNewLine(_header, ConsoleColor.Cyan); consoleLog.AppendLine(_header); ConsoleIO.ResizeConsoleWindow(Console.WindowWidth + 20, Console.WindowHeight); ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); consoleLog.AppendLine(string.Format("{0}{1}{0}", ConsoleIO.ConsoleRowSeparator, "\n")); int answer = GetTypedValue(ref consoleLog); Console.Clear(); ConsoleIO.WriteColorText(consoleLog); ConsoleIO.WriteColorTextNewLine("\n-!Well Done! You've made a great thing! Now your PC is trying to process it!-\n", ConsoleColor.Green); Convert(answer);//, ExpressionType.SubtractChecked); ConsoleIO.Console_ToMainMenu(); return(true); } catch (Exception ex) { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(false); }
/// <summary> /// To show the full current/actual status of organisation hardware /// </summary> public virtual void ShowFullStatusOfOrganization() { try { for (int dep = OrganizationHardwaresArray.GetLowerBound(0); dep <= OrganizationHardwaresArray.GetUpperBound(0); dep++) { ConsoleIO.WriteColorTextNewLine(string.Format("Department №: '{0}'", dep + 1), ConsoleColor.Green); for (int compType = OrganizationHardwaresArray[dep].GetLowerBound(0); compType <= OrganizationHardwaresArray[dep].GetUpperBound(0); compType++) { Computer[] comp = (OrganizationHardwaresArray[dep][compType] as Computer[]); ConsoleIO.WriteColorTextNewLine(string.Format("ComputerType: '{0}'", comp[0].ToString()), ConsoleColor.Cyan); for (int i = 0; i < comp.Length; i++) { ConsoleIO.WriteColorTextNewLine(string.Format("ArrayIndex: '[{0}][[{1}][{2}]]', RAM: '{3}', CPU: '{4}', HDD: '{5}'", dep, compType, i, comp[i].RAM, comp[i].CPU, comp[i].HDD)); } } ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator + "\n" + ConsoleIO.ConsoleRowSeparator); } } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
/// <summary> /// To count and show the number of unique hardware types in each departments /// </summary> public virtual void ShowNumberOfEachHardwareTypes() { try { Random rndObj = new Random(); //ConsoleIO.WriteColorTextNewLine("Organization consist of 4 department. Every department has several computers of different types:", ConsoleColor.Green); for (int dep = OrganizationHardwaresArray.GetLowerBound(0); dep <= OrganizationHardwaresArray.GetUpperBound(0); dep++) { ConsoleIO.WriteColorText(string.Format("- {0} department:", dep + 1), ConsoleColor.White, dep + 1, ConsoleColor.Green); // (ConsoleColor)rndObj.Next((int)ConsoleColor.DarkBlue, (int)ConsoleColor.White)); for (int compType = OrganizationHardwaresArray[dep].GetLowerBound(0); compType <= OrganizationHardwaresArray[dep].GetUpperBound(0); compType++) { Computer[] comp = (OrganizationHardwaresArray[dep][compType] as Computer[]); if (comp.Length >= 1) { ConsoleIO.WriteColorText(string.Format("{0} {1} {2}{3}", (compType != 0 ? "," : string.Empty), comp.Length, comp[0].ToString(), (comp.Length > 1 ? "s" : string.Empty))); } } ConsoleIO.WriteColorTextNewLine(); } ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator + "\n"); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
/// <summary> /// To count and show the number of selected (T) hardware type /// </summary> /// <typeparam name="T">the type of hardware that should be inspected</typeparam> public virtual void ShowNumberOfHardwareType <T>() { try { int compCount = 0; string nameAsStringRep = string.Empty; for (int dep = OrganizationHardwaresArray.GetLowerBound(0); dep <= OrganizationHardwaresArray.GetUpperBound(0); dep++) { for (int compType = OrganizationHardwaresArray[dep].GetLowerBound(0); compType <= OrganizationHardwaresArray[dep].GetUpperBound(0); compType++) { Computer[] comp = (OrganizationHardwaresArray[dep][compType] as Computer[]); if (comp != null && comp.Length > 0) { if (comp[0] is T) { compCount += comp.Length; if (string.IsNullOrEmpty(nameAsStringRep)) { nameAsStringRep = comp[0].ToString(); } } } } } ConsoleIO.WriteColorTextNewLine(string.Format("Number of '{0}': '{1}'", (typeof(T) != typeof(Computer) ? nameAsStringRep : "all computers"), compCount), ConsoleColor.White, compCount.ToString(), ConsoleColor.Green); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
protected virtual string TranslateToMorse(string answer) { try { StringBuilder stringBuilder = new StringBuilder(); foreach (char character in answer) { if (_morseAlphabetDictionary.ContainsKey(character)) { stringBuilder.Append(_morseAlphabetDictionary[character] + " "); } else if (character == ' ') { stringBuilder.Append("/ "); } else { stringBuilder.Append(character + " "); } } return(stringBuilder.ToString()); } catch (Exception ex) { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(string.Empty); }
/// <summary> /// Update the selected (T1) hardware parameter value (fieldName) /// </summary> /// <typeparam name="T1">the type of hardware that should be modified</typeparam> /// <typeparam name="T2">the type of hardware parameter new value</typeparam> /// <param name="fieldName">the field (hardware parameter name) that should be modified</param> /// <param name="newValue">new parameter value</param> public virtual void UpdateFieldValue <T1, T2>(string fieldName, T2 newValue) { try { FieldInfo field = typeof(T1).GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != default(FieldInfo)) { for (int dep = OrganizationHardwaresArray.GetLowerBound(0); dep <= OrganizationHardwaresArray.GetUpperBound(0); dep++) { for (int compType = OrganizationHardwaresArray[dep].GetLowerBound(0); compType <= OrganizationHardwaresArray[dep].GetUpperBound(0); compType++) { Computer[] comp = (OrganizationHardwaresArray[dep][compType] as Computer[]); for (int i = 0; i < comp.Length; i++) { if (comp[i] is T1) { field.SetValue(comp[i], newValue); } } } } } } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
public virtual bool RunAndContinue() { try { //to store the user last pressed key info ConsoleKeyInfo keyInfo = default(ConsoleKeyInfo); //if user press any button whitch is deffined in _calcOperationType dictionary (math operation) //this variable will be used to store a referene to the struct KeyValuePair<MathOperation, char> //which will be show the current math operation (+, -, *, .....) KeyValuePair <MathOperation, char> operation = default(KeyValuePair <MathOperation, char>); //show calculator initial screen _calcProvider.ClearBufferAndShowInitScreen(); do // until user presses on the key 'q' or 'Q' { // get the last pressed key info keyInfo = Console.ReadKey(true); switch (GetKeyType(keyInfo, ref operation)) { //if numeric / point / comma key has been pressed case KeyType.Numeric: char number = keyInfo.KeyChar == '.' ? _calcProvider.NumberDecimalSeparator : keyInfo.KeyChar; _calcProvider.AddNewNumeric(number); break; //if any calc operation key (+, -, *, /, e ...) has been pressed than try to do entered math operation case KeyType.CalcOperation: _calcProvider.MathOperation(operation); break; //if 'c' button has been pressed, than delete last entered symbol case KeyType.DeleteLast: _calcProvider.DeleteLastNumeric(); break; //if 'Enter' button has been pressed then clear calc upper row (buffer) and show the result of operation case KeyType.ClearBufferAndShowResult: _calcProvider.ClearBufferAndShowResult(); break; //if 'c' button has been pressed than clear calculator buffer and show initial screen case KeyType.ClearBufferAndShowInitScreen: _calcProvider.ClearBufferAndShowInitScreen(); break; //if 'q' or 'Q' button has been pressed than exit from calculator case KeyType.Exit: return(true); } } while (true); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(false); }
public virtual bool RunAndContinue() { try { //resize console window ConsoleIO.ResizeConsoleWindow(Console.WindowWidth + 20, Console.WindowHeight); //to store current operation log (for redrawing in console) StringBuilder consoleLog = new StringBuilder(); //clear console Console.Clear(); //show current task name ConsoleIO.WriteColorTextNewLine(this.ToString(), ConsoleColor.Cyan); //add current task name to gen log consoleLog.AppendLine(this.ToString()); //show text separator (by default: ------------) ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); //add text separator to gen log consoleLog.AppendLine(string.Format("{0}{1}{0}", ConsoleIO.ConsoleRowSeparator, "\n")); //get user answer int answer = GetTypedValue(ref consoleLog); //clear console Console.Clear(); //show all log info ConsoleIO.WriteColorText(consoleLog); //show the congrats message ConsoleIO.WriteColorTextNewLine("\n-!Well Done! You've made a great thing! Now your PC is trying to process it!-\n", ConsoleColor.Green); //for getting the time of opeartiona Stopwatch sw = new Stopwatch(); sw.Start(); // start the stopwatch double factorial = GetFactorial(answer); sw.Stop(); // stop the stopwatch //show the generic output info (facotrail for -> result -> time of operation) ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); ConsoleIO.WriteColorText(string.Format("The factorail of '{0}' -> ", answer), ConsoleColor.White, answer.ToString(), ConsoleColor.Red); ConsoleIO.WriteColorTextNewLine(string.Format("'{0}'", factorial), ConsoleColor.White, factorial.ToString(), ConsoleColor.Green); ConsoleIO.WriteColorTextNewLine(string.Format("Time of calculation -> '{0}' milliseconds", sw.Elapsed.TotalMilliseconds), ConsoleColor.White, sw.Elapsed.TotalMilliseconds.ToString(), ConsoleColor.Yellow); ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator + "\n"); //show the suggestion of pressing any key to return to the main menu ConsoleIO.Console_ToMainMenu(); return(true); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(false); }
/// <summary> /// depending on the user input (pressed key) in calculator, /// return the type of operation which must be done /// </summary> /// <param name="keyInfo"></param> /// <param name="operation"></param> /// <returns></returns> public virtual KeyType GetKeyType(ConsoleKeyInfo keyInfo, ref KeyValuePair <MathOperation, char> operation) { try { int number = 0; //if numeric / point / comma key has been pressed if (int.TryParse(keyInfo.KeyChar.ToString(), out number) || keyInfo.KeyChar == ',' || keyInfo.KeyChar == '.') { return(KeyType.Numeric); } //if backspace '<-' button has been pressed else if (keyInfo.KeyChar == '\b') { return(KeyType.DeleteLast); } //if 'c' button has been pressed else if (keyInfo.KeyChar.ToString().ToLower() == "c") { return(KeyType.ClearBufferAndShowInitScreen); } //if 'Enter' button has been pressed else if (keyInfo.KeyChar.ToString().ToLower() == "\r") { return(KeyType.ClearBufferAndShowResult); } //if 'q' or 'Q' button has been pressed else if (keyInfo.KeyChar.ToString().ToLower() == "q") { return(KeyType.Exit); } else { //if any calc operation key (+, -, *, /, e ...) has been pressed operation = _calcOperationType.FirstOrDefault(x => x.Value == keyInfo.KeyChar); if (Enum.IsDefined(typeof(MathOperation), operation.Key)) { return(KeyType.CalcOperation); } else { return(KeyType.Na); } } } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(KeyType.Na); }
/// <summary> /// check if current answer is correct (compare with the dictionary of keys and previous answers) /// </summary> /// <param name="enteredKeyChar"></param> /// <param name="availableAnsw"></param> /// <param name="alreadyEntCorrectAnsw"></param> /// <returns></returns> protected virtual string GetCorrectAnswer(string enteredKeyChar, IDictionary <FarmerPazle_Answers, string> availableAnsw, ref StringBuilder alreadyEntCorrectAnsw) { try { //to store all previous correct answers StringBuilder correctAnsw = alreadyEntCorrectAnsw; byte enteredVal = 0; //try to parse enterd key char. if successfully -> check if such value is check if such value is defined in FarmerPazle_Answers enum (if it's suitable) in FarmerPazle_Answers enum if (Byte.TryParse(enteredKeyChar, out enteredVal) && Enum.IsDefined(typeof(FarmerPazle_Answers), enteredVal)) { string position = string.Empty; if (correctAnsw.Length > 0) //check if it's a first correct enter //get the first suitable key { position = _rulesProvider.KeysList.FirstOrDefault(k => k.Substring(0, correctAnsw.Length) == correctAnsw.ToString() && k.Substring(correctAnsw.Length, 1) == enteredKeyChar); } else //it's first correct enter { position = _rulesProvider.KeysList.FirstOrDefault(k => k.Substring(0, 1) == enteredKeyChar); } if (!String.IsNullOrEmpty(position)) //if there is any suitable key { /*get the KeyValuePair<FarmerPazle_Answers, string> where last entered value (ets: 1, 2, 3...) * == key from all posible answers (from dictionary 'FarmerPazle_Answers')*/ var selectedDictValue = availableAnsw .Where(x => x.Key == (FarmerPazle_Answers)Enum.Parse(typeof(FarmerPazle_Answers), enteredVal.ToString())) .Select(k => new KeyValuePair <FarmerPazle_Answers, string>(k.Key, k.Value)) .FirstOrDefault(); //add '+' char as a sign of correct answer string selectedValue = string.Format(selectedDictValue.Value, Rules.CorrectAnswerLabel + "{0}"); availableAnsw[selectedDictValue.Key] = selectedValue; //save last correct answer (key char) correctAnsw.Append(enteredVal); alreadyEntCorrectAnsw = correctAnsw; return(selectedValue); } } //if answer was incorrect than user life - 1 _rulesProvider.PlusAttempt(); return(string.Empty); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(string.Empty); }
/// <summary> /// guess number algorithm /// </summary> /// <returns> /// true - if user find the correct answer /// false - if user didn't find the correct answer /// </returns> protected virtual bool TryToGuessTheNumber() { try { Random rndObj = new Random(); int lastMinValue = _rulesProvider.MinTypingValue; int lastMaxValue = _rulesProvider.MaxTypingValue; //generate a random value that user must guess int rndValue = rndObj.Next(lastMinValue, lastMaxValue); int enteredValue = 0, attemptCount = 0; string typedValue = string.Empty; string showMessage = "LifesCount: '{0}'\nGuessed number is at range [{1};{2}]. Enter your guess: -> "; do { //check if it's not a first loop if (attemptCount != 0) { //show the info message that current input value was too low or too high ConsoleIO.WriteColorTextNewLine( string.Format("{0} - Too {1}!", enteredValue, (enteredValue < rndValue ? "low" : "high")), (ConsoleColor)rndObj.Next((int)ConsoleColor.DarkBlue, (int)ConsoleColor.White)); ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); } //check if entered value is in range of min and max possible values if (enteredValue >= _rulesProvider.MinTypingValue && enteredValue > lastMinValue && enteredValue <= _rulesProvider.MaxTypingValue && enteredValue <= lastMaxValue) { lastMinValue = enteredValue < rndValue ? enteredValue : lastMinValue; lastMaxValue = enteredValue > rndValue ? enteredValue : lastMaxValue; } ConsoleIO.WriteColorText(string.Format(showMessage, _rulesProvider.MaxAttemptsCount - attemptCount, lastMinValue, lastMaxValue)); typedValue = Console.ReadLine(); attemptCount++; } while ((!int.TryParse(typedValue, out enteredValue) || enteredValue != rndValue) && attemptCount < _rulesProvider.MaxAttemptsCount); //show text separator (by default: ------------) ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); //check if user answer number >= MAX attempts return(attemptCount >= _rulesProvider.MaxAttemptsCount ? false : true); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(false); }
/// <summary> /// Calculate factorial by using the recursion /// </summary> /// <param name="number"></param> /// <returns></returns> protected virtual double GetFactorial(int number) { try { return(number > 1 ? number * GetFactorial(number - 1) : 1); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(0); }
/// <summary> /// To show the selected (T) hardware type with the lowest parameter (fieldName) value /// </summary> /// <typeparam name="T">the type of hardware that should be inspected</typeparam> /// <param name="fieldName">the field that is used to compare the hardware</param> public virtual void ShowHardwareWithTheLowestParameterData <T>(string fieldName) { try { double minValue = double.MaxValue; StringBuilder lowestCapacity = new StringBuilder(); FieldInfo field = typeof(T).GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != default(FieldInfo)) { for (int dep = OrganizationHardwaresArray.GetLowerBound(0); dep <= OrganizationHardwaresArray.GetUpperBound(0); dep++) { for (int compType = OrganizationHardwaresArray[dep].GetLowerBound(0); compType <= OrganizationHardwaresArray[dep].GetUpperBound(0); compType++) { Computer[] comp = (OrganizationHardwaresArray[dep][compType] as Computer[]); for (int i = 0; i < comp.Length; i++) { double curValue = 0; object fieldValue = field.GetValue(comp[i]); if (double.TryParse(Regex.Match(fieldValue.ToString(), @"\d+").Value, out curValue)) { if (minValue == curValue) { lowestCapacity.AppendFormat("\nDepartment №: '{0}', ComputerType: '{1}', ArrayIndex: '[{2}] [[{3}][{4}]]', {5}: '{6}'", dep + 1, comp[i].ToString(), dep, compType, i, fieldName, fieldValue.ToString()); } else if (minValue > curValue) { lowestCapacity.Clear(); lowestCapacity.AppendFormat("\nDepartment №: '{0}', ComputerType: '{1}', ArrayIndex: '[{2}] [[{3}][{4}]]', {5}: '{6}'", dep + 1, comp[i].ToString(), dep, compType, i, fieldName, fieldValue.ToString()); minValue = curValue; } } } } } } ConsoleIO.WriteColorTextNewLine(lowestCapacity); ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator + "\n"); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
/// <summary> /// method that is handled the event /// of adding a new numeric (or decimal number separator) symbol /// that has been pressed by user /// </summary> /// <param name="number"></param> public override void AddNewNumeric(char number) { try { //unlock the changing of result in local buffer OpProvider.LockResult = false; //get the user input string in calc screen string inputText = GetRow(RowInputData).ToString().TrimEnd(); //get only user input data (numbers and decimal number separator) string alreadyInpNumber = inputText.Substring(inputText.LastIndexOf('_') + 1, inputText.LastIndexOf("|") - inputText.LastIndexOf('_') - 1); //variable that will be contained an output string in calc display StringBuilder outputText = new StringBuilder(number.ToString()); //if the current screen state is by default (___0) and user current input key is '0' //or user current input string (with numbers) length > 10 and user current input operation isn't a math operation //or user current input key == decimal number separator (',') and user current input string already consist that separator //than return if ((alreadyInpNumber == DefaultValueForInputString && number.ToString() == DefaultValueForInputString) || (alreadyInpNumber.Length > 10 && !_wasAlreadyCalcOp) || (number == NumberDecimalSeparator && inputText.IndexOf(NumberDecimalSeparator) >= 0)) { return; } //if the row with input data != 0 (DefaultValueForInputString) or user current input key == decimal number separator //and user current input operation isn't a math operation if ((alreadyInpNumber != DefaultValueForInputString || number == NumberDecimalSeparator) && !_wasAlreadyCalcOp) { outputText.Insert(0, alreadyInpNumber); } else { _wasAlreadyCalcOp = false; } //define a new view of the calculator screen (row with input data), based on the current input data (and on it length) inputText = "|" + new string('_', UndelineSpaceCalcUI.Length - outputText.Length) + outputText + "|"; //write the user input data to the buffer Draw(inputText, 0, RowInputData); //clear console Console.Clear(); //print the buffer to the console screen. Print(); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
public virtual bool RunAndContinue() { try { //clear console Console.Clear(); //show current task name ConsoleIO.WriteColorTextNewLine(this.ToString(), ConsoleColor.Cyan); //add current rues description ConsoleIO.WriteColorTextNewLine(_rulesProvider.RulesDescription); //for getting the time of opeartiona Stopwatch sw = new Stopwatch(); // start the stopwatch sw.Start(); //play game bool IsAWinner = TryToGuessTheNumber(); // stop the stopwatch sw.Stop(); //check the result if (!IsAWinner) { ConsoleIO.WriteColorTextNewLine("\n-!-!-!-!-!-!-!GAME OVER!-!-!-!-!-!-!-\n", ConsoleColor.Red); } else //user find the right answer { ConsoleIO.WriteColorTextNewLine("\n-!-!-!-!-!-!-!Well Done!-!-!-!-!-!-!-\n", ConsoleColor.Green); ConsoleIO.WriteColorTextNewLine(string.Format("{0}!, you are a winner! Your Time is: '{1}' sec\n", Environment.UserName, sw.Elapsed.Seconds), ConsoleColor.Green); } ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator + "\n"); //show the suggestion of pressing any key to return to the main menu ConsoleIO.Console_ToMainMenu(); return(true); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(false); }
protected virtual void Convert(int answer) { try { int tmp = 0; StringBuilder result = new StringBuilder(); ConsoleIO.WriteColorText(string.Format("Converted value: {0} decimal format ({1:N2}) {0} binary format {0} ", "->", answer), ConsoleColor.White, "->", ConsoleColor.Red); while (answer > 0) { tmp = answer % 2; result.Insert(0, tmp); answer /= 2; } if (result.Length % 4 != 0) { result.Insert(0, "0", 4 - result.Length % 4); } while (result.Length > 0) { Thread.Sleep(DelayBetweenTypingInMillisec); ConsoleIO.WriteColorText(result[0].ToString(), result[0].ToString() == "0" ? ConsoleColor.Red : ConsoleColor.Green); result.Remove(0, 1); if (result.Length % 4 == 0) { ConsoleIO.WriteColorText(" "); } } ConsoleIO.WriteColorTextNewLine(); } catch (Exception ex) { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
protected virtual void DoMathOperation(string answer) { try { int firstArg = 0, secondArg = 0; int answerLength = answer.Length; string emptySpace = string.Empty; string endingVar1 = string.Concat(ReplaceToSymbol, Delimiter); string endingVar2 = string.Concat(Delimiter, ReplaceToSymbol); string replaceFrom = string.Concat(ReplaceToSymbol, Delimiter, ReplaceToSymbol); while (true) { Thread.Sleep(DelayBetweenTypingInMillisec); ConsoleIO.WriteColorText(answer, ConsoleColor.White, Delimiter.ToString(), ConsoleColor.Red); firstArg = answer.Substring(0, answer.IndexOf(Delimiter)).Count(x => x == ReplaceToSymbol); secondArg = answer.Substring(answer.IndexOf(Delimiter)).Count(x => x == ReplaceToSymbol); ConsoleIO.WriteColorTextNewLine(string.Concat(new string(' ', 3 + answerLength - answer.Length), "| ", firstArg, " - ", secondArg, " = ", (firstArg - secondArg))); if (answer.IndexOf(endingVar1) < 0 || answer.IndexOf(endingVar2) < 0) { return; } //"↓▼" emptySpace = new string(' ', 3 + answerLength); ConsoleIO.WriteColorTextNewLine(string.Format("{0}{1}{0}", emptySpace, "↓"), ConsoleColor.DarkGreen); answer = answer.Replace(replaceFrom, Delimiter.ToString()); } } catch (Exception ex) { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
/// <summary> /// Get the list of objects for transferring /// </summary> /// <param name="tranferDescr"></param> /// <returns></returns> public virtual List <FarmerPazle_ObjectToTransfer> GetListOfObjectsToTransfer(string tranferDescr) { try { //check if input string arg is null or empty if (string.IsNullOrEmpty(tranferDescr)) { return(default(List <FarmerPazle_ObjectToTransfer>)); } return(tranferDescr .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) //split the current user answer by ' ' .Where(x => Enum.IsDefined(typeof(FarmerPazle_ObjectToTransfer), x.ToLower())) .ToEnumListButFirstlyTryParse <FarmerPazle_ObjectToTransfer>() .ToList()); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(default(List <FarmerPazle_ObjectToTransfer>)); }
/// <summary> /// Show the current status of objects/persons/animals/vegetables transferring /// </summary> /// <param name="tranferDescr"></param> public virtual void ShowCurrentTransferStatus(string tranferDescr) { try { //to transfer objects/persons/animals depends on the the user answer TransferObjectsByFerry(tranferDescr); //to show the objects/persons/animals/vegetables that are in the first river bank ConsoleIO.WriteColorText(_fromBankDescr); FromBank.ToList().ForEach(x => ConsoleIO.WriteColorText(string.Format(" {0} {1}", x, _bankStatusDelimiter), ConsoleColor.Red, _bankStatusDelimiter, ConsoleColor.White)); ConsoleIO.WriteColorTextNewLine(); //to show the objects/persons/animals/vegetables that are in the opposite river bank ConsoleIO.WriteColorText(_toBankDescr); ToBank.ToList().ForEach(x => ConsoleIO.WriteColorText(string.Format(" {0} {1}", x, _bankStatusDelimiter), ConsoleColor.Green, _bankStatusDelimiter, ConsoleColor.White)); ConsoleIO.WriteColorTextNewLine(); ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
/// <summary> /// method that is handled the event /// of deleting the last entered number (or decimal number separator) /// that has been pressed by user /// </summary> public override void DeleteLastNumeric() { try { //get the user input string in calc screen string inputText = GetRow(RowInputData).ToString().TrimEnd(); //get only user input data (numbers and decimal number separator) string alreadyInpNumber = inputText.Substring(inputText.LastIndexOf('_') + 1, inputText.LastIndexOf("|") - inputText.LastIndexOf('_') - 1); //variable that will be contained an output string in calc display string outputText = string.Empty; //if there is only one number on the calc screen, set the output as default (in init screen) if (alreadyInpNumber.Length == 1) { outputText = DefaultValueForInputString; } else //delete the last entered number or decimal number separator { outputText = alreadyInpNumber.Substring(0, alreadyInpNumber.Length - 1); } //define a new view of the calculator screen (row with input data), based on the current input data (and on it length) inputText = "|" + new string('_', UndelineSpaceCalcUI.Length - outputText.Length) + outputText + "|"; //write the user input data to the buffer Draw(inputText, 0, RowInputData); //clear console Console.Clear(); //print the buffer to the console screen. Print(); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
protected virtual void Convert(string answer) { try { answer.ToList().ForEach(c => { if (c == '.') { Console.Beep(2000, 500); } else if (c == '-') { Console.Beep(2000, 1200); } Thread.Sleep(500); }); ConsoleIO.WriteColorTextNewLine(); } catch (Exception ex) { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
protected virtual int GetTypedValue(string valueName, ref StringBuilder consoleLog) { try { int value = 0, attemptCount = 0; string typedValue = string.Empty; string showMessage = string.Format("Enter {0} value (it must be integer and in range [{1};{2}]): -> ", valueName, MinTypingValue, MaxTypingValue); do { Console.Clear(); ConsoleIO.WriteColorTextNewLine(consoleLog); if (attemptCount > 0) { ConsoleIO.WriteColorTextNewLine("Invalid input data!", ConsoleColor.Red); ConsoleIO.WriteColorText("Attempt count: "); ConsoleIO.WriteColorTextNewLine(attemptCount.ToString(), ConsoleColor.Red); ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); } ConsoleIO.WriteColorText(showMessage); typedValue = Console.ReadLine(); attemptCount++; } while (!int.TryParse(typedValue, out value) || value < MinTypingValue || value > MaxTypingValue); consoleLog.AppendLine(showMessage + typedValue + "\n" + ConsoleIO.ConsoleRowSeparator); return(value); } catch (Exception ex) { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(0); }
protected virtual string GetTypedValue(ref StringBuilder consoleLog) { try { int attemptCount = 0; string typedValue = string.Empty; string showMessage = "Enter string for converting: -> "; do { Console.Clear(); ConsoleIO.WriteColorTextNewLine(consoleLog); if (attemptCount > 0) { ConsoleIO.WriteColorTextNewLine("Invalid input data!", ConsoleColor.Red); ConsoleIO.WriteColorText("Attempt count: "); ConsoleIO.WriteColorTextNewLine(attemptCount.ToString(), ConsoleColor.Red); ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); } ConsoleIO.WriteColorText(showMessage); typedValue = Console.ReadLine(); attemptCount++; } while (string.IsNullOrWhiteSpace(typedValue)); consoleLog.AppendLine(showMessage + typedValue + "\n" + ConsoleIO.ConsoleRowSeparator); return(typedValue); } catch (Exception ex) { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(string.Empty); }
/// <summary> /// Try to get a user input value (number) for calc the factorial /// </summary> /// <param name="consoleLog"></param> /// <returns></returns> protected virtual int GetTypedValue(ref StringBuilder consoleLog) { try { int value = 0, attemptCount = 0; string typedValue = string.Empty; string showMessage = string.Format("Enter a value to find the factorial (it must be integer and in range [{0};{1}]): -> ", _rulesProvider.MinTypingValue, _rulesProvider.MaxTypingValue); do { Console.Clear(); ConsoleIO.WriteColorTextNewLine(consoleLog); if (attemptCount > 0) { ConsoleIO.WriteColorTextNewLine("Invalid input data!", ConsoleColor.Red); ConsoleIO.WriteColorText("Attempt count: "); ConsoleIO.WriteColorTextNewLine(attemptCount.ToString(), ConsoleColor.Red); ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); } ConsoleIO.WriteColorText(showMessage); typedValue = Console.ReadLine(); attemptCount++; } while (!int.TryParse(typedValue, out value) || value < _rulesProvider.MinTypingValue || value > _rulesProvider.MaxTypingValue); consoleLog.AppendLine(showMessage + typedValue + "\n" + ConsoleIO.ConsoleRowSeparator); return(value); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(0); }
/// <summary> /// Method that is handled the event /// of 'Enter' button pressing /// </summary> public override void ClearBufferAndShowResult() { try { //check if there is a saved previous math operation in buffer //it's necessary when enter key was pressed a several times one by one //and the next math operation must be the same as a previous one if (!OpProvider.LastOperation.Equals(default(KeyValuePair <MathOperation, char>))) { //to store the result of math operation double result = 0.0; //get the user input string in calc screen string inputText = GetRow(RowInputData).ToString().TrimEnd(); //to store only user input data (numbers and decimal number separator) double alreadyInpNumber = default(double); //check if the parsing of user entered data (numbers and decimal number separator) is successfull if (Double.TryParse(inputText.Substring(inputText.LastIndexOf('_') + 1, inputText.LastIndexOf("|") - inputText.LastIndexOf('_') - 1), out alreadyInpNumber)) { //check if parsed data is not a double.NaN or double.Infinity if (!double.IsNaN(alreadyInpNumber) && !double.IsInfinity(alreadyInpNumber)) { //check if current math operation in not a Math.Pow if (OpProvider.LastOperation.Key != SimpleCalculator.MathOperation.Exponentiation) { string resultAsString = OpProvider.Result.ToString(); resultAsString += ((resultAsString.IndexOf(',') < 0 && resultAsString.IndexOf(',') < 0) ? ",0" : string.Empty); string alreadyInpNumberAsString = alreadyInpNumber.ToString(); alreadyInpNumberAsString += ((alreadyInpNumberAsString.IndexOf(',') < 0 && alreadyInpNumberAsString.IndexOf(',') < 0) ? ",0" : string.Empty); if (!OpProvider.LockResult) { result = Evaluate(string.Format("({0}{1}{2})", resultAsString, OpProvider.LastOperation.Value.ToString(), alreadyInpNumberAsString)); } else { result = Evaluate(string.Format("({0}{1}{2})", alreadyInpNumberAsString, OpProvider.LastOperation.Value.ToString(), resultAsString)); } } else //current math operation is a Math.Pow { //check if this is a first time when enter key has been pressed in current session if (!OpProvider.LockResult) { //if yes than get the specified number (in buffer) raised to the specified power (last entered value) result = Math.Pow(OpProvider.Result, alreadyInpNumber); } else { //if yes than get the specified number (that is being shown to user) raised to the specified power (value in buffer) result = Math.Pow(alreadyInpNumber, OpProvider.Result); } } } //clear OpProvider.BufferNumber.Clear(); //try to set a new value to the result variable in buffer //but if the OpProvider.LockResult == true //then a new value won't be setted to the result variable //-------------------------------- //it used for saving the last user entered number //on which current shown value will be (+, -, *, /, e) OpProvider.Result = alreadyInpNumber; //lock current result in buffer for changing OpProvider.LockResult = true; string buffer = "|" + new string(' ', EmptySpaceCalcUI.Length) + "|"; string resultOfOperation = string.Empty; if (UndelineSpaceCalcUI.Length >= result.ToString().Length) { resultOfOperation = "|" + new string('_', UndelineSpaceCalcUI.Length - result.ToString().Length) + result + "|"; } else { resultOfOperation = "|_" + result.ToString("#").Substring(0, UndelineSpaceCalcUI.Length - 1) + "|"; } //replace the row with the previous math operations in the buffer Draw(buffer, 0, RowBufferOperation); //replace the row with the current user input value in the buffer Draw(resultOfOperation, 0, RowInputData); //this flag will be showing that the last operation was the math operation (+, -, *, /) _wasAlreadyCalcOp = true; } } //clear console Console.Clear(); //print the buffer to the console screen. Print(); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
private static void ShowAndSolveTasks() { try { //to create and store the reference to object that represents all methods //with the manipulation of organization hardware (creation/modifying/inspection) IOrganization orgProvider = new Organization(); //resize the console window /* * Збільшувати розмір консолі, завчасно не дізнавшись який максимальний допустимий на комп'ютері користувача не бажано, * буде помилка (T:System.ArgumentOutOfRangeException). Наприклад, якщо в мене вже стоїть макс розмір консолі, * а в коді "Console.WindowWidth + 30" * його збільшують ще більше, такі нюанси зачасту прописані в описі до методу чи властивостей (Console.WindowHeight). */ ConsoleIO.ResizeConsoleWindow(100, 40); //to show the full status of organisation hardware ConsoleIO.WriteColorTextNewLine("Organization hardware status", ConsoleColor.Yellow); orgProvider.ShowFullStatusOfOrganization(); Console.ReadKey(true); ConsoleIO.WriteColorTextNewLine( "Task 1: Organization consist of 4 department. Every department has several computers of different types:", ConsoleColor.Cyan, "Task 1:", ConsoleColor.Red); //show the number of unique hardware types in each departments orgProvider.ShowNumberOfEachHardwareTypes(); Console.ReadKey(true); ConsoleIO.WriteColorTextNewLine( "Task 2: Count total number of all computers and every type", ConsoleColor.Cyan, "Task 2:", ConsoleColor.Red); //show the number of all computers in whole organization orgProvider.ShowNumberOfHardwareType <Computer>(); //show the number of Desktop computers in whole organization orgProvider.ShowNumberOfHardwareType <DesktopBuilder>(); //show the number of Laptop computers in whole organization orgProvider.ShowNumberOfHardwareType <LaptopBuilder>(); //show the number of Server computers in whole organization orgProvider.ShowNumberOfHardwareType <ServerBuilder>(); ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator + "\n"); Console.ReadKey(true); ConsoleIO.WriteColorTextNewLine( "Task 3: Find computer with the largest (HDD):", ConsoleColor.Cyan, "Task 3:", ConsoleColor.Red); orgProvider.ShowHardwareWithTheLargestParameterData <Computer>("HDD"); Console.ReadKey(true); ConsoleIO.WriteColorTextNewLine( "Task 4: Find computer with the lowest (RAM):", ConsoleColor.Cyan, "Task 4:", ConsoleColor.Red); orgProvider.ShowHardwareWithTheLowestParameterData <Computer>("RAM"); Console.ReadKey(true); ConsoleIO.WriteColorTextNewLine( "Task 5: Find computer with the largest number of cores (CPU):", ConsoleColor.Cyan, "Task 5:", ConsoleColor.Red); orgProvider.ShowHardwareWithTheLargestParameterData <Computer>("CPU"); Console.ReadKey(true); ConsoleIO.WriteColorTextNewLine( "Task 6: Make desktop upgrade: set RAM up to 8GB", ConsoleColor.Cyan, "Task 6:", ConsoleColor.Red); ConsoleIO.WriteColorTextNewLine("Organization new hardware status", ConsoleColor.Yellow); orgProvider.UpdateFieldValue <DesktopBuilder, string>("RAM", "8 GB"); orgProvider.ShowFullStatusOfOrganization(); Console.ReadKey(true); ConsoleIO.WriteColorTextNewLine( "Task 7: Make laptop upgrade: set HDD up to 1024 GB", ConsoleColor.Cyan, "Task 7:", ConsoleColor.Red); orgProvider.UpdateFieldValue <LaptopBuilder, string>("HDD", "1024 GB"); Console.ReadKey(true); //to show the full status of organisation hardware ConsoleIO.WriteColorTextNewLine("Organization new hardware status", ConsoleColor.Yellow); orgProvider.ShowFullStatusOfOrganization(); Console.ReadKey(true); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }
private static void ShowMainMenu() { try { //pause (in millisec) after user correct answer, before redirecting to selected operation ushort delay = 3000; //to store the user wrong answers count in main menu byte attemptCount = 0; //to store the number of MAX posible wrong answers in main menu byte maxAttemptCount = 0; //try parse unprotected value of MAX posible wrong answers in main menu from config/settings file if (!byte.TryParse(Security.SecurityHelper.ProtectConfigParameter(Properties.Settings.Default.MainMenu_MaxIncorectInputCount), out maxAttemptCount)) { maxAttemptCount = 5; //if the parsing was unsuccessful than set the default value } //to store the instance of a class/struct that is implementing an interface IOperationType IOperationType selectedOperation = default(IOperationType); //all user wrong answers StringBuilder attemptStr = new StringBuilder(); //to store user input key ConsoleKeyInfo keyInfo = default(ConsoleKeyInfo); //get menu description from setting file string mainMemu = Properties.Settings.Default.MainMenu; //to store default console window size (width and height) int consoleWindowWidth = Console.WindowWidth, consoleWindowHeight = Console.WindowHeight; do // while user wanna running the program (for default - always:) ) { //Resize console window size to default width and height ConsoleIO.ResizeConsoleWindow(consoleWindowWidth, consoleWindowHeight); attemptCount = 0; attemptStr.Clear(); //clear console do // while user is entering invalid data { if (attemptCount < 5) // check the number of incorrect user input in sequence { //clear console Console.Clear(); //show main menu ConsoleIO.WriteColorTextNewLine(string.Format(mainMemu, "\t", "\n", ConsoleIO.ConsoleRowSeparator)); if (attemptCount > 0) //check if invalid input data have been entered { //show the number of incorrect input data entering ConsoleIO.ShowIncorrectUserInputDataWarning(attemptCount); //show all wrong answers in sequence ConsoleIO.WriteColorTextNewLine(string.Format("Entered keys: {0}{1}{2}", attemptStr, "\n", ConsoleIO.ConsoleRowSeparator)); } else // if it's a first program running, show the row separator (for default '-----------') { ConsoleIO.WriteColorTextNewLine(ConsoleIO.ConsoleRowSeparator); } //read user input keyInfo = Console.ReadKey(true); if (keyInfo.Key == ConsoleKey.Q) //if user entered 'q' or 'Q' -> exit { return; } //get an instance of a class that is implementing an interface IOperationType (depends on user answer) selectedOperation = OperationFactory.GetSelectedOperation(keyInfo.Key); //add user incorrect answers (if it was) attemptStr.AppendFormat((attemptCount > 0 ? ", " : string.Empty) + "'{0}'", keyInfo.KeyChar); attemptCount++; } else //if number of user incorrect answers >= MAX { ConsoleIO.WriteColorTextNewLine("\nIt looks like that you don't know what are you doing or maybe you are an idiot!", ConsoleColor.Red); Console.ReadKey(); return; } } while (selectedOperation == default(IOperationType)); // while user is entering invalid data ConsoleIO.WriteColorTextNewLine(string.Format("\nNice choice! \nYou'll be redirected to the {0} after '{1}'sec", selectedOperation.ToString(), delay / 1000), ConsoleColor.Green); System.Threading.Thread.Sleep(delay); } while (selectedOperation.RunAndContinue()); } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } }