public void Run() { if (_sampleList.Count == 0) // if it's empty, abort run { throw new ArgumentException("There are no samples registered. Aborting..."); } // Switch to the alternate screen buffer. _consoleBuffer.Append(_formatter.SwitchAlternateScreenBuffer(true)); // Hide the cursor. _consoleBuffer.Append(_formatter.SetCursorVisibility(false)); try { // Create the initial sample menu CreateSampleMenu(_consoleBuffer); FlushConsoleBuffer(); ConsoleKeyInfo keyPressed; do { keyPressed = Console.ReadKey(true); var keyChar = keyPressed.KeyChar; var selectedSample = _sampleList.Where(x => x.Key == keyChar).Select(x => x.Value).SingleOrDefault(); if (selectedSample != null) { RunSample(selectedSample.Instance); // After the sample has run, press any key to continue. Console.ReadKey(true); // Clear the console and recreate the main menu. Console.Clear(); // Clear the sample data if it's an interactive sample. var writable = selectedSample as IWritableSample; if (writable != null) { writable.Clear(); } CreateSampleMenu(_consoleBuffer); FlushConsoleBuffer(); } } while (keyPressed.Key != ConsoleKey.Enter); } finally { _consoleBuffer.Append(_formatter.SwitchAlternateScreenBuffer(false)); _consoleBuffer.Append(_formatter.SetCursorVisibility(true)); _consoleBuffer.Append(_formatter.Format(0)); FlushConsoleBuffer(); } }
public static void RunConsole(TerminalFormatter formatter, WriteConsoleDelegate writeConsoleDelegate = null) { if (formatter == null) { throw new ArgumentNullException(nameof(formatter)); } if (writeConsoleDelegate == null) { writeConsoleDelegate = (str, newLine) => { if (newLine) { Console.Out.WriteLine(str); } else { Console.Out.Write(str); } }; } ConsoleUtils.TrySetConsoleTitle("Nibbles!"); // Add a \r to overwrite the title if the terminal doesn't support "ESC ] 0" var sb = new StringBuilder("\r"); const string heading = "N I B B L E S !"; sb.AppendLine(new string(' ', Math.Max(0, ConsoleUtils.ConsoleWidth / 2 - heading.Length / 2)) + heading); sb.AppendLine(); sb.AppendLine(" Game Controls:"); sb.AppendLine(); sb.AppendLine(" General Player"); sb.AppendLine(" (Up)"); sb.AppendLine(" P - Pause ↑"); sb.AppendLine(" Q - Quit (Left) ← → (Right)"); sb.AppendLine(" ↓"); sb.AppendLine(" (Down)"); sb.AppendLine(); sb.Append("Please enter your name: "); writeConsoleDelegate(sb.ToString(), false); string name = Console.ReadLine(); writeConsoleDelegate(); writeConsoleDelegate("Please enter the speed (1-10): ", false); try { int speed = int.Parse(Console.ReadLine()); Run(name, speed, formatter, writeConsoleDelegate); } catch (Exception ex) { writeConsoleDelegate(); writeConsoleDelegate(formatter.Format(TerminalFormatting.ForegroundRed, TerminalFormatting.BoldBright) + "ERROR:" + formatter.Format(TerminalFormatting.None) + " " + ConsoleUtils.FixDisplayCharacters(ex.Message)); } }