두 명의 연결된 클라이언트가 게임을 할 수있는 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