首页 > 解决方案 > 计算 4x3 阵列中 AOE 命中的插槽

问题描述

我什至不确切地使用什么术语来查找它,我认为解释它的最佳方法是使用示例图像。

我有一个由 12 个(编号为 1-12)插槽组成的游戏场,4 个宽和 3 个深,我需要能够命中主要插槽号并获取效果区域系统的相邻插槽的数量。

示例图像:4x3 插槽阵列上的 AoE

标签: c#

解决方案


这是一个示例实现,但它可能无法正常工作,具体取决于您存储数据的方式。第一部分只是创建数组,然后第二部分要求用户选择一个数字,以便我们可以突出显示它和它的邻居。

我们所要做的就是检查当前行是否在1所选行之内,以及当前列是否在1所选列之内,并突出显示该正方形(因为它是邻居)。当然,如果行和列都匹配,那么我们会以不同的方式突出显示,因为这是他们选择的数字:

private static void Main(string[] args)
{
    var rowCount = 4;
    var colCount = 3;
    var slots = new int[rowCount, colCount];

    // Populate the grid
    for (int i = 0; i < rowCount * colCount; i++)
    {
        var col = i / rowCount;
        var row = i % rowCount;

        slots[row, col] = i + 1;
    }

    // Print the grid
    for (int row = 0; row < rowCount; row++)
    {
        for (int col = 0; col < colCount; col++)
        {
            Console.Write($" {slots[row, col]}");
        }

        Console.WriteLine();
    }

    // Ask the user to select a number from the grid
    var chosenNumber = GetIntFromUser("\nSelect a number: ", 
        x => x > 0 && x < rowCount * colCount);

    // Get the coordinates of that selected number
    var selCol = (chosenNumber - 1) / 4;
    var selRow = (chosenNumber - 1) % 4;

    // Print the grid, highlighting their 
    // selected number and it's neighbors
    Console.WriteLine();
    for (int row = 0; row < rowCount; row++)
    {
        for (int col = 0; col < colCount; col++)
        {
            if (row == selRow && col == selCol)
            {
                Console.BackgroundColor = ConsoleColor.White;
                Console.ForegroundColor = ConsoleColor.Red;
            }
            else if (row >= selRow - 1 && row <= selRow + 1 &&
                     col >= selCol - 1 && col <= selCol + 1)
            {
                Console.BackgroundColor = ConsoleColor.Gray;
                Console.ForegroundColor = ConsoleColor.Blue;
            }
            else
            {
                Console.ResetColor();
            }

            Console.Write($" {slots[row, col]}");
        }

        Console.WriteLine();
    }

    GetKeyFromUser("\nDone! Press any key to exit...");
}

输出

![![上述代码的示例输出

哦,我用来获取有效数字的辅助函数是:

private static int GetIntFromUser(string prompt, Func<int, bool> validator = null)
{
    int result;
    var cursorTop = Console.CursorTop;

    do
    {
        Console.SetCursorPosition(0, cursorTop);
        Console.Write(new string(' ', Console.WindowWidth));
        Console.SetCursorPosition(0, cursorTop);
        Console.Write(prompt);

    } while (!int.TryParse(Console.ReadLine(), out result) ||
                !(validator?.Invoke(result) ?? true));

    return result;
}

推荐阅读