Reputation: 49
I made this game and I want to make a loop that continuously checks if a key has been pressed but when I make the loop it automatically feeds the character instead of feeding it X the amount you pressed the button. Without the loop you can only feed it once so how do I create a loop that just checks if the button has been pressed and then released.
{
Console.WriteLine("Enter your name, please: ");
string name = Console.ReadLine();
Console.WriteLine("Nice to met you, " + name);
Console.WriteLine("Press F to feed yourself(+10) and D to drink some water(+10)");
int hunger = 60;
int thirst = 60;
ConsoleKeyInfo info = Console.ReadKey();
//here is where I want it too loop but I dont want it too automatically feed every half seconds, how do I do this?
{
if (info.Key == ConsoleKey.F)
{
System.Threading.Thread.Sleep(500);
{
hunger = hunger + 10;
Console.WriteLine("Food: {0:0.0}".PadRight(15), hunger);
Console.WriteLine("Water: {0:0.0}".PadRight(70), thirst);
}
}
if (info.Key == ConsoleKey.D)
{
System.Threading.Thread.Sleep(500);
{
thirst = thirst + 10;
Console.WriteLine("Food: {0:0.0}".PadRight(15), hunger);
Console.WriteLine("Water: {0:0.0}".PadRight(70), thirst);
}
}
}
while (hunger > 1 && hunger < 101 && thirst > 1 && thirst < 101)
{
System.Threading.Thread.Sleep(5000);
Console.Write(" ");
{
hunger = hunger - 2;
thirst = thirst - 4;
Console.Write("Food: {0:0.0}".PadRight(15), hunger);
Console.Write("Water: {0:0.0}".PadRight(70), thirst);
}
Upvotes: 0
Views: 217
Reputation: 1570
You are only getting the value of Console.ReadKey()
once, so once they press f or d, a loop would continue to feed them. try something like this:
do
{
ConsoleKeyInfo info = Console.ReadKey();
if (info.Key == ConsoleKey.F)
{
System.Threading.Thread.Sleep(500);
{
hunger = hunger + 10;
Console.WriteLine("Food: {0:0.0}".PadRight(15), hunger);
Console.WriteLine("Water: {0:0.0}".PadRight(70), thirst);
}
}
if (info.Key == ConsoleKey.D)
{
System.Threading.Thread.Sleep(500);
{
thirst = thirst + 10;
Console.WriteLine("Food: {0:0.0}".PadRight(15), hunger);
Console.WriteLine("Water: {0:0.0}".PadRight(70), thirst);
}
}
}
while(info.Key != ConsoleKey.Escape);
this will do the loop, constantly checking for key presses until the user hits escape (you could make the cancelling condition be whatever you like, for example, some threshold amount of hunger or thirst being met)
Upvotes: 1