2 in a row game [duplicate] - c#

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
c# using 2d arrays for buttons
I'm working on a game using a 2x2 board that will be extended to a 7x6.
I'm doing the winning detection at the moment, but I think I'm doing it the long way. There must be a much shorter way.
The winn
Horizontally
Vertically
Diagonally
Here's a pic of game board:
This is how I'm currently detecting winner
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");
}
This way seems like I have to list all combinations, and it would not be very ideal when I extend to 7x6.
Here is the whole code of the program
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;
}
}
}
}
}
I have tried a lot of other ways but I can't seem to get it working.

Maybe this answer is complicated and I'll get many downvotes but I couldn't resist solving this as optimal as possible. Try to inspect this code to the detail:
int n; //dimension of the matrix
Button [,] btns;
public Form1()
{
InitializeComponent();
n = 2;/*You should set here the dimension of your matix. I considered it nxn because of diagonals. If you want nxm matrix than the code is a little bit complicated but not too much*/
btns = new Button[n, n];
for(int i = 0;i<n;i++)
for(int j = 0; j<n; j++)
{
Button btn = new Button();
btn.Location = new Point(i*20,j*40);
btn.Size = new Size(18,38);
btns[i,j] = btn;
this.Controls.Add(btn);
}
}
private void button1_Click(object sender, EventArgs e)
{
int mainDiag = 0;
int secDiag = 0;
int i = 0;
int j = 0;
int [] cols = new int[n];
int winner = 0; //no winner
while(winner == 0 && i<n)
{
int row = 0;
j = 0;
while(j<n)
{
if (btns[i, j].BackColor == Color.Blue)
{
if (i == j)
mainDiag++;//inrement main diagonal
if(i + j == n-1)
secDiag++;//increment second diagonal
row++; //increment row
cols[i]++; //increment column
}
else if (btns[i, j].BackColor == Color.Red)
{
if (i == j)
mainDiag--;
if(i + j == n-1)
secDiag--;
row--;
cols[i]++;
}
j++;
}
if(row == n) //if row value == n whole row is blue and blue player wins
winner = 1;
else if(row == -n)
winner = -1; //if row value == -n whole row is red and red player wins
i++;
}
if(winner == 0)
{
if(mainDiag == n)
winner = 1; //similar for the diagonal
else if(mainDiag == -n)
winner = -1;
else if(secDiag == n)
winner = 1;//similar for the second diagonal
else if(secDiag == -n)
winner = -1;
else
{
i = 0;
while (winner == 0 && i < n)
{
if (cols[i] == n)
winner = 1; //i-th column is whole blue and blue player wins
else if (cols[i] == -n)
winner = -1; //i-th column is whole red and red player wins
}
}
}
if (winner == 1)
MessageBox.Show("Blue wins");
else if(winner == -1)
MessageBox.Show("Red wins");
}

As people have said in the comments, you'll probably want to use loops in order to do this.
I'm not going to go into a lot of detail here, but I'll describe some algorithms to accomplish your win condition detection.
Algorithm 1:
For Each cell, detect whether that's part of a horizontal, vertical, or diagonal row. The time complexity for this will be O(n^(3/2)). You can account for duplicate checks if you want to but you don't have to.
Algorithm 2:
Check All vertical rows, all horizontal rows, and all diagonal rows, and see if any win conditions lie upon those rows. The time complexity for this method should be roughly O(n). You could probably save a little bit of time by not checking diagonal rows that aren't large enough to hold a win condition, but you don't have to.

If you wanted a really basic answer I would consider the following
Add each row into an array
Add each column into an array
For Each item in the array if they all equal a single colour then you have won
You may want to use a multi-dim array when you go to larger numbers (ie 6x6 grid)

Related

how to determine the mouse pointer is on tablelayoutpanel cell border c#

