2012-12-12 3 views
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; 
      } 
     })); 
    } 
+1

왜 switch 문에 동일한 코드가 반복해서 복사 되었습니까? – theMayer

답변

1

클라이언트 코드를 소유하고 있습니까? 그렇다면 당신이 필요로하는 것보다 더 어렵게 만드는 것처럼 들립니다. 왜 각 tic 발가락 위치에있는 버튼에 대한 참조를 포함하는 3x3 배열을 사용하여 구현을 단순화하지 않는 것이 좋을까요? 그런 다음 클라이언트 메시지에서 버튼의 좌표를 추출하고 다른 클라이언트의 동일한 위치에있는 버튼을 업데이트하면됩니다. 로 번역 것 :

예컨대, 메시지는 "2, 1 버튼을 클릭"버튼으로 할 필요가 어떤 다른

buttonArray[2,1].Enabled = false; 

나.

관련 문제