gpt4 book ai didi

c# - 检查按钮的颜色并使用二维数组更改它

转载 作者:行者123 更新时间:2023-11-30 22:21:54 25 4
gpt4 key购买 nike

我正在创建一个小游戏,就像游戏 Reversi/Othello 我已经成功地创建了一个带有按钮的 2x3 棋盘。

按钮会在您单击它们时改变颜色,但我无法检测两种黑色之间是否有白色,如果有,则将白色更改为黑色。我希望这是有道理的。按钮在二维数组中。任何可以帮助我做到这一点的建议都将不胜感激。

图片:

enter image description here这是我的代码:

![namespace reversitest
{
public partial class Form1 : Form
{

private Button\[,\] squares;
public Form1()
{
InitializeComponent();

squares = new Button\[3, 2\];
squares = new Button\[,\] {{button1, button2, button3},
{button4, button5, button6,}};
}

private void Form1_Load(object sender, EventArgs e)
{
foreach (Button sqrr in squares)
{
sqrr.Click += new System.EventHandler(this.DrawCharacter);
}
}
int _turn = 0;
private void DrawCharacter(object sender, EventArgs e)
{
Button sqrr = (Button)sender;
int col = 0;

if (sqrr.BackColor.Equals(Color.Black) || sqrr.BackColor.Equals(Color.White))
{
MessageBox.Show("Move Not Allowed!");
}
else
{
for ( int i = 0; i < squares.GetLongLength(1); ++i)
{

// check othere squares and change color
if (i < 2)
{
for (int f = 0; f < 3; ++f)
{
var ss = squares\[i, f\];
if (ss.BackColor.Equals(Color.Black))
{

MessageBox.Show("we have a black");

//ss = squares\[i, f+1\];
ss.BackColor = Color.Black;

}
else
{
MessageBox.Show("no black");
}
}

}

if (_turn == 0)
{
_turn = 1;
sqrr.BackColor = Color.Black;


}
else
{
_turn = 0;
sqrr.BackColor = Color.White;


}

}


}


}
}
}

最佳答案

首先使用数组索引命名您的按钮。它将帮助您找到按钮。
例如,根据您的图片,button1 名称将是 btn_1_1。

然后在您的按钮单击事件中首先获取按钮名称,然后确定按钮的位置。

        Button b = sender as Button;
string[] btnData = b.Name.Split('_');
int x = int.Parse(btnData[1]);
int y = int.Parse(btnData[2]);

//check for possible combinations
int top = y - 2;
int botton = y + 2;

int left = x - 2;
int right = x + 2;

if (top >= 0 && squares[top, y].Background == Color.Black)
{
squares[top+1, y].Background = Color.Black;
}
...
...

继续这样。如果您需要更多详细信息,请随时询问。

关于c# - 检查按钮的颜色并使用二维数组更改它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14063191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com