I have TableLayoutPanel on windows form. I want mouse pointer cursor style is cross when the pointer on/near the cell border.
Edit I tried with mouse move event. I get the cell positions where the mouse point is moving.But I couldn't use this information and I was stuck. How can achieve that?
Edit: I fixed the problem. It is about size type. The code is working. I'm sharing it for those who have similar demands. Thanx.
bool calcCells = false;
List<float> XCoordinates = new List<float>();
List<float> YCoordinates = new List<float>();
public Form3()
{
InitializeComponent();
// Set the DoubleBuffered property via reflection (if needed)
var flags = BindingFlags.Instance | BindingFlags.NonPublic;
tlp1.GetType().GetProperty("DoubleBuffered", flags).SetValue(tlp1, true);
tlp1.Layout += tlp1_Layout;
tlp1.CellPaint += tlp1_CellPaint;
tlp1.MouseMove += tlp1_MouseMove;
}
// Added the x coordinates of cell borders in a List
private void CreateXCoordinateList()
{
XCoordinates.Clear();
// first and last column sizetype is SizeType.Absoulute.
float tlpWidth = tlp1.Width- tlp1.ColumnStyles[0].Width - tlp1.ColumnStyles[tlp1.ColumnCount-1].Width;
float x = 0;
for (int i = 0; i < tlp1.ColumnCount; i++)
{
if(tlp1.ColumnStyles[i].SizeType==SizeType.Absolute)
x += tlp1.ColumnStyles[i].Width;
else if(tlp1.ColumnStyles[i].SizeType == SizeType.Percent)
{
double k = tlpWidth * tlp1.ColumnStyles[i].Width * 0.01;
x += Convert.ToSingle(k);
}
XCoordinates.Add(x);
}
}
// Added the y coordinates of cell borders in a List
private void CreateYCoordinateList()
{
YCoordinates.Clear();
// first and last row sizetype is SizeType.Absoulute.
float tlpHeight = tlp1.Height - tlp1.RowStyles[0].Height - tlp1.RowStyles[tlp1.RowCount - 1].Height;
float y = 0;
for (int i = 0; i < tlp1.RowCount; i++)
{
if (tlp1.RowStyles[i].SizeType == SizeType.Absolute)
y += tlp1.RowStyles[i].Height;
else if (tlp1.RowStyles[i].SizeType == SizeType.Percent)
{
double k = tlpHeight * tlp1.RowStyles[i].Height*0.01;
y += Convert.ToSingle(k);
}
YCoordinates.Add(y);
}
}
private void tlp1_Layout(object sender, LayoutEventArgs e) => calcCells = true;
private void tlp1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if (calcCells)
{
CreateXCoordinateList();
CreateYCoordinateList();
if (e.Column == tlp1.ColumnCount - 1 &&
e.Row == tlp1.RowCount - 1)
calcCells = false;
}
}
private void tlp1_MouseMove(object sender, MouseEventArgs e)
{
//Comparing the mouse pointer position with the cellborder coordinates,
//if the difference is less than and equal to 4, change the cursor style.
float x = e.Location.X;
float y = e.Location.Y;
if (MouseNearCellBorderXAxis(e) || MouseNearCellBorderYAxis(e))
tlp1.Cursor = Cursors.Cross;
else
tlp1.Cursor = Cursors.Default;
}
private bool MouseNearCellBorderXAxis(MouseEventArgs e)
{
float x = e.Location.X;
for (int i = 0; i < XCoordinates.Count; i++)
{
float Border = XCoordinates[i];
double difference = Math.Abs(x - Border);
if (difference <= 4)
return true;
}
return false;
}
private bool MouseNearCellBorderYAxis(MouseEventArgs e)
{
float y = e.Location.Y;
for (int i = 0; i < YCoordinates.Count; i++)
{
float Border = YCoordinates[i];
double difference = Math.Abs(y - Border);
if (difference <= 4)
return true;
}
return false;
}
If I get what you're asking, provided you have controls in the cells of the TableLayoutPanel all one would have to do is set the different cursors one time for:
Main form (Arrow)
Table layout panel (Cross)
The controls therein contained (e.g. Hand)
Everything else should happen on its own.
public MainForm()
{
InitializeComponent();
// MainForm has ARROW
this.Cursor = Cursors.Arrow;
// TableLayoutPanel has CROSS
tableLayoutPanel.Cursor = Cursors.Cross;
int key = 0; string text;
for (int column = 0; column < tableLayoutPanel.ColumnCount; column++)
for (int row = 0; row < tableLayoutPanel.RowCount; row++)
{
switch (++key)
{
case 10: text = "*"; break;
case 11: text = "0"; break;
case 12: text = "#"; break;
default: text = $"{key}"; break;
}
tableLayoutPanel.Controls.Add(new Label
{
BackColor = Color.LightGreen,
Anchor = (AnchorStyles)0xF,
Margin = new Padding(10),
Text = text,
TextAlign = ContentAlignment.MiddleCenter,
// Controls in the table have HAND
Cursor = Cursors.Hand,
});
}
}

How to disable a picture box once I clicked a button and an image has been inserted

