【问题标题】:Getting an error in (C# Program for Tic Tac Toe)在(井字游戏的 C# 程序)中出现错误
【发布时间】:2016-12-04 10:48:16
【问题描述】:

关于计划:

我编写了一个用于制作井字游戏的 C# 代码。它是在 Windows 窗体应用程序(Visual Studio)中制作的。 在玩这个游戏时,当 X 或 O 获胜时,调用方法=> checkForwinner() 进行水平、垂直和对角线检查以确定获胜者。变量 there_is_a_winner 设置为 true,并显示消息“获胜者获胜”。否则它会检查平局。

错误:

当我编译此代码时,它显示 0 错误/警告/消息。但尽管如此,此代码不起作用。它无法确定获胜者。弹出框,显示谁赢了/画了..从不执行,除此之外,这段代码工作正常。我希望有人可以提供帮助。

提前致谢。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    bool turn = true;//(To check turn) True means X's turn, False=Y turn
    int turn_count = 0;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void aboutToolStripMenuItem_Click(object sender, EventArgs e)/*About Section*/
    {
        MessageBox.Show("This Program is of Tic Tac Toe. It was created by Me for his C# project.","Tic Tac Toe -About");
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)/*Exit Section*/
    {
        Application.Exit();
    }

    private void button_click(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        if(turn)
            b.Text="x";
        else
        b.Text="o";
        turn=!turn;
        b.Enabled = false;//disable the button, to prevent double entering.
        turn_count++;
    }
    private void checkForwinner()
    {
        bool there_is_a_winner= false;

        //horizontal check
        
         if ((A1.Text == A2.Text) && (A2.Text == A3.Text) && (!A1.Enabled))
            there_is_a_winner = true;//if above conditions are true, then bool variable=true.
        else if ((B1.Text == B2.Text) && (B2.Text == B3.Text) && (!B1.Enabled))
            there_is_a_winner = true;

        else if ((C1.Text == C2.Text) && (C2.Text == C3.Text) && (!C1.Enabled))
            there_is_a_winner = true;

        //Vertical Check
        else if ((A1.Text == B1.Text) && (B1.Text == C1.Text) && (!A1.Enabled))
            there_is_a_winner = true;

        else if ((A2.Text == B2.Text) && (B2.Text == C2.Text) && (!A2.Enabled))
            there_is_a_winner = true;

        else if ((A3.Text == B3.Text) && (B3.Text == C3.Text) && (!A3.Enabled))
            there_is_a_winner = true;

        //Diagonal Check
        else if ((A1.Text == B2.Text) && (B2.Text == C3.Text) && (!A1.Enabled))
            there_is_a_winner = true;

        else if ((A3.Text == B2.Text) && (B2.Text == C1.Text) && (!C1.Enabled))
            there_is_a_winner = true;

         if (there_is_a_winner)
         {
             dissableButtons();// If there is a winner call for buttons to be disbaled.

             String winner = "";
             if (turn)
                 winner = "0";
             else
                 winner = "x";
             MessageBox.Show(winner + "Wins!", "Congratulations!");
         }
        else
        {
            if (turn_count == 9)
                MessageBox.Show("Match Draw", "Result");
        }

        
    }
        private void dissableButtons()
        {
            try
            {
                foreach (Control c in Controls)
                {
                    Button b = (Button)c;
                    b.Enabled = false;//If there is a winner, disable all the buttons on the form
                }

            }
            catch { }
        }
    // New Game//Need to Reset Everything
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            turn = true;
            turn_count = 0;
            try
            {
                foreach (Control c in Controls)
                {
                    Button b = (Button)c;
                    b.Enabled = true;
                    b.Text = "";//Initially we want blank Text

                }
            }
            catch { }
        }
    }
}

【问题讨论】:

  • 使用调试器并单步执行您的代码。 “它不起作用”也太宽泛了 - 请解释您提供的输入和您期望的输出。

标签: c# visual-studio visual-studio-2010


【解决方案1】:

问题是函数 checkForwinner() 永远不会在程序的任何地方被调用。

我希望 button_click 函数在适当的单元格中放置一个 X 或一个 O,因此当单击该按钮时,它还需要检查是否有赢家。我建议你在 button_click 函数的最后一行调用 checkForwinner() ,这样每次点击时都会进行检查。

另外,作为样式说明,请将其重命名为 checkForWinner 并带有大写 W。此外,您应该缩进 b.Text="o"; 行。像这样:

    if(turn)
        b.Text="x";
    else
        b.Text="o";

话虽如此,我更喜欢在单行上使用花括号,所以我更喜欢这个:

    if(turn) 
    {
        b.Text="x";
    }
    else
    {
        b.Text="o";
    }

尽管这会占用更多的行,但当您在“if”子句或“else”子句中添加另一行而忘记添加那些最重要的花括号时,它确实可以避免您将来遇到问题。这是一个好习惯 - 到处都是花括号。

【讨论】:

  • 是的,checkForwinner() 永远不会在程序的任何地方被调用......这就是问题所在。谢谢。
【解决方案2】:

当您提出问题时,您必须更加具体。在这种情况下,您可以做更多的事情,因为我在这段代码中看到了几个大错误。我只是指出其中的几个:

  1. 你不应该这样做:

    try 
    {
     ...
    }
    catch {}
    

如果你这样做,你会“吃掉”异常,你永远不知道发生了什么。只有极少数情况下需要使用 catch。在您知道自己在做什么之前,请勿使用 catch

您可以在应用程序级别显示任何异常:

在 Program.cs 中,在 Main 方法中添加:

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.ThreadException += Application_ThreadException;
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        Application.Run(new Form());
    }

    private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
          MessageBox.Show(((Exception)e.ExceptionObject).Message);      
    }

    private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
          MessageBox.Show(e.Exception.Message);      
    }
}       
  1. 在您的方法 button_click 中,您使用 if .. else ...,但请检查是否不需要添加 { ... }

    if (...) {
        code here
    }
    else {
       code here
    }
    
  2. 对私有字段使用可见性限定符private

    private bool turn = true;//(To check turn) True means X's turn, False=Y turn    
    private int turn_count = 0;
    
  3. 代替Application.Exit();使用方法Form.Close()this.Close();

  4. 如果您使用 if .. else if .. 块,请始终使用 final else 块,但有例外。它会告诉你你错过了什么:

    if (...)
    {
       ...
    }
    else if (...)  
    {
       ...
    }
    else
    {
      throw new NotImplementedException("Not Implemented Yet");
    }
    

【讨论】:

  • 谢谢您的回答。
猜你喜欢
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 2017-08-28
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多