using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GameEdition3
{
class Program
{
static void Main(string[] args)
{
Data classData = new Data();
Console.WriteLine("{0}", classData.TitleMenu());
while (true)
{
ConsoleKeyInfo PressKey;
PressKey = Console.ReadKey();
while (PressKey.Key == ConsoleKey.Backspace)
{
Console.Clear();
Console.WriteLine("{0}", classData.TitleMenu());
PressKey = Console.ReadKey();
}
while (PressKey.Key == ConsoleKey.I)
{
Console.Clear();
Console.WriteLine("{0}", classData.Information());
PressKey =Console.ReadKey();
}
while (PressKey.Key == ConsoleKey.D1)
{
Console.Clear();
Console.Write("Please type in the Item you want. Warhammer, Heavy Armor, Boots, or Sword: ");
Console.WriteLine("{0}", classData.myFunction());
Console.WriteLine("\nPress Backspace to go back to the menu and you can view your item in the Display all Items tab");
PressKey = Console.ReadKey();
}
while (PressKey.Key == ConsoleKey.D2)
{
Console.Clear();
Console.WriteLine("{0}", classData.result);
PressKey = Console.ReadKey();
}
while (PressKey.Key == ConsoleKey.D3)
{
Console.Clear();
PressKey = Console.ReadKey();
}
if (PressKey.Key == ConsoleKey.D4)
{
return;
}
Console.Read();
}
}
}
}
**/
Hello. I made this noob game where you press a key to get a different menu and set of directions up. The problem is, once I press a key and go to that specific method, I can’t go back. I would like PressedKey to keep looping so I can press keys to go to the different parts of the program. I hope I explained this good enough.
Example: I press the key I. Key I goes to the set of directions. I need to hit backspace to go to the Main menu. Backspace doesn’t work. How do I make these ConsoleKeys to work?
PS: I tried while, if statements, do while, and while(true).
Here is the class that comes with it if someone wants to try it out:
http://pastebin.com/GivANrwC
Name the class Data.cs.
Thanks.
One problem is the line
Console.Read();at the end of the loop. This tells the program to wait for a line of text to be entered, followed by the Enter key. The first letter of the text that was typed is not saved anywhere and is lost.After removing that line, you still call
Console.ReadKey()too much. Each time you call that method, it eats the key that is typed. So if, for example, you press ‘I’, then you enter this section:After the
WriteLine, it callsReadKey(), and if it’s notConsoleKey.I, it exits the small loop and then restarts the bigger loop. But at the beginning of the bigger loop, you callReadKey()again, without ever checking the value of the last key pressed.Try this version instead:
This also shows that there’s no need to use small
whileloops when you’re checking which key was pressed. Let all the looping be done by the outer loop.