2012-12-12 179 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

您是否拥有客户端代码?如果是这样,这听起来像你让它比它需要更困难。你为什么不简化3x3数组的实现,该数组包含对每个井字头位置按钮的引用。然后,您只需从客户端消息中提取按钮的坐标,并在另一个客户端上的相同位置更新该按钮。

例如,消息“点击按钮:2,1”将转化为:

buttonArray[2,1].Enabled = false; 

,或者你需要的任何其他做的按钮。

相关问题