Click here to Skip to main content
Click here to Skip to main content
Alternative Article

Tic Tac Toe Game Programming Using C#

, 31 May 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
This is an alternative for "C# Development in Windows Applications"

Introduction

Etudes are technical studies for musicians who concentrate on a fully complete musical idea but in a small form. Often, there are a variety of these smaller pieces that solve the same problem and differ in the details. This concept can be borrowed for learning computer languages.

In this tip, a functioning Tic-Tac-Toe program is developed - it might not be the fullest implementation, but it works. The program concentrates on a sensible implementation that might serve as a foundation for possibly more intricate implementations. The following assumes you are familiar with the rules of Tic-Tac-Toe – if not, take a minute to look them up. Also, a basic understanding of C#, WinForms, VS.NET and data structures is assumed.

Tic-Tac-Toe is a simple game but has a number of interesting issues like:

  • How to represent each square and how should it be addressed?
  • How to process the mouse click on the box and trap errors/incorrect mouse clicks?
  • What is the best way to determine if someone has won?

The first design choice is made to represent the game squares with the Button control. With this control, there is a simple way to change the text from blank to an X or Y, establish an event handler for the Clickevent and easily address them as a group. By using this control, we can concentrate on other design decisions without struggling with many technical details.

Starting with the default Windows project, add nine (3x3) buttons with the same dimensions arranged 3x3. Each of the Buttons is called but1, but2, etc. Another Button, labeled Play, is added to trigger a new game. Finally, the form is titled Tic Tac Toe for Windows32.

To check for winners, the buttons need to be addressed as a group. You could use the Controls array, but then extra processing would be required to account for the non-box buttons – like the Play button. Also discarded was placing them in an ArrayList construct – as this has too much overhead. Finally, we settle on the single dimensional array.

public class TicTacToeUtils
        {
            // Winners contains all the array locations of
            // the winning combination -- if they are all 
            // either X or O (and not blank)
            static private int[,] Winners = new int[,]
				   {
						{0,1,2},
						{3,4,5},
						{6,7,8},
						{0,3,6},
						{1,4,7},
						{2,5,8},
						{0,4,8},
						{2,4,6}
				   };

            //--------------------------------------------------------------
            // CheckAndProcessWinner determines if either X or O has won.
            // Once a winner has been determined, play stops.
            //--------------------------------------------------------------
            static public bool CheckAndProcessWinner(Button[] myControls)
            {
                bool gameOver = false;
                for (int i = 0; i < 8; i++)
                {
                    int a = Winners[i, 0], b = Winners[i, 1], 
                    	c = Winners[i, 2];		// get the indices
                    // of the winners

                    Button b1 = myControls[a], b2 = myControls[b], 
                    	b3 = myControls[c];// just to make the 
                    // the code readable

                    if (b1.Text == "" || b2.Text == "" || 
                    	b3.Text == "")	// any of the squares blank
                        continue;		// try another -- no need to go further

                    if (b1.Text == b2.Text && 
                    	b2.Text == b3.Text) // are they the same?
                    {			  // if so, they WIN!
                        b1.BackColor = b2.BackColor = b3.BackColor = Color.LightCoral;
                        b1.Font = b2.Font = b3.Font = new System.Drawing.Font
                        ("Microsoft Sans Serif", 32F, System.Drawing.FontStyle.Italic & 
                        System.Drawing.FontStyle.Bold, 
                        System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
                        gameOver = true;
                        break;  // don't bother to continue
                    }
                }
                return gameOver;                
            }
        } 

The below code is to check for possible move for the players...

 void possi_moves(int button_no, string player, Button butt)
        {
            int[] a = new int[] { 1, 3 };
            int[] b = new int[] { 0, 2, 4 };
            int[] c = new int[] { 1, 5 };
            int[] d = new int[] { 0, 4, 6 };
            int[] e = new int[] { 1, 3, 5, 7 };
            int[] f = new int[] { 2, 4, 8 };
            int[] g = new int[] { 3, 7 };
            int[] h = new int[] { 4, 6, 8 };
            int[] i = new int[] { 5, 7 };
            hold_button = butt;
            if ((button_no == 1) && (butt.Text == player.ToString().Trim()))
            {
                for (int j = 0; j <= a.Count(); j++)
                {
                    if (_buttonArray[a[j]].Text == "")
                    {
                        _buttonArray[a[j]].BackColor = Color.LightGreen;
                    }
                }
            }
            if ((button_no == 2) && (butt.Text == player.ToString().Trim()))
            {
                for (int j = 0; j <= b.Count(); j++)
                {
                    if (_buttonArray[b[j]].Text == "")
                    {
                        _buttonArray[b[j]].BackColor = Color.LightGreen;
                    }
                }
            }
            if ((button_no == 3) && (butt.Text == player.ToString().Trim()))
            {
                for (int j = 0; j <= c.Count(); j++)
                {
                    if (_buttonArray[c[j]].Text == "")
                    {
                        _buttonArray[c[j]].BackColor = Color.LightGreen;
                    }
                }
            }
            if ((button_no == 4) && (butt.Text == player.ToString().Trim()))
            {
                for (int j = 0; j <= d.Count(); j++)
                {
                    if (_buttonArray[d[j]].Text == "")
                    {
                        _buttonArray[d[j]].BackColor = Color.LightGreen;
                    }
                }
            }
            if ((button_no == 5) && (butt.Text == player.ToString().Trim()))
            {
                for (int j = 0; j <= e.Count(); j++)
                {
                    if (_buttonArray[e[j]].Text == "")
                    {
                        _buttonArray[e[j]].BackColor = Color.LightGreen;
                    }
                }
            }
            if ((button_no == 6) && (butt.Text == player.ToString().Trim()))
            {
                for (int j = 0; j <= f.Count(); j++)
                {
                    if (_buttonArray[f[j]].Text == "")
                    {
                        _buttonArray[f[j]].BackColor = Color.LightGreen;
                    }
                }
            }
            if ((button_no == 7) && (butt.Text == player.ToString().Trim()))
            {
                for (int j = 0; j <= g.Count(); j++)
                {
                    if (_buttonArray[g[j]].Text == "")
                    {
                        _buttonArray[g[j]].BackColor = Color.LightGreen;
                    }
                }
            }
            if ((button_no == 8) && (butt.Text == player.ToString().Trim()))
            {
                for (int j = 0; j <= h.Count(); j++)
                {
                    if (_buttonArray[h[j]].Text == "")
                    {
                        _buttonArray[h[j]].BackColor = Color.LightGreen;
                    }
                }
            }
            if ((button_no == 9) && (butt.Text == player.ToString().Trim()))
            {
                for (int j = 0; j <= i.Count(); j++)
                {
                    if (_buttonArray[i[j]].Text == "")
                    {
                        _buttonArray[i[j]].BackColor = Color.LightGreen;
                    }
                }
            }
        }  

A completed game might look like:

Thanks.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Domavarapu Srinivasa Rao
Software Developer Avvas Infotech Pvt Ltd
United States United States
No Biography provided

Comments and Discussions

 
GeneralMy vote of 3 Pinmembergico29-Jun-14 0:16 
QuestionFacing Powerpack Error PinmemberHellism27-Mar-14 7:10 
Questionthank you PinmemberMember 103615998-Nov-13 1:47 
SuggestionTic Tac Toe in C# Pinmemberithinkunomee22-Jul-13 9:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 31 May 2013
Article Copyright 2013 by Domavarapu Srinivasa Rao
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid