2 Replies - 2299 Views - Last Post: 09 August 2015 - 10:31 AM Rate Topic: -----

#1 cross101   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 06-January 15

C# Button Instance PerformClick issue

Posted 09 August 2015 - 09:42 AM

Hello
I recently started to learn C#. I have some small c++ knowledge, and i started to follow a Tic Tac Toe tutorial in Visual C#, Windows form.
Everything went on ok until i tried to add a "single-player" mode, where the user can play vs the Computer.

I am trying to select a game mode in the first form that loads, in the case of loading the player vs player mode, everything runs ok, if i try the player vs computer mode, it doesnt run "so ok".
The "Computer" makes its moves, but in the end if he wins i get a pop-up with him winning twice, and the stats update as he has 2 wins, and if its a draw, no pop-up message shows up, and i get and exception for the Button instance("move") i am using to select the Computer choice .
After i play into a draw vs Computer, and use all the available moves, instead of the draw message i get the following exception from "move.PerformClick()":

An unhandled exception of type 'System.NullReferenceException' occurred in xO.exe
Additional information: Object reference not set to an instance of an object.



Here is the code from the Form i'm having issues:

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

namespace xO
{
    public partial class Form1 : Form
    {
        bool turn = true;  //true - X's turn;  false - O's turn;
        int turnsCount = 0;
        static string player1, player2;
        public static bool vsComputehr = false;


        public Form1()
        {
            InitializeComponent();
        }

        public static void SetPlayerNames(string n1, string n2)
        {
            player1 = n1;
            player2 = n2;
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("X si O ......", "X si O About");
        }

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

        private void Buttonclick(object sender, EventArgs e)
        {
            Button b = (Button)sender;

            if (turn)
            {
                b.Text = "X";
                turn = false;
                b.Enabled = false;
                turnsCount++;
            }
            else
            {
                b.Text = "O";
                turn = true;
                b.Enabled = false;
                turnsCount++;
            }

            if ((turn == false) && (vsComputehr == true))
            {
                ComputehrMakeMove();
            }

            CheckForWinner();
        }

        private void ComputehrMakeMove()
        {
            Button move = null;

            //look for tic tac toe opportunities
            move = LookForWinOrBlock("O"); //look for win
            if (move == null)
            {
                move = LookForWinOrBlock("X"); //look for block
                if (move == null)
                {
                    move = LookForCorner();
                    if (move == null)
                    {
                        move = LookForOpenSpace();
                    }//end if
                }//end if
            }//end if
           
            move.PerformClick();

        }

        private Button LookForOpenSpace()
        {
                Console.WriteLine("Looking for open space");
                Button b = null;
                foreach (Control c in Controls)
                {
                    b = c as Button;
                    if (b != null)
                    {
                        if (b.Text == "")
                            return b;
                    }//end if
                }//end if

                return null;
         }

        private Button LookForCorner()
        {
            Console.WriteLine("Looking for corner");
            if (A1.Text == "O")
            {
                if (A3.Text == "")
                    return A3;
                if (C3.Text == "")
                    return C3;
                if (C1.Text == "")
                    return C1;
            }

            if (A3.Text == "O")
            {
                if (A1.Text == "")
                    return A1;
                if (C3.Text == "")
                    return C3;
                if (C1.Text == "")
                    return C1;
            }

            if (C3.Text == "O")
            {
                if (A1.Text == "")
                    return A3;
                if (A3.Text == "")
                    return A3;
                if (C1.Text == "")
                    return C1;
            }

            if (C1.Text == "O")
            {
                if (A1.Text == "")
                    return A3;
                if (A3.Text == "")
                    return A3;
                if (C3.Text == "")
                    return C3;
            }

            if (A1.Text == "")
                return A1;
            if (A3.Text == "")
                return A3;
            if (C1.Text == "")
                return C1;
            if (C3.Text == "")
                return C3;

            return null;
        }

