Reputation: 33
I am doing my programming examn and I am almost done with the game. I decided to go with connect four as it seemed to be a good chance to deal with some algrothicy features as I am not very used to that kind of coding.
The problem is simple: I need to color the buttons to create the effect of a falling brick. I wanted to do something like a big ass if statement to check if the coodinates == this then its this button to be colored. else if...
But thats gonna be pain and not very pretty. I was thinking if its possible by any chance to more or less take ALL buttons in the form and then take the x and y from the function generate a string and then find a button with that name
My buttons are label btxy however I messed up the array first button is: 0,0 the name of first button is bt11 next one on x is bt12
I am from denmark so some variables is on Danish so is this function:
private void farv(int x, int y)
{
x += 1;
y += 1;
MessageBox.Show("bt" + y.ToString() + x.ToString());
foreach (Control c in this.Controls)
{
if (c is Button)
{
if (c.Name == "bt" + x.ToString() + y.ToString())
{
if (playerValue == 1)
{
c.BackColor = Color.Blue;
}
else if (playerValue == 10)
{
c.BackColor = Color.Red;
}
}
}
}
}
That is the Coloring method. I call it by this:
temp = 0;
while (temp < 6)
{
MessageBox.Show("While");
farv(rowNr, temp);
temp += 1;
}
I cant really get it to working any way. Any suggestion? This turned out way harder than I expected, haha.
Upvotes: 2
Views: 232
Reputation: 37020
Not sure what part "isn't working", but this works for me:
private void farv(int x, int y)
{
var buttonName = string.Format("bt{0}{1}", x + 1, y + 1);
var buttonControl = Controls.Find(buttonName, true).FirstOrDefault();
if (buttonControl != null)
{
buttonControl.BackColor = GetColorForPlayer(playerValue);
}
}
private Color GetColorForPlayer(int playerValue)
{
Color defaultColor = SystemColors.Control;
switch (playerValue)
{
case 1:
return Color.Blue;
case 10:
return Color.Red;
default:
return defaultColor;
}
}
Assuming you have a 6 x 6 board, you could use this like:
for (int x = 0; x < 6; x++)
{
for (int y = 0; y < 6; y++)
{
farv(x, y);
}
}
Upvotes: 3