尝试重置井字游戏

时间:2021-07-04 11:34:07

标签: c# wpf

我正在用 C# WPF 编写 Tic Tac Toe 游戏。这是我的代码

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace TicTacToe
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public bool isPlayer1Turn { get; set; }
        public int counter { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            NewGame();
        }
        

        public void NewGame()
        {
            counter = 0;
            isPlayer1Turn = false;

            button_0_0.Content = string.Empty;
            button_1_0.Content = string.Empty;
            button_2_0.Content = string.Empty;
            button_0_1.Content = string.Empty;
            button_1_1.Content = string.Empty;
            button_2_1.Content = string.Empty;
            button_0_2.Content = string.Empty;
            button_1_2.Content = string.Empty;
            button_2_2.Content = string.Empty;
        }

       

        private void Button_Click(object sender, RoutedEventArgs e)
        {
      
            if(counter>9)
            {
               NewGame();
               return;
            }
            var whichButton = sender as Button;

            if (whichButton.Content != null)
            {
                whichButton.Content += "";
                counter += 0;
            }
            else
            {
                counter++;
                if (isPlayer1Turn)                      // this can by replaced by:
                    isPlayer1Turn = false;              // isPlayer1Turn ^= true;
                else
                    isPlayer1Turn = true;
                    whichButton.Content = isPlayer1Turn ? "O" : "X";
            }
        }
    }
}

问题在于“新游戏”方法。我添加这个是因为我想在移动计数器大于 9 时重置游戏。当我添加这个方法时,即使我点击它们,我的按钮也是空的。如果我删除此方法,我可以单击按钮,它们会毫无问题地切换到“X”或“O”。有什么问题?有没有其他方法可以在不将按钮内容设置为空字符串的情况下重置游戏?

2 个答案:

答案 0 :(得分:1)

为什么在 Button_Click 方法中使用 null 检查按钮的内容?

您需要使用 string.Empty 检查按钮的内容,并在重新启动时检查“计数器”变量值是否等于 9:

private void Button_Click(object sender, RoutedEventArgs e)
{

    if (counter == 9)
    {
        NewGame();
        return;
    }
    var whichButton = sender as Button;

    if (whichButton.Content != string.Empty)
    {
        whichButton.Content += "";
        counter += 0;
    }
    else
    {
        counter++;
        if (isPlayer1Turn)                      // this can by replaced by:
            isPlayer1Turn = false;              // isPlayer1Turn ^= true;
        else
            isPlayer1Turn = true;
        whichButton.Content = isPlayer1Turn ? "O" : "X";
    }
}

答案 1 :(得分:0)

似乎您的 if 语句总是在 else 语句之前执行。

尝试替换下面的块

if (whichButton.Content != null)
{
    whichButton.Content += "";
    counter += 0;
}
    

if (whichButton.Content != null && !string.IsNullOrEmpty(whichButton.Content.ToString()))
{
    whichButton.Content += "";
    counter += 0;
}