使用c#和ASP.NET的XO游戏

时间:2014-01-18 10:33:44

标签: c# asp.net

我是C#的新手(以及编程),我正在尝试与ASP.NET一起编写'XO'游戏 第一个玩家点击按钮后,我遇到了问题。

转弯没有切换,1号后的任何点击都没有。我的代码出了什么问题?

public partial class GamePage : System.Web.UI.Page
{
    Player player1 = new Player();
    Player player2 = new Player();
    int turn;

    protected void Page_Load(object sender, EventArgs e)
    {

        this.turn = 0;
        if (!IsPostBack)
        {
            Label1.Visible = true;
        }

        if (turn == 0)
        {
            Label1.Text = (Session["player1"] as Player).getname();
        }
        else
        {
            Label1.Text = (Session["player2"] as Player).getname();
        }

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Session["p1"] = player1;
        Session["p2"] = player2;
        player1.setsymbol("X");
        player2.setsymbol("O");

        if (Button1.Text == "")
        {
            if (turn == 0)
            {
                Button1.Text = player1.getsymbol();
                Label1.Text = (Session["player2"] as Player).getname();
                turn = 1;
            }
            else
            {
                Button1.Text = player2.getsymbol();
                Label1.Text = (Session["player1"] as Player).getname();
                turn = 0;
            }
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        if (Button2.Text == "")
        {
            if (turn == 0)
            {
                Button2.Text = player1.getsymbol();
                Label1.Text = (Session["player2"] as Player).getname();
                turn = 1;
            }
            else
            {
                Button2.Text = player2.getsymbol();
                Label1.Text = (Session["player1"] as Player).getname();
                turn = 0;
            }
        }
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        if (Button3.Text == "")
        {
            if (turn == 0)
            {
                Button3.Text = player1.getsymbol();
                Label1.Text = (Session["player2"] as Player).getname();
                turn = 1;
            }
            else
            {
                Button3.Text = player2.getsymbol();
                Label1.Text = (Session["player1"] as Player).getname();
                turn = 0;
            }
        }
    }

//这是一个例子 - 我从button1到9具有相同的行

2 个答案:

答案 0 :(得分:1)

每次页面渲染时,您都会在turn中将Page_Load设置为0。因为Page_Load是在每次加载页面时执行的,所以你不会得到任何其他值,这可能是这里的主要问题。

要正确支持应在连续请求中保持值的变量的生命周期,请将它们包装在simple属性中:

public int turn
{
    get
    {
        if ( Session["turn"] != null )
             return (int)Session["turn"];
        return 0; // default value if not set before
    }
    set
    {
        Session["turn"] = value;
    }
}

这种方式每当您在代码中引用turn,将其设置为0或1或值设置为0或1时,您将引用相同的值,可能存储在之前的请求中。

答案 1 :(得分:0)

仅当this.turn=0;为false时才应执行

IsPostBack。在if。{/ p>中的Page_Load内移动此行