Getting Button location in array by clicking on it - c#

I have a grid made out of modified buttons named in the code as GridEl. Every GridEl are inside the array named as Grid[,], i want to get GridEl's location in array by clicking on it, how i can do it?
For example it have to write in the console the row and the column, and that's how it should look in the console: "Row: 2; Column: 5". Of course every button have to write its own location.*
void CreateGrid()
{
GridEl[,] Grid = new GridEl[4, 6];
int c, r, gcount; // c = Column, r = Row, gcount = GridEls count
c = 0; r = 0; gcount = 0;
while ((c < 7)&&(r < 5) && (gcount != 24)) //Loop that creates grid
{
if ((c == 6) && (r < 4))
{
r++;
c = 0;
}
Grid[r, c] = new GridEl();
Grid[r, c].Size = new System.Drawing.Size(64, 64);
Grid[r, c].Location = new System.Drawing.Point(21 * 3 * c, 21 * 3 * r);
MainForm.Controls.Add(Grid[r,c]);
c++;
gcount++;
}
}
public class GridEl : Button
{
//here is the code of GridEl
}

Use this for your GridEl button class definition
public class GridEl : Button
{
public int R { get; set; }
public int C { get; set; }
}
Add this to your while loop
Grid[r, c].R = r;
Grid[r, c].C = c;
Grid[r, c].Click += OnClick;
and finally your Click event handler for the button
private void OnClick(object sender, EventArgs eventArgs)
{
GridEl thisButton = sender as GridEl;
Console.WriteLine($"Row: {thisButton.R}; Column: {thisButton.C}");
}
What you are doing here is simply setting the Row and Column values on the grid button itself, so it always know what the value is and is accessible when it needs it.

Related

C#, Having an issue with two buttons starting one method

If you're from the USA, and you've ever been to a Cracker Barrel, then you've probably played the board game where you have to jump pegs until you only have one left. It's similar to Chinese checkers, with just a pyramid, or a triangle.
I have a form that makes the buttons and adds them to the form, and I have a "TheBoard" class that has all of the rules for how jumping works on the form. In my form, I also have a button clicker method that needs to run all of this.
I seem to have hit a brick wall. I can't figure out the logic behind getting it to accept a second click, in order to move through the whole if statements in the board class. My parameter for the move method in the board class takes an int x, which is the button you click on as a parameter. I feel like I'm missing the second half of the move. How do I get my move method to register two button clicks (the starting location of the peg and the end location of the peg)?
Code for form:
public partial class Form1 : Form
{
private Button[] btn = new Button[15];
private TheBoard myboard = new TheBoard();
public Form1()
{
InitializeComponent();
int buttonsPerRow = 1;
int index = 0;
while (index < btn.Length)
{
int increment = this.Width / (buttonsPerRow + 1);
for (int j = 1; j <= buttonsPerRow; j++)
{
btn[index] = new Button
{
//other style elements of the button
Name = "btn" + index
}
btn[index].Click += new EventHandler(this.My_Click);
Controls.Add(btn[index]);
index++;
}
buttonsPerRow++;
}
}
private void My_Click(object sender, EventArgs e) {
myboard.getValues();
Button b = (Button)sender;
string bName = b.Name;
// Now pull off the btn
string num = bName.Substring(3, bName.Length - 3);
// Parsing the number to an int
int x = Int32.Parse(num);
myboard.move(x);
int[] color = myboard.getValues();
for (int i = 0; i < 15; i++)
{
color = myboard.getValues();
if (color[i] == TheBoard.hasPeg)
{
btn[i].BackColor = System.Drawing.Color.Yellow;
}
else
btn[i].BackColor = System.Drawing.Color.Black;
}//for
}
}
Code for TheBoard class:
class TheBoard
{
static public int hasPeg = 100;
static public int noPeg = 50;
private int[] board;
private int firstMove; //1st click
public TheBoard()
{
board = new int[15];
board[0] = noPeg;
for(int i = 1; i < 15; i++)
{
board[i] = hasPeg;
}
firstMove = -1; //giving last move a location, starting it at the beginning
}
public int move(int x)
{
if(firstMove == -1)
{
firstMove = x;
return 0;
}
// blank at 0
// if you click a blank your 1st move
if (firstMove == noPeg)
{
Console.WriteLine("You cant move if there isn't a peg.");
return 666;
}
// first---------------------------------------middle-----------------------end
if (firstMove == 1 && board[0] == hasPeg && board[3] == hasPeg && board[6] == noPeg)
{
RemovePeg(board[0], board[3], board[6]);
return 0;
}
if (firstMove == 1 && board[0] == hasPeg && board[2] == hasPeg && board[4] == noPeg)
{
RemovePeg(board[0], board[2], board[4]);
return 0;
}
//etc for remaining firstMove possibilities
firstMove = -1;
return 5;
}
private int RemovePeg(int first, int second, int goal) {
board[goal] = hasPeg;
board[first] = noPeg;
board[second] = noPeg;
return 0;
}
public int[] getValues()
{
return board;
}
}
I looked over the code and I think I understand your problem; you can select the starting peg but you don't have a way to select where it should go. With minimal edit to your code, I would store the first button click in a global variable and then the second button click knows that it is the second and initiates the board move with the two pieces of information (and resets the global variable).

