C# 从控制台导航获取数组索引

问题描述 投票:0回答:1

我有这个子程序(如下),它让我可以使用箭头键导航这个打印到控制台的二维数组,是否有可能(如果是,如何?)在按下回车键时获得悬停的项目的索引?如果需要,我可以添加其余代码。

    public static void BoardMobility(string[,] ChessBoard, Board board)
    {
        Console.CursorLeft = 1;
        Console.CursorTop = 0;
        bool exit = false;
        int vertical = 0;
        int horizontal = 0;
        do
        {
            ConsoleKeyInfo choice = Console.ReadKey(true);
            if (choice.Key == ConsoleKey.UpArrow && vertical > 0)
            {
                Console.CursorTop = vertical;
                vertical--;
                Console.CursorTop = vertical;
            }
            else if (choice.Key == ConsoleKey.DownArrow && vertical < 7)
            {
                Console.CursorTop = vertical;
                vertical++;
                Console.CursorTop = vertical;
            }
            else if (choice.Key == ConsoleKey.RightArrow && horizontal < 21)
            {
                if (horizontal == 0)
                {
                    Console.CursorLeft = horizontal;
                    horizontal = horizontal + 4;
                    Console.CursorLeft = horizontal;
                }
                else
                {
                    Console.CursorLeft = horizontal;
                    horizontal = horizontal + 3;
                    Console.CursorLeft = horizontal;
                }
            }
            else if (choice.Key == ConsoleKey.LeftArrow && horizontal > 2)
            {
                Console.CursorLeft = horizontal;
                horizontal = horizontal - 3;
                Console.CursorLeft = horizontal;
            }
            else if (choice.Key == ConsoleKey.Enter)
            {
                // this is where i would like to "collect" the index of the item hovered over
            }
        } while (!exit);
    }
c# chess
1个回答
0
投票

可以在按下回车键时获取悬停项的索引。您可以使用光标的当前垂直和水平位置来计算索引。

以下是修改代码以实现此目的的方法:

else if (choice.Key == ConsoleKey.Enter)
{
    int index = (vertical * 8) + (horizontal - ((horizontal + 1) / 4));

    // Now you can use the index to access the corresponding element in the 2D array
    Console.WriteLine("Selected element: " + ChessBoard[vertical, index]);
}

在上面的代码中,索引是根据光标当前的垂直和水平位置计算的。该公式计算所选元素的索引,就像将 2D 数组展平为 1D 数组一样(请注意,我们从水平位置除以 4 中减去 1,因为每列之间有 3 个空格)。

计算索引后,您可以使用它来访问二维数组中的相应元素(在本例中为 ChessBoard[vertical, index])并用它做任何您需要的事情。

希望对您有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.