        private Button LookForWinOrBlock(string xso)
        {
            Console.WriteLine("Looking for win or block:  " + xso);

            //Verificari Orizontala
            if ((A1.Text == xso) && (A2.Text == xso) && (A3.Text == ""))
                return A3;
            if ((A2.Text == xso) && (A3.Text == xso) && (A1.Text == ""))
                return A1;
            if ((A1.Text == xso) && (A3.Text == xso) && (A2.Text == ""))
                return A2;

            if ((B1.Text == xso) && (B2.Text == xso) && (B3.Text == ""))
                return B3;
            if ((B2.Text == xso) && (B3.Text == xso) && (B1.Text == ""))
                return B1;
            if ((B1.Text == xso) && (B3.Text == xso) && (B2.Text == ""))
                return B2;

            if ((C1.Text == xso) && (C2.Text == xso) && (C3.Text == ""))
                return C3;
            if ((C2.Text == xso) && (C3.Text == xso) && (C1.Text == ""))
                return C1;
            if ((C1.Text == xso) && (C3.Text == xso) && (C2.Text == ""))
                return C2;

            //Verificari Verticala
            if ((A1.Text == xso) && (B1.Text == xso) && (C1.Text == ""))
                return C1;
            if ((B1.Text == xso) && (C1.Text == xso) && (A1.Text == ""))
                return A1;
            if ((A1.Text == xso) && (C1.Text == xso) && (B1.Text == ""))
                return B1;

            if ((A2.Text == xso) && (B2.Text == xso) && (C2.Text == ""))
                return C2;
            if ((B2.Text == xso) && (C2.Text == xso) && (A2.Text == ""))
                return A2;
            if ((A2.Text == xso) && (C2.Text == xso) && (B2.Text == ""))
                return B2;

            if ((A3.Text == xso) && (B3.Text == xso) && (C3.Text == ""))
                return C3;
            if ((B3.Text == xso) && (C3.Text == xso) && (A3.Text == ""))
                return A3;
            if ((A3.Text == xso) && (C3.Text == xso) && (B3.Text == ""))
                return B3;

            //Verificari Diagonala
            if ((A1.Text == xso) && (B2.Text == xso) && (C3.Text == ""))
                return C3;
            if ((B2.Text == xso) && (C3.Text == xso) && (A1.Text == ""))
                return A1;
            if ((A1.Text == xso) && (C3.Text == xso) && (B2.Text == ""))
                return B2;

            if ((A3.Text == xso) && (B2.Text == xso) && (C1.Text == ""))
                return C1;
            if ((B2.Text == xso) && (C1.Text == xso) && (A3.Text == ""))
                return A3;
            if ((A3.Text == xso) && (C1.Text == xso) && (B2.Text == ""))
                return B2;

            return null;
        }

        private void CheckForWinner()
        {
            bool castigatohr = false;

            //Verificari Orizontala

            if ((A1.Text == A2.Text) && (A2.Text == A3.Text) && (!A1.Enabled))
                castigatohr = true;
            else if ((B1.Text == B2.Text) && (B2.Text == B3.Text) && (!B1.Enabled))
                castigatohr = true;
            else if ((C1.Text == C2.Text) && (C2.Text == C3.Text) && (!C1.Enabled))
                castigatohr = true;

            //Verificari Verticala
             if ((A1.Text == B1.Text) && (B1.Text == C1.Text) && (!A1.Enabled))
                castigatohr = true;
            else if ((A2.Text == B2.Text) && (B2.Text == C2.Text) && (!A2.Enabled))
                castigatohr = true;
            else if ((A3.Text == B3.Text) && (B3.Text == C3.Text) && (!A3.Enabled))
                castigatohr = true;

            //Verificari Diagonala
             if ((A1.Text == B2.Text) && (B2.Text == C3.Text) && (!A1.Enabled))
                castigatohr = true;
            else if ((A3.Text == B2.Text) && (B2.Text == C1.Text) && (!C1.Enabled))
                castigatohr = true;


            if (castigatohr == true)
            {
                string winner = "";
                if (turn == true)
                {
                    winner = player2;
                    OWinCount.Text = (Int32.Parse(OWinCount.Text)+1).ToString();
                }
                else
                {
                    winner = player1;
                    XWinCount.Text = (Int32.Parse(XWinCount.Text) + 1).ToString();
                }

                MessageBox.Show(winner + " Wins ", " Well done! ");
                DisableButtons();
            }
            else
            {
                if (turnsCount == 9)
                {
                    MessageBox.Show("Draw!", "heh..");
                    DrawCount.Text = (Int32.Parse(DrawCount.Text) + 1).ToString();
                }
            }
        }

        private void DisableButtons()
        {
            foreach (Control c in Controls)
            {
                try {
                    Button b = (Button)c;
                    b.Enabled = false;
                     }
                catch { }

                }

        }

        private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            

            turn = true;
            turnsCount = 0;

            foreach (Control c in Controls)
            {
                try
                {
                    Button b = (Button)c;
                    b.Enabled = true;
                    b.Text = "";
                }
                catch { }

            }
        }

