![](/img/trans.png)
[英]Is it possible to iterate through enums like an array by its position value?
[英]How to Iterate through the array of enums
我在tictactoe 5x5 WPF应用程序上工作,我需要检查按钮是否与附近的按钮具有相同的标记,以检查获胜者(左2,右1到左,右2到右)。
有一个静态数组声明为mResults = new MarkType[25];
其中MarkType
是枚举(自由,无,交叉)。
我想每次在Button_Click
函数中遍历按钮的数组( mResults
)。
我知道一种解决方案,基本上可以在其中复制并粘贴(大约粘贴到索引中),但是如果这样的话似乎太多了:
if (mResults[0] != MarkType.Free && (mResults[0] & mResults[1] & mResults[2]) == mResults[0])
{
// game ends
mGameEnded = true;
// highlight winning cells in green
Button0_0.Background =Button1_0.Background=Button2_0.Background=Brushes.Green;
}
当我声明index
有什么方法可以声明要遍历mResults
数组的函数?
var column = Grid.GetColumn(button);
var row = Grid.GetRow(button);
var index = column + (row * 5);`
我尝试使用(作为示例)函数, if
仅用于数组mResults
前三个元素,但它似乎不起作用:
if (mResults[index] != MarkType.Free && (mResults[index] & mResults[index+1] & mResults[index+2]) == mResults[index])
{
// game ends
mGameEnded = true;
// highlight winning cells in green
Button0_0.Background = Button1_0.Background = Button2_0.Background = Brushes.Green;
}
水平,垂直或对角线地检查三个连续标记的获胜组合并不困难(我相信这是您追求的目标):
public enum MarkType
{
Free = 0,
Nought = 1,
Cross = 2
}
private const int size = 5;
private readonly MarkType[] mResults = new MarkType[size * size];
public MarkType CheckWin()
{
for (var x = 0; x < size; x++)
{
for (var y = 0; y < size; y++)
{
var offset = y * size + x;
var mark = mResults[offset];
if (mark == MarkType.Free)
{
// We don't do the checks when we are on a free mark
continue;
}
if (x <= size - 3 && mark == mResults[offset + 1] && mark == mResults[offset + 2])
{
// Horizontal match at (x,y)..(x+2,y)
return mark;
}
if (y <= size - 3 && mark == mResults[offset + size] && mark == mResults[offset + size * 2])
{
// Vertical match at (x,y)..(x,y+2)
return mark;
}
if (x <= size - 3 && y <= size - 3 && mark == mResults[offset + (size + 1)] && mark == mResults[offset + (size + 1) * 2])
{
// Diagonal match at (x,y)..(x+2,y+2)
return mark;
}
if (x <= size - 3 && y >= 2 && mark == mResults[offset - (size - 1)] && mark == mResults[offset - (size - 1) * 2])
{
// Diagonal match at (x,y)..(x+2,y-2)
return mark;
}
}
}
return MarkType.Free;
}
但是,只要您不将按钮着色在与mResult
数组偏移量匹配的数组中,就将更加困难。 但是,这不是问题的一部分,因此我将其留给您练习...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.