I have created a grid in a panel and added 42 picture boxes for a 6x7 grid, Every time I click a button for the row it inserts an image of a red or yellow checker. I am trying to make the button add another image of the other image on the box on top. I have created an array as a check feature to see which player has won.
My code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Connect4
{
public partial class Form2 : Form
{
int i = 1;
int[,] a = new int[7, 6];
public Form2()
{
InitializeComponent();
}
private void tableLayoutPanel1_MouseClick(object sender, MouseEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (i %2 == 1)
{
pictureBox1.Image = Image.FromFile(#"C:\ Documents\Desktop\PROJECT FOR LAPTOP\red.png");
pictureBox1.Enabled = false;
}
else
{
pictureBox1.Image = Image.FromFile(#"C:\ Documents\Desktop\PROJECT FOR LAPTOP=\yellow.png");
pictureBox1.Enabled = false;
}
i++;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
int cols = 7;
int rows = 6;
int width = panel1.Width / cols;
int height = panel1.Height / rows;
for (int col = 1; col < cols; col++)
{
e.Graphics.DrawLine(Pens.Black, new Point(col * width, 0), new Point(col * width, panel1.Height));
}
for (int row = 1; row < rows; row++)
{
e.Graphics.DrawLine(Pens.Black, new Point(0, row * height), new Point(panel1.Width, row * height));
}
}
private void Form2_Load(object sender, EventArgs e)
{
panel1.SizeChanged += Panel1_SizeChanged;
panel1.Paint += panel1_Paint;
}
private void Panel1_SizeChanged(object sender, EventArgs e)
{
panel1.Invalidate();
}
}
}
This is what my design looks like so far(https://i.stack.imgur.com/Rg8Vg.png)
The red changes to a yellow circle one the button is clicked
I was expecting for it put in a red counter image first and then when I clicked the same button it would add a yellow counter on the picture box on top of it
This is the Upper right to bottom left code:
if (!winFound) //if win is not found on horizontal check Right Diagonals
{
//Diagonal Upper right to bottom left(2D Array)
for (int row = 3; row < 5 && !winFound; row++)
{
rowFound = row;
for (int col = 0; col <= 3 && !winFound; col++)
{
colFound = col;
if (board[row, col] != null)
{
temp = true;
winFound =
(board[row, col] == board[row + 1, col + 1]) &&
(board[row, col] == board[row + 2, col + 2]) &&
(board[row, col] == board[row + 3, col + 3]);
}
}
}
}
I am unsure on why it doesnt check win
Assuming the first column on the left is pb1 at the bottom and pb7 at the bottom right, and button1 is on the left with button7 on the right.
Here's how you'd do it with just ONE set of buttons across the bottom to pick which column to drop the next piece into:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private String[,] board = new String[6,7]; // six rows by seven columns
private int i = 1; // odd = red, even = yellow
private List<Button> buttons;
private Image red;// = Image.FromFile(#"C:\Users\ogisi\OneDrive - Wilmslow High School\Desktop\PROJECT FOR LAPTOP\red.png");
private Image yellow;// = Image.FromFile(#"C:\Users\ogisi\OneDrive - Wilmslow High School\Desktop\PROJECT FOR LAPTOP\yellow.png");
private void Form1_Load(object sender, EventArgs e)
{
// only ONE row of buttons, from Left to Right, BELOW all the PictureBoxes
// PBs are placed from left to right, bottom to top
// pb1 is at bottom left, pb2 to its right, pb3 to its right, etc...
// pb8 in second row from the bottom on the left, pb9 to its right, pb10 to its right, etc...
// pb15 in third row from bottom on the left, etc..
// pb42 is in the top row in the rightmost column
buttons = new List<Button> { button1, button2, button3, button4, button5, button6, button7 };
foreach (Button btn in buttons)
{
btn.Click += Btn_Click;
}
nextTurnColor();
}
private void Btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
int column = buttons.IndexOf(btn);
int rowPlaced = -1;
for(int row=0; row<6; row++)
{
if(board[row,column] == null)
{
rowPlaced = row;
board[row, column] = (i % 2 == 1) ? "R" : "Y";
String pbPrefix = "pictureBox"; // "pb"
String ctlName = pbPrefix + ((row * 7) + (column + 1));
PictureBox pb = this.Controls.Find(ctlName, true).FirstOrDefault() as PictureBox;
pb.BackColor = (i % 2 == 1) ? Color.Red : Color.Yellow;
//pb.Image = (i % 2 == 1) ? red : yellow;
if (row == 5)
{
btn.Enabled = false; // column is full!
}
i++;
break;
}
}
if (rowPlaced != -1)
{
// ... check "board" for a win condition ...
// if no win, then change player
nextTurnColor();
}
}
private void nextTurnColor()
{
this.Text = (i % 2 == 1) ? "Red's turn." : "Yellow's turn.";
}
}
Sample run: (*No win condition check being performed!)
Here's an example of checking for a horizontal win.
Read those comments carefully!
// an empty spot in the board will be null
// red spot will contain "R"
// yellow spot will contain "Y"
private String[,] board = new String[6, 7];
private void FooBar()
{
// here is how to check for a horizontal win
// we need to check each row, this is the outer loop
// we need to check the columns, thus the inner loop
// for four in a row, horizontally, we canstart anywhere
// from column 0 up to to column 3, but cannot start
// from column 4 or above as there wouldn't be enough
// room to finish the row of four
//
// 0 1 2 3 4 5 6
// x x x x
// x x x x
//
// board.getLength(0) tells us how many rows in 2D array
// board.getLength(1) tells us how many columns in 2D array
int rowFound = -1;
int colFound = -1;
bool winFound = false; // assume no win until proven otherwise
for (int row = 0; row < board.GetLength(0) && !winFound; row++)
{
rowFound = row;
for (int col = 0; col <= (board.GetLength(1) - 4) && !winFound; col++)
{
colFound = col;
// we want to ignore any starting position that is blank
// so we don't end up getting a four in a row "match"
// because all of them are equal, but contain null
if (board[row, col] != null)
{
// are the next 3 horizontally the same as the first?
// we don't need to worry about an index out of bounds
// here since we controlled the inner loop above
// with "(board.GetLength(1) - 4)"
// both loops will drop out if winFound becomes true!
winFound =
(board[row, col] == board[row, col + 1]) &&
(board[row, col] == board[row, col + 2]) &&
(board[row, col] == board[row, col + 3]);
}
}
}
if (!winFound) {
// ... check for vertical win in here ...
}
if (!winFound) {
// ... check for diagonal win (upper left to bottom right) in here ...
}
if (!winFound) {
// ... check for diagonal win (upper right to bottom left) in here ...
}
// if four in a row was never found, winFound will still be false
if (winFound)
{
// ... there was a winner! ...
String winner = board[rowFound, colFound];
Console.WriteLine("The winner was: " + winner);
}
}
Hopefully you can take this example and figure out how to apply it to a check for a vertical and/or diagonal win condition. Don't forget that when checking for a diagonal win you'd need to check for both an upper left to bottom right diagonal, and an upper right down to bottom left diagonal.
For the upper left to bottom right check, here's an image showing where possible starting positions could be:
For the rows, they only start between rows 3 and 5 inclusive. For the columns, they can only start between 0 and 3 inclusive. We need to take these constraints into account in our two for loops:
// Upper Left to Bottom Right Diagonal Check
for (int row = 3; row <= 5 && !winFound; row++)
{
rowFound = row;
for (int col = 0; col <= 3 && !winFound; col++)
{
colFound = col;
if (board[row, col] != null)
{
// are the next 3 diagonal the same?
// Upper Left to Bottom Right direction!
winFound =
(board[row, col] == board[row - 1, col + 1]) &&
(board[row, col] == board[row - 2, col + 2]) &&
(board[row, col] == board[row - 3, col + 3]);
}
}
}
Here's one way to do the Upper Right to Bottom Left Diagonal check:
// Diagonal Check - Upper Right to Bottom Left:
for (int row = 3; row <= 5 && !winFound; row++)
{
rowFound = row;
for (int col = 3; col <= 6 && !winFound; col++)
{
colFound = col;
if (board[row, col] != null)
{
// are the next 3 diagonal the same?
// Upper Right to Bottom Left direction!
winFound =
(board[row, col] == board[row - 1, col - 1]) &&
(board[row, col] == board[row - 2, col - 2]) &&
(board[row, col] == board[row - 3, col - 3]);
}
}
}

Can't make a win checker in c# connect four game using windows forms

This is my code so far,im trying to make a c# connect four game but i cant seem to get the win checker to work! I'd like for my game to be able to check for four in a row, horizontally, vertically and diagonally and show a message telling you the winner. I have checked and everything else works as it should.
namespace ConnectFour
{
public partial class Form1 : Form
{
Button[] gameButtons = new Button[42]; //array of buttons for markers(red and blue)
bool blue = true; //blue is set to true if the next marker is to be a blue
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Text = "Connect 4";
this.BackColor = Color.BlanchedAlmond;
this.Width = 500;
this.Height = 500;
for (int i = 0; i < gameButtons.Length; i++)
{
int index = i;
this.gameButtons[i] = new Button();
int x = 50 + (i % 7) * 50;
int y = 50 + (i / 7) * 50;
this.gameButtons[i].Location = new System.Drawing.Point(x, y);
this.gameButtons[i].Name = "btn" + (index + 1);
this.gameButtons[i].Size = new System.Drawing.Size(50, 50);
this.gameButtons[i].TabIndex = i;
//this.gameButtons[i].Text = Convert.ToString(index);
this.gameButtons[i].UseVisualStyleBackColor = true;
this.gameButtons[i].Visible = true;
gameButtons[i].Click += (sender1, ex) => this.buttonHasBeenPressed(sender1, index);
this.Controls.Add(gameButtons[i]);
}
}
private void buttonHasBeenPressed(object sender, int i)
{
if (((Button)sender).BackColor == Color.BlanchedAlmond)
{
if (blue == true)
{
((Button)sender).BackColor = Color.Red;
}
else
{
((Button)sender).BackColor = Color.Blue;
}
blue = !blue;
}
}
private void fourInARow(int a, int b, int c,int d)
{
if (gameButtons[a].BackColor == gameButtons[b].BackColor && gameButtons[a].BackColor == gameButtons[c].BackColor && gameButtons[a].BackColor==gameButtons[d].BackColor)
{
if (gameButtons[a].BackColor == Color.Blue)
{
MessageBox.Show("the winner is player 1");
}
else
{
MessageBox.Show("the winner is player 2");
}
}
}
}
Why do you use Index?
int index = I;
will stay at "0" - because its an initializer and only called once in for-loop.
But it makes no sense for me at all to have an index var.

Reversi game color detection

I am recreating the classic game Reversi using c# in order to improve my skills at programming
but I have a problem when I check the colors. So far I have managed to revers colors from left and from top but it doesn't work correctly it only reverses the colors when I hit the last square on the board.
Any help would be much appreciated
Here is an image that may explain what I mean (the code is below) mean
The code that I have:
namespace praprevers
{
public partial class Form1 : Form
{
private Button[,] squares;
//private Button[,] r0;
public Form1()
{
InitializeComponent();
squares = new Button[4, 4];
squares = new Button[,] {
{btn_0_0, btn_0_1, btn_0_2, btn_0_3},
{btn_1_0, btn_1_1, btn_1_2, btn_1_3},
{btn_2_0, btn_2_1, btn_2_2, btn_2_3},
{btn_3_0, btn_3_1, btn_3_2, btn_3_3}
};
}
int _turn = 0;
private void DrawColor(object sender, EventArgs e)
{
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 = x - 3;
int botton = x +3;
int left = y - 3;
int right = y + 3;
for (int l = 0; l < 4; ++l)
{
if (top >= 0 && squares[top, y].BackColor == Color.Black)
{
squares[top + l, y].BackColor = Color.Black;
}
else if (left >= 0 && squares[x, left].BackColor == Color.Black)
{
squares[x, left + l].BackColor = Color.Black;
}
}
if (_turn == 0)
{
_turn = 1;
b.BackColor = Color.Black;
}
else
{
_turn = 0;
b.BackColor = Color.Red;
}
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (Button sqrr in squares)
{
sqrr.Click += new System.EventHandler(this.DrawColor);
}
}
}
}

checking a color of a button and changing it using a 2D array

I'm creating a small game just like the game Reversi/Othello I have managed to created a 2x3 board with buttons.
The buttons change colour ones you click on them but I'm having trouble to detect if there is a white colour in between 2 black colours and if so change that white colour into black.. I hope this make sense. the buttons are in a 2D array. Any suggestions that could help me do this would be much appreciated.
The image:
Here is my code:
![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;
}
}
}
}
}
}
First name your buttons with the array index. It will help you to find the button.
For example according to you picture button1 name would be btn_1_1.
Then inside your button click event first get the button name and then identify the button positioned.
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;
}
...
...
Continue like that. If you need more detail please free to ask.
Final Answer
//check for possible combinations
int top = x - 2;
int botton = x + 2;
int left = y - 2;
int right = y + 2;
if (top >= 0 && squares[top, y].BackColor == Color.Black)
{
squares[top + 1, y].BackColor = Color.Black;
}
else if (left >= 0 && squares[x, left].BackColor == Color.Black)
{
squares[x, left + 1].BackColor = Color.Black;
}
else if (left >= 0 && squares[x, left].BackColor == Color.Black)
{
squares[x, left + 1].BackColor = Color.Black;
}
Will be extended for a 8x8 board later on
Do you need it to be elegant? A kind of brute force method: You could check for pieces in the 8 different directions it is possible for them to be aligned. So for example, you start with a black piece. Check the next piece over in one direction. If it's white, keep going and take a note of the position that was white so you can change it to black later. When you finally hit a black piece, change all the stored positions to black and move on to the next direction and repeat the process until you've done all 8 directions.

Categories