static void CaptureKeyPressed(ConsoleKey key) { if (key == ConsoleKey.Enter) { HandleEnter(null, ConsoleKey.Enter); } }
public void Move(ConsoleKey direction) { switch (direction) { case ConsoleKey.LeftArrow: if (this.X > 0) { this.X -= Constants.CarWidth; } break; case ConsoleKey.RightArrow: if (this.X < Constants.PlayfieldWidth - Constants.CarWidth) { this.X += Constants.CarWidth; } break; case ConsoleKey.DownArrow: if (this.Y < Constants.PlayfieldHeight - Constants.CarHeight) { this.Y++; } break; default: break; } }
/// <summary> /// ทำให้เกมมีการทำงานซ้ำ สั่งให้งูเคลื่อนที่ข้างหน้าไปเรื่อย แสดงอาหารให้งูเข้าไปจับกินได้ /// </summary> public static void Loop() { while (true) { Thread.Sleep(1); //sleep for 1 second if (Console.KeyAvailable) { keyboardInput = Console.ReadKey(true).Key; // get key input snake.LastKeyBoardInput = keyboardInput; } snake.Forward(); if (snake.IsCollide()) { Console.SetCursorPosition(grassField.Left, grassField.Bottom + 2); Console.WriteLine("Game Over"); return; } if (snake.IsEatFood()) { food = new Food(grassField); snake.Food = food; food.Render(); snake.Lengthen(); } snake.Render(); } }
internal static char GetCharFromConsoleKey(ConsoleKey key, ConsoleModifiers modifiers) { // default for unprintables and unhandled char keyChar = '\u0000'; // emulate GetKeyboardState bitmap - set high order bit for relevant modifier virtual keys var state = new byte[256]; state[NativeMethods.VK_SHIFT] = (byte)(((modifiers & ConsoleModifiers.Shift) != 0) ? 0x80 : 0); state[NativeMethods.VK_CONTROL] = (byte)(((modifiers & ConsoleModifiers.Control) != 0) ? 0x80 : 0); state[NativeMethods.VK_ALT] = (byte)(((modifiers & ConsoleModifiers.Alt) != 0) ? 0x80 : 0); // a ConsoleKey enum's value is a virtual key code uint virtualKey = (uint)key; // get corresponding scan code uint scanCode = NativeMethods.MapVirtualKey(virtualKey, NativeMethods.MAPVK_VK_TO_VSC); // get corresponding character - maybe be 0, 1 or 2 in length (diacriticals) var chars = new char[2]; int charCount = NativeMethods.ToUnicode( virtualKey, scanCode, state, chars, chars.Length, NativeMethods.MENU_IS_INACTIVE); // TODO: support diacriticals (charCount == 2) if (charCount == 1) { keyChar = chars[0]; } return keyChar; }
public ConsoleKeyInfo (char keyChar, ConsoleKey key, bool shift, bool alt, bool control) { this.key = key; this.keychar = keyChar; modifiers = 0; SetModifiers (shift, alt, control); }
public void ChangeBoard(ConsoleKey moveKey) { _snake.ChangeDirection(moveKey); _snake.MoveSnake (); _snake.CheckForCollision(_apple); ReplaceApple(); }
public void Enqueue(ConsoleKey key) { lock (inputQueue) { inputQueue.Enqueue(new HumanInputItem(new ConsoleKeyInfo('\u0000', key, false, false, false), TimeSpan.Zero, HumanInputItem.NormalDelay)); } }
internal ConsoleKeyInfo (char keyChar, ConsoleKey key, ConsoleModifiers modifiers) { this.keyChar = keyChar; this.key = key; this.modifiers = modifiers; }
public static void OnKeyPressed(ConsoleKey key) { switch (key) { case ConsoleKey.F1: CurrentPage = Page.Connections; return; case ConsoleKey.F2: CurrentPage = Page.Log; return; case ConsoleKey.F3: CurrentPage = Page.Status; return; case ConsoleKey.F4: CurrentPage = Page.GK; return; case ConsoleKey.F5: CurrentPage = Page.Polling; return; case ConsoleKey.F6: CurrentPage = Page.Operations; return; case ConsoleKey.F7: CurrentPage = Page.License; return; case ConsoleKey.LeftArrow: { var index = Pages.Keys.ToList().IndexOf(CurrentPage); if (index > 0) CurrentPage = Pages.Keys.ElementAt(index - 1); return; } case ConsoleKey.RightArrow: { var index = Pages.Keys.ToList().IndexOf(CurrentPage); if (index < Pages.Count - 1) CurrentPage = Pages.Keys.ElementAt(index + 1); return; } default: Pages[CurrentPage].OnKeyPressed(key); return; } }
static void PlayGame() { Dungeon dungeon = new Dungeon(); player.X = dungeon.SpawnPoint[0]; player.Y = dungeon.SpawnPoint[1]; Cell currentRoom; ConsoleKey key = new ConsoleKey(); do { IO.CleanConsole(); //Console.WriteLine(player.X + ", " + player.Y); dungeon.Print(player); currentRoom = dungeon.Cells[player.X, player.Y]; if (IO.PickUp(key)) { player.Loot(currentRoom); } else { if (currentRoom.HasItem) { IO.PlayFoundItem(); currentRoom.Item.WriteFoundItem(); } else { IO.PadLines(2); } } key = Console.ReadKey().Key; player.Move(dungeon, key); } while (player.Health > 0); }
public override void KeysPressed(ConsoleKey _key, EKeyModifiers _modifiers) { if (_modifiers != EKeyModifiers.NONE) return; switch (_key) { case ConsoleKey.Escape: case ConsoleKey.Z: CloseTopBlock(); return; case ConsoleKey.V: MessageManager.SendMessage(this, new OpenUIBlockMessage(new BackpackUiBlock(Rct))); return; } var presenter = m_presenters.SingleOrDefault(_presenter => _presenter.Key == _key); if (presenter != null) { if (presenter.Item == null) { MessageManager.SendMessage(this, new OpenUIBlockMessage(new SelectToTakeOnUiBlock(Rct, this, presenter))); } else { Intelligent.TakeOff(presenter.Place); Rebuild(); } } }
public static Point GetDirection(ConsoleKey _key) { if (!MoveKeys.Contains(_key)) { return null; } var dx = (_key == ConsoleKey.LeftArrow ? -1 : 0) + (_key == ConsoleKey.RightArrow ? 1 : 0); var dy = (_key == ConsoleKey.UpArrow ? -1 : 0) + (_key == ConsoleKey.DownArrow ? 1 : 0); dx += (_key == ConsoleKey.NumPad4 ? -1 : 0) + (_key == ConsoleKey.NumPad6 ? 1 : 0); dx += (_key == ConsoleKey.NumPad7 ? -1 : 0) + (_key == ConsoleKey.NumPad9 ? 1 : 0); dx += (_key == ConsoleKey.NumPad1 ? -1 : 0) + (_key == ConsoleKey.NumPad3 ? 1 : 0); dx += (_key == ConsoleKey.Home ? -1 : 0) + (_key == ConsoleKey.PageUp ? 1 : 0); dx += (_key == ConsoleKey.End ? -1 : 0) + (_key == ConsoleKey.PageDown ? 1 : 0); dy += (_key == ConsoleKey.NumPad8 ? -1 : 0) + (_key == ConsoleKey.NumPad2 ? 1 : 0); dy += (_key == ConsoleKey.NumPad7 ? -1 : 0) + (_key == ConsoleKey.NumPad1 ? 1 : 0); dy += (_key == ConsoleKey.NumPad9 ? -1 : 0) + (_key == ConsoleKey.NumPad3 ? 1 : 0); dy += (_key == ConsoleKey.Home ? -1 : 0) + (_key == ConsoleKey.End ? 1 : 0); dy += (_key == ConsoleKey.PageUp ? -1 : 0) + (_key == ConsoleKey.PageDown ? 1 : 0); return new Point(dx, dy); }
static void AddKey(ConsoleKey key, ConsoleModifiers mod) { if ((int)mod != 0) Console.Write(mod.ToString() + " + "); //Console.WriteLine(key); }
public void HandlKey(ConsoleKey key) { if (key == ConsoleKey.LeftArrow) { direct = Direction.left; } else { if (key == ConsoleKey.RightArrow) { direct = Direction.right; } else { if (key == ConsoleKey.DownArrow) { direct = Direction.down; } else { direct = Direction.up; } } } }
public MenuItem(Sub method, string description) { this.Method = method; this.Description = description; this.Key = ConsoleKey.NoName; }
public override void KeysPressed(ConsoleKey _key, EKeyModifiers _modifiers) { switch (_key) { case ConsoleKey.A: Constants.WORLD_MAP_SIZE = 32; Constants.WORLD_SEED = new Random().Next(10000); //Constants.WORLD_SEED = 2; m_game.Run(); break; case ConsoleKey.B: Constants.WORLD_MAP_SIZE = 100; Constants.WORLD_SEED = new Random().Next(10000); m_game.Run(); break; case ConsoleKey.C: Constants.WORLD_MAP_SIZE = 1; Constants.WORLD_SEED = 1; m_game.Run(); break; case ConsoleKey.D: Constants.WORLD_MAP_SIZE = 1; Constants.WORLD_SEED = 2; m_game.Run(); break; case ConsoleKey.E: Constants.WORLD_MAP_SIZE = 1; Constants.WORLD_SEED = 0; m_game.Run(); break; } }
public void Action(ConsoleKey key) { Console.Clear(); switch (key) { case ConsoleKey.D0: break; case ConsoleKey.D1: break; case ConsoleKey.D2: break; case ConsoleKey.D3: break; case ConsoleKey.D4: break; case ConsoleKey.D5: break; case ConsoleKey.D6: break; case ConsoleKey.D7: break; case ConsoleKey.D8: break; case ConsoleKey.D9: break; default: break; } }
public override void OnKeyPressed(ConsoleKey key) { switch (key) { case ConsoleKey.F8: Console.BackgroundColor = ColorTheme.TextBoxBackgroundColor; Console.ForegroundColor = ColorTheme.TextBoxForegroundColor; Console.SetCursorPosition(_left, _height + _top - 4); for (int i = 0; i < 4; i++) ConsoleHelper.WriteToEnd(_width); EndDraw(); Console.SetCursorPosition(_left, _height + _top - 4); Console.CursorVisible = true; Console.Write("Введите путь к файлу лицензии: "); var path = Console.ReadLine(); Console.CursorVisible = false; var error = LicensePresenter.LoadLicense(path); if (!String.IsNullOrEmpty(error)) { Console.SetCursorPosition(_left, _height + _top - 4); for (int i = 0; i < 4; i++) ConsoleHelper.WriteToEnd(_width); Console.SetCursorPosition(_left, _height + _top - 4); Console.Write(error); EndDraw(); Console.ReadKey(); } Draw(_left, _top, _width, _height); break; } }
static void Main(string[] args) { int curX, curY; //CursorVisible = false; curX = 10; //Starting positions curY = 10; //Starting positions spawnFood(curX, curY); SetCursorPosition(0, 0); Write(new string(snake, 4)); ConsoleKey up = ConsoleKey.UpArrow; ConsoleKey down = ConsoleKey.DownArrow; ConsoleKey left = ConsoleKey.LeftArrow; ConsoleKey right = ConsoleKey.RightArrow; ConsoleKeyInfo cki; while (true) { cki = Console.ReadKey(); if (cki.Key == up || cki.Key == right || cki.Key == down || cki.Key == left) direction = cki.Key; } ReadKey(); }
public void Update(ConsoleKey key) { switch (key) { //This is grim. Needs a better method. case ConsoleKey.W: this._messenger.AddMessage("Up"); Console.SetCursorPosition(this._player.PosX, this._player.PosY); this._map.map2[this._player.PosY, this._player.PosX].Draw(); this._player.Move(Direction.Up); break; case ConsoleKey.A: this._messenger.AddMessage("Left"); Console.SetCursorPosition(this._player.PosX, this._player.PosY); this._map.map2[this._player.PosY, this._player.PosX].Draw(); this._player.Move(Direction.Left); break; case ConsoleKey.S: this._messenger.AddMessage("Down"); Console.SetCursorPosition(this._player.PosX, this._player.PosY); this._map.map2[this._player.PosY, this._player.PosX].Draw(); this._player.Move(Direction.Down); break; case ConsoleKey.D: this._messenger.AddMessage("Right"); Console.SetCursorPosition(this._player.PosX, this._player.PosY); this._map.map2[this._player.PosY, this._player.PosX].Draw(); this._player.Move(Direction.Right); break; default: break; } }
protected override Object SpecialInputs(ConsoleKey cki, EDirection currentDirection, EGameState gameState) { switch (cki) { case ConsoleKey.Escape: if (gameState == EGameState.Running) return gameState == EGameState.Running ? EGameState.Over : EGameState.Running; if (gameState == EGameState.Over || gameState == EGameState.Init) Environment.Exit(0); break; case ConsoleKey.Spacebar: return gameState == EGameState.Running ? EGameState.Paused : EGameState.Running; case ConsoleKey.Q: if (gameState == EGameState.Init) Environment.Exit(0); if (gameState == EGameState.Over) StartupManager.Reset(); break; case ConsoleKey.P: if (gameState == EGameState.Init) return EGameState.Running; break; } if (cki == ConsoleKey.UpArrow && currentDirection != EDirection.South) return EDirection.North; if (cki == ConsoleKey.RightArrow && currentDirection != EDirection.West) return EDirection.East; if (cki == ConsoleKey.DownArrow && currentDirection != EDirection.North) return EDirection.South; if (cki == ConsoleKey.LeftArrow && currentDirection != EDirection.East) return EDirection.West; return cki; }
public void Move(ConsoleKey direction) { this.Clear(); switch (direction) { case ConsoleKey.RightArrow: case ConsoleKey.D: if (this.X < Console.WindowWidth - 4) { this.X++; } break; case ConsoleKey.LeftArrow: case ConsoleKey.A: if (this.X > 0) { this.X--; } break; } this.Print(); }
static void Trigger(ConsoleKey key) { if (key == ConsoleKey.X) HandleX(null, ConsoleKey.X); if (key == ConsoleKey.Spacebar) HandleSpace(null, ConsoleKey.Spacebar); }
public Subscription PushUnmanaged(ConsoleKey key, ConsoleModifiers? modifier, Action<ConsoleKeyInfo> handler) { Dictionary<ConsoleKey, Stack<Action<ConsoleKeyInfo>>> target; if (modifier.HasValue == false) target = nakedHandlers; else if (modifier.Value.HasFlag(ConsoleModifiers.Alt)) target = altHandlers; else if (modifier.Value.HasFlag(ConsoleModifiers.Shift)) target = shiftHandlers; else if (modifier.Value.HasFlag(ConsoleModifiers.Control)) target = controlHandlers; else throw new ArgumentException("Unsupported modifier: "+modifier.Value); Stack<Action<ConsoleKeyInfo>> targetStack; if(target.TryGetValue(key, out targetStack) == false) { targetStack = new Stack<Action<ConsoleKeyInfo>>(); target.Add(key, targetStack); } targetStack.Push(handler); var sub = new Subscription(() => { targetStack.Pop(); if(targetStack.Count == 0) { target.Remove(key); } }); return sub; }
static void WaitForKey (ConsoleKey key) { while (true) { Application.DoEvents(); Thread.Sleep(9); if (Console.KeyAvailable) { if (Console.ReadKey(true).Key==key) { break; } } } }
// Измененение направления змейки в соответствии с нажатиепм кнопки public void HandelKey(ConsoleKey key) { if (key == ConsoleKey.LeftArrow) { if (direction != Direction.RIGHT) { setDirection(Direction.LEFT); } } else if (key == ConsoleKey.RightArrow) { if (direction != Direction.RIGHT) { setDirection(Direction.RIGHT); } } else if (key == ConsoleKey.DownArrow) { if (direction != Direction.UP) { setDirection(Direction.DOWN); } } else if (key == ConsoleKey.UpArrow) { if (direction != Direction.DOWN) { setDirection(Direction.UP); } } }
public override void KeysPressed(ConsoleKey _key, EKeyModifiers _modifiers) { var dPoint = KeyTranslator.GetDirection(_key); if (dPoint != null) { var newPoint = m_targetPoint + dPoint + m_avatarScreenPoint; if (ContentRct.Contains(newPoint)) { m_targetPoint += dPoint; } } switch (_key) { case ConsoleKey.Escape: case ConsoleKey.Z: m_act.IsCancelled = true; CloseTopBlock(); break; case ConsoleKey.Enter: case ConsoleKey.M: if (m_path != null) { m_act.AddParameter(m_path); m_act.AddParameter(int.MaxValue); CloseTopBlock(); } return; } //MessageManager.SendMessage(this, WorldMessage.JustRedraw); }
public ConsoleKeyInfo (char keyChar, ConsoleKey key, bool shift, bool alt, bool control) { _key = key; _keyChar = keyChar; _mods = 0; SetModifiers (shift, alt, control); }
static public bool IsEscape(this ConsoleKey key) => key == ConsoleKey.Escape;
internal Controller() { //Haritaya kullanıcı tarafından çok fazla yol yapılan girilmemesi için denetim. ushort essentialRoadCount = ESSENTIALROADCOUNT; if (ESSENTIALROADCOUNT > Math.Ceiling(MAPSIZEX / 3.0)) { essentialRoadCount = (ushort)Math.Ceiling(MAPSIZEX / 3.0); } if (essentialRoadCount > 9) { essentialRoadCount = 9; } // ushort mapSizeX = MAPSIZEX; if (MAPSIZEX < 3) { mapSizeX = 3; } else if (MAPSIZEX > 40) { mapSizeX = 40; } // ushort mapSizeY = MAPSIZEY; if (MAPSIZEY < 3) { mapSizeY = 3; } else if (MAPSIZEY > 40) { mapSizeY = 40; } //Lokal Değişkenler bool bombVisibility = false; bool userInMap = false; byte gameOver = 0; byte[,] map = new byte[mapSizeX, mapSizeY]; ushort[] userCoordinate = new ushort[2]; short[,] roadEssentialPoints = new short[mapSizeY, essentialRoadCount]; var rand = new Random(); short randomNumber; short score = 0; //Yolların oluşturulması. for (int y = mapSizeY - 1; y >= 0; y--) { for (int essentialRoad = 0; essentialRoad < essentialRoadCount; essentialRoad++) { //İlk esas noktaların bulunması if (y == mapSizeY - 1) { do { randomNumber = (short)rand.Next(0, mapSizeX); }while (IsThereARoadNear(randomNumber, y, map, mapSizeX)); map[randomNumber, y]++; roadEssentialPoints[y, essentialRoad] = randomNumber; } else { //Esas noktanın yöneliminin belirlenmesi if (rand.Next(0, ROADSTRAIGHTNESS + 10) >= 10) { randomNumber = 0; } else { if (roadEssentialPoints[y + 1, essentialRoad] == 0) { randomNumber = (short)rand.Next(minValue: 0, maxValue: 2); } else if (roadEssentialPoints[y + 1, essentialRoad] == mapSizeX - 1) { randomNumber = (short)rand.Next(minValue: -1, maxValue: 1); } else { randomNumber = (short)rand.Next(minValue: -1, maxValue: 2); } } //Yeni esas noktanın belirlenmesi roadEssentialPoints[y, essentialRoad] = (short)(roadEssentialPoints[y + 1, essentialRoad] + randomNumber); //Önceki esas noktayı haritada yol olarak işaretle. map[roadEssentialPoints[y + 1, essentialRoad], y] = 1; //Güncel esas noktayı haritada yol olarak işaretle. map[roadEssentialPoints[y, essentialRoad], y] = 1; } } } //Bombaların oluşturulması randomNumber = (short)rand.Next(0, essentialRoadCount); for (int essentialRoad = 0; essentialRoad < essentialRoadCount; essentialRoad++) { if (randomNumber != essentialRoad) { int yPoint; bool xControl; do { yPoint = rand.Next(0, mapSizeY - 1); xControl = true; int xValue = roadEssentialPoints[yPoint, essentialRoad]; for (int essentialRoad2 = 0; essentialRoad2 < essentialRoadCount; essentialRoad2++) { if (essentialRoad2 != essentialRoad) { if (xValue == roadEssentialPoints[yPoint, essentialRoad2]) { xControl = false; } } } } while (!xControl); map[roadEssentialPoints[yPoint, essentialRoad], yPoint] = 2; } } ushort[] essentialPointsSortID = SortEssentialPoints(roadEssentialPoints, essentialRoadCount, mapSizeY); //Karşılama Ekranı HelpScreen(0); //Oyun Akışı do { Console.Clear(); PrintMap(map, mapSizeX, mapSizeY, roadEssentialPoints, essentialRoadCount, essentialPointsSortID, bombVisibility, userCoordinate, userInMap, ref gameOver, ref score); //PrintEssantialPoints(roadEssentialPoints, essentialRoadCount, cursorLeft: (ushort)(mapSizeX * 2 + 2), cursorTop: 0, mapSizeX); while (!Console.KeyAvailable) { } //Tuşa basılı değilken çalışır. ConsoleKey key = Console.ReadKey(true).Key; if (key == ConsoleKey.Escape) { break; } else if (gameOver == 0) { if (key == ConsoleKey.G) { bombVisibility = !bombVisibility; } else if (userInMap && (key == ConsoleKey.W || key == ConsoleKey.A || key == ConsoleKey.S || key == ConsoleKey.D)) { ActionInMaze(key, map, ref userCoordinate, ref score, ref bombVisibility, mapSizeX, mapSizeY, roadEssentialPoints, essentialRoadCount, essentialPointsSortID, ref userInMap, ref gameOver); } else if (!userInMap && (key == ConsoleKey.D1 || key == ConsoleKey.D2 || key == ConsoleKey.D3 || key == ConsoleKey.D4 || key == ConsoleKey.D5 || key == ConsoleKey.D6 || key == ConsoleKey.D7 || key == ConsoleKey.D8 || key == ConsoleKey.D9)) { SelectRoad(key, ref userCoordinate, ref userInMap, mapSizeX, mapSizeY, map); } } } while (true); }
static int Main(string[] args) { bool Inicialization = true; Student student = new Student(); Console.Write("Enter the nubmer of students in database:"); Student.Size = int.Parse(Console.ReadLine()); Console.Clear(); int Index = 0; while (Inicialization) { try { Console.Write(Index + 1 + ")"); student[Index] = new Student(); student[Index].SetStudentData(); Index++; if (Index == Student.Size) { Inicialization = false; } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("Press Enter to refill correct information"); ConsoleKey choice = Console.ReadKey().Key; { switch (choice) { case ConsoleKey.Enter: Console.Clear(); for (int i = 0; i < Index; i++) { Console.Write(i + 1 + ")"); student[i].GetStudentData(); } continue; default: return(-1); } } } } Console.Clear(); while (true) { student.ShowStudentsSet(); Console.WriteLine("---------------------------------------------------------"); Console.WriteLine("Choose option"); Console.WriteLine("\t1-Show Session reults"); Console.WriteLine("\t2-Show Scholarships"); int ChoosingTheOption = -1; try { ChoosingTheOption = int.Parse(Console.ReadLine()); } catch { Console.WriteLine("Wrong input data format"); } switch (ChoosingTheOption) { case 1: Console.WriteLine("\tSession results:"); for (int i = 0; i < Student.Size; i++) { University.Session(student[i]); } break; case 2: Console.WriteLine("\tScholarships:"); for (int i = 0; i < Student.Size; i++) { University.CalculatingScholarships(student[i]); } break; default: Console.WriteLine("Wrong option..."); System.Threading.Thread.Sleep(1000); Console.Clear(); continue; } Console.WriteLine("Press Enter to choose new option"); ConsoleKey choice = Console.ReadKey().Key; { switch (choice) { case ConsoleKey.Enter: Console.Clear(); continue; default: return(0); } } } }
/// <summary> /// Makes the move based on the player's <see cref="choice"/> . /// </summary> /// <param name="choice">Player's choice.</param> public bool Movement() { ConsoleKey choice = ConsoleKey.NoName; while (choice != ConsoleKey.W && choice != ConsoleKey.A && choice != ConsoleKey.S && choice != ConsoleKey.D && choice != ConsoleKey.UpArrow && choice != ConsoleKey.DownArrow && choice != ConsoleKey.LeftArrow && choice != ConsoleKey.RightArrow && choice != ConsoleKey.Escape) { choice = Console.ReadKey(true).Key; } switch (choice) { //Goes up //Checks if there are any bosses, minions or blocks around case ConsoleKey.W: case ConsoleKey.UpArrow: // Moves the player very move takes 1 Hp CheckIfPlayerCanMove( new Position(Position.Row, Position.Col - 1)); break; //Goes left //Checks if there are any bosses, minions or blocks around case ConsoleKey.A: case ConsoleKey.LeftArrow: // Moves the player very move takes 1 Hp CheckIfPlayerCanMove( new Position(Position.Row - 1, Position.Col)); break; //Goes down //Checks if there are any bosses, minions or blocks around case ConsoleKey.S: case ConsoleKey.DownArrow: // Moves the player very move takes 1 Hp CheckIfPlayerCanMove( new Position(Position.Row, Position.Col + 1)); break; //Goes right //Checks if there are any bosses, minions or blocks around case ConsoleKey.D: case ConsoleKey.RightArrow: // Moves the player very move takes 1 Hp CheckIfPlayerCanMove( new Position(Position.Row + 1, Position.Col)); break; case ConsoleKey.Escape: return(true); //If he doesn't chose any legal choices. default: break; } return(false); }
private void KeyCommands(ConsoleKey key) { switch (key) { case ConsoleKey.UpArrow: if (MyCursor.GetCords()[0] == 0) { MyCursor.SetX(Rooms.GetLength(0) - 1); refresh = true; } else if (Rooms[MyCursor.GetX() - 1, MyCursor.GetY()] != null) { MyCursor.SetX(MyCursor.GetX() - 1); refresh = true; } MyCursor.SetCurrentRoom(Rooms[MyCursor.GetX(), MyCursor.GetY()]); break; case ConsoleKey.DownArrow: if (MyCursor.GetCords()[0] == (Rooms.GetLength(0) - 1)) { MyCursor.SetX(0); refresh = true; } else if (Rooms[MyCursor.GetX() + 1, MyCursor.GetY()] != null) { MyCursor.SetX(MyCursor.GetX() + 1); refresh = true; } MyCursor.SetCurrentRoom(Rooms[MyCursor.GetX(), MyCursor.GetY()]); break; case ConsoleKey.RightArrow: if (MyCursor.GetCords()[1] == (Rooms.GetLength(1) - 1)) { MyCursor.SetY(Rooms.GetLength(1) - 1); refresh = true; } else if (Rooms[MyCursor.GetX(), MyCursor.GetY() + 1] != null) { MyCursor.SetY(MyCursor.GetY() + 1); refresh = true; } MyCursor.SetCurrentRoom(Rooms[MyCursor.GetX(), MyCursor.GetY()]); break; case ConsoleKey.LeftArrow: if (MyCursor.GetCords()[1] == 0) { MyCursor.SetY(Rooms.GetLength(0) - 1); refresh = true; } else if (Rooms[MyCursor.GetX(), MyCursor.GetY() - 1] != null) { MyCursor.SetY(MyCursor.GetY() - 1); refresh = true; } MyCursor.SetCurrentRoom(Rooms[MyCursor.GetX(), MyCursor.GetY()]); break; } if (refresh) { Console.Clear(); DrawArray(); refresh = false; } }
public void ActionInMaze(ConsoleKey key, byte[,] map, ref ushort[] userCoordinate, ref short score, ref bool bombVisibility, int sizeX, int sizeY, short[,] essentialPoints, ushort essentialRoadCount, ushort[] essentialSortID, ref bool userInMap, ref byte gameOver) { byte destination; switch (key) { case ConsoleKey.W: if (userCoordinate[1] > 0) { destination = map[userCoordinate[0], userCoordinate[1] - 1]; if (destination == 1) { if (userCoordinate[1] > 1) { WalkInMaze(direction.Forward, ref score, ref userCoordinate); } else { userCoordinate[1]--; bombVisibility = true; gameOver = 2; } } else if (destination == 0) { score--; } else if (destination == 2) { bombVisibility = true; gameOver = 1; } } break; case ConsoleKey.A: if (userCoordinate[0] > 0) { destination = map[userCoordinate[0] - 1, userCoordinate[1]]; if (destination == 1) { WalkInMaze(direction.Left, ref score, ref userCoordinate); } else if (destination == 0) { score--; } else if (destination == 2) { bombVisibility = true; gameOver = 1; } } break; case ConsoleKey.S: if (userCoordinate[1] < sizeY - 1) { destination = map[userCoordinate[0], userCoordinate[1] + 1]; if (destination == 1) { WalkInMaze(direction.Bacward, ref score, ref userCoordinate); } else if (destination == 0) { score--; } else if (destination == 2) { bombVisibility = true; gameOver = 1; } } else { userInMap = false; //Yol değştir. } break; case ConsoleKey.D: if (userCoordinate[0] < sizeX - 1) { destination = map[userCoordinate[0] + 1, userCoordinate[1]]; if (destination == 1) { WalkInMaze(direction.Right, ref score, ref userCoordinate); } else if (destination == 0) { score--; } else if (destination == 2) { bombVisibility = true; gameOver = 1; } } break; default: break; } }
public PlayButton(string text, ConsoleKey consoleKey) : base(text, consoleKey) { }
public static void Start() { score = 0; count = 0; lose = false; direction = EDirection.none; x = new int[] { Console.WindowWidth / 2 }; y = new int[] { Console.WindowHeight / 2 }; do { // GameLoop { // Read the key ConsoleKey key = Console.ReadKey().Key; // Set the direction if (key == ConsoleKey.UpArrow) { direction = EDirection.up; } else if (key == ConsoleKey.DownArrow) { direction = EDirection.down; } else if (key == ConsoleKey.LeftArrow) { direction = EDirection.left; } else if (key == ConsoleKey.RightArrow) { direction = EDirection.right; } // Up if (direction == EDirection.up) { y[y.Length] = y[y.Length - 1] - 1; if (y[y.Length - 1] == 0) { lose = true; } } // Down else if (direction == EDirection.down) { y[y.Length] = y[y.Length - 1] + 1; if (y[y.Length - 1] == Console.WindowHeight) { lose = true; } } // Left else if (direction == EDirection.left) { x[x.Length] = x[x.Length - 1] - 1; if (x[x.Length - 1] == 0) { lose = true; } } // Right else if (direction == EDirection.right) { x[x.Length] = x[x.Length - 1] + 1; if (x[x.Length - 1] == Console.WindowWidth) { lose = true; } } // Clear screen Console.Clear(); // Draw X positions foreach (int posx in x) { Console.CursorLeft = posx; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("#"); Console.ForegroundColor = ConsoleColor.White; } // Draw Y position foreach (int posy in y) { Console.CursorTop = posy; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("#"); Console.ForegroundColor = ConsoleColor.White; } // Check if count is >= 8 if (count >= 8) { // Remove first X pos x[count] = 0; // Remove first Y pos y[count] = 0; } // Increment count if (direction != EDirection.none) { count++; } // Increment score if (direction != EDirection.none) { score += 2; } } }while (!lose); Console.Clear(); Console.CursorTop = (Console.WindowWidth / 2) - 2; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("YOU LOSE!"); Console.ForegroundColor = ConsoleColor.White; Console.CursorTop++; Console.WriteLine("Your score: " + score.ToString()); }
} // 0x0000000180022C20-0x0000000180022C30 // Constructors public ConsoleKeyInfo(char keyChar, ConsoleKey key, bool shift, bool alt, bool control) : this() { _keyChar = default; _key = default; _mods = default; } // 0x000000018002FE80-0x0000000180030310
//const int Max = 240; //const int Min = 20; static void Main(string[] args) { string[] Ports = SerialPort.GetPortNames(); Console.WriteLine("Avalible Ports:"); foreach (string Port in Ports) { Console.WriteLine(Port); } int PortSelect = 0; bool success = false; do { Console.WriteLine("Please Select a valid port."); success = int.TryParse(Console.ReadLine(), out PortSelect); }while (!(success && PortSelect <= Ports.Count() && PortSelect > 0)); JMDM_PortControl ChairPort = new JMDM_PortControl(); Console.WriteLine("Hello to angelo's Chair Test program.\nPlease use the arrow keys.\nPress up to put chair up.\nPress down to put chair down.\nPress right to put the chair on a right tilt.\nPress left to put the chair on a left tilt.\nAdditionaly, Press R to reset and E to exit."); ChairPort.Open_Port(SerialPort.GetPortNames()[PortSelect]); ChairPort.Reset_Zerp(); Thread.Sleep(2000); ConsoleKey Key = Console.ReadKey().Key; while (Key != ConsoleKey.E) { switch (Key) { case ConsoleKey.UpArrow: ChairPort.Send_Data(1, Max); ChairPort.Send_Data(2, Max); ChairPort.Send_Data(3, Max); break; case ConsoleKey.DownArrow: ChairPort.Send_Data(1, Min); ChairPort.Send_Data(2, Min); ChairPort.Send_Data(3, Min); break; case ConsoleKey.LeftArrow: ChairPort.Send_Data(1, Min); ChairPort.Send_Data(2, Max); ChairPort.Send_Data(3, 175); break; case ConsoleKey.RightArrow: ChairPort.Send_Data(2, Min); ChairPort.Send_Data(1, Max); ChairPort.Send_Data(3, 175); break; case ConsoleKey.W: //ChairPort.Rotate_Control(250); ChairPort.Send_Data(0, Max); ChairPort.Send_Data(4, Max); ChairPort.Send_Data(5, Max); ChairPort.Send_Data(6, Max); break; case ConsoleKey.Q: //ChairPort.Rotate_Control(10); ChairPort.Send_Data(0, Min); ChairPort.Send_Data(4, Min); ChairPort.Send_Data(5, Min); ChairPort.Send_Data(6, Min); break; case ConsoleKey.R: ChairPort.Reset_Zerp(); break; case ConsoleKey.C: Loop(ChairPort); break; case ConsoleKey.Z: WildLoop(ChairPort); break; case ConsoleKey.X: SandBoxTilt2U(ChairPort, 1); break; } Key = Console.ReadKey().Key; } ChairPort.Close_Port(); }
private static int CheckKey(ConsoleKey key) { switch (key) { case ConsoleKey.D0: return(0); case ConsoleKey.D1: return(1); case ConsoleKey.D2: return(2); case ConsoleKey.D3: return(3); case ConsoleKey.D4: return(4); case ConsoleKey.D5: return(5); case ConsoleKey.D6: return(6); case ConsoleKey.D7: return(7); case ConsoleKey.D8: return(8); case ConsoleKey.D9: return(9); case ConsoleKey.NumPad0: return(0); case ConsoleKey.NumPad1: return(1); case ConsoleKey.NumPad2: return(2); case ConsoleKey.NumPad3: return(3); case ConsoleKey.NumPad4: return(4); case ConsoleKey.NumPad5: return(5); case ConsoleKey.NumPad6: return(6); case ConsoleKey.NumPad7: return(7); case ConsoleKey.NumPad8: return(8); case ConsoleKey.NumPad9: return(9); case ConsoleKey.Enter: return(13); case ConsoleKey.Backspace: return(18); case ConsoleKey.OemMinus: return(17); default: return(10); } }
static void Main(string[] args) { // Setup DI Service Collection ServiceCollection serviceCollection = new ServiceCollection(); IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("config.json", optional: false, reloadOnChange: true).Build(); ConfigureServices(serviceCollection, configuration); // Setup DI Service Provider var serviceProvider = serviceCollection.BuildServiceProvider(); // Instanciate services for Program Main method use var _loggerService = serviceProvider.GetService <ILogger <Program> >(); var _userService = serviceProvider.GetService <UserService>(); #region - PROGRAM - Console.WriteLine("-- COVID19 TRACKER --"); ConsoleKey commandKey = ConsoleKey.H; while (!Console.KeyAvailable) { if (commandKey == ConsoleKey.Spacebar) { break; } else if (commandKey == ConsoleKey.H) // Help { Console.WriteLine(); Console.WriteLine("\n## Help \n"); Console.WriteLine("> quit app : [spacebar]"); Console.WriteLine("> print help : [h]"); Console.WriteLine("> pull all users : [u]"); Console.WriteLine("> pull all matches : [m]"); Console.WriteLine("> pull all alerts : [a]"); Console.WriteLine("> subscribe : [s]"); Console.WriteLine("> unsubscribe : [x]"); Console.WriteLine("> push match : [p]"); Console.WriteLine("> pull match : [g]"); Console.WriteLine("> push alert : [e]"); Console.WriteLine("> remove alert : [c]"); Console.WriteLine("> pull alerts : [z]"); Console.WriteLine("> pull infections : [i]"); } else if (commandKey == ConsoleKey.U) // All Users { var result = _userService.AdminPullUsers(); if (result.Exception == null) { Console.WriteLine("\n"); if (result.Value.Count <= 0) { Console.WriteLine("No user found."); } foreach (var user in result.Value) { Console.WriteLine($" - { user.Key }"); } } else { Console.WriteLine($"\nUnable to list users. Error : { result.Exception.Message }"); } } else if (commandKey == ConsoleKey.M) // All matches { var result = _userService.AdminPullMatches(); if (result.Exception == null) { Console.WriteLine("\n"); if (result.Value.Count <= 0) { Console.WriteLine("No match found."); } foreach (var match in result.Value) { Console.WriteLine($" - { match.When }, { match.UserX.Key } matched with { match.UserY.Key }"); } } else { Console.WriteLine($"\nUnable to list matches. Error : { result.Exception.Message }"); } } else if (commandKey == ConsoleKey.A) // All alerts { var result = _userService.AdminPullAlerts(); if (result.Exception == null) { Console.WriteLine("\n"); if (result.Value.Count <= 0) { Console.WriteLine("No alert found."); } foreach (var alert in result.Value) { Console.WriteLine($" - { alert.When }, emitted by { alert.User.Key }"); } } else { Console.WriteLine($"\nUnable to list alerts. Error : { result.Exception.Message }"); } } else if (commandKey == ConsoleKey.S) // Subscribe { var result = _userService.Subscribe(); if (result.Exception == null) { Console.WriteLine(); Console.WriteLine(); Console.WriteLine($" - User Key: { result.Value.Key }"); } else { Console.WriteLine($"\nSubscription failed. Error : { result.Exception.Message }"); } } else if (commandKey == ConsoleKey.X) // Unsubscribe { Console.WriteLine("Your Key: "); string key = Console.ReadLine(); var result = _userService.Unsubcribe(key); if (result.Exception == null) { Console.WriteLine($"\nSuccessfully unsubscribed."); } else { Console.WriteLine($"\nUnsubscription failed. Error : { result.Exception.Message }"); } } else if (commandKey == ConsoleKey.P) // Push match { Console.WriteLine("Your Key: "); string userKey = Console.ReadLine(); Console.WriteLine("Matched Key: "); string matchedKey = Console.ReadLine(); var result = _userService.PushMatch(userKey, matchedKey, DateTime.Now); if (result.Exception == null) { Console.WriteLine($"\nMatch successfully pushed !"); } else { Console.WriteLine($"\nPushing match failed. Error : { result.Exception.Message }"); } } else if (commandKey == ConsoleKey.G) // Pull match { Console.WriteLine("Your Key: "); string key = Console.ReadLine(); var result = _userService.PullMatches(key); if (result.Exception == null) { Console.WriteLine(); if (result.Value.Count <= 0) { Console.WriteLine("No match found."); } foreach (var match in result.Value) { if (match.UserX.Key.ToString() == key) { // You matched with someone Console.WriteLine($" - { match.When }, You matched with { match.UserY.Key }"); } else { // Someone matched with you Console.WriteLine($" - { match.When }, You matched with { match.UserX.Key }"); } } } else { Console.WriteLine($"\nPulling matches failed. Error : { result.Exception.Message }"); } } else if (commandKey == ConsoleKey.E) // Push alert { Console.WriteLine("Your Key: "); string key = Console.ReadLine(); var result = _userService.PushAlert(key, DateTime.Now); if (result.Exception == null) { Console.WriteLine("\nAlert successfully emitted"); } else { Console.WriteLine($"\nFailed to emit alert. Error : { result.Exception.Message }"); } } else if (commandKey == ConsoleKey.C) // Remove alert { Console.WriteLine("Your Key: "); string key = Console.ReadLine(); var result = _userService.RemoveAlert(key); if (result.Exception == null) { Console.WriteLine("\nAlert successfully pushed"); } else { Console.WriteLine($"\nFailed to push alert. Error : { result.Exception.Message }"); } } else if (commandKey == ConsoleKey.Z) // User alert { Console.WriteLine("Your Key: "); string key = Console.ReadLine(); var result = _userService.PullAlerts(key); if (result.Exception == null) { Console.WriteLine(); if (result.Value.Count <= 0) { Console.WriteLine("No alert found."); } foreach (var alert in result.Value) { Console.WriteLine($" - Active alert, emitted: { alert.When }"); } } else { Console.WriteLine($"\nFailed to get user alert. Error : { result.Exception.Message }"); } } else if (commandKey == ConsoleKey.I) // Infection alerts { Console.WriteLine("Your Key: "); string key = Console.ReadLine(); Console.WriteLine("\nIncubation days: "); int incubation; if (int.TryParse(Console.ReadLine(), out incubation)) { var result = _userService.PullInfections(key, incubation); if (result.Exception == null) { if (result.Value.Count > 0) { Console.WriteLine(); foreach (var infectionDate in result.Value) { Console.WriteLine($" - You've crossed someone infected: { infectionDate }"); } Console.WriteLine("\nIt would be safer to contact a doctor as soon as possible."); } else { Console.WriteLine($"It seams you've not crossed someone else at risk last { incubation } days"); } } else { Console.WriteLine($"\nFailed to pull desease alerts. Error : { result.Exception.Message }"); } } else { Console.WriteLine($"Invalid incubation days value"); } } else { Console.WriteLine("\nUnknown command."); } Console.Write("\nChoose a command: "); commandKey = Console.ReadKey(true).Key; } #endregion }
static void Main(string[] args) { int sel; int getAnswer = 0; Telas tela; ConsoleKey k = ConsoleKey.F24; Tarefas ts = new Tarefas(); Prompt p = new Prompt(ts); Tarefa t = new Tarefa(); Console.CursorSize = 4; Console.Title = "ilucTask 1.0"; ts.orderBy(0, 4); //0 ordena pela prioridade, e 4 ordena pela Data sel = 0; tela = Telas.Tabela; do { switch (tela) { case Telas.Tabela: Console.CursorVisible = false; Console.SetCursorPosition(0, 0); //Console.Clear(); p.DrwHeader(); p.DrwTasks(sel); k = Console.ReadKey().Key; switch (k) { case ConsoleKey.UpArrow: if (sel > 0) { sel--; } break; case ConsoleKey.DownArrow: if (sel < ts.getTaskCount() - 1) { sel++; } break; case ConsoleKey.RightArrow: t = ts.getTask(sel); if (t.Status < 100) { t.Status = t.Status + 10; } ts.updateTask(t, sel); if (t.Status == 100) { Console.SetCursorPosition(0, 0); ts.orderBy(0, 4); //0 ordena pela prioridade, e 4 ordena pela Data p.DrwHeader(); p.DrwTasks(sel); } break; case ConsoleKey.LeftArrow: t = ts.getTask(sel); if (t.Status >= 10) { t.Status = t.Status - 10; } ts.updateTask(t, sel); break; case ConsoleKey.E: case ConsoleKey.Enter: t = ts.getTask(sel); tela = Telas.Edit; //campo = 0; Console.Clear(); Console.CursorVisible = true; p.DrwEdit(t); break; case ConsoleKey.A: //t = null; t = new Tarefa(); tela = Telas.Add; //campo = 0; Console.Clear(); Console.CursorVisible = true; p.DrwAdd(t); break; case ConsoleKey.Delete: Console.Clear(); ts.deleteTask(sel); break; } break; case Telas.Edit: getAnswer = p.GetKey(Console.ReadKey(true)); if (getAnswer == 0) { tela = Telas.Tabela; ts.orderBy(0, 4); //0 ordena pela prioridade, e 4 ordena pela Data } else if (getAnswer == 0) { } break; case Telas.Add: getAnswer = p.GetKey(Console.ReadKey(true)); if (getAnswer == 0) { tela = Telas.Tabela; ts.addTask(t); ts.orderBy(0, 4); //0 ordena pela prioridade, e 4 ordena pela Data } else if (getAnswer == 0) { } //Console.Clear(); //p.DrwAdd(); /*switch (campo) * { * case 0: * Console.CursorVisible = true; * Console.SetCursorPosition(13, campo); * string str = Console.ReadLine(); * int priori = Convert.ToInt32(str); * if (priori == 0 || priori > 4) * priori = 3; * t.Prioridade = priori; * campo++; * break; * * case 1: * Console.SetCursorPosition(13, campo); * t.Projeto = Console.ReadLine(); * campo++; * break; * * case 2: * Console.SetCursorPosition(13, campo); * t.Titulo = Console.ReadLine(); * campo++; * break; * * case 3: * Console.SetCursorPosition(13, campo); * t.Usuario = Console.ReadLine(); * campo++; * break; * * case 4: * Console.SetCursorPosition(13, campo); * t.Data = Console.ReadLine(); * campo++; * break; * * case 5: * Console.SetCursorPosition(13, campo); * t.Descricao = Console.ReadLine(); * campo++; * break; * * case 6: * t.Status = 0; * tela = Telas.Tabela; * ts.addTask(t); * break; * * }*/ break; } } while (k != ConsoleKey.Q && k != ConsoleKey.Escape); ts.save(); }
public virtual void Edit() { Show(); var fgc = Console.ForegroundColor; var bgc = Console.BackgroundColor; var x = 0; var y = 0; var currentline = Console.CursorTop; Console.CursorVisible = false; while (Console.KeyAvailable) { Console.ReadKey(); } for (; ;) { Console.SetCursorPosition(x * 4, currentline - height + y); Console.BackgroundColor = fgc; Console.ForegroundColor = bgc; Console.Write("{0,4}", mat[x, y]); Console.ResetColor(); Console.SetCursorPosition(0, currentline); ConsoleKey key = Console.ReadKey(true).Key; Console.SetCursorPosition(x * 4, currentline - height + y); Console.Write("{0,4}", mat[x, y]); Console.SetCursorPosition(0, currentline); switch (key) { case ConsoleKey.Enter: goto Exit; case ConsoleKey.LeftArrow: if (x > 0) { x--; } break; case ConsoleKey.UpArrow: if (y > 0) { y--; } break; case ConsoleKey.RightArrow: if (x < width - 1) { x++; } break; case ConsoleKey.DownArrow: if (y < height - 1) { y++; } break; case ConsoleKey.D0: case ConsoleKey.D1: case ConsoleKey.D2: case ConsoleKey.D3: case ConsoleKey.D4: case ConsoleKey.D5: case ConsoleKey.D6: case ConsoleKey.D7: case ConsoleKey.D8: case ConsoleKey.D9: if (mat[x, y] < 0) { mat[x, y] = -mat[x, y]; } mat[x, y] = (mat[x, y] % 10 * 10) + (key - ConsoleKey.D0); break; case ConsoleKey.NumPad0: case ConsoleKey.NumPad1: case ConsoleKey.NumPad2: case ConsoleKey.NumPad3: case ConsoleKey.NumPad4: case ConsoleKey.NumPad5: case ConsoleKey.NumPad6: case ConsoleKey.NumPad7: case ConsoleKey.NumPad8: case ConsoleKey.NumPad9: if (mat[x, y] < 0) { mat[x, y] = -mat[x, y]; } mat[x, y] = (mat[x, y] % 10 * 10) + (key - ConsoleKey.NumPad0); break; case ConsoleKey.OemMinus: case ConsoleKey.Subtract: mat[x, y] = -mat[x, y]; break; default: break; } } Exit: Console.CursorVisible = true; }
static void Main(string[] args) { Bezoeker nieuweBezoeker = new Bezoeker(); //nieuweItemCollectieBeb = new CollectieBeb(); Item testNieuwItem = new Item(); testNieuwItem.soorItem = SoortItem.Boek; testNieuwItem.ItemId = 1; testNieuwItem.Titel = "De GVR"; testNieuwItem.Auteur = "Shaquille O'neil"; testNieuwItem.Jaartal = 2000; testNieuwItem.Uitgeleend = true; testNieuwItem.Afgevoerd = false; Item nieuwItem002 = new Item(); nieuwItem002.soorItem = SoortItem.DVD; nieuwItem002.ItemId = 2; nieuwItem002.Titel = "The Last Dance"; nieuwItem002.Auteur = "Michael Jordan"; nieuwItem002.Jaartal = 1995; nieuwItem002.Uitgeleend = false; nieuwItem002.Afgevoerd = false; // KEUZE MENU Console.WriteLine("Hallo en welkom in onze vernieuwde Bibliotheek-console\n" + "Hoe wilt u zich aanmelden:\nA)LID\nB)MEDEWERKER\nC)BEZOEKER"); ConsoleKey instructionKey = Console.ReadKey().Key; Console.Clear(); switch (instructionKey) { // SWITCH CASE LIDMENU case ConsoleKey.A: Console.WriteLine("A)LID:\n"); break; // SWITCH CASE MEDEWERKERMENU case ConsoleKey.B: Console.WriteLine("B)MEDEWERKER:\n"); break; // SWITCH CASE BEZOEKERMENU case ConsoleKey.C: break; //Console.WriteLine("C)BEZOEKER:\n"); Console.WriteLine("Geef je familienaam:"); nieuweBezoeker.FamilieNaam = Console.ReadLine(); Console.WriteLine("\nGeef je voornaam:"); nieuweBezoeker.Voornaam = Console.ReadLine(); Console.Clear(); Console.WriteLine(nieuweBezoeker.Voornaam); Console.WriteLine("Wat wil je doen:\n" + "A-->Registreer als Lid\n" + "B-->Zoek een Item op Titel of op item Id\n" + "C-->Toon overzichten"); ConsoleKey instructionKeyBezoeker = Console.ReadKey().Key; Console.Clear(); switch (instructionKeyBezoeker) { case ConsoleKey.A: case ConsoleKey.B: Console.WriteLine("B)Zoek een Item op titel of ItemId\n"); break; case ConsoleKey.C: Console.WriteLine("C)Toon overzichten\n"); break; } } Console.ReadLine(); }
private void PlayHandler() { Mutex mutex = new Mutex(); Render.RenderStatisticInfo("Start"); string message = ""; while (runGame) { ConsoleKey key = Console.ReadKey(true).Key; if (key == ConsoleKey.DownArrow) { if (startPosition == StartPosition.Left) { if (posLeftRacket < 22) { mutex.WaitOne(); posLeftRacket++; mutex.ReleaseMutex(); } } else { if (posRightRacket < 23) { mutex.WaitOne(); posRightRacket++; mutex.ReleaseMutex(); } } } else if (key == ConsoleKey.UpArrow) { if (startPosition == StartPosition.Left) { if (posLeftRacket > 1) { mutex.WaitOne(); posLeftRacket--; mutex.ReleaseMutex(); } } else { if (posRightRacket > 1) { mutex.WaitOne(); posRightRacket--; mutex.ReleaseMutex(); } } } else if (isChar(key)) { if (message.Length < 60) { message += key.ToString(); mutex.WaitOne(); Render.RenderSendMessage(key); mutex.ReleaseMutex(); } } else if (key == ConsoleKey.Spacebar) { if (message.Length < 60) { message += " "; mutex.WaitOne(); Render.RenderSendMessage(" "); mutex.ReleaseMutex(); } } else if (key == ConsoleKey.Enter) { if (message.Length > 0) { chat.AddMsg(selfNick, message); chatSocket.Send(Encoding.Default.GetBytes(message)); message = ""; mutex.WaitOne(); Render.RenderEnter(); Render.RenderChat(chat); mutex.ReleaseMutex(); } } else if (key == ConsoleKey.Backspace) { if (message.Length > 1) { message = message.Substring(0, message.Length - 1); mutex.WaitOne(); Render.RenderBackspace(); mutex.ReleaseMutex(); } } } if (scoreLeft == 5) { Render.RenderStatisticInfo("Left win"); } else if (scoreRight == 5) { Render.RenderStatisticInfo("Right win"); } Render.RenderStatisticInfo("Finish the game"); }
public void KeyUpFromJS1(int e) { if (Game.Is_Enabled) { if (!Game.Is_Bot_Mode) { ConsoleKey consoleKey = (ConsoleKey)Enum.Parse(typeof(ConsoleKey), e.ToString()); switch (consoleKey) { case ConsoleKey.DownArrow: if (LocalData.Curr_Direction != DirectionType.Up) { LocalData.Curr_Direction = DirectionType.Down; } if (!Game.Is_Started) { Game.start(); } break; case ConsoleKey.RightArrow: if (LocalData.Curr_Direction != DirectionType.Left) { LocalData.Curr_Direction = DirectionType.Right; } if (!Game.Is_Started) { Game.start(); } break; case ConsoleKey.UpArrow: if (LocalData.Curr_Direction != DirectionType.Down) { LocalData.Curr_Direction = DirectionType.Up; } if (!Game.Is_Started) { Game.start(); } break; case ConsoleKey.LeftArrow: if (LocalData.Curr_Direction != DirectionType.Right) { LocalData.Curr_Direction = DirectionType.Left; } if (!Game.Is_Started) { Game.start(); } break; default: break; } } } }
public static void PauseGame() { Console.ReadKey(true); key = ConsoleKey.Enter; }
static void EditMatrix(MyMatrix <int> matrix) { ShowMatrix(matrix); var fgc = Console.ForegroundColor; var bgc = Console.BackgroundColor; var x = 0; var y = 0; var currentline = Console.CursorTop; // Запам'ятати номер рядка в консолі. Console.CursorVisible = false; // Приховати курсор, щоб не заважав. while (Console.KeyAvailable) { Console.ReadKey(); // Очистити буфер вводу. } for (; ;) { // Оновити та підсвітити елемент матриці. Console.SetCursorPosition(x * 4, currentline - matrix.Height + y); Console.BackgroundColor = fgc; Console.ForegroundColor = bgc; Console.Write("{0,4}", matrix[x, y]); // Скинути стан курсора на випадок, якщо програму буде примусово закрито. Console.ResetColor(); Console.SetCursorPosition(0, currentline); ConsoleKey key = Console.ReadKey(true).Key; // Прибрати підсвітку елемента. Console.SetCursorPosition(x * 4, currentline - matrix.Height + y); Console.Write("{0,4}", matrix[x, y]); Console.SetCursorPosition(0, currentline); switch (key) { case ConsoleKey.Enter: goto Exit; // Вийти з нескінченого циклу for(;;). case ConsoleKey.LeftArrow: // Перемістити курсор вліво. if (x > 0) { x--; } break; case ConsoleKey.UpArrow: // Перемістити курсор вверх. if (y > 0) { y--; } break; case ConsoleKey.RightArrow: // Перемістити курсор вправо. if (x < matrix.Width - 1) { x++; } break; case ConsoleKey.DownArrow: // Перемістити курсор вниз. if (y < matrix.Height - 1) { y++; } break; case ConsoleKey.D0: case ConsoleKey.D1: case ConsoleKey.D2: case ConsoleKey.D3: case ConsoleKey.D4: case ConsoleKey.D5: case ConsoleKey.D6: case ConsoleKey.D7: case ConsoleKey.D8: case ConsoleKey.D9: // Якщо ввести цифру, мінус губиться. if (matrix[x, y] < 0) { matrix[x, y] = -matrix[x, y]; } matrix[x, y] = (matrix[x, y] % 10 * 10) + (key - ConsoleKey.D0); break; case ConsoleKey.NumPad0: case ConsoleKey.NumPad1: case ConsoleKey.NumPad2: case ConsoleKey.NumPad3: case ConsoleKey.NumPad4: case ConsoleKey.NumPad5: case ConsoleKey.NumPad6: case ConsoleKey.NumPad7: case ConsoleKey.NumPad8: case ConsoleKey.NumPad9: // Якщо ввести цифру, мінус губиться. if (matrix[x, y] < 0) { matrix[x, y] = -matrix[x, y]; } matrix[x, y] = (matrix[x, y] % 10 * 10) + (key - ConsoleKey.NumPad0); break; case ConsoleKey.OemMinus: case ConsoleKey.Subtract: // Переключити мінус. matrix[x, y] = -matrix[x, y]; break; default: break; } } Exit: Console.CursorVisible = true; // Показати курсор. }
/// <summary> /// Delete a person /// isEdit is true when updating a row, ie delete the old and replace with the new /// </summary> /// <param name="isEdit"></param> public void DeletePerson(bool isEdit = false) { // the Id will only be -1 if no id has been found (invalid id) by the GetId method if (Globals.Person.Id != -1) { // Variables bool personFound = false; bool invalidResponse = false; string file = String.Empty; List <string> list = new List <string>(); //try get the lines from the correct csv file try { //player if (Globals.UserInput.RawTextArr[1][1] == 'p') { file = Globals.Auth.Dir + Constants.PLAYER_CSV_FILE; list = File.ReadLines(file).ToList(); } //staff else if (Globals.UserInput.RawTextArr[1][1] == 's') { file = Globals.Auth.Dir + Constants.STAFF_CSV_FILE; list = File.ReadLines(file).ToList(); } else { Console.WriteLine(Constants.SYNTAX_ERROR); } } catch (Exception ex) { Console.WriteLine(ex.Message); } //step through each line looking for the matching Id for (int i = 0; i < list.Count; i++) { if (list[i].Split(',')[0].Equals(Globals.Person.Id.ToString())) { personFound = true; //Delete if (!isEdit) { do { //Confirm deletion Console.WriteLine("Delete {0}? (Y/N)", list[i].Split(',')[1]); ConsoleKey key = Console.ReadKey().Key; if (key == ConsoleKey.Y) { //Do deletion list.RemoveAt(i); try { File.WriteAllLines(file, list); //Display feedback Console.WriteLine(Constants.DELETE_SUCCESSFUL_FEEDBACK); } catch (Exception ex) { Console.WriteLine(ex.Message); } } else if (key == ConsoleKey.N) { //abort deletion and display feedback Console.WriteLine(Constants.DELETE_ABORT_FEEDBACK); } else { invalidResponse = true; Console.WriteLine(Constants.INVALID_RESPONSE_ERROR); } //exit the for loop i = list.Count; //Keep prompting user until valid key pressed } while (invalidResponse); } //delete for updating else { list.RemoveAt(i); try { File.WriteAllLines(file, list); } catch (Exception ex) { Console.WriteLine(ex.Message); } i = list.Count; } } } // if no person found, display feedback if (!personFound) { Console.WriteLine(Constants.NO_MATCH_FEEBACK); } } //Invalid Id else { Console.WriteLine(Constants.INVALID_ID_ERROR); } }
public virtual void TakeTurn(Board board) { Console.WriteLine($"{DisplayName} [${Money} | {OwnedTiles.Count} properties | {MortgagedTiles.Count} mortgaged]."); if (boardLocation == board.GetSpecialTile(SpecialTileType.Jail).BoardPosition&& JailTurnRemaining > 0) // In jail { Console.WriteLine($"{DisplayName} is in jail. {JailTurnRemaining} turn{(JailTurnRemaining > 1 ? "s" : "")} remaining."); if (OutOfJailCards.Count > 0) { if (IsHuman) { Console.WriteLine($"Do you want to use 1 Get out of Jail card? (You have {OutOfJailCards.Count}) (Y/n)"); } if (!IsHuman || Console.ReadKey(true).Key == ConsoleKey.Y) { JailTurnRemaining = 0; Console.WriteLine($"{DisplayName} used 1 Get out of Jail card."); } } } else { DiceRoll = random.Next(1, 7); Tile tile = AdvanceBoardPostiion(board, DiceRoll, false); Console.WriteLine($"{DisplayName} rolled a {DiceRoll}."); Console.WriteLine($"{DisplayName} is visiting {tile.DisplayName}. {((tile is PropertyTile && ((PropertyTile)tile).Owner != null) ? $"[{((PropertyTile)tile).Owner.DisplayName}]" : String.Empty)}"); tile.OnVisit(this, board); } var canUnmortgage = MortgagedTiles.Where(tile => Money > tile.TileOptions.UnMortgageValue).ToList(); if (canUnmortgage.Count > 0) { if (IsHuman) { Console.WriteLine($"Do you want to buy back any mortgaged property? (Y/n)"); ConsoleKey key = Console.ReadKey(true).Key; if (key == ConsoleKey.Y) { do { for (int i = 0; i < canUnmortgage.Count(); i++) { PurchasableRentTile tile = canUnmortgage[i]; Console.WriteLine($"Choose the property to unmortgage by entering the corressponding number:"); Console.WriteLine($"{i + 1}. {tile.DisplayName} for ${tile.TileOptions.UnMortgageValue}."); } char c; bool isDigit, isValid; int choice = 0; do { c = Console.ReadKey(true).KeyChar; isDigit = isValid = char.IsDigit(c); if (c == 'q' || c == 'Q') // Quit { key = ConsoleKey.N; break; } else if (!isDigit) { Console.WriteLine("The value you have entered is not a number. To exit, enter 'Q'."); } else { choice = int.Parse(c.ToString()); if (choice < 0 || choice >= canUnmortgage.Count()) { Console.WriteLine("The number you have entered is not a valid choice."); isValid = false; } } }while (!(isDigit && isValid)); PurchasableRentTile tileToBuyBack = canUnmortgage[choice]; tileToBuyBack.UnMortgage(); Console.WriteLine($"Continue rebuying more mortgaged property? (Y/n)"); key = Console.ReadKey(true).Key; }while (key == ConsoleKey.Y); } } else { canUnmortgage = canUnmortgage.OrderBy(tile => tile.TileOptions.UnMortgageValue).ToList(); while (MortgagedTiles.Count > 0 && Money > canUnmortgage.Min(tile => tile.TileOptions.UnMortgageValue * 3 / 2)) { PurchasableRentTile tileToBuyBack = canUnmortgage.SkipWhile(tile => !tile.IsMortgaged).First(); tileToBuyBack.UnMortgage(); } } } if (JailTurnRemaining > 0) { JailTurnRemaining--; } Console.WriteLine($"{DisplayName} [${Money} | {OwnedTiles.Count} properties | {OwnedTiles.Where(tile => tile.IsMortgaged).Count()} mortgaged]."); }
static public bool IsBackspace(this ConsoleKey key) => key == ConsoleKey.Backspace;
} // Запуск программы static public void AdminMenu() { Console.Clear(); Console.WriteLine("Введите логин: "); string enteredLogin = EnterString(); if (enteredLogin == "Esc") { goto endAdminMenu; } Console.WriteLine("Введите пароль: "); string enteredPassword = EnterString(); if (enteredPassword == "Esc") { goto endAdminMenu; } Console.Clear(); if ((enteredLogin == login) && (enteredPassword == password)) { Console.WriteLine("Верный пароль"); ConsoleKey key = ConsoleKey.Enter; do { Console.Clear(); Console.WriteLine("***Меню администратора ресторана***"); PrintMenu(AdminMenuStrings); key = Console.ReadKey(true).Key; switch (key) { case ConsoleKey.D1: //1 - вывести текущие списки", PrintList(); break; case ConsoleKey.D2: //2 - Добавить блюдо", AddFood(); break; case ConsoleKey.D3: //"3- Удалить блюдо", RemoveFood(); break; case ConsoleKey.D4: //"4 - Добавить тип блюда", AddTypeFood(); break; case ConsoleKey.D5: //"5 - Удалить тип блюда", RemoveTypeFood(); break; case ConsoleKey.D6: //6 - Изменить имеющееся блюдо", ChangeFood(); break; case ConsoleKey.D7: //7 - Инфляция Inflation(); break; default: continue; } } while (key != ConsoleKey.D8); // 8- Выход в главное меню" } else { Console.WriteLine("Неверный пароль"); Console.WriteLine("Нажмите любую клавишу чтобы выйти в главное меню..."); Console.ReadKey(true); } endAdminMenu: Console.WriteLine(); } // меню администратора и взаимодействие с ним
static public bool IsEnter(this ConsoleKey key) => key == ConsoleKey.Enter;
public override void KeysPressed(ConsoleKey _key, EKeyModifiers _modifiers) { if (m_turnMessages.Count > 0) { PrepareText(); } }
public void Update(ConsoleKey? keyPress) { if (State == GameState.Play) { Player.Update(keyPress, World); UpdateEnemies(); UpdateBullets(); UpdateWorld(); if (Enemy.Count == 0) State = GameState.Win; } else if (State == GameState.Win) { Console.Clear(); Console.WriteLine("You Won."); } else if (State == GameState.Lose) { Console.Clear(); Console.WriteLine("You Lose."); } Fire(keyPress); }