控制台启动菜单

时间:2014-02-15 13:28:32

标签: c#

 public  static int Menu() // 1 - Start Game , 2 - Quit Game
    {
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.WriteLine("Rock - Paper - Scissors");
        Console.ForegroundColor = ConsoleColor.White;
        Console.WriteLine("_______________________");
        Console.WriteLine();
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("- Start Game");
        Console.ForegroundColor = ConsoleColor.White;
        Console.WriteLine("- Quit Game");
        ConsoleKeyInfo keyInfo;
        keyInfo = Console.ReadKey(true);
        if (keyInfo.Key == ConsoleKey.Enter)
        {
            Console.Clear();
            return 1; // Start Game
        }
        else
        {
            if (keyInfo.Key == ConsoleKey.DownArrow)
            {
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Rock - Paper - Scissors");
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("_______________________");
                Console.WriteLine();
                Console.WriteLine("- Start Game");
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("- Quit Game");
                if (Console.ReadKey(true).Key == ConsoleKey.Enter)
                {
                    Console.Clear();
                    return 2; // Quit Game
                }
                else
                {
                    if (Console.ReadKey(true).Key == ConsoleKey.UpArrow)
                    {
                        Console.Clear();
                        return Menu(); // Recursion :)
                    }
                }
            }
        }
        return 2;
    }

我的问题是当它到达“退出游戏”并且我向上按箭头时我实际上需要按2次向上箭头才能使它工作而不是1.

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

这是因为每次评估ReadKey条件时都会调用if。而是将结果存储在变量中。

var key = Console.ReadKey(true).Key;
if (key == ConsoleKey.Enter)
{
    Console.Clear();
    return 2; // Quit Game
}
else
{
    if (key == ConsoleKey.UpArrow)
    {
        Console.Clear();
        return Menu(); // Recursion :)
    }
}

这样,您只需拨打ReadKey一次,即可考虑第一个

在代码的当前状态下,您可以第一次按下任何不是 Enter 的键,如果检查,则仍然读取第二个键。

// ReadKey is called for the first time...
if (Console.ReadKey(true).Key == ConsoleKey.Enter)
{
    Console.Clear();
    return 2; // Quit Game
}
else // ...if it wasn't Enter...
{
    // ...ReadKey is called a second time.
    if (Console.ReadKey(true).Key == ConsoleKey.UpArrow)
    {
        Console.Clear();
        return Menu(); // Recursion :)
    }
}