Random labels in Tic Tac Toe simulation

I am working on a Tic Tac Toe simulator for a class and have run into an issue.
I created a 2-dimensional array to simulate the board and populate it with either 0 or 1 in all the boxes.
The issue I am having is getting those numbers to apply to the labels I have created (a1, a2, a3, b1, b2, etcetera).
Is there a way that my nested for loops can have each element in the array apply to a new label? I can't seem to find anything in my book or online about this.
Here is my related code:
private void newBTN_Click(object sender, EventArgs e)
{
Random rand = new Random();
const int ROWS = 3;
const int COLS = 3;
int [,] board = new int[ROWS, COLS];
for (int row = 0; row < ROWS; row++)
{
for (int col = 0; col < COLS; col++)
{
board[row, col] = rand.Next(1);
}
}
}
What are the names of the labels? I assumed below that the labels are Label0_0, Label0_1, Label1_1 and so on... This way you can find them using the row and column values.
You want to find the Label control on your form dynamically, because you don't know the name in advance while coding.
If you know the name in advance you just say: label1.Text = "1";.
But in your case, you are trying to find a particular control in each iteration of the loop. So you need to have a name for the labels so you can find them using Form.Controls.Find(string, bool) like this:
var row = 4;
var col = 6;
var l = this.Controls.Find("Label" + row.ToString() + "_" + col.ToString(), false).FirstOrDefault() as Label;
if (l == null)
{
//problem... create label?
l = new Label() { Text = "X or O" }; //the position of this need to be set (the default is 0,0)
this.Controls.Add(l);
}
else
{
l.Text = "X or O";
}
Your board stores integers, which is an internal representation of your game state. You can create a UniformGrid that holds Label for your game GUI. The code below returns a grid based on your current board. You need to add this returned grid to your MainWindow (or whatever you use) to see it.
private UniformGrid fillLabels(int[,] board)
{
int numRow = board.GetLength(0);
int numCol = board.GetLength(1);
UniformGrid g = new UniformGrid() { Rows = numRow, Columns = numCol };
for (int i = 0; i < numRow; i++)
{
for (int j = 0; j < numCol; j++)
{
Label l = new Label();
l.Content = (board[i, j] == 0) ? "O" : "X";
Grid.SetRow(l, i);
Grid.SetColumn(l, j);
g.Children.Add(l);
}
}
return g;
}
First, do not re-create (and re-initialize) Random each time you need it: it makes generated sequences skewed badly:
private static Random s_Rand = new Random();
Try not implement algorithm in the button enent directly, it's a bad practice:
private void CreateField() { ... }
private void newBTN_Click(object sender, EventArgs e) {
CreateField();
}
putting all together:
private static Random s_Rand = new Random();
private void ApplyLabelText(String name, String text, Control parent = null) {
if (null == parent)
parent = this;
Label lb = parent as Label;
if ((lb != null) && (String.Equals(name, lb.Name))) {
lb.Text = text;
return;
}
foreach(Control ctrl in parent.Controls)
ApplyLabelText(name, text, ctrl);
}
private void CreateField() {
for (Char row = 'a'; row <= 'c'; ++row)
for (int col = 1; col <= 3; ++col)
ApplyLabelText(row.ToString() + col.ToString(), s_Rand.Next(1) == 0 ? "O" : "X");
}
private void newBTN_Click(object sender, EventArgs e) {
CreateField();
}
How about you skip the INTEGER board and go directly to a Label array?
You can then do the following to loop trough all of them:
Label[,] listOfLabels; // Do also initialize this.
foreach(Label current in listOfLabels)
{
current.Text = _rand.Next(2) == 0 ? "0" : "X";
}

