重複の可能性:
ボタンに2D配列を使用するC#
私は7x6に拡張される2x2ボードを使用してゲームに取り組んでいます。
私は現在、勝者の検出を行っていますが、長い道のりを行っていると思います。はるかに短い方法があるはずです。
勝者
- 水平方向
- 垂直方向
- 対角線
これがゲームボードの写真です:
これは私が現在勝者を検出している方法です
if (btns[0, col].BackColor.Equals(Color.Red) && btns[1, col].BackColor.Equals(Color.Red))
{
MessageBox.Show("Red Win");
}
if (btns[0, col].BackColor.Equals(Color.Blue) && btns[1, col].BackColor.Equals(Color.Blue))
{
MessageBox.Show("Blue Win");
}
この方法では、すべての組み合わせをリストする必要があるようです。7x6に拡張する場合はあまり理想的ではありません。
これがプログラムのコード全体です
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Button[,] btns;
public Form1()
{
InitializeComponent();
btns = new Button[,] { { button2 , button1 },
{ button4 , button3 }};
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (var btn in btns)
{
btn.Enabled = false;
}
}
int cc = 0;
private void button5_Click(object sender, EventArgs e)
{
// Button[] row1 = new Button[] {button2, button1};
for (int col = 0; col < btns.GetLength(1); ++col)
{
var btn = btns[0, col];
if (!btn.Enabled)
{
btn.Enabled = true;
if (cc == 0)
{
cc = 1;
btn.BackColor = Color.Red;
}
else
{
cc = 0;
btn.BackColor = Color.Blue;
}
if (btns[0, col].BackColor.Equals(Color.Red) && btns[1, col].BackColor.Equals(Color.Red))
{
MessageBox.Show("Red Win");
}
if (btns[0, col].BackColor.Equals(Color.Blue) && btns[1, col].BackColor.Equals(Color.Blue))
{
MessageBox.Show("Blue Win");
}
return;
}
}
}
private void button6_Click(object sender, EventArgs e)
{
// Button[] row2 = new Button[] { button4, button3 };
for (int col = 0; col < btns.GetLength(1); ++col)
{
var btn = btns[1, col];
if (!btn.Enabled)
{
btn.Enabled = true;
if (cc == 0)
{
cc = 1;
btn.BackColor = Color.Red;
}
else
{
cc = 0;
btn.BackColor = Color.Blue;
}
if (btns[1, col].BackColor.Equals(Color.Red) && btns[0, col].BackColor.Equals(Color.Red))
{
MessageBox.Show("Red Win");
}
if (btns[1, col].BackColor.Equals(Color.Blue) && btns[0, col].BackColor.Equals(Color.Blue))
{
MessageBox.Show("Blue Win");
}
return;
}
}
}
}
}
私は他の多くの方法を試しましたが、うまくいかないようです。