我目前正在寫一個XO遊戲與C#和有問題。 XO表是一個asp按鈕的集合,我想寫一個函數,在每個按鈕中放入X或O值 - 它需要是動態的。我該怎麼寫這樣的功能?這是我到目前爲止所做的一個例子。XO遊戲在ASP.net和C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
turndisplay.Visible = true;
Session["p1"] = player1;
Session["p2"] = player2;
player1.setsymbol("X");
player2.setsymbol("O");
//Button1.Click += Button1_Click;
//Button2.Click += Button_Click;
//Button3.Click += Button_Click;
//Button4.Click += Button_Click;
//Button5.Click += Button_Click;
//Button6.Click += Button_Click;
//Button7.Click += Button_Click;
//Button8.Click += Button_Click;
//Button9.Click += Button_Click;
}
if (turn == 0)
{
turndisplay.Text = (Session["player1"] as Player).getname();
}
else
{
turndisplay.Text = (Session["player2"] as Player).getname();
}
}
public void pushthebutton() // currently effects only on button 1 !
{
if (turn == 0)
{
player1.setsymbol("X");
Button1.Text = (Session["p1"]as Player).getsymbol();
turndisplay.Text = (Session["player2"] as Player).getname();
turn = 1;
}
else
{
player2.setsymbol("O");
Button1.Text = player2.getsymbol();
turndisplay.Text = (Session["player1"] as Player).getname();
turn = 0;
}
}
protected void Button1_Click(Button sender, EventArgs e)
{
if (Button1.Text == " ")
{
pushthebutton();
gamecheck();
}
}
我該如何影響玩家想要的每個按鈕,而不用寫9次?
編輯後*所以你說..改變(對象發件人)爲(按鈕發件人)?但我的功能pushtebutton只知道Button1.Text
@WilliamCustode有你答案。爲按鈕單擊事件創建一個方法 - 並將該方法分配給每個按鈕「OnClick」事件。你需要將'sender'轉換爲'Button'類型,然後你可以得到'Text'屬性 - 'Button btn = sender as Button; if(btn!= null){if(btn.Text ==「」){}}' – Tim