public static void ConsoleKeyValueCheck() { ConsoleKeyInfo info; info = new ConsoleKeyInfo('\0', (ConsoleKey)0, false, false, false); info = new ConsoleKeyInfo('\0', (ConsoleKey)255, false, false, false); Assert.Throws<ArgumentOutOfRangeException>(() => new ConsoleKeyInfo('\0', (ConsoleKey)256, false, false, false)); }
public void Ctor_DefaultCtor_PropertiesReturnDefaults() { ConsoleKeyInfo cki = new ConsoleKeyInfo(); Assert.Equal(default(ConsoleKey), cki.Key); Assert.Equal(default(char), cki.KeyChar); Assert.Equal(default(ConsoleModifiers), cki.Modifiers); }
static void Main() { FixConsoleScreen(); InicializeScreen(); while (exitFlag) { if (Console.KeyAvailable) { KeyPressed = Console.ReadKey(); if (KeyPressed.Key == ConsoleKey.Escape) { exitFlag = false; DrawGoodbuyScreen(); break; } else if (KeyPressed.Key == ConsoleKey.LeftArrow) { MoveDwardLeft(); } else if (KeyPressed.Key == ConsoleKey.RightArrow) { MoveDwarRight(); } } PopulateFirstLine(); CalculateScore(); RedrawScreen(); ClearKeyBuffer(); Thread.Sleep((int)levelTimeout); } }
public void NotEquals_DifferentData(ConsoleKeyInfo left, ConsoleKeyInfo right) { Assert.False(left == right); Assert.False(left.Equals(right)); Assert.False(left.Equals((object)right)); Assert.True(left != right); }
public void Ctor_ValueCtor_ValuesPassedToProperties(bool shift, bool alt, bool ctrl) { ConsoleKeyInfo cki = new ConsoleKeyInfo('a', ConsoleKey.A, shift, alt, ctrl); Assert.Equal(ConsoleKey.A, cki.Key); Assert.Equal('a', cki.KeyChar); Assert.Equal(shift, (cki.Modifiers & ConsoleModifiers.Shift) == ConsoleModifiers.Shift); Assert.Equal(alt, (cki.Modifiers & ConsoleModifiers.Alt) == ConsoleModifiers.Alt); Assert.Equal(ctrl, (cki.Modifiers & ConsoleModifiers.Control) == ConsoleModifiers.Control); }
public void Equals_SameData(ConsoleKeyInfo cki) { ConsoleKeyInfo other = cki; // otherwise compiler warns about comparing the instance with itself Assert.True(cki.Equals((object)other)); Assert.True(cki.Equals(other)); Assert.True(cki == other); Assert.False(cki != other); Assert.Equal(cki.GetHashCode(), other.GetHashCode()); }
public static void Main(string[] args) { ConsoleKeyInfo cki = new ConsoleKeyInfo(); do { while (Console.KeyAvailable == false) { MainLoop(args); Console.WriteLine("\nPress the 'x' key to quit."); Thread.Sleep(60000); } cki = Console.ReadKey(true); } while(cki.Key != ConsoleKey.X); //RL(); }
static void Main() { string fileContent = ""; string path = ""; ConsoleKeyInfo retry = new ConsoleKeyInfo(); while (true) { try { Console.Write("Enter path and file name: "); path = Console.ReadLine(); StreamReader reader = new StreamReader(path); try { fileContent = reader.ReadToEnd(); } finally { reader.Close(); } } catch (Exception exp) { Console.WriteLine("{0} Retry ? y = yes , n = no;", exp.Message); retry = Console.ReadKey(); Console.WriteLine(); if (retry.Key == ConsoleKey.N) { break; } else { continue; } } Console.WriteLine(fileContent); Console.Write("Exit y = yes, n = no"); retry = Console.ReadKey(); Console.WriteLine(); if (retry.Key == ConsoleKey.Y) { break; } else { continue; } } }
private static MoveDirection GetMoveDir(ConsoleKeyInfo key) { switch (key.Key) { case ConsoleKey.Q: return MoveDirection.UpLeft; case ConsoleKey.W: return MoveDirection.UpRight; case ConsoleKey.A: return MoveDirection.DownLeft; case ConsoleKey.S: return MoveDirection.DownRight; default: throw new ArgumentException(); } }
static void TitleScreen() { Console.Clear(); title: Console.WriteLine("KILLALL\n\n"); Console.WriteLine("Launch Game - Press A"); Console.WriteLine("Instructions - Press S"); Console.WriteLine("Credits - Press D"); if(File.Exists(@"save.txt")) { Console.WriteLine("\nDelete Save- Press F"); } string inputString = "ssss"; ConsoleKeyInfo input = new ConsoleKeyInfo(); input = Console.ReadKey(true); inputString = input.Key.ToString(); inputString = inputString.ToLower(); if(File.Exists(@"save.txt") && inputString == "f") { Console.Clear(); DeleteSave(); } else if(inputString == "s") { Console.Clear(); Instructions(); } else if(inputString == "d") { Console.Clear(); Credits(); } else if(inputString == "a") { Console.Clear(); } else { Console.Clear(); goto title; } }
static void ReadKeyStartPage() { ConsoleKeyInfo pressed = new ConsoleKeyInfo(); bool isValid = false; while (!isValid) { pressed = Console.ReadKey(true); if (pressed.Key == ConsoleKey.S) { isValid = true; StartNewGame(); } else if (pressed.Key == ConsoleKey.V) { isValid = true; ViewHighscores(); } else if (pressed.Key == ConsoleKey.H) { isValid = true; HelpPage(); } else if (pressed.Key == ConsoleKey.Q) { isValid = true; Exit(); } else { string msg = ("Invalid key, please, try again!"); Console.SetCursorPosition(20, 25); Console.WriteLine(msg); Console.SetCursorPosition(20, 25); } } return; }
static void ChangePlayerDirection(ConsoleKeyInfo key) { if (key.Key == ConsoleKey.W && firstPlayerDirection != down) { firstPlayerDirection = up; } if (key.Key == ConsoleKey.A && firstPlayerDirection != right) { firstPlayerDirection = left; } if (key.Key == ConsoleKey.D && firstPlayerDirection != left) { firstPlayerDirection = right; } if (key.Key == ConsoleKey.S && firstPlayerDirection != up) { firstPlayerDirection = down; } if (key.Key == ConsoleKey.UpArrow && secondPlayerDirection != down) { secondPlayerDirection = up; } if (key.Key == ConsoleKey.LeftArrow && secondPlayerDirection != right) { secondPlayerDirection = left; } if (key.Key == ConsoleKey.RightArrow && secondPlayerDirection != left) { secondPlayerDirection = right; } if (key.Key == ConsoleKey.DownArrow && secondPlayerDirection != up) { secondPlayerDirection = down; } }
internal static void Main() { // The exit code of the sample application. int exitCode = 0; try { // Create a camera object that selects the first camera device found. // More constructors are available for selecting a specific camera device. // For multicast only look for GigE cameras here. using (Camera camera = new Camera(DeviceType.GigE, CameraSelectionStrategy.FirstFound)) { // Print the model name of the camera. Console.WriteLine("Using camera {0}.", camera.CameraInfo[CameraInfoKey.ModelName]); String deviceType = camera.CameraInfo[CameraInfoKey.DeviceType]; Console.WriteLine("=========="); System.Collections.Generic.List <ICameraInfo> allCameraInfos = CameraFinder.Enumerate(); foreach (ICameraInfo cameraInfo in allCameraInfos) { Console.WriteLine("{0}", cameraInfo[CameraInfoKey.DeviceType]); } Console.WriteLine("{0} Camera", deviceType); Console.WriteLine("=========="); camera.StreamGrabber.ImageGrabbed += OnImageGrabbed; camera.StreamGrabber.ImageGrabbed += OnImageSkipped; // Get the Key from the user for selecting the mode Console.Write("Start multicast sample in (c)ontrol or in (m)onitor mode? (c/m) "); ConsoleKeyInfo keyPressed = Console.ReadKey(); switch (keyPressed.KeyChar) { // The default configuration must be removed when monitor mode is selected // because the monitoring application is not allowed to modify any parameter settings. case 'm': case 'M': // Monitor mode selected. Console.WriteLine("\nIn Monitor mode"); // Set MonitorModeActive to true to act as monitor camera.Parameters [PLCameraInstance.MonitorModeActive].SetValue(true); // Set monitor mode // Open the camera. camera.Open(); // Select transmission type. If the camera is already controlled by another application // and configured for multicast, the active camera configuration can be used // (IP Address and Port will be set automatically). camera.Parameters[PLGigEStream.TransmissionType].TrySetValue(PLGigEStream.TransmissionType.UseCameraConfig); // Alternatively, the stream grabber could be explicitly set to "multicast"... // In this case, the IP Address and the IP port must also be set. // //camera.Parameters[PLGigEStream.TransmissionType].SetValue(PLGigEStream.TransmissionType.Multicast); //camera.Parameters[PLGigEStream.DestinationAddr].SetValue("239.0.0.1"); //camera.Parameters[PLGigEStream.DestinationPort].SetValue(49152); if ((camera.Parameters[PLGigEStream.DestinationAddr].GetValue() != "0.0.0.0") && (camera.Parameters[PLGigEStream.DestinationPort].GetValue() != 0)) { camera.StreamGrabber.Start(countOfImagesToGrab); } else { throw new Exception("Failed to open stream grabber (monitor mode): The acquisition is not yet started by the controlling application. Start the controlling application before starting the monitor application."); } break; case 'c': case 'C': // Controlling mode selected. Console.WriteLine("\nIn Control mode"); // Open the camera. camera.Open(); // Set transmission type to "multicast"... // In this case, the IP Address and the IP port must also be set. camera.Parameters[PLGigEStream.TransmissionType].SetValue(PLGigEStream.TransmissionType.Multicast); //camera.Parameters[PLGigEStream.DestinationAddr].SetValue("239.0.0.1"); //camera.Parameters[PLGigEStream.DestinationPort].SetValue(49152); // Maximize the image area of interest (Image AOI). camera.Parameters[PLGigECamera.OffsetX].TrySetValue(camera.Parameters[PLGigECamera.OffsetX].GetMinimum()); camera.Parameters[PLGigECamera.OffsetY].TrySetValue(camera.Parameters[PLGigECamera.OffsetY].GetMinimum()); camera.Parameters[PLGigECamera.Width].SetValue(camera.Parameters[PLGigECamera.Width].GetMaximum()); camera.Parameters[PLGigECamera.Height].SetValue(camera.Parameters[PLGigECamera.Height].GetMaximum()); // Set the pixel data format. camera.Parameters[PLGigECamera.PixelFormat].SetValue(PLGigECamera.PixelFormat.Mono8); camera.StreamGrabber.Start(); break; default: throw new NotSupportedException("Invalid mode selected."); } IGrabResult grabResult; // Camera.StopGrabbing() is called automatically by the RetrieveResult() method // when countOfImagesToGrab images have been retrieved in monitor mode // or when a key is pressed and the camera object is destroyed. Console.WriteLine("Press any key to quit FrameGrabber..."); while (!Console.KeyAvailable && camera.StreamGrabber.IsGrabbing) { grabResult = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException); using (grabResult) { // Image grabbed successfully? if (grabResult.GrabSucceeded) { // Display the image ImageWindow.DisplayImage(1, grabResult); // The grab result could now be processed here. } else { Console.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription); } } } camera.Close(); } } catch (Exception e) { // Error handling Console.Error.WriteLine("\nException: {0}", e.Message); exitCode = 1; } finally { // Comment the following two lines to disable waiting on exit. Console.Error.WriteLine("\nPress enter to exit."); Console.ReadLine(); } Environment.Exit(exitCode); }
// Manage all key pressed private static void ProcessKeyAction(ConsoleKeyInfo key) { for (int i = 0; i < objectList.Count; i++) { // For all objects GameObject obj = objectList[i]; // Move DWARF if (obj.type == "DWARF") { if (key.Key == ConsoleKey.LeftArrow && obj.posX > 0) { obj.posX--; isFieldChanged = true; } if (key.Key == ConsoleKey.RightArrow && obj.posX + obj.SizeOfLabel < fieldMaxX) { obj.posX++; isFieldChanged = true; } if (key.Key == ConsoleKey.UpArrow && obj.posY > 0) { obj.posY--; isFieldChanged = true; } if (key.Key == ConsoleKey.DownArrow && obj.posY < fieldMaxY - 3) { obj.posY++; isFieldChanged = true; } } // For all objects if (key.Key == ConsoleKey.Escape) // Press "ESC" to exit the game { Environment.Exit(0); } if (key.Key == ConsoleKey.Spacebar) // Press "Space" for new game if game is over { objectList = new List<GameObject>(); playerLives = 5; score = 0; InitializeGame(); } objectList[i] = obj; } }
static string ChooseName() { string name; ConsoleKeyInfo input = new ConsoleKeyInfo(); string inputString; selectname: Console.Clear(); Console.WriteLine("I need to know your name."); Console.Write("My name is: "); name = Console.ReadLine(); confirmname: Console.Clear(); Console.WriteLine("Your name is {0}?\n", name); Console.WriteLine("My name is {0} - Press Y\nMy name isn't {0} - Press N", name); input = Console.ReadKey(true); inputString = input.Key.ToString(); inputString = inputString.ToLower(); if(inputString == "y") { Console.Clear(); Console.WriteLine("Hello, {0}!", name); Console.ReadKey(true); } else if (inputString == "n") { Console.Clear(); WriteRed("Then what is your name?"); Console.ReadKey(true); goto selectname; } else { Console.Clear(); WriteRed("Please input the correct key.\n"); Console.ReadKey(true); goto confirmname; } Console.Clear(); return name; }
private void Insert(ConsoleKeyInfo key) { char c; if (key.Key == ConsoleKey.F6) { Debug.Assert(FinalLineText.Length == 1); c = FinalLineText[0]; } else { c = key.KeyChar; } Insert(c); }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Please specify a file after the command like water.exe 'default 2015.greet'"); return; } if (new FileInfo(args[0]).Exists == false) { Console.WriteLine("The specified file does not exists"); return; } int search = -1; int replaceWith = -1; while (search == -1) { Console.WriteLine("Specify resource ID to look for:"); string line = Console.ReadLine(); if (int.TryParse(line, out search)) { break; } } while (replaceWith == -1) { Console.WriteLine("Specify resource ID to replace with:"); string line = Console.ReadLine(); if (int.TryParse(line, out replaceWith)) { break; } } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(args[0]); bool doItAll = false; foreach (XmlNode node in xmlDoc.SelectNodes("greet/data/processes/stationary")) { string processName = node.Attributes["name"].Value; List <XmlNode> inputNodes = new List <XmlNode>(); foreach (XmlNode input in node.SelectNodes("input")) { inputNodes.Add(input); } foreach (XmlNode input in node.SelectNodes("group/shares/input")) { inputNodes.Add(input); } bool isContainingSearch = false; foreach (XmlNode n in inputNodes) { isContainingSearch |= n.Attributes["ref"].Value.Equals(search.ToString()); } if (isContainingSearch) { Console.Write("Process named: "); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write(processName); char answer = 'n'; if (!doItAll) { Console.ResetColor(); Console.WriteLine(", has input(s) with reference " + search.ToString() + " replace? (y/n/a)"); ConsoleKeyInfo key = Console.ReadKey(); answer = key.KeyChar; if (answer == 'a') { doItAll = true; answer = 'y'; } } else { Console.WriteLine(); Console.ResetColor(); answer = 'y'; } if (answer == 'y') { foreach (XmlNode n in inputNodes) { if (n.Attributes["ref"].Value == search.ToString()) { n.Attributes["ref"].Value = replaceWith.ToString(); } } xmlDoc.Save(args[0]); } } } Console.ResetColor(); }
public bool Equals (ConsoleKeyInfo obj) { return key == obj.key && obj.keychar == keychar && obj.modifiers == modifiers; }
static void Main(string[] args) { Player player = new Player(); Window window = new Window(60, 50); Menu menu = new Menu(player); Admin admin = new Admin(); World world = new World(); Platform platform = new Platform(); Game game = new Game(); UI ui = new UI(); Blocks actualBlock = game.RandomBlock(); while (true) { if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(); menu.Start(key.Key, world, ui); //admin.ConsolePos(key.Key); //admin.ConsoleChangePos(key.Key , Console.CursorLeft , Console.CursorTop); if (menu.IfStarted() && !game.IfLose(platform)) { if (actualBlock.moveable && actualBlock.created) { actualBlock.Move(actualBlock.squares, key.Key, world, platform, player); } } if (game.IfLose(platform)) { game.PlayAgain(key.Key, world, platform, player); } } //admin.ConsolePosShow(Console.CursorLeft , Console.CursorTop); if (menu.IfStarted() && !game.IfLose(platform)) { player.ChangePlayerLevel(); ui.ShowPlayerStatus(player); platform.FullPlatform(player); if (!actualBlock.created) { actualBlock.Create(); } } if (menu.IfStarted() && actualBlock.moveable && actualBlock.created && !game.IfLose(platform)) { if (actualBlock.gravityTime == 3) { actualBlock.Gravity(actualBlock.squares, world, platform); } } if (!actualBlock.moveable && !game.IfLose(platform)) { actualBlock = game.RandomBlock(); } if (game.IfLose(platform)) { game.Lose(player); } actualBlock.AddGravityTime(); Thread.Sleep(150 / player.speed); } }
static void Main(string[] args) { string filePathFromArgs = checkArgs(args); if (!checkIfFileExists(filePathFromArgs)) { errorClose("Die angegebene Textdatei existiert nicht!"); } buildUpData(filePathFromArgs); printCurrentPage(); while (continueFlag) { ConsoleKeyInfo info = Console.ReadKey(); switch (info.Key) { case ConsoleKey.D7: if (info.KeyChar == '/') { searchInput = Console.ReadLine(); searchBook(searchInput); if (hitCount > 0) { printWithSearchHighLight(); } else { printCurrentPageWithError("Keine Suchtreffer!"); } } else { printCurrentPageWithError("Unbekannter Befehl!"); } break; case ConsoleKey.N: if (String.IsNullOrEmpty(searchInput)) { printCurrentPageWithError("Keine Suche ausgeführt!"); } else { currentSearchResult++; printWithSearchHighLight(); } break; case ConsoleKey.G: string jumpInput = Console.ReadLine(); jumpToPage(jumpInput); break; case ConsoleKey.B: LastPage(); break; case ConsoleKey.Spacebar: NextPage(); break; case ConsoleKey.Q: Close(); break; default: printCurrentPageWithError("Unbekannter Befehl!"); break; } } }
public static void CheckGameOver() { if (Game.snake.CollisionWithItself() || Game.snake.CollisionWithWall()) { Over = true; string path = @"C:\snake game\usernames\" + Game.snake.username + "\\gamestats"; if (Directory.Exists(path)) { Directory.Delete(path, true); } bool highscrbeated = false; if (Game.snake.score > Game.snake.highscore) { highscrbeated = true; } string path2 = @"C:\snake game\usernames\" + Game.snake.username + "\\highscores.txt"; FileStream fs = new FileStream(path2, FileMode.OpenOrCreate); fs.Close(); StreamReader sr = new StreamReader(path2); List <int> scores = new List <int>(); string line; bool found = false; while (true) { line = sr.ReadLine(); if (line == null) { if (!found) { scores.Add(Game.snake.score); } break; } int score = int.Parse(line.Remove(0, 4)); if (Game.snake.score >= score && !found) { scores.Add(Game.snake.score); if (score != Game.snake.score) { scores.Add(score); } found = true; } else { scores.Add(score); } } sr.Close(); StreamWriter sw = new StreamWriter(path2); for (int i = 0; i < scores.Count; i++) { if (i < 10) { sw.WriteLine(i + 1 + ")" + (i + 1 == 10 ? " " : " ") + scores[i]); } else { break; } } sw.Close(); Console.Clear(); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("GAME OVER!"); Thread.Sleep(500); Console.Write("Score: "); Thread.Sleep(500); Console.Write(Game.snake.score); if (highscrbeated) { Thread.Sleep(500); Console.Write(" NEW HIGHSCORE!"); } Thread.Sleep(500); Console.WriteLine(); Console.WriteLine("Highscore: " + Game.snake.highscore); Console.WriteLine("Do you want to retry?"); int option = 1; bool chosen = false; ConsoleColor selected = ConsoleColor.White; ConsoleColor unselected = ConsoleColor.Black; while (true) { Console.SetCursorPosition(0, 4); Console.BackgroundColor = option == 1 ? selected : unselected; Console.WriteLine("Exit"); Console.BackgroundColor = option == 2 ? selected : unselected; Console.WriteLine("Retry"); ConsoleKeyInfo key = Console.ReadKey(true); switch (key.Key) { case ConsoleKey.UpArrow: if (option != 1) { option--; } break; case ConsoleKey.DownArrow: if (option != 2) { option++; } break; case ConsoleKey.Enter: chosen = true; break; } if (!chosen) { Console.SetCursorPosition(0, 4); Console.WriteLine(" "); Console.Write(" "); } else { if (option == 1) { exit = true; } else { Console.BackgroundColor = ConsoleColor.Black; } break; } } if (!exit) { Console.Clear(); Program.Main(null); } } }
/// <summary> /// 入力情報更新 /// </summary> public void Update() { ConsoleKeyInfo c = Console.ReadKey(); int[] nowKey = new int[3]; nowKey[0] = 0; nowKey[1] = 0; nowKey[2] = 0; //入力を読み込む。ここに処理を書く============ if (c.Key == ConsoleKey.LeftArrow) { nowKey[0] = 1; } if (c.Key == ConsoleKey.DownArrow) { nowKey[1] = 1; } if (c.Key == ConsoleKey.RightArrow) { nowKey[2] = 1; } //============================================ if ((nowKey[0] + nowKey[1] + nowKey[2]) == 0) { //何も押されていない場合は前回値をそのままキープ } else if ((nowKey[0] + nowKey[1] + nowKey[2]) == 1) { //1つしか押されていないのでそれを渡す if (nowKey[0] == 1) { lastKeyIndex = 0; } if (nowKey[1] == 1) { lastKeyIndex = 1; } if (nowKey[2] == 1) { lastKeyIndex = 2; } } else { //複数押された場合はエッジ検出 int[] trigKey = new int[3];//今回エッジ検出したキー int trigsum = 0; for (int i = 0; i < 3; i++) { trigKey[i] = 0; if (nowKey[i] == 1 && nowKey[i] != preKey[i]) { trigsum++; trigKey[i] = 1; } } if (trigsum == 1) { if (trigKey[0] == 1) { lastKeyIndex = 0; } if (trigKey[1] == 1) { lastKeyIndex = 1; } if (trigKey[2] == 1) { lastKeyIndex = 2; } } else { //複数完全同時に押された場合は真ん中で lastKeyIndex = 1; } } inputFader.SetFaderValue(faderValue[lastKeyIndex]); preKey[0] = nowKey[0]; preKey[1] = nowKey[1]; preKey[2] = nowKey[2]; }
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo) { console.CursorPosition = console.CurrentLine.Length; }
/// <summary> /// This is not implemented because this assist provider always takes over the console during the draw menu. /// </summary> /// <param name="parentReaderContext">not implemented</param> /// <param name="keyPress">not implemented</param> /// <returns>not implemented</returns> public virtual ContextAssistResult OnKeyboardInput(RichCommandLineContext parentReaderContext, ConsoleKeyInfo keyPress) { throw new NotImplementedException(); }
public void Start() { Console.ForegroundColor = unselectedColor; Console.SetCursorPosition(0, 0); ConsoleKeyInfo button = new ConsoleKeyInfo(); bool quit = false; while (!quit) { Draw(); button = Console.ReadKey(true); switch (button.Key) { case ConsoleKey.UpArrow: { selectedItem--; if (selectedItem < 0) { selectedItem = ItemsCount - 1; } break; } case ConsoleKey.DownArrow: { selectedItem++; if (selectedItem >= ItemsCount) { selectedItem = 0; } break; } case ConsoleKey.Enter: { switch (selectedItem) { case 0: case 1: case 2: { if (Product.Money >= itemsPrice[selectedItem]) { Product.Show(items[selectedItem]); Product.Money -= itemsPrice[selectedItem]; Product.Basket++; } else { Product.CannotBuy(); } break; } case 3: { quit = true; Console.Clear(); break; } } break; } default: break; } } }
private void ProcessKeyInfo(ConsoleKeyInfo keyInfo, Action <string, CancellationToken> dispatchCommand) { int activeLineLen = m_activeLine.Length; switch (keyInfo.Key) { case ConsoleKey.Backspace: // The BACKSPACE key. if (m_cursorPosition > 0) { EnsureNewEntry(); m_activeLine.Remove(m_cursorPosition - 1, 1); m_cursorPosition--; RefreshLine(); } break; case ConsoleKey.Insert: // The INS (INSERT) key. m_insertMode = !m_insertMode; RefreshLine(); break; case ConsoleKey.Delete: // The DEL (DELETE) key. if (m_cursorPosition < activeLineLen) { EnsureNewEntry(); m_activeLine.Remove(m_cursorPosition, 1); RefreshLine(); } break; case ConsoleKey.Enter: // The ENTER key. string newCommand = m_activeLine.ToString(); if (m_modified) { m_history.Add(m_activeLine); } m_selectedHistory = m_history.Count; Dispatch(newCommand, dispatchCommand); SwitchToHistoryEntry(); break; case ConsoleKey.Escape: // The ESC (ESCAPE) key. EnsureNewEntry(); m_activeLine.Clear(); m_cursorPosition = 0; RefreshLine(); break; case ConsoleKey.End: // The END key. m_cursorPosition = activeLineLen; RefreshLine(); break; case ConsoleKey.Home: // The HOME key. m_cursorPosition = 0; RefreshLine(); break; case ConsoleKey.LeftArrow: // The LEFT ARROW key. if (keyInfo.Modifiers == ConsoleModifiers.Control) { while (m_cursorPosition > 0 && char.IsWhiteSpace(m_activeLine[m_cursorPosition - 1])) { m_cursorPosition--; } while (m_cursorPosition > 0 && !char.IsWhiteSpace(m_activeLine[m_cursorPosition - 1])) { m_cursorPosition--; } } else { m_cursorPosition--; } RefreshLine(); break; case ConsoleKey.UpArrow: // The UP ARROW key. if (m_selectedHistory > 0) { m_selectedHistory--; } SwitchToHistoryEntry(); break; case ConsoleKey.RightArrow: // The RIGHT ARROW key. if (keyInfo.Modifiers == ConsoleModifiers.Control) { while (m_cursorPosition < activeLineLen && !char.IsWhiteSpace(m_activeLine[m_cursorPosition])) { m_cursorPosition++; } while (m_cursorPosition < activeLineLen && char.IsWhiteSpace(m_activeLine[m_cursorPosition])) { m_cursorPosition++; } } else { m_cursorPosition++; } RefreshLine(); break; case ConsoleKey.DownArrow: // The DOWN ARROW key. if (m_selectedHistory < m_history.Count) { m_selectedHistory++; } SwitchToHistoryEntry(); RefreshLine(); break; default: if (keyInfo.KeyChar != 0) { if ((keyInfo.Modifiers & (ConsoleModifiers.Control | ConsoleModifiers.Alt)) == 0) { AppendNewText(new string(keyInfo.KeyChar, 1)); } } break; } }
public static void Move(ConsoleKeyInfo? info, char[] lastLine, ref int curPos) { if (info != null) { switch (info.Value.Key) { case ConsoleKey.LeftArrow: if (curPos - 2 >= 0) { lastLine[curPos - 1] = ' '; lastLine[curPos] = ' '; if (curPos + 1 < field.GetLength(1)) lastLine[curPos + 1] = ' '; lastLine[curPos - 2] = '('; lastLine[curPos - 1] = '0'; lastLine[curPos] = ')'; curPos--; } break; case ConsoleKey.RightArrow: if (curPos + 2 < lastLine.Length) { if (curPos - 1 >= 0) lastLine[curPos - 1] = ' '; if (curPos - 2 >= 0) lastLine[curPos - 2] = ' '; lastLine[curPos] = ' '; lastLine[curPos] = '('; lastLine[curPos + 1] = '0'; lastLine[curPos + 2] = ')'; curPos++; } break; default: break; } } }
static void Main(string[] args) { Console.CursorVisible = false; int[,] maze = new int[, ] //Паттерн лабиринта { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1 }, { 1, 0, 1, 2, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1 }, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 }, { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1 }, { 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1 }, { 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1 }, { 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1 }, { 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1 }, { 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 }, { 1, 0, 1, 1, 1, 2, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 }, { 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1 }, { 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1 }, { 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1 }, { 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1 }, { 1, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1 }, { 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1 }, { 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 0, 0, 2, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 2, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1 }, { 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1 }, { 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 }, { 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } }; int x = 1, y = 1; //Х и У - координаты Игрока int i = 0; int j = 0; Console.WriteLine("Играя со своими братьями и сестрами, вы потерялись в саду. Уже темнеет, и вам лучше побыстрее найти выход из лабиринта." + "\nМама наругает, если мы опоздаем к ужину."); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("\nВ любой момент времени, вы можете позвать на помощь взрослых, нажав на клавишу Esc"); Console.WriteLine("\nНажмите любую клавишу."); Console.ReadKey(); Again: x = 1; y = 1; try { while (true) //Прорисовка Лабиринта путем бесконечного цикла { Console.Clear(); for (i = 0; i < maze.GetLength(0); i++) { for (j = 0; j < maze.GetLength(1); j++) { if (maze[i, j] == 0) { Console.Write("*"); } if (maze[i, j] == 1) { Console.Write("▒"); } if (maze[i, j] == 2) { Console.Write("۩"); } } Console.WriteLine(); } Console.Write("\n Найди выход!"); Console.CursorLeft = x; Console.CursorTop = y; Console.ForegroundColor = ConsoleColor.White; Console.Write("☻"); Console.ForegroundColor = ConsoleColor.Gray; Console.BackgroundColor = ConsoleColor.Black; ConsoleKeyInfo ki = Console.ReadKey(); // Обработка управления с клавиатуры if (ki.Key == ConsoleKey.Escape) { Console.Clear(); Console.WriteLine(" Вы громко крикнули, и на поиски вас отправились взрослые" + "\nМама не оценила вашу глупость и запретила играть в саду!"); Console.ReadKey(); break; } if (ki.Key == ConsoleKey.LeftArrow && maze[y, x - 1] == 0) { x--; } if (ki.Key == ConsoleKey.RightArrow && maze[y, x + 1] == 0) { x++; } if (ki.Key == ConsoleKey.UpArrow && maze[y - 1, x] == 0) { y--; } if (ki.Key == ConsoleKey.DownArrow && maze[y + 1, x] == 0) { y++; } if (ki.Key == ConsoleKey.LeftArrow && maze[y, x - 1] == 2) { goto Dead; } if (ki.Key == ConsoleKey.RightArrow && maze[y, x + 1] == 2) { goto Dead; } ; if (ki.Key == ConsoleKey.UpArrow && maze[y - 1, x] == 2) { goto Dead; } ; if (ki.Key == ConsoleKey.DownArrow && maze[y + 1, x] == 2) { goto Dead; } ; } } catch (System.IndexOutOfRangeException e) { Console.Clear(); Console.WriteLine("Поздравляю! Вы пришли домой к ужину!"); Console.ReadKey(); Environment.Exit(0); } Dead: Console.Clear(); Console.WriteLine("В спешке вы споткнулись о корень, торчащий из земли."); Console.ReadKey(); Console.WriteLine("\nС размаху вы упали в куст шимповника, и очень громко закричали от боли и испуга."); Console.WriteLine("\nВам грустно, больно и страшно, к тому же становится совсем темно..."); Console.ReadKey(); Console.WriteLine("\nПродолжая беспорядочное движение вперед, вы натыкаетесь на маму. Она обнимает вас и отводит домой."); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.ReadKey(); Console.Clear(); Console.WriteLine("\nИгра окончена. Нажмите любую клавишу для повтора попытки."); Console.ReadKey(); goto Again; }
static void MovePlayer(ConsoleKeyInfo keyInfo) { if (keyInfo.Key == ConsoleKey.LeftArrow && playerPositionX > 0) playerPositionX--; if (keyInfo.Key == ConsoleKey.RightArrow && playerPositionX + player.Length - 1 < Console.WindowWidth - 1) playerPositionX++; if (keyInfo.Key == ConsoleKey.UpArrow && playerPositionY > 0) playerPositionY--; if (keyInfo.Key == ConsoleKey.DownArrow && playerPositionY < Console.WindowHeight - 1) playerPositionY++; }
static void Main() { ConsoleKeyInfo cki; do { Console.Clear(); Menu(); cki = Console.ReadKey(true); switch (cki.KeyChar.ToString()) { case "1": bool notInMenu1 = true; while (notInMenu1) { Console.Clear(); Console.WriteLine(firstTask); Console.WriteLine("Please enter a number to reverse it:"); decimal numberToReverse = decimal.Parse(Console.ReadLine()); while (numberToReverse < 0) { Console.WriteLine("The number should not be negative!"); Console.WriteLine("Please eneter another positive number:"); numberToReverse = decimal.Parse(Console.ReadLine()); } Console.WriteLine(ReverseDecimal(numberToReverse)); Console.WriteLine("Press ecape to exit to menu or press enter to reverse another decimal:"); ConsoleKeyInfo cki1 = new ConsoleKeyInfo(); cki1 = Console.ReadKey(true); if (cki1.Key== ConsoleKey.Escape) { notInMenu1 = false; } } break; case "2": bool notInMenu2 = true; while (notInMenu2) { Console.Clear(); Console.WriteLine(secondTask); Console.WriteLine("Please enter a sequence of integers separated by comma:"); string sequence = Console.ReadLine(); while (Average(sequence)==0) { Console.WriteLine("The sequnece is empty!"); Console.WriteLine("Please eneter another sequnece:"); sequence = Console.ReadLine(); } Console.WriteLine("The average of you sequence is:" + Average(sequence)); Console.WriteLine("Press ecape to exit to menu or press enter to calculate the average of another sequence:"); ConsoleKeyInfo cki1 = new ConsoleKeyInfo(); cki1 = Console.ReadKey(true); if (cki1.Key == ConsoleKey.Escape) { notInMenu2 = false; } } break; case "3": bool notInMenu3 = true; while (notInMenu3) { Console.Clear(); Console.WriteLine(thirdTask); Console.WriteLine("Please enter a:"); double a = double.Parse(Console.ReadLine()); Console.WriteLine("Please enter b:"); double b = double.Parse(Console.ReadLine()); while (a == 0) { Console.WriteLine("a should not be zero:"); Console.WriteLine("Please eneter another value for a:"); a = double.Parse(Console.ReadLine()); } Console.WriteLine("The value of x in your linear euqation => {0} * x + {1} = 0 is: x={2}",a,b,SolveLinearEquation(a,b)); Console.WriteLine("Press ecape to exit to menu or press enter to calculate another linear equation:"); ConsoleKeyInfo cki1 = new ConsoleKeyInfo(); cki1 = Console.ReadKey(true); if (cki1.Key == ConsoleKey.Escape) { notInMenu3 = false; } } break; } } while (cki.Key != ConsoleKey.Escape); }
private TaskCompletionSource<ConsoleKeyInfo> defr;// Task<ConsoleKeyInfo> cki = null; private async void processKey(Element elem, jQueryEvent ev) { int m = 0; if (ev.AltKey) m = m | ConsoleModifiers.Alt; if (ev.CtrlKey) m = m | ConsoleModifiers.Control; if (ev.ShiftKey) m = m | ConsoleModifiers.Shift; if (m != 0) kc = new ConsoleKeyInfo(ev.Which, m); else kc = new ConsoleKeyInfo(ev.Which); /*if (!Intercept && KeyAvailable) { // SetCursorPosition(CursorLeft - 1, CursorTop); Write(kc.KeyChar); }*/ jQuery.Select("#key").ReplaceWith("<div id=\"key\"><p>Key Down, Key is " + kc.Key + ", Char is " + kc.KeyChar.ToString() + "</p></div>"); //cki = Task<ConsoleKeyInfo>.FromResult(kc); KeyAvailable = false; //jQuery.Select("#main").Off("keyup", "canvas", processKey); //defr = new TaskCompletionSource<ConsoleKeyInfo>(); defr.TrySetResult(kc); await Task.Delay(10); }
public static void Main() { ConsoleKeyInfo cki = new ConsoleKeyInfo(); List<string> asdasd = new List<string>(); do { Console.WriteLine("\nPress a key to display; press the 'x' key to quit."); // Your code could perform some useful task in the following loop. However, // for the sake of this example we'll merely pause for a quarter second. Thread.Sleep(250); // Loop until input is entered. if (Console.KeyAvailable == true) { cki = Console.ReadKey(true); Console.WriteLine("You pressed the '{0}' key.", cki.Key); } } while (cki.Key != ConsoleKey.X); //for (int i = 0; i < 20; i++) //{ // for (int j = 0; j < 60; j++) // { // Console.CursorLeft = j; // Console.CursorTop = i; // Console.Write("x"); // } //} //Console.ReadLine(); //Main(); //ConsoleKeyInfo cki; //// Prevent example from ending if CTL+C is pressed. //Console.TreatControlCAsInput = true; //Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key."); //Console.WriteLine("Press the Escape (Esc) key to quit: \n"); //do //{ // cki = Console.ReadKey(); // Console.Write(" --- You pressed "); // if ((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+"); // if ((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+"); // if ((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+"); // Console.WriteLine(cki.Key.ToString()); //} while (cki.Key != ConsoleKey.Escape); //int[,] maas = new int[10, 20]; //int zzz = 0; //for (int a = 0; a < maas.GetLength(0); a++) //{ // for (int b = 0; b < maas.GetLength(1); b++) // { // maas[a, b] = zzz++; // } //} //for (int a = 0; a < maas.GetLength(0); a++) //{ // for (int b = 0; b < maas.GetLength(1); b++) // { // Console.Write(maas[a, b] + " "); // } // Console.WriteLine(); //} }
public static void Main(string[] args) { Console.WriteLine("Здраствуйете, Ваше имя"); string nameofclient = Console.ReadLine(); Console.Clear(); Shop shop = new Shop(); bool t; int cursor = 0; int n = shop.n; shop.ReadProducts(); shop.MoveinProduct(cursor); while (true) { ConsoleKeyInfo keyinfo = Console.ReadKey(); if (keyinfo.Key == ConsoleKey.UpArrow) { cursor--; if (cursor == -1) { cursor = shop.n - 1; } } if (keyinfo.Key == ConsoleKey.DownArrow) { cursor++; if (cursor == shop.n) { cursor = 0; } } if (keyinfo.Key == ConsoleKey.Enter) { shop.Buy(shop.listofproduct[cursor]); } if (keyinfo.Key == ConsoleKey.S) { cursor = 0; shop.n = shop.bought.Count; shop.listofproduct = shop.bought; shop.ShowBought(); } if (keyinfo.Key == ConsoleKey.B) { t = true; break; } shop.MoveinProduct(cursor); } Console.Clear(); if (t == true) { Console.WriteLine("Thanks " + nameofclient); Console.WriteLine("Your check"); int sum = 0; for (int i = 0; i < shop.bought.Count; i++) { Console.WriteLine(shop.bought[i]); sum += shop.bought[i].cost; } Console.WriteLine("Total: " + sum); } }
static void ReadKeyVictoryPage() { ConsoleKeyInfo pressed = new ConsoleKeyInfo(); while (true) { pressed = Console.ReadKey(true); if (pressed.Key == ConsoleKey.Escape) { return; } else if (pressed.Key == ConsoleKey.Q) { Exit(); } else { string msg = ("Invalid key, please, try again!"); Console.SetCursorPosition(20, 27); Console.WriteLine(msg); Console.SetCursorPosition(20, 27); } } }
public void CreateDentist() { SetCursorPosition(1, 1); Write("Förnamn: "); SetCursorPosition(1, 2); Write("Efternamn: "); SetCursorPosition(1, 3); Write("Personnummer: "); SetCursorPosition(1, 4); Write("Telefonnummer: "); SetCursorPosition(1, 5); Write("E-mail: "); SetCursorPosition(1, 6); Write("Lön: "); SetCursorPosition(1, 7); Write("Tandläkar ID: "); SetCursorPosition(1, 9); Write("Är detta rätt? (J)a (N)ej"); SetCursorPosition(1, 11); WriteLine("(L)ämna utan att spara?"); SetCursorPosition("Förnamn: ".Length + 1, 1); string firstName = ReadLine(); SetCursorPosition("Efternamn: ".Length + 1, 2); string lastName = ReadLine(); SetCursorPosition("Personnummmer: ".Length + 1, 3); string socialSercurityNumber = ReadLine(); SetCursorPosition("Telefonnummer: ".Length + 1, 4); string phoneNumber = ReadLine(); SetCursorPosition("E-mail: ".Length + 1, 5); string email = ReadLine(); SetCursorPosition("Lön: ".Length + 1, 6); int.TryParse(ReadLine(), out int salary); SetCursorPosition("Tandläkar ID: ".Length + 1, 7); string dentistID = ReadLine(); SetCursorPosition("Är detta rätt? (J)a (N)ej ".Length + 1, 9); bool Exit = false; while (!Exit) { ConsoleKeyInfo menuChoice = ReadKey(true); switch (menuChoice.Key) { case ConsoleKey.J: Dentist newDentist = new Dentist(firstName, lastName, socialSercurityNumber, phoneNumber, email, salary, dentistID); Clear(); if (Program.listOfDentists.ContainsKey(dentistID)) { WriteLine("Tandläkaren finns redan registrerad"); Thread.Sleep(1200); Clear(); CreateDentist(); } else { WriteLine($"Tandläkare {firstName} {lastName} registrerad"); Program.listOfDentists.Add(dentistID, newDentist); Thread.Sleep(1200); } Exit = true; break; case ConsoleKey.N: Clear(); CreateDentist(); break; case ConsoleKey.L: Exit = true; break; default: break; } } }
public string[,] GenerateMap() { const int MAP_HEIGHT = 4; const int MAP_WIDTH = 6; int xPos = 0; int yPos = 0; string[,] map = new string[MAP_WIDTH, MAP_HEIGHT]; for (int row = 0; row < MAP_HEIGHT; row++) { for (int col = 0; col < MAP_WIDTH; col++) { map[col, row] = ""; } } // Top info bar. Console.BackgroundColor = ConsoleColor.Gray; Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine("ROOM WIDTH: " + MAP_WIDTH + " ROOM HEIGHT: " + MAP_HEIGHT); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("-----------------------------"); Console.ResetColor(); // Bottom info bar. Console.SetCursorPosition(0, 18); Console.BackgroundColor = ConsoleColor.Gray; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("-----------------------------"); Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine("POS X: " + xPos + " POS Y: " + yPos + " "); Console.ResetColor(); // Draw rooms. Console.SetCursorPosition(0, 2); for (int row = 0; row < MAP_HEIGHT; row++) { for (int col = 0; col < MAP_WIDTH; col++) { bool up = false; bool down = false; bool left = false; bool right = false; if (map[col, row].Contains("U")) { up = true; } else if (map[col, row].Contains("D")) { down = true; } else if (map[col, row].Contains("L")) { left = true; } else if (map[col, row].Contains("R")) { right = true; } Console.SetCursorPosition(col * 5, row * 4); if (col != 0 && col != MAP_WIDTH && row != 0 && row != MAP_HEIGHT) { if (up && down && left && right) { Console.WriteLine(" _ _ "); Console.WriteLine("| |"); Console.WriteLine(" "); Console.WriteLine("|_ _|"); } else if (up && down && left) { Console.WriteLine(" _ _ "); Console.WriteLine("| |"); Console.WriteLine(" |"); Console.WriteLine("|_ _|"); } else if (up && down && right) { Console.WriteLine(" _ _ "); Console.WriteLine("| |"); Console.WriteLine("| "); Console.WriteLine("|_ _|"); } else if (up && down) { Console.WriteLine(" _ _ "); Console.WriteLine("| |"); Console.WriteLine("| |"); Console.WriteLine("|_ _|"); } else if (up && left) { Console.WriteLine(" _ _ "); Console.WriteLine("| |"); Console.WriteLine(" |"); Console.WriteLine("|___|"); } else if (up && right) { Console.WriteLine(" _ _ "); Console.WriteLine("| |"); Console.WriteLine("| "); Console.WriteLine("|___|"); } else if (left && right) { Console.WriteLine(" ___ "); Console.WriteLine("| |"); Console.WriteLine(" "); Console.WriteLine("|___|"); } else if (left && down) { Console.WriteLine(" ___ "); Console.WriteLine("| |"); Console.WriteLine(" |"); Console.WriteLine("|_ _|"); } else if (up) { Console.WriteLine(" _ _ "); Console.WriteLine("| |"); Console.WriteLine("| |"); Console.WriteLine("|___|"); } else if (down) { Console.WriteLine(" ___ "); Console.WriteLine("| |"); Console.WriteLine("| |"); Console.WriteLine("|_ _|"); } else if (left) { Console.WriteLine(" ___ "); Console.WriteLine("| |"); Console.WriteLine(" |"); Console.WriteLine("|___|"); } else if (right) { Console.WriteLine(" ___ "); Console.WriteLine("| |"); Console.WriteLine("| "); Console.WriteLine("|___|"); } else { Console.WriteLine(" ___ "); Console.WriteLine("| |"); Console.WriteLine("| |"); Console.WriteLine("|___|"); } } } } bool exit = false; do { ConsoleKeyInfo key = Console.ReadKey(); if (key.Key == ConsoleKey.UpArrow) { if (yPos > 0) { yPos--; } } else if (key.Key == ConsoleKey.DownArrow) { if (yPos < MAP_HEIGHT) { yPos++; } } else if (key.Key == ConsoleKey.LeftArrow) { if (xPos > 0) { xPos--; } } else if (key.Key == ConsoleKey.RightArrow) { if (xPos < MAP_WIDTH) { xPos++; } } else if (key.Key == ConsoleKey.Escape) { exit = true; } else { if (key.Key == ConsoleKey.W) { if (map[xPos, yPos].Contains("W")) { map[xPos, yPos].Remove('W'); } else { map[xPos, yPos] += 'U'; } } else if (key.Key == ConsoleKey.S) { if (map[xPos, yPos].Contains("D")) { map[xPos, yPos].Remove('D'); } else { map[xPos, yPos] += 'D'; } } else if (key.Key == ConsoleKey.D) { if (map[xPos, yPos].Contains("R")) { map[xPos, yPos].Remove('R'); } else { map[xPos, yPos] += 'R'; } } else if (key.Key == ConsoleKey.A) { if (map[xPos, yPos].Contains("L")) { map[xPos, yPos].Remove('L'); } else { map[xPos, yPos] += 'L'; } } } }while (!exit); return(map); }
public bool Equals(ConsoleKeyInfo obj) { throw null; }
public KeyPressedEventArgs(ConsoleKeyInfo keyInfo) { KeyPressed = keyInfo; }
public void MenuBar() { Console.Clear(); for (int i = 0; i < 3; i++) { if (i == index) { Console.ForegroundColor = ConsoleColor.Magenta; } else { Console.ForegroundColor = ConsoleColor.Yellow; } Console.WriteLine(s[i]); } while (a) { ConsoleKeyInfo pressedKey = Console.ReadKey(); switch (pressedKey.Key) { case ConsoleKey.UpArrow: if (index > 0) { index--; } MenuBar(); break; case ConsoleKey.DownArrow: if (index < 2) { index++; } MenuBar(); break; case ConsoleKey.Enter: if (index == 0) { Console.Clear(); Game g = new Game(); g.Start(true); } if (index == 1) { Console.Clear(); Game g = new Game(); g.Start(false); } if (index == 2) { a = false; } break; default: break; } }//end while }
static void Main(string[] args) { string programMemoryFile = args[0]; string dataMemoryFile = args[1]; bool showControlFlow = (args.Length < 3 ? false : args[2].Contains(ShowControlFlowFlag)); bool startPaused = (args.Length < 3 ? false : args[2].Contains(StartPausedFlag)); bool monitorProgramFlow = (args.Length < 3 ? false : args[2].Contains(MonitorProgramFlowFlag)); bool benchmark = (args.Length < 3 ? false : args[2].Contains(BenchmarkFlag)); programMemory = new BufferMemory16(System.IO.File.ReadAllBytes(programMemoryFile)); dataMemory = new BufferMemory16(System.IO.File.ReadAllBytes(dataMemoryFile)); cpu = new SerialAbacus16Cpu( programMemory, dataMemory); virtualSystem = new Host(cpu); virtualSystem.ExecutionCompleted += virtualSystem_ExecutionCompleted; if (showControlFlow) { cpu.InstructionPending += cpu_InstructionPending; //virtualSystem.ClockCycleScheduled += virtualSystem_ClockCycleScheduled; Console.WriteLine("Press ESC to cancel execution"); } if (monitorProgramFlow) { FlowMonitoringMapping = new Dictionary <int, FlowInfo>(); } if (!startPaused) { virtualSystem.Start(); } if (benchmark) { System.Threading.Thread.Sleep(1000); virtualSystem.SuspendAsync().Wait(); WriteDumps(); Console.ReadLine(); return; } while (true) { ConsoleKeyInfo input = Console.ReadKey(true); switch (input.Key) { case ConsoleKey.Escape: if (virtualSystem.IsRunning) { Console.WriteLine("Suspending Execution..."); virtualSystem.SuspendAsync().Wait(); WriteDumps(); Console.WriteLine("Execution suspended. Press ENTER to exit."); Console.ReadLine(); } return; case ConsoleKey.P: Console.WriteLine("Suspending execution..."); virtualSystem.SuspendAsync().Wait(); Console.WriteLine("Execution suspended. Press H for help."); break; case ConsoleKey.R: if (!virtualSystem.IsRunning) { virtualSystem.Start(); } else { Console.WriteLine("Already running."); } break; case ConsoleKey.S: if (!virtualSystem.IsRunning) { virtualSystem.Step(1); } else { Console.WriteLine("Already running."); } break; case ConsoleKey.F: WriteFlowDump(); break; case ConsoleKey.D: WriteDumps(); break; case ConsoleKey.H: Console.WriteLine("ESC: exit | P: pause | S: single step | D: dump | F: flow info | H: help"); break; } } }
public bool Equals(ConsoleKeyInfo obj) { return obj._keyChar == _keyChar && obj._key == _key && obj._mods == _mods; }
static void Main(string[] args) { try { OpenConfigFile(); Console.WriteLine("Select one of the following options: "); Console.WriteLine("1. Create Handy Sync Task in Task Scheduler. "); Console.WriteLine("2. Remove Handy Sync Task from Task Scheduler. "); Console.WriteLine(); ConsoleKeyInfo info = Console.ReadKey(); if (info.Key == ConsoleKey.D1) { Console.WriteLine(); Console.WriteLine("Creating HandySync Task."); // Get the service on the local machine using (TaskService ts = new TaskService()) { try { // Create a new task definition and assign properties TaskDefinition td = ts.NewTask(); int minutes = Int32.Parse(config.AppSettings.Settings["SyncPeriodMinutes"].Value); RepetitionPattern rp = new RepetitionPattern(new TimeSpan(0, minutes, 0), TimeSpan.Zero); td.RegistrationInfo.Description = "Runs the HandySync"; // Create a trigger that will fire the task at this time every other day td.Triggers.Add(new DailyTrigger { DaysInterval = 1, Repetition = rp, Enabled = true }); // Create an action that will launch Notepad whenever the trigger fires string HandySyncPath = config.AppSettings.Settings["HandySyncPath"].Value; td.Actions.Add(new ExecAction(HandySyncPath + @"\HandySyncService.exe")); // Register the task in the root folder ts.RootFolder.RegisterTaskDefinition(@"HandySync", td); // Remove the task we just created //ts.RootFolder.DeleteTask("Test"); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } Console.WriteLine("HandySync Task created successfully."); } else if (info.Key == ConsoleKey.D2) { using (TaskService ts = new TaskService()) { try { Console.WriteLine(); ts.RootFolder.DeleteTask("HandySync"); Console.WriteLine("Handy Sync Task removed successfully."); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } } else { Console.WriteLine(); Console.WriteLine("Invalid Option."); } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } Console.WriteLine(); Console.WriteLine("PRESS ANY KEY TO EXIT"); Console.ReadKey(); }
public abstract bool TryHandleKeyboardInput(ConsoleKeyInfo key);
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo) { console.CurrentLine = string.Empty; console.CursorPosition = 0; }
static ConsoleKeyInfo CombatPrompt(Character player, Monster enemy) { ConsoleKeyInfo playerPress = new ConsoleKeyInfo(); Console.Clear(); promptAction: player.PrintStats(); enemy.PrintStats(); Console.WriteLine("What would you like to do?"); Console.WriteLine("\n Blunt Force Attack - A" + "\n Piercing Attack - 1MP- S" + "\n Obliterate -4MP - D" + "\n Flee -1 Progress - F" + "\n Instant Kill - G" + "\n Heal Yourself - H"); playerPress = Console.ReadKey(true); string playerPressString = playerPress.Key.ToString(); playerPressString = playerPressString.ToLower(); switch(playerPressString) { case"a": case"s": case"d": case"f": case"g": case"h": break; default: Console.Clear(); WriteRed("Please press the correct key.\n"); Console.ReadKey(true); goto promptAction; } return playerPress; }
static void Main(string[] args) { Console.Title = "StoneVox 3D"; string version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); string Title = String.Format("StoneVox 3D Voxel Modeler for StoneHearth : build {0}", version.Split('.').Last()); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(Title); Console.WriteLine(""); Console.ForegroundColor = ConsoleColor.White; if (args.Length == 0) { args = new string[] { "/startclient" }; } Regex r = new Regex("(?<match>[^\\s\"]+)|(?<match>\"[^\"]*\")"); var cmds = typeof(ConsoleCommands).GetMethods(BindingFlags.Static | BindingFlags.Public); for (int i = 0; i < args.Length; i++) { string arg = args[i]; while (true) { if (i + 1 < args.Length && !args[i + 1].Contains('/')) { arg += " " + args[i + 1]; i++; } else { MatchCollection matches = r.Matches(arg); List <string> splits = new List <string>(); foreach (Match m in matches) { splits.Add(m.Value.Replace("\"", "")); } int argcount = splits.Count; foreach (var c in cmds) { ConsoleCommand command = (ConsoleCommand)c.GetCustomAttribute(typeof(ConsoleCommand)); if (arg.Contains(command.name) && argcount - 1 == command.argcount) { List <object> cmdargs = new List <object>(); if (argcount > 1) { for (int ii = 1; ii < argcount; ii++) { cmdargs.Add(splits[ii]); } } c.Invoke(null, cmdargs.ToArray()); } } break; } } } string read = ""; while (true) { ConsoleKeyInfo ki = Console.ReadKey(true); if ((ki.Key == ConsoleKey.V) && (ki.Modifiers == ConsoleModifiers.Control)) { string s = Clipboard.GetText(); if (!string.IsNullOrEmpty(s)) { s = s.Replace("\r", "").Replace("\n", ""); } Console.Write(s); read += s; } else if (ki.Key == ConsoleKey.Enter) { Console.Write("\r\n"); read = read.ToLower(); read = read.Trim(); if (!string.IsNullOrEmpty(read) && read[0] == '/') { MatchCollection matches = r.Matches(read); List <string> splits = new List <string>(); foreach (Match m in matches) { splits.Add(m.Value.Replace("\"", "")); } int argcount = splits.Count; foreach (var c in cmds) { ConsoleCommand command = (ConsoleCommand)c.GetCustomAttribute(typeof(ConsoleCommand)); if (read.Contains(command.name) && argcount - 1 == command.argcount) { List <object> cmdargs = new List <object>(); if (argcount > 1) { for (int i = 1; i < argcount; i++) { cmdargs.Add(splits[i]); } } c.Invoke(null, cmdargs.ToArray()); } } } else { var packet = PacketWriter.write <Packet_Chat>(NetEndpoint.CLIENT); packet.outgoingmessage.Write(Client.ID); packet.outgoingmessage.Write(read); packet.send(); } read = ""; } else if (ki.Key == ConsoleKey.Backspace) { if (read.Length > 0) { read = read.Remove(read.Length - 1); } Console.Write("\b \b"); } else { read += ki.KeyChar; Console.Write(ki.KeyChar); if (read == "/exit") { break; } } } Server.net?.Shutdown("shutting down"); Client.net?.Shutdown("shutting down"); Client.window?.Close(); }
public static void Main() { WelcomeScreen(); while (playGame) { StartGame(); key = Console.ReadKey(true).Key; while (key != ConsoleKey.Escape) { if (Console.KeyAvailable) { movePlayer = true; keyInfo = Console.ReadKey(true); key = keyInfo.Key; ClearInputStreamBuffer(); } if (key == ConsoleKey.Spacebar) { PauseGame(); } Console.MoveBufferArea(0, 2, newWidth, newHeight - 3, 0, 3); DrawNewRocks(); GetNewData(); RedrawGoods(); CheckCollision(); DrawScore(); MovePlayer(); Thread.Sleep(sleep); if (!playGame) { break; } } ResetGame(); } EndGame(); }
//this method checks if the char inputted by the user matches any letters in the secret word public void CheckGuess(List <DisplayLetter> displayLetters, HangmanPicture draw) { bool correctGuess = false; bool validInput = false; char guess; Console.Write("Please enter a letter: "); do { int checkedLetters = 0; //Gets user input ConsoleKeyInfo info = Console.ReadKey(); string keyString = info.Key.ToString(); guess = keyString[0]; Console.WriteLine(); //checks user input against already guessed letters, if letter has already been guessed prompts user //to try another letter foreach (char character in guesses) { if (character == char.ToUpper(guess)) { Console.Write("You have already entered \"" + guess + "\", please enter a different letter: "); break; } else { checkedLetters++; } } if (checkedLetters == guesses.Count()) { validInput = true; } } while (validInput == false); Console.WriteLine(); //checks user input against secretWord foreach (DisplayLetter item in displayLetters) { if (item.Letter == char.ToUpper(guess) && item.Guessed == false) { item.Guessed = true; correctGuess = true; this.Correct++; } } if (correctGuess) { Console.WriteLine("You guessed correctly!"); } else { this.Incorrect++; Console.WriteLine("I'm sorry, you guessed incorrectly"); draw.Draw(this.Incorrect); } this.guesses.Add(guess); Console.WriteLine(); }
public (string transportName, DateTime date) Transfer(double weightTransfer, double distanceTransfer, ConsoleKeyInfo withEngineOrNotTransfer, ConsoleKeyInfo speedOrEconomTransfer) { DepartureNowOrLate(); var haveNotNeedTransport = false; var haveNotNeedDriver = false; var havingDriver = false; weight = weightTransfer; distance = distanceTransfer; withEngineOrNot = withEngineOrNotTransfer; speedOrEconom = speedOrEconomTransfer; FindExtraArrayTransport(); transportLength = 0; while (true) { needTransport = FindTranport(); haveNotNeedTransport = NotNeedTransport(); if (haveNotNeedTransport) { Departure(); continue; } havingDriver = FindDriver(); haveNotNeedDriver = NotNeedTransport(); if (havingDriver) { break; } else { NotNeedDriver(); if (transportLength == 0) { Departure(); } } } var needArrival = needTransport.Arrival(distance, departure, withEngineOrNot); needTransport.Trasfer(departure, needArrival); return(needTransport.GetType().Name, needArrival); }
static char[,] FrogMove(Container container, char[,] mappos, Frog frog)//判断青蛙运动 { ConsoleKeyInfo keyInfo = Console.ReadKey(true); int y = frog.y; int x = frog.x; if (keyInfo.Key == ConsoleKey.RightArrow || keyInfo.Key == ConsoleKey.LeftArrow)//如果往左或者往右运动,就计算按键时差 { float oversecond = 0, startsecond = 0; startsecond = DateTime.Now.Millisecond; if (System.Math.Abs(startsecond - oversecond) < 100) { return(mappos); } else { if (!frog.Be_Brick(frog.x, frog.y + 1, container) && frog.airmove <= 0) { return(mappos); } else { frog.airmove--; oversecond = startsecond; if (keyInfo.Key == ConsoleKey.RightArrow) { if (frog.Be_Brick(frog.x + 1, frog.y, container)) { return(mappos); } //往左撞墙 else { frog.x++; Clear(mappos); mappos[frog.y, frog.x] = 'm'; } } else if (keyInfo.Key == ConsoleKey.LeftArrow) { if (frog.Be_Brick(frog.x - 1, frog.y, container)) { return(mappos); } //往右撞墙 else if (frog.x - 1 < 0) { frog.x++; return(mappos); } else { frog.x--; Clear(mappos); mappos[frog.y, frog.x] = 'm'; } } } } } if (keyInfo.Key == ConsoleKey.UpArrow && frog.Be_Brick(frog.x, frog.y + 1, container))//如果按键跳跃就计算是否站在地面上,是则跳跃,否则不跳跃 { frog.jump = true; frog.starty = frog.y; frog.airmove = 5; frog.jumpstart = DateTime.Now; } if (frog.Be_Glasses(frog.x, frog.y, container))//如果碰到眼镜,则捡到武器 { frog.arm = true; } if (keyInfo.Key == ConsoleKey.Spacebar && frog.arm == true)//如果持有武器且按键,则射击 { frog.attack = true; Bullet bullet = new Bullet(); container.bu.Add(bullet); bullet.x = frog.x; bullet.y = frog.y; bullet.startx = frog.x; } if (frog.Be_Timecoin(frog.x, frog.y, container))//碰到硬币 { container.ti.Remove((y + 1) * 100 + x); frog.timecoin++; } if (frog.Be_Brick(frog.x, frog.y + 1, container)) { frog.airmove = 5; } return(mappos); }
internal ConsoleKeyInfo (ConsoleKeyInfo other) { this.key = other.key; this.keychar = other.keychar; this.modifiers = other.modifiers; }
private static void Main() { ExceptionlessClient.Default.Configuration.UseFolderStorage("store"); ExceptionlessClient.Default.Configuration.UseFileLogger("store\\exceptionless.log"); ExceptionlessClient.Default.Startup(); var tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; if (false) { SampleApiUsages(); } ExceptionlessClient.Default.Configuration.AddEnrichment(ev => ev.Data[RandomHelper.GetPronouncableString(5)] = RandomHelper.GetPronouncableString(10)); ExceptionlessClient.Default.Configuration.Settings.Changed += (sender, args) => Trace.WriteLine(String.Format("Action: {0} Key: {1} Value: {2}", args.Action, args.Item.Key, args.Item.Value)); WriteOptionsMenu(); while (true) { Console.SetCursorPosition(0, OPTIONS_MENU_LINE_COUNT + 1); ConsoleKeyInfo keyInfo = Console.ReadKey(true); if (keyInfo.Key == ConsoleKey.D1) { SendEvent(); } else if (keyInfo.Key == ConsoleKey.D2) { SendContinuousEvents(50, token, 100); } else if (keyInfo.Key == ConsoleKey.D3) { SendContinuousEvents(_delays[_delayIndex], token); } else if (keyInfo.Key == ConsoleKey.D4) { Console.SetCursorPosition(0, OPTIONS_MENU_LINE_COUNT + 2); Console.WriteLine("Telling client to process the queue..."); ExceptionlessClient.Default.ProcessQueue(); ClearNonOptionsLines(); } else if (keyInfo.Key == ConsoleKey.D5) { SendAllCapturedEventsFromDisk(); ClearNonOptionsLines(); } else if (keyInfo.Key == ConsoleKey.D) { _dateSpanIndex++; if (_dateSpanIndex == _dateSpans.Length) { _dateSpanIndex = 0; } WriteOptionsMenu(); } else if (keyInfo.Key == ConsoleKey.T) { _delayIndex++; if (_delayIndex == _delays.Length) { _delayIndex = 0; } WriteOptionsMenu(); } else if (keyInfo.Key == ConsoleKey.Q) { break; } else if (keyInfo.Key == ConsoleKey.S) { tokenSource.Cancel(); tokenSource = new CancellationTokenSource(); token = tokenSource.Token; ClearNonOptionsLines(); } } }
public void Move(ConsoleKeyInfo pressedKey, GameField field) { if (pressedKey.Key == ConsoleKey.LeftArrow) { if (CurrentPositionX > 0) { if (currentPosition == CellStatus.Empty) { this.lastPosition = CellStatus.Trail; } else if (currentPosition == CellStatus.Filled) { this.lastPosition = CellStatus.Filled; } else if (currentPosition == CellStatus.Trail) { this.lastPosition = currentPosition; } this.LastPositionX = this.CurrentPositionX; this.LastPositionY = this.CurrentPositionY; this.CurrentPositionX--; this.currentPosition = field.gameField[this.CurrentPositionY, this.CurrentPositionX]; if (this.currentPosition == CellStatus.Empty && this.movement != MovementStatus.Left) { this.movement = MovementStatus.Left; } } } else if (pressedKey.Key == ConsoleKey.RightArrow) { if (CurrentPositionX < field.width - 1) { if (currentPosition == CellStatus.Empty) { this.lastPosition = CellStatus.Trail; } else if (currentPosition == CellStatus.Filled) { this.lastPosition = CellStatus.Filled; } else if (currentPosition == CellStatus.Trail) { this.lastPosition = currentPosition; } this.LastPositionX = this.CurrentPositionX; this.LastPositionY = this.CurrentPositionY; this.CurrentPositionX++; this.currentPosition = field.gameField[this.CurrentPositionY, this.CurrentPositionX]; if (this.currentPosition == CellStatus.Empty && this.movement != MovementStatus.Right) { this.movement = MovementStatus.Right; } } } else if (pressedKey.Key == ConsoleKey.UpArrow) { if (CurrentPositionY > 0) { if (currentPosition == CellStatus.Empty) { this.lastPosition = CellStatus.Trail; } else if (currentPosition == CellStatus.Filled) { this.lastPosition = CellStatus.Filled; } else if (currentPosition == CellStatus.Trail) { this.lastPosition = currentPosition; } this.LastPositionX = this.CurrentPositionX; this.LastPositionY = this.CurrentPositionY; this.CurrentPositionY--; this.currentPosition = field.gameField[this.CurrentPositionY, this.CurrentPositionX]; if (this.currentPosition == CellStatus.Empty && this.movement != MovementStatus.Up) { this.movement = MovementStatus.Up; } } } else if (pressedKey.Key == ConsoleKey.DownArrow) { if (CurrentPositionY < field.height - 1) { if (currentPosition == CellStatus.Empty) { this.lastPosition = CellStatus.Trail; } else if (currentPosition == CellStatus.Filled) { this.lastPosition = CellStatus.Filled; } else if (currentPosition == CellStatus.Trail) { this.lastPosition = currentPosition; } this.LastPositionX = this.CurrentPositionX; this.LastPositionY = this.CurrentPositionY; this.CurrentPositionY++; this.currentPosition = field.gameField[this.CurrentPositionY, this.CurrentPositionX]; if (this.currentPosition == CellStatus.Empty && this.movement != MovementStatus.Down) { this.movement = MovementStatus.Down; } } } if (this.lastPosition == CellStatus.Trail && field.gameField[this.CurrentPositionY, this.CurrentPositionX] == CellStatus.Filled) { field.isForFilling = true; } field.gameField[this.LastPositionY, this.LastPositionX] = this.lastPosition; field.gameField[this.CurrentPositionY, this.CurrentPositionX] = CellStatus.Head; }
public void StartStage_1() { Score score = new Score(); Console.Clear(); Console.SetCursorPosition(45, 10); Console.WriteLine("======================"); Console.SetCursorPosition(48, 12); Console.WriteLine("L E V E L 2"); Console.SetCursorPosition(45, 14); Console.WriteLine("======================"); System.Threading.Thread.Sleep(2000); Console.Clear(); //Drawing a frame Stage_1 walls = new Stage_1(120, 30); walls.Draw(); //Drawing a snake Point point = new Point(4, 5, '*'); Snake snake = new Snake(point, 3, Direction.RIGHT); snake.SnakeSpeed(); snake.Draw(); //Create the food FoodGenerator foodGenerator = new FoodGenerator(120, 30, '$'); Point food = foodGenerator.CreateFood(snake); food.Draw(); while (Score.score != 4) { //Show game info snake.SnakeSpeed(); score.ShowScore(); if (walls.IsHit(snake) || snake.IsHitTail()) { if (Score.score > Score.maxScore) { Score.maxScore = Score.score; } score.PrintScore(); while (true) { if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(); if (key.Key == ConsoleKey.Y) { Console.Clear(); Score.score = 0; StartStage_0(); } else if (key.Key == ConsoleKey.N) { Environment.Exit(0); } else { continue; } } } } if (snake.Eat(food)) { food = foodGenerator.CreateFood(snake); food.Draw(); } else { food.Draw(); snake.Move(); } if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(); snake.PushKey(key.Key); } } StartStage_2(); }
/* public async Task<ConsoleKeyInfo> ReadKey() { await Task.Run(() => (jQuery.Select("body").On("keydown", processKey))); jQuery.Select("body").Off("keydown", "body", processKey); return kc; }*/ public async Task<ConsoleKeyInfo> ReadKey(bool intercept) { // cki = null; Intercept = intercept; defr = new TaskCompletionSource<ConsoleKeyInfo>(); //defr.Done(() => ); jQuery.Select("body").One("keyup", processKey); //(, 2, "on", "keydown", "canvas", "processKey"); /*while (cki == null) await Task.Delay(35);*/ kc = await defr.Task; return kc; }
public static int Menu(params string[] items) { int[] span = new int[items.Length + 1]; for (int i = 1; i < span.Length; i++) { span[i] = items[i - 1].Length / Console.WindowWidth + 1; } Console.CursorVisible = false; for (int i = 0; i < items.Length; i++) { Console.WriteLine("\n"); } int positionY = Console.CursorTop - 2 * items.Length + 1; int currentIndex = 0, previousIndex = 0; int positionX = 2; bool itemSelected = false; int sum = 0; //Начальный вывод пунктов меню. for (int i = 0; i < items.Length; i++) { sum += span[i]; Console.CursorLeft = positionX; Console.CursorTop = positionY + sum; Console.ForegroundColor = ConsoleColor.Gray; Console.BackgroundColor = ConsoleColor.Black; Console.Write(items[i]); } do { sum = 0; for (int i = 0; i <= previousIndex; i++) { sum += span[i]; } // Вывод предыдущего активного пункта основным цветом. Console.CursorLeft = positionX; Console.CursorTop = positionY + sum; Console.ForegroundColor = ConsoleColor.Gray; Console.BackgroundColor = ConsoleColor.Black; Console.Write(items[previousIndex]); sum = 0; for (int i = 0; i <= currentIndex; i++) { sum += span[i]; } //Вывод активного пункта. Console.CursorLeft = positionX; Console.CursorTop = positionY + sum; Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.Gray; Console.Write(items[currentIndex]); ConsoleKeyInfo keyInfo = Console.ReadKey(true); previousIndex = currentIndex; switch (keyInfo.Key) { case ConsoleKey.DownArrow: currentIndex++; break; case ConsoleKey.UpArrow: currentIndex--; break; case ConsoleKey.Enter: itemSelected = true; break; } if (currentIndex == items.Length) { currentIndex = 0; } else if (currentIndex < 0) { currentIndex = items.Length - 1; } } while (!itemSelected); Console.CursorVisible = true; Console.ForegroundColor = ConsoleColor.Gray; Console.BackgroundColor = ConsoleColor.Black; Console.Clear(); return(currentIndex + 1); } // Позволяет быстро организовать меню, введя его пункты
public static void Main(string[] args) { Random rng = new Random(); bool stop = false; bool secondCar = false; bool ThirdCar = false; int points = 0; Cordinates temp = new Cordinates(0, 0); Cordinates temp2 = new Cordinates(0, 0); Cordinates temp1 = new Cordinates(0, 0); Console.BufferHeight = Console.WindowHeight; Console.BufferWidth = Console.BufferWidth; int UserCarX = Console.BufferWidth / 2 - 2; int UserCarY = 15; List <Cordinates> enemyCars = new List <Cordinates>(); for (int i = 0; i < 12; i += 3) { enemyCars.Add(new Cordinates(Console.BufferWidth / 2 - 2 + i, 3)); } var enemyCar = enemyCars[rng.Next(0, enemyCars.Count)]; var enemyCar2 = enemyCars[rng.Next(0, enemyCars.Count)]; var enemyCar3 = enemyCars[rng.Next(0, enemyCars.Count)]; temp1.X = enemyCar.X; temp1.Y = enemyCar.Y; temp.X = enemyCar2.X; temp.Y = enemyCar2.Y; temp2.X = enemyCar3.X; temp2.Y = enemyCar3.Y; while (stop == false) { drawField(); if (temp1.Y < 18) { temp1.Y++; Car.PrintEnemyCar(temp1.X, temp1.Y); } else { points += 100; temp1.Y = 3; temp1 = enemyCars[rng.Next(0, enemyCars.Count)]; } if (points > 600 && temp1.Y == 11) { secondCar = true; } if (secondCar == true) { if (temp.Y < 18) { temp.Y++; Car.PrintEnemyCar(temp.X, temp.Y); } else { points += 100; enemyCar2.Y = 3; enemyCar2 = enemyCars[rng.Next(0, enemyCars.Count)]; temp.X = enemyCar2.X; temp.Y = enemyCar2.Y; secondCar = false; } } if (points > 2000 && temp1.Y == 15) { ThirdCar = true; } if (ThirdCar == true) { if (temp2.Y < 18) { temp2.Y++; Car.PrintEnemyCar(temp2.X, temp2.Y); } else { points += 100; enemyCar3 = enemyCars[rng.Next(0, enemyCars.Count)]; temp2.X = enemyCar3.X; temp2.Y = enemyCar3.Y; ThirdCar = false; } } if (Console.KeyAvailable) { ConsoleKeyInfo usr = Console.ReadKey(); if (usr.Key == ConsoleKey.LeftArrow && UserCarX > Console.BufferWidth / 2 - 2) { UserCarX -= 3; } if (usr.Key == ConsoleKey.RightArrow && UserCarX < Console.BufferWidth / 2 - 2 + 9) { UserCarX += 3; } } Car.PrintMyCar(UserCarX, UserCarY); Console.SetCursorPosition(Console.WindowWidth / 2, 0); Console.Write("Current points: {0}", points); if (points > 3000) { System.Threading.Thread.Sleep(30); } else if (points > 2000) { System.Threading.Thread.Sleep(35); } else if (points > 1000) { System.Threading.Thread.Sleep(45); } else { System.Threading.Thread.Sleep(50); } if (temp1.X == UserCarX && temp1.Y - 2 == UserCarY || temp.X == UserCarX && temp.Y - 2 == UserCarY || temp2.X == UserCarX && temp2.Y - 2 == UserCarY) { stop = true; } Console.Clear(); } Console.WriteLine("Game over!\nYour points are {0}\nPress Enter to continue...", points); ConsoleKeyInfo user = Console.ReadKey(); while (user.Key != ConsoleKey.Enter) { user = Console.ReadKey(); } }
public static void Main(string[] args) { bool running = true; // use Ctrl-C to stop the programm Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) { e.Cancel = true; running = false; }; string portName = "COM8"; // e.g. "COM3" on windows if (args.Length > 0) { portName = args [0]; } SerialPort port = new SerialPort(); port.PortName = portName; port.BaudRate = 9600; port.Parity = Parity.Even; port.Handshake = Handshake.None; port.Open(); LinkLayerParameters llParameters = new LinkLayerParameters(); llParameters.AddressLength = 1; llParameters.TimeoutForACK = 500; llParameters.UseSingleCharACK = true; CS101Slave slave = new CS101Slave(port, llParameters); slave.DebugOutput = true; slave.LinkLayerAddress = 1; slave.LinkLayerAddressOtherStation = 3; slave.LinkLayerMode = lib60870.linklayer.LinkLayerMode.BALANCED; slave.SetInterrogationHandler(myInterrogationHandler, null); slave.SetUserDataQueueSizes(50, 20); ASDU asdu = new ASDU(slave.Parameters, CauseOfTransmission.SPONTANEOUS, false, false, 0, 1, false); asdu.AddInformationObject(new StepPositionInformation(301, 1, false, new QualityDescriptor())); slave.EnqueueUserDataClass1(asdu); long lastTimestamp = SystemUtils.currentTimeMillis(); Int16 measuredValue = 0; TransparentFile file = new TransparentFile(1, 30000, NameOfFile.TRANSPARENT_FILE); byte[] fileData = new byte[1025]; for (int i = 0; i < 1025; i++) { fileData [i] = (byte)(i + 1); } file.AddSection(fileData); slave.GetAvailableFiles().AddFile(file); while (running) { slave.Run(); // call the protocol stack if ((SystemUtils.currentTimeMillis() - lastTimestamp) >= 5000) { lastTimestamp = SystemUtils.currentTimeMillis(); ASDU newAsdu = new ASDU(slave.Parameters, CauseOfTransmission.PERIODIC, false, false, 0, 1, false); newAsdu.AddInformationObject(new MeasuredValueScaled(110, measuredValue, new QualityDescriptor())); slave.EnqueueUserDataClass2(newAsdu); measuredValue++; } if (Console.KeyAvailable) { ConsoleKeyInfo keyInfo = Console.ReadKey(); if (keyInfo.KeyChar == 't') { slave.SendLinkLayerTestFunction(); } else { Console.WriteLine("Send spontaneous message"); bool value = false; if (keyInfo.KeyChar == 's') { value = true; } ASDU newAsdu = new ASDU(slave.Parameters, CauseOfTransmission.SPONTANEOUS, false, false, 0, 1, false); newAsdu.AddInformationObject(new SinglePointInformation(100, value, new QualityDescriptor())); slave.EnqueueUserDataClass1(newAsdu); } } } }
static void Main() { ResetBuffer(); Random randomGenerator = new Random(); List <Unit> RocksList = new List <Unit>(); int livesCount = 1; int score = 0; char[] symbolList = { '^', '*', '&', '+', '%', '$', '#', '!', '.', ';' }; int speed = 0; // Init Dwarf Unit Dwarf = new Unit(); Dwarf.x = (Console.WindowWidth / 2) - 1; Dwarf.y = Console.WindowHeight - 1; Dwarf.color = ConsoleColor.White; Dwarf.symbol = '@'; while (true) { bool hitted = false; int spawnBuffChance = randomGenerator.Next(0, 100); if (spawnBuffChance < 10) { // Spawn buff Unit newBuff = new Unit(); newBuff.x = randomGenerator.Next(0, Console.WindowWidth - 2); newBuff.y = 5; newBuff.color = ConsoleColor.Red; // We start from blue because black is not Good in our game :) // newInitRock.color = (ConsoleColor)randomGenerator.Next((int)ConsoleColor.Blue, (int)ConsoleColor.Yellow); // We start from blue because black is not Good in our game :) newBuff.symbol = '¤'; // TODO: Random RocksList.Add(newBuff); } else { // Spawn Rock Unit newInitRock = new Unit(); newInitRock.x = randomGenerator.Next(0, Console.WindowWidth - 2); newInitRock.y = 5; newInitRock.color = ConsoleColor.Cyan; // We start from blue because black is not Good in our game :) // newInitRock.color = (ConsoleColor)randomGenerator.Next((int)ConsoleColor.Blue, (int)ConsoleColor.Yellow); // We start from blue because black is not Good in our game :) newInitRock.symbol = symbolList[randomGenerator.Next(0, 9)]; // TODO: Random RocksList.Add(newInitRock); } // Move Dwarf if (Console.KeyAvailable) { ConsoleKeyInfo keyPressed = Console.ReadKey(true); while (Console.KeyAvailable) { Console.ReadKey(true); } if (keyPressed.Key == ConsoleKey.LeftArrow) { if (Dwarf.x > 0) { Dwarf.x--; } } if (keyPressed.Key == ConsoleKey.RightArrow) { if (Dwarf.x < Console.WindowWidth - 2) { Dwarf.x++; } } } // Move Rocks List <Unit> newList = new List <Unit>(); for (int i = 0; i < RocksList.Count; i++) { Unit oldRock = RocksList[i]; Unit NewMovedRock = new Unit(); NewMovedRock.x = oldRock.x; NewMovedRock.y = oldRock.y + 1; NewMovedRock.color = oldRock.color; NewMovedRock.symbol = oldRock.symbol; // Buff Detection if (NewMovedRock.symbol == '¤' && NewMovedRock.x == Dwarf.x && NewMovedRock.y == Dwarf.y) { speed = speed - 50; } // Collision Detection if (NewMovedRock.symbol != '¤' && NewMovedRock.x == Dwarf.x && NewMovedRock.y == Dwarf.y) { livesCount--; hitted = true; speed = 0; if (livesCount <= 0) { PrintStringAtPosition(42, 2, "GAME OVER", ConsoleColor.Red); PrintStringAtPosition(33, 3, "Press [enter] to continue", ConsoleColor.Red); Console.ReadLine(); } } if (NewMovedRock.y < Console.WindowHeight) { newList.Add(NewMovedRock); } else { score++; } } RocksList = newList; // Clear All Console.Clear(); // Draw Dwarf if (hitted) { PrintAtPosition(Dwarf.x, Dwarf.y, 'X', ConsoleColor.Red); RocksList.Clear(); } else { PrintAtPosition(Dwarf.x, Dwarf.y, Dwarf.symbol, Dwarf.color); } // Draw Rocks foreach (Unit rock in RocksList) { PrintAtPosition(rock.x, rock.y, rock.symbol, rock.color); } // Draw Score and lives for (int i = 0; i < Console.WindowWidth; i++) // Score Divider { PrintAtPosition(i, 5, '-', ConsoleColor.Gray); } PrintStringAtPosition(10, 2, "Lives: " + livesCount, ConsoleColor.Green); PrintStringAtPosition(20, 2, "Score: " + score, ConsoleColor.Green); PrintStringAtPosition(20, 3, "Speed: " + speed, ConsoleColor.Green); // Slow the game down if (speed < 170) { speed++; } Thread.Sleep(250 - speed); } }
public void Login(string username) { string query = "Select * FROM users WHERE name =" + "'" + username + "'"; string pass = ""; DataSet ds; ds = Connection.DataSet(query); if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { Console.Write("Jepni fjalekalimin:"); do { ConsoleKeyInfo key = Console.ReadKey(true); if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter) { pass += key.KeyChar; Console.Write("*"); } else { if (key.Key == ConsoleKey.Backspace && pass.Length > 0) { pass = pass.Substring(0, (pass.Length - 1)); Console.Write("\b \b"); } else if (key.Key == ConsoleKey.Enter) { break; } } } while (true); string dbPassword = ds.Tables[0].Rows[0]["password"].ToString(); string dbSalt = ds.Tables[0].Rows[0]["saltt"].ToString(); HashAlgorithm algorithm = new SHA256Managed(); byte[] ssalt = System.Text.Encoding.UTF8.GetBytes(pass + dbSalt); byte[] hash = algorithm.ComputeHash(ssalt); string SaltedHashPassword = Convert.ToBase64String(hash); if (dbPassword.Equals(SaltedHashPassword)) { var payloadOBJ = new JwtPayload { { "exp: ", DateTimeOffset.UtcNow.AddMinutes(20).ToUnixTimeSeconds() }, { "name", username } }; string payload = JsonConvert.SerializeObject(payloadOBJ); Console.WriteLine("\nToken: " + SignToken(payload, username)); } else { Console.WriteLine("\nGabim: Shfrytezuesi ose fjalekalimi i gabuar."); } } else { Console.WriteLine("\nGabim: Shfrytezuesi nuk ekziston!"); } }