如果将按钮存储在多维数组中,则可以编写一些扩展方法来获取行、列和对角线。
public static class MultiDimensionalArrayExtensions
{
public static IEnumerable<T> Row<T>(this T[,] array, int row)
{
var columnLower = array.GetLowerBound(1);
var columnUpper = array.GetUpperBound(1);
for (int i = columnLower; i <= columnUpper; i++)
{
yield return array[row, i];
}
}
public static IEnumerable<T> Column<T>(this T[,] array, int column)
{
var rowLower = array.GetLowerBound(0);
var rowUpper = array.GetUpperBound(0);
for (int i = rowLower; i <= rowUpper; i++)
{
yield return array[i, column];
}
}
public static IEnumerable<T> Diagonal<T>(this T[,] array,
DiagonalDirection direction)
{
var rowLower = array.GetLowerBound(0);
var rowUpper = array.GetUpperBound(0);
var columnLower = array.GetLowerBound(1);
var columnUpper = array.GetUpperBound(1);
for (int row = rowLower, column = columnLower;
row <= rowUpper && column <= columnUpper;
row++, column++)
{
int realColumn = column;
if (direction == DiagonalDirection.DownLeft)
realColumn = columnUpper - columnLower - column;
yield return array[row, realColumn];
}
}
public enum DiagonalDirection
{
DownRight,
DownLeft
}
}
如果您使用TableLayoutPanel
3 行和 3 列的 a,您可以轻松地以可编程方式创建按钮并将其存储到Button[3, 3]
数组中。
Button[,] gameButtons = new Button[3, 3];
for (int row = 0; column <= 3; row++)
for (int column = 0; column <= 3; column++)
{
Button button = new Button();
// button...
gameLayoutPanel.Items.Add(button);
gameButtons[row, column] = button;
}
并检查获胜者:
string player = "X";
Func<Button, bool> playerWin = b => b.Value == player;
gameButtons.Row(0).All(playerWin) ||
// ...
gameButtons.Column(0).All(playerWin) ||
// ...
gameButtons.Diagonal(DiagonalDirection.DownRight).All(playerWin) ||
// ...