c# - 计算 4x3 阵列中 AOE 命中的插槽
问题描述
我什至不确切地使用什么术语来查找它,我认为解释它的最佳方法是使用示例图像。
我有一个由 12 个(编号为 1-12)插槽组成的游戏场,4 个宽和 3 个深,我需要能够命中主要插槽号并获取效果区域系统的相邻插槽的数量。
解决方案
这是一个示例实现,但它可能无法正常工作,具体取决于您存储数据的方式。第一部分只是创建数组,然后第二部分要求用户选择一个数字,以便我们可以突出显示它和它的邻居。
我们所要做的就是检查当前行是否在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;
}
推荐阅读
- sql - 计算日期范围内每个状态的计数
- node.js - axios 不工作,而 fetch 工作
- haskell - Haskell 中缀符号在左边有 2 个参数
- php - 在 woocommerce 中创建重置过滤器按钮
- php - 用于向特定人员发送电子邮件的联系表
- c# - 不能修改返回值字典
因为它不是变量 - python - 如何在 Python 2.7 中使用正在运行的程序写入另一个终端?
- android - android gradle 错误:库必须使用完全相同的版本规范。找到版本 28.0.0
- scala - 我需要持久化不断更新的 RDD 吗?
- java - 在“Invasion.Project.Invasion”类中找不到属性“hScore”的设置器