Reputation: 804
I am making a client/server application that contains a Tic Tac Toe game where two connected clients can play the game. The 3 x 3 grid is made up of 9 dynamically created buttons. When the first client clicks a button on the grid, the button is disabled and the content shows a 'X'. A value is sent to the server and then to the other connected client. Based on the value received by the client, I want the same button to be disabled and the content changed to 'X'.
The problem I have is finding the button that was dynamically created on the client side. Any help appreciated!
//Dynamically created 9 buttons on the client
private void initBoard(int rank)
{
board = new tttBoard(rank);
boardGrid.Children.Clear();
boardGrid.Rows = rank;
for (int i = 0; i < rank; i++)
{
for (int j = 0; j < rank; j++)
{
newButton = new Button();
newButton.Tag = new Point(i, j);
newButton.Name = "b" + i.ToString() + j.ToString();
newButton.Content = newButton.Tag;
boardGrid.Children.Add(newButton);
}
}
}
//Method that receives data - CheckButton called method within this
public void OnDataReceived(IAsyncResult ar)
{
try
{
SocketPacket sckID = (SocketPacket)ar.AsyncState;
int iRx = sckID.thisSocket.EndReceive(ar);
char[] chars = new char[iRx];
Decoder d = Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(sckID.dataBuffer, 0, iRx, chars, 0);
szData = new String(chars);
this.Dispatcher.Invoke((Action)(() =>
{
if(szData.Contains("Clicked button : "))
{
return;
}
else
lbxMessages.Items.Add(txtMessage.Text + szData);
}));
ClickButton();
WaitForData();
}
catch (ObjectDisposedException)
{
Debugger.Log(0, "1", "\n OnDataRecieved: Socket has been closed\n");
}
catch(SocketException se)
{
MessageBox.Show(se.Message);
}
}
//based on the message received from the server, I check to see if
//it contains "Clicked button: " and a value that I use to locate the correct
//button to disable and change content to 'x' to represent the move made by the
//other client
public void ClickButton()
{
if (szData.Contains("Clicked button : "))
{
value = szData.Substring(17, 1);
}
this.Dispatcher.Invoke((Action)(() =>
{
btnName = "b0" + value;
object item = grdClient.FindName(btnName);//boardGrid.FindName(btnName);
if (item is Button)
{
Button btn = (Button)item;
btn.IsEnabled = false;
}
}));
}
Upvotes: 0
Views: 171
Reputation: 1107
Do you own the client code? If so, it sounds like you are making it more difficult than it needs to be. Why don't you just simplify the implementation with a 3x3 array that contains references to the buttons in each of the tic tac toe positions. Then all you have to do is extract the coordinates of the button from the client message and update the button in the same position on the other client.
E.g., the message "clicked button : 2, 1" would translate to:
buttonArray[2,1].Enabled = false;
or whatever else you needed to do to the button.
Upvotes: 1