        private void ButtonEnter(object sender, EventArgs e)
        {
            Button b = (Button)sender;
            if (b.Enabled)
            {
                if (turn)
                    b.Text = "X";
                else
                    b.Text = "O";
            }
        }

        private void ButtonLeave(object sender, EventArgs e)
        {
            Button b = (Button)sender;
            if (b.Enabled)
                b.Text = "";

        }

        private void resetCountsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            XWinCount.Text = "0";
            OWinCount.Text = "0";
            DrawCount.Text = "0";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            GameType gt = new GameType();
            gt.ShowDialog();
            label1.Text = player1;
            label2.Text = player2;
        }

        private void playerVsPlayerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GameType pn = new GameType();
            pn.ShowDialog();

            turn = true;
            turnsCount = 0;

            foreach (Control c in Controls)
            {
                try
                {
                    Button b = (Button)c;
                    b.Enabled = true;
                    b.Text = "";
                }
                catch { }

            }
        }
    }
}




I would really appreciate your help!
Thank you!

Is This A Good Question/Topic? 0
  • +

Replies To: C# Button Instance PerformClick issue

#2 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: C# Button Instance PerformClick issue

Posted 09 August 2015 - 10:17 AM

This looks like a very straight-forward debugging situation.
Between the debugging tutorials and the 'What does this error mean?' article, I think you'll be well on your way.


tlhIn`toq's FAQ list

Learning to debug one's own code is an essential skill. Sadly, one that apparently few college courses teach. Silly if you ask me.
Placing breakpoints and walking through the code line by line allows you to actually WATCH it execute, check the condition of each of variable's run-time value, and watch the logic unfold right before your eyes.
Visualizing what your code does will let you see why it behaves the way it does.
It would be well worth your time to do the tutorials on FAQ 2. A couple hours learning this skill will save you hundreds of hours of confusion in one project alone.

In addition to FAQ 2 in the list below, also check my signature block for a link on how to look at your variables' values at run-time.

TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Class1/Form1 talk to Class2/Form2


FAQ (Frequently Asked Questions - Updated July 2013
Spoiler



Was This Post Helpful? 0
  • +
  • -

#3 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: C# Button Instance PerformClick issue

Posted 09 August 2015 - 10:31 AM

I would also point out a few things:

Its the year 2015 not 1995 - WinForms is pretty much for legacy applications that already exist. These days new projects are done in WPF. There's already a couple hundred coders out there that have 2 decades of experience in WinForms and you're not going to get competitive with that head start. You'd be better off jumping into WPF with both feet.

Any tutorial that has you using the text of the GUI elements like your private variables the way I see here, is not a tutorial worth following. That is one of the horrible habits we beat on rookies for so they don't do it. You want your GUI and your logic to NOT be tightly intertwined like that.

Any tutorial that has you doing these massive if... &&... &&... && blocks like this is not a tutorial to be followed.
What are you doing to do when you or your teacher says "Okay. Now expand it to a 10x10 grid."??
A loop that calculates the horizontal, vertical and diagonals is much more expandable.
A row for example is x to x+width
A column is x to x*height step width
Etc. With the right logic you can set the size to 3x3 or 3,000x3,000 and it would run just fine with no additional lines.

Video tutorials in general suck. Get a good book and learn C#. Don't learn how to make a given kind of program: You're not there yet. Nobody is in the beginning. Just learn the language and the logic and the foundation concepts.


My standard beginner resources post - Updated June 2013


Plan your study route:
There are three routes people seem to take when learning programming.
  • Just start trying to create programs
  • Start taking apart other programs and try to figure out the language by reverse engineering
  • Follow a guided learning course (school or self-teaching books)


For the life of me I can't figure out why people try 1 & 2. I strongly suggest taking the guided learning approach. Those book authors go in a certain order for a reason: They know what they're doing and they know the best order to learn the materials.

  • First learn the language by working 2-5 "Learn C# in 30 days" type books cover to cover.
  • Do a dozen on-line tutorial projects where you build what you're told to build, the way you are told to build it WITH AN EXPLANATION OF WHY so you can learn.
  • Learn to plan before you type.
  • THEN you start designing software with a purpose.



I don't learn from reading books: I learn by doing.
Spoiler


Newbie/Rookie said:

I have little/no programming experience but I need to write a program by Friday that does XYZ.
Spoiler



Resources, references and suggestions for new programmers.
Spoiler

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1