我在C#上使用Visual Studio制作游戏(在控制台中)。这是关于对话,你可以用2个选项回答它们,一个键(用于回答第一个问题)是1,另一个是2。 问题是,当你按一个键时,你不能再按另一个键,我的意思是,如果你按1,你就不能按2,反之亦然。
static void Main(string[] args)
{
Console.WriteLine("Press 1 or 2 please...");
//I know there are some errors in this code, i'm new at c#
ConsoleKeyInfo number1;
do
{
number1 = Console.ReadKey();
Console.WriteLine("Number 1 was pressed");
//This is the 1st answer
}
while (number1.Key != ConsoleKey.D1);
ConsoleKeyInfo number2;
//The problem is that when I already pressed D1 (1), I shouldn't be
//able to press D2 (2). And if I press D2 (2), I shoundn´t be able
//to press D1 (1).
do
{
number2 = Console.ReadKey();
Console.WriteLine("Number 2 was pressed");
//This is the 2nd answer
}
while (number2.Key != ConsoleKey.D2);
Console.ReadLine();
}
答案 0 :(得分:1)
您的代码中的问题是您的逻辑对于您想要开发的游戏是错误的。
在下面的代码中,我只使用一个Do / while循环来获取密钥,然后决定使用交换机,如果密钥是我想要获得的密钥之一,如果没有,我继续循环和再问一下另一把钥匙。
class Program
{
static void Main(string[] args)
{
bool knownKeyPressed = false;
do
{
Console.WriteLine("Press 1 or 2 please...");
ConsoleKeyInfo keyReaded = Console.ReadKey();
switch (keyReaded.Key)
{
case ConsoleKey.D1: //Number 1 Key
Console.WriteLine("Number 1 was pressed");
Console.WriteLine("Question number 1");
knownKeyPressed = true;
break;
case ConsoleKey.D2: //Number 2 Key
Console.WriteLine("Number 2 was pressed");
Console.WriteLine("Question number 2");
knownKeyPressed = true;
break;
default: //Not known key pressed
Console.WriteLine("Wrong key, please try again.");
knownKeyPressed = false;
break;
}
} while(!knownKeyPressed);
Console.WriteLine("Bye, bye");
Console.ReadLine();
}
}