C# - How to access property of an array object?

I dont know how to show clearly, so:
Example - I create an array of button like this:
Button[,] _button = new Button[3, 3];
public MainPage()
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
_button[i, j] = new Button();
_button[i, j].Name = "btn" + i.ToString() + j.ToString();
_button[i, j].Tag = 0;
//Add Click event Handler for each created button
_button[i, j].Click += _button_Click;
boardGrid.Children.Add(_button[i, j]);
Grid.SetRow(_button[i, j], i);
Grid.SetColumn(_button[i, j], j);
}
} // end MainPage()
private void _button_Click(object sender, RoutedEventArgs e)
{
Button b = (Button)sender;
if (...)
b.Tag = 1;
else
b.Tag = 2;
}// end Click Event
Now how can I compare the Tag of 2 buttons in that array like:
b[1,1].Tag == b[1,2].Tag ? ...<do st>... : ....<do st>...
If you need to find position of control in array consider to set Control.Tag to that position instead of search:
_button[i, j].Tag = new System.Drawing.Point{ X = j, Y = i};
And instead of searching just
Point position = (Point)((Button)sender).Tag;
Or if you need more information (like Position + 0/x/empty choice you have) - have custom class to hold all information you need:
enum CellState { Empty, Player1, Player2 };
class TicTacToeCell
{
public Point Position {get;set;}
public CellState State {get;set;}
}
Now when you have position and state - use _buttons array to index access other ones:
Check same row:
Point position = (Point)((Button)sender).Tag;
int player1CountInThisRow = 0;
for (var col = 0; col < 3; col++)
{
if (((TicTacToeCell)(_button[position.Y, col].Tag).State == CellState.Player1)
{
player1CountInThisRow ++;
}
}
This is more of a long-winded clarification than a definite answer, but it may uncover what you're really trying to do:
In the code that you show b is (presumably) a single Button, not an array of buttons. Do you mean:
_button[1,1].Tag == _button[1,2].Tag ? ...<do st>... : ....<do st>...
Or are you trying to compare b (the event sender) to a button relative to it in the array?

C# label control not working properly

When I run the following code, it populates the label1 control one time. Then the label1 control does nothing else. How do I get the label1 control to change on the mouse enter events. Please provide code examples.
int currentXposition, currentYposition;
const string positionLabel = "Current Position: ";
private void Test_Load(object sender, EventArgs a)
{
var temp=Color.Transparent; //Used to store the old color name of the panels before mouse events
var colorName = Color.Red; //Color used to highlight panel when mouse over
int numBlocks = 8; //Used to hold the number of blocks per row
int blockSize=70;
//Initialize new array of Panels new
string[,] Position = new string[8, 8];
Panel[,] chessBoardPanels = new Panel[numBlocks, numBlocks];
string Alphabet = "A,B,C,D,E,F,G,H";
string Numbers ="1,2,3,4,5,6,7,8";
string[] alphaStrings = Alphabet.Split(',');
string[] numStrings=Numbers.Split(',');
// b = sub[0];
int FirstValue, SecondValue;
//Store Position Values
for (int firstValue = 0; firstValue < 8; ++firstValue)
{
FirstValue = Alphabet[firstValue];
for (int SecValue = 0; SecValue < 8; ++SecValue)
{
SecondValue = Numbers[SecValue];
Position[firstValue, SecValue] = alphaStrings[firstValue] + numStrings[SecValue];
}
}
//Loop to create panels
for (int iRow = 0; iRow < numBlocks; iRow++)
{
for (int iColumn = 0; iColumn < numBlocks; iColumn++)
{
Panel p = new Panel();
//set size
p.Size = new Size(blockSize, blockSize);
//set back colour
p.BackColor = (iRow + (iColumn % 2)) % 2 == 0 ? Color.Black : Color.White;
//set location
p.Location = new Point(blockSize *iRow+15, blockSize * iColumn+15);
chessBoardPanels[iRow, iColumn] = p;
chessBoardPanels[iRow,iColumn].MouseEnter += (s,e) =>
{
currentXposition = iRow;
currentYposition = iColumn;
var oldColor = (s as Panel).BackColor;
(s as Panel).BackColor = colorName;
temp = oldColor;
label1.Text = Position[iRow, iColumn];
};
chessBoardPanels[iRow, iColumn].MouseLeave += (s, e) => {
(s as Panel).BackColor = temp;
};
groupBox1.Controls.Add(p);
}
}
}
I'm answering this only because I think it's important to show what happens when scope is confused. The reason you're having your issue is the scope of your variables. Your label is changing iRow * iColumn times, but only during initial execution. From then on, iRow and iColumn are fixed at their final values.
To achieve your desired end goal, it'd be easiest to create an extension of Panel:
public class ChessPanel : Panel {
private const Color HighlightColor = Color.Red;
public int iColumn { get; set; }
public int iRow { get; set; }
public Color PrimaryColor { get; set; }
public ChessPanel() : base()
{
this.MouseEnter += (s,e) =>
{
this.PrimaryColor = this.BackColor;
this.BackColor = HighlightColor;
};
this.MouseLeave += (s,e) =>
{
this.BackColor = this.PrimaryColor;
};
}
}
This will then allow you to reduce your code as follows:
int currentXposition, currentYposition;
const string positionLabel = "Current Position: ";
private void Test_Load(object sender, EventArgs a)
{
var temp=Color.Transparent; //Used to store the old color name of the panels before mouse events
var colorName = Color.Red; //Color used to highlight panel when mouse over
int numBlocks = 8; //Used to hold the number of blocks per row
int blockSize=70;
//Initialize new array of Panels new
string[,] Position = new string[8, 8];
ChessPanel[,] chessBoardPanels = new ChessPanel[numBlocks, numBlocks];
string Alphabet = "A,B,C,D,E,F,G,H";
string Numbers ="1,2,3,4,5,6,7,8";
string[] alphaStrings = Alphabet.Split(',');
string[] numStrings=Numbers.Split(',');
int FirstValue, SecondValue;
//Store Position Values --- no idea what this is supposed to do...
for (int firstValue = 0; firstValue < 8; ++firstValue)
{
FirstValue = Alphabet[firstValue];
for (int SecValue = 0; SecValue < 8; ++SecValue)
{
SecondValue = Numbers[SecValue];
Position[firstValue, SecValue] = alphaStrings[firstValue] + numStrings[SecValue];
}
}
//Loop to create panels
for (int iRow = 0; iRow < numBlocks; iRow++)
{
for (int iColumn = 0; iColumn < numBlocks; iColumn++)
{
ChessPanel p = new ChessPanel();
//set size
p.Size = new Size(blockSize, blockSize);
//set back colour
p.BackColor = (iRow + (iColumn % 2)) % 2 == 0 ? Color.Black : Color.White;
//set location
p.Location = new Point(blockSize *iRow+15, blockSize * iColumn+15);
p.MouseEnter += (s,e) =>
{
var cpSelf = s as ChessPanel;
if (cpSelf != null)
{
label1.Text = Position[cpSelf.iRow, cpSelf.iColumn];
}
};
groupBox1.Controls.Add(p);
chessBoardPanels[iRow, iColumn] = p;
}
}
}
I'm assuming you're making use of many of those variables later on int the program, and looking at this kind of makes my head hurt, so I left most of it in place.
Delegates are a very powerful and useful utility, but they can cause confusion with variable scope. Be very careful when using these, and make sure you treat them as functional units that execute later and can therefore only rely on the state of the program at execution of the block rather than at creation of the block. If you notice, I kept the reference to the Position array simply to show that you can still access local variables within the scope of the delegate because it is technically still in scope. Structurally, this could easily be moved into the ChessPanel class and referenced 100% locally. This example should be used as a caution as it can show how a "local" variable that many people assume are garbage-collected at end of function execution can hang around and eat up memory.
This code is untested and may have minor syntax errors. Hopefully the spirit of the structure is understood.

Why won't the label populate

I have been trying to create a chess strategy application. I seem to be having issues with trying to get the label1 control to populate during run time. I am actually pretty new to the idea of dynamically creating events like 'mouse enter, mouse leave' How do I get the label to show the coordinates in the mouse enter event
int currentXposition, currentYposition;
const string positionLabel = "Current Position: ";
private void Test_Load(object sender, EventArgs a)
{
var temp=Color.Transparent; //Used to store the old color name of the panels before mouse events
var colorName = Color.Red; //Color used to highlight panel when mouse over
int numBlocks = 8; //Used to hold the number of blocks per row
int blockSize=70;
//Initialize new array of Panels new
string[,] Position = new string[8, 8];
Panel[,] chessBoardPanels = new Panel[numBlocks, numBlocks];
string Alphabet = "A,B,C,D,E,F,G,H";
string Numbers ="1,2,3,4,5,6,7,8";
string[] alphaStrings = Numbers.Split(',');
string[] numStrings=Numbers.Split(',');
// b = sub[0];
int FirstValue, SecondValue;
//Store Position Values
for (int firstValue = 0; firstValue < 8; ++firstValue)
{
FirstValue = Alphabet[firstValue];
for (int SecValue = 0; SecValue < 8; ++SecValue)
{
SecondValue = Numbers[SecValue];
Position[firstValue, SecValue] = alphaStrings[firstValue] + numStrings[SecValue];
}
}
//Loop to create panels
for (int iRow = 0; iRow < numBlocks; iRow++)
for (int iColumn = 0; iColumn < numBlocks; iColumn++)
{
Panel p = new Panel();
//set size
p.Size = new Size(blockSize, blockSize);
//set back colour
p.BackColor = (iRow + (iColumn % 2)) % 2 == 0 ? Color.Black : Color.White;
//set location
p.Location = new Point(blockSize *iRow+15, blockSize * iColumn+15);
chessBoardPanels[iRow, iColumn] = p;
chessBoardPanels[iRow,iColumn].MouseEnter += (s,e) =>
{
currentXposition = iRow;
currentYposition = iColumn;
var oldColor = (s as Panel).BackColor;
(s as Panel).BackColor = colorName;
temp = oldColor;
label1.Text = Position[iRow, iColumn];
};
chessBoardPanels[iRow, iColumn].MouseLeave += (s, e) =>
{
(s as Panel).BackColor = temp;
};
groupBox1.Controls.Add(p);
}
}
Try this.. It was not populating because of a out of range.. iRow always = 8...
Add this class to your project.
public class ChessSquare
{
public string Letter { get; set; }
public int Number { get; set; }
public Color Color { get; set; }
public string Position
{
get { return string.Format("{0}{1}", Letter, Number); }
}
public ChessSquare()
{
}
public ChessSquare(string letter, int number)
{
Letter = letter;
Number = number;
}
}
Replace the FormLoad method with this:
int blockSize = 20;
Panel[,] chessBoardPanels = new Panel[8, 8];
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
ChessSquare sq = new ChessSquare(((char)(65+i)).ToString(), j);
sq.Color = (i + (j % 2)) % 2 == 0 ? Color.AliceBlue : Color.White;
Panel p = new Panel()
{ Size = new Size(blockSize, blockSize),
BackColor = sq.Color,
Tag = sq,
Location = new Point(blockSize * i + 15, blockSize * j+15),
};
p.MouseEnter+=new EventHandler(squareMouseEnter);
p.MouseLeave += new EventHandler(squareMouseLeave);
chessBoardPanels[i, j] = p;
groupBox1.Controls.Add(p);
}
}
And add those two methods to your code:
void squareMouseEnter(object sender, EventArgs e)
{
Panel p = (Panel)sender;
ChessSquare sq = (ChessSquare)p.Tag;
p.BackColor = Color.Aqua;
label1.Text = string.Format("Current position: {0}", sq.Position);
}
void squareMouseLeave(object sender, EventArgs e)
{
Panel p = (Panel) sender;
ChessSquare sq = (ChessSquare)p.Tag;
p.BackColor = sq.Color;
}
I there are several ways of doing it... This one is pretty straight forward.

Categories