更简单/更好的方法来查看2D阵列中的颜色是否匹配

时间:2014-03-07 14:20:22

标签: c# multidimensional-array

我有一个名为网格的btn二维数组6,7,我想扫描一下水平,垂直和对角线是否有四个黄色或红色。目前我正在使用if语句并在可能的情况下放入for循环,例如;

for (int i = 0; i < 6; i++)
{
   if (grid[i, 0].BackColor == Color.Red && grid[i, 1].BackColor == Color.Red && grid[i, 2].BackColor == Color.Red && grid[i, 3].BackColor == Color.Red
       || grid[i, 1].BackColor == Color.Red && grid[i, 2].BackColor == Color.Red && grid[i, 3].BackColor == Color.Red && grid[i, 4].BackColor == Color.Red
       || grid[i, 2].BackColor == Color.Red && grid[i, 3].BackColor == Color.Red && grid[i, 4].BackColor == Color.Red && grid[i, 5].BackColor == Color.Red
       || grid[i, 3].BackColor == Color.Red && grid[i, 4].BackColor == Color.Red && grid[i, 5].BackColor == Color.Red && grid[i, 6].BackColor == Color.Red)
   {
       txtBoxWinner.Text = "RED is the WINNER";
   }
}

有人可以帮助我寻找更短的选择吗?谢谢!

1 个答案:

答案 0 :(得分:1)

这对我来说感觉更干净

for (int i = 0; i < 6; i++)
{
     int correctCount = 0;
     for (int j = i; j < i + 3 && j < 7; j++)
     {
          if (grid[i, j].BackColor == Color.Red)
                correctCount++;
     }
     if (correctCount >= 3)
         txtBoxWinner.Text = "RED is the WINNER"; 
}

对不起,在我没有意识到你之前还有声明之前......这应该可以做到。