Tic Tac Toe转变问题C#

时间:2015-10-26 17:51:59

标签: c# if-statement tic-tac-toe

我在基础编程课中,现在我们假设在一个模拟播放tic tac toe的程序中进行编码。在我的代码中,我打算让这个人选择他们是否想要观看模拟游戏,或者他们是否想要玩游戏,然后这将是一个双人游戏,我还没准备好尝试让游戏对抗电脑。

我被困在模拟部分上,因此转移到游戏部分。玩家一方,但我的if语句正在运行它的方式为玩家1做了动作,但随后也为玩家2做了。代码很长,但每个按钮都是相同基本代码的设置,所以我只发布一个按钮值。

我添加了"lblTest.Text = OneDown.ToString();"代码,所以我可以看到它的数学运算,每次点击都会计算玩家1和2,结果显示结束数为8.如何让它只为玩家运行一个或两个玩家?

private void btn1_Click(object sender, EventArgs e)
{
    if (PlayerTurn == 1)
    {
        OneDown = OneDown + 5;
        OneAcross = OneAcross + 5;
        SlashOne = SlashOne + 5;
        btn1.Text = "X";
        btn1.Enabled = false;
        PlayerTurn = PlayerTurn - 1;
        lblTurn.Text = "O";
    }

    if (SlashOne == 15 || OneAcross == 15 || OneDown == 15)
    {
        MessageBox.Show("Player 1 Wins!");
    }
    else if (PlayerTurn == 0)
    {
        OneDown = OneDown + 3;
        OneAcross = OneAcross + 3;
        SlashOne = SlashOne + 3;
        btn1.Text = "O";
        btn1.Enabled = false;
        PlayerTurn = PlayerTurn + 1;
        lblTurn.Text = "X";
        lblTest.Text = OneDown.ToString();
    }

    if (SlashOne == 9 || OneAcross == 9 || OneDown == 9)
    {
        MessageBox.Show("Player 2 Wins!");
    }

1 个答案:

答案 0 :(得分:2)

基本上你的其他 - 如果没有附加到正确的if。

private void btn1_Click(object sender, EventArgs e)
{
    if (PlayerTurn == 1)
    {
        OneDown = OneDown + 5;
        OneAcross = OneAcross + 5;
        SlashOne = SlashOne + 5;
        btn1.Text = "X";
        btn1.Enabled = false;
        PlayerTurn = PlayerTurn - 1;
        lblTurn.Text = "O";

        if (SlashOne == 15 || OneAcross == 15 || OneDown == 15)
        {
            MessageBox.Show("Player 1 Wins!");
        }

    }
    else if (PlayerTurn == 0)
    {
        OneDown = OneDown + 3;
        OneAcross = OneAcross + 3;
        SlashOne = SlashOne + 3;
        btn1.Text = "O";
        btn1.Enabled = false;
        PlayerTurn = PlayerTurn + 1;
        lblTurn.Text = "X";
        lblTest.Text = OneDown.ToString();

        if (SlashOne == 9 || OneAcross == 9 || OneDown == 9)
        {
            MessageBox.Show("Player 2 Wins!");
        }
    }