我创建了一个二维数组19,19的标签。在单击时,用户会根据迭代将标签的颜色更改为黑色或白色。当有五个颜色相同的标签水平排列时,我想要一个消息框弹出。这是不需要递归的。任何帮助都将不胜感激。
public partial class Form1 : Form
{
int labelCount = 0;
int iteration = 0;
public Label[,] board = new Label[19,19];
const int WinLength = 5;
const int BoardWidth = 19;
const int BoardHeight = 19;
gamePlay obj = new gamePlay();
public Form1()
{
InitializeComponent();
}
private void labelClick (object sender, EventArgs e)
{
Label x = (Label)sender;
if (x.BackColor == Color.Transparent)
{
if (iteration % 2 == 0)
{
x.BackColor = Color.Black;
}
else
{
x.BackColor = Color.White;
}
iteration++;
}
else
{
}
for (int r = 0; r < BoardHeight; r++)
{
for (int c = 0; c < BoardWidth; c++)
{
if (board[r, c] == x)
{
Color? winner = obj.CheckForWinner(board, r, c);
if (winner == Color.Black)
{
MessageBox.Show("Black is the winner!");
}
else if (winner == Color.White)
{
MessageBox.Show("White is the winner!");
}
// else winner is null, meaning no winner yet.
}
}
}
private int[] FindClickedLabelCoordinates(Label[,] board, Label label)
{
for (int r = 0; r < BoardHeight; r++)
{
for (int c = 0; c < BoardWidth; c++)
{
if (board[r, c] == label)
return new int[] { r, c };
}
}
return null;
}
}
class gamePlay
{
const int WinLength = 5;
const int BoardWidth = 19;
const int BoardHeight = 19;
private Color? CheckForWinner(Label[,] board, int r, int c)
{
Color startColor = board[r, c].BackColor;
for (int c1 = c - WinLength + 1; c1 <= c; c1++)
{
if (c1 >= 0 && c1 < BoardWidth && board[r, c1].BackColor == startColor)
{
MessageBox.Show("you win!");
bool win = true;
for (int c2 = c1 + 1; c2 < c1 + WinLength; c2++)
{
if (c2 < 0 || c2 >= BoardWidth || board[r, c2].BackColor != startColor)
{
win = false;
break;
}
}
if (win)
{
return startColor;
}
}
}
return null;
}发布于 2015-11-18 02:05:16
在19x19,他们将需要点击大量的时间来减缓你的程序,即使你确实检查了整个董事会。想一想:,除非你能证明它对你的用例来说太慢,否则不要太早地优化,因为它浪费了你的精力。如果你有点击位置,并且可以找出位置,你可以从那里恢复,试图用同样的颜色找到相邻的位置。
基本的方法是从一个点开始,在保持计数器的同时,从左/右、上/下(或任何您的要求)开始。一旦你达到了成功的状态,你就会一直往上走。
https://stackoverflow.com/questions/33770469
复制相似问题