我甚至都不是用什么术语来查找这个词,我想通过一个示例图像来解释它的最好方法。
我有一个游戏场,该游戏场由12个(编号1-12)插槽,4个宽和3个深的插槽组成,我需要能够获得命中的主要插槽编号并获得其区域为A的相邻插槽的编号效果系统。
答案 0 :(得分:1)
这是一个示例实现,但它可能无法正常运行,具体取决于您存储数据的方式。第一部分仅创建数组,然后第二部分要求用户选择一个数字,以便我们可以突出显示该数字及其邻居。
我们要做的就是检查当前行是否在所选行的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;
}