0
我正在製作一個包含Tic Tac Toe遊戲的客戶端/服務器應用程序,其中兩個連接的客戶端可以玩遊戲。 3 x 3網格由9個動態創建的按鈕組成。 當第一個客戶端單擊網格上的按鈕時,該按鈕被禁用,並且內容顯示「X」。值被髮送到服務器,然後發送到其他連接的客戶端。根據客戶收到的價值,我希望禁用同一個按鈕,並將內容更改爲'X'。我怎樣才能找到一個動態創建的按鈕?
我遇到的問題是找到在客戶端動態創建的按鈕。 任何幫助表示讚賞!
//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;
}
}));
}
爲什麼在switch語句中一遍又一遍地複製相同的代碼? – theMayer