You are on page 1of 1

  In Focus ANSWERSTIP:BLOGS

TECHNOLOGIES How toVIDEOS


protect yourself BOOKS
INTERVIEWS from online
NEWS hacking
EVENTS CAREER JOBS TRAINING MORE C# Corner Search  

Ask a Question Contribute

Tic-Tac-Toe Game in C#
Sourabh Somani Apr 07 2014 Article

5 6 232.6k

TIC_TAC_TOE.rar Download Free O ce API

In this article I am showing you how to create a very simple game of Tic-Tac-Toe in a C# console
application.

Hire a blockchain developer


Introduction Want to get your applications
built on Blockchain technology?
Tic-Tac-Toe is a very simple two player game. So only two players can play at a time. This game is Come, meet the blockchain
also known as Noughts and Crosses or Xs and Os game. One player plays with X and the other experts and hire a team or
player plays with O. In this game we have a board consisting of a 3X3 grid. The number of grids individuals as per your need.
may be increased.

The Tic-Tac-Toe board looks like: TRENDING UP


Multithreading Process With Real-Time
01 Updates In ASP.NET Core Web Application

02 Understanding Server-Side Blazor

SOLID - Single Responsibility Principle


03 With C#
Let's Learn To Make Shopping Cart Using
04 ASP.NET Core Blazor Using EF And Web
API
SharePoint Framework - Develop First
05 Client Side Web Part
Top 10 Tips To Protect From Online
06 Hacking
SharePoint Framework - Understanding
07 The Solution Structure
SharePoint Framework - Avoiding NPM
08 Package Dependencies
SharePoint Framework - Introduction To
09 Web Part Property Pane

10 Chatbot Using Microsoft Bot Framework


View All

Game Rules

1. Traditionally the rst player plays with "X". So you can decide who wants to go "X" and who
wants go with "O". 
2. Only one player can play at a time.
3. If any of the players have lled a square then the other player and the same player cannot
override that square.
4. There are only two conditions that may be match will be draw or may be win.
5. The player that succeeds in placing three respective mark (X or O) in a horizontal, vertical or
diagonal row wins the game.

Winning condition

Whoever places three respective marks (X or O) horizontally vertically or diagonally will be the
winner.

The code for the game is as follows:

using System;
using System.Threading;
 
namespace TIC_TAC_TOE
{
    class Program
    {
        //making array and   
        //by default I am providing 0-9 where no use of zero  
        static char[] arr = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        static int player = 1; //By default player 1 is set  
        static int choice; //This holds the choice at which position user want to mark   

       
// The flag veriable checks who has won if it's value is 1 then some one has won the match if -1 then Match has Draw if 0 then match is still running  
        static int flag = 0;

        static void Main(string[] args)


        {
            do
            {
                Console.Clear();// whenever loop will be again start then screen will be clear  
                Console.WriteLine("Player1:X and Player2:O");
                Console.WriteLine("\n");
                if (player % 2 == 0)//checking the chance of the player  
                {
                    Console.WriteLine("Player 2 Chance");
                }
                else
                {
                    Console.WriteLine("Player 1 Chance");
                }
                Console.WriteLine("\n");
                Board();// calling the board Function  
                choice = int.Parse(Console.ReadLine());//Taking users choice   

                // checking that position where user want to run is marked (with X or O) or not  
                if (arr[choice] != 'X' && arr[choice] != 'O')
                {
                    if (player % 2 == 0) //if chance is of player 2 then mark O else mark X  
                    {
                        arr[choice] = 'O';
                        player++;
                    }
                    else
                    {
                        arr[choice] = 'X';
                        player++;
                    }
                }
               
else //If there is any possition where user want to run and that is already marked then show message and load board again  
                {
                    Console.WriteLine("Sorry the row {0} is already marked with {1}", choice, arr[choice]);
                    Console.WriteLine("\n");
                    Console.WriteLine("Please wait 2 second board is loading again.....");
                    Thread.Sleep(2000);
                }
                flag = CheckWin();// calling of check win  
            } while (flag != 1 && flag !=
-1);// This loof will be run until all cell of the grid is not marked with X and O or some player is not win  

            Console.Clear();// clearing the console  
            Board();// getting filled board again  

            if (flag ==
1)// if flag value is 1 then some one has win or means who played marked last time which has win  
            {
                Console.WriteLine("Player {0} has won", (player % 2) + 1);
            }
            else// if flag value is -1 the match will be draw and no one is winner  
            {
                Console.WriteLine("Draw");
            }
            Console.ReadLine();
        }
        // Board method which creats board  
        private static void Board()
        {
            Console.WriteLine("     |     |      ");
            Console.WriteLine("  {0}  |  {1}  |  {2}", arr[1], arr[2], arr[3]);
            Console.WriteLine("_____|_____|_____ ");
            Console.WriteLine("     |     |      ");
            Console.WriteLine("  {0}  |  {1}  |  {2}", arr[4], arr[5], arr[6]);
            Console.WriteLine("_____|_____|_____ ");
            Console.WriteLine("     |     |      ");
            Console.WriteLine("  {0}  |  {1}  |  {2}", arr[7], arr[8], arr[9]);
            Console.WriteLine("     |     |      ");
        }

        //Checking that any player has won or not  
        private static int CheckWin()
        {
            #region Horzontal Winning Condtion
            //Winning Condition For First Row   
            if (arr[1] == arr[2] && arr[2] == arr[3])
            {
                return 1;
            }
            //Winning Condition For Second Row   
            else if (arr[4] == arr[5] && arr[5] == arr[6])
            {
                return 1;
            }
            //Winning Condition For Third Row   
            else if (arr[6] == arr[7] && arr[7] == arr[8])
            {
                return 1;
            }
            #endregion

            #region vertical Winning Condtion
            //Winning Condition For First Column       
            else if (arr[1] == arr[4] && arr[4] == arr[7])
            {
                return 1;
            }
            //Winning Condition For Second Column  
            else if (arr[2] == arr[5] && arr[5] == arr[8])
            {
                return 1;
            }
            //Winning Condition For Third Column  
            else if (arr[3] == arr[6] && arr[6] == arr[9])
            {
                return 1;
            }
            #endregion

            #region Diagonal Winning Condition
            else if (arr[1] == arr[5] && arr[5] == arr[9])
            {
                return 1;
            }
            else if (arr[3] == arr[5] && arr[5] == arr[7])
            {
                return 1;
            }
            #endregion

            #region Checking For Draw
            // If all the cells or values filled with X or O then any player has won the match  
            else if (arr[1] != '1' && arr[2] != '2' && arr[3] != '3' && arr[4] != '4' && arr[5] != '5' && arr[6] != '6' &&
arr[7] != '7' && arr[8] != '8' && arr[9] != '9')
            {
                return -1;
            }
            #endregion

            else
            {
                return 0;
            }
        }
    }

Output

1. Starting game screen

 
2. If a player has marked a place that is already marked with O or X then the output will be like:

 
3. If the game is a draw or all places are lled with Xs and Os and no winning condition is
satis ed then the output will be like:

 
4. I Player 1 wins then the output will be:

 
5. If Player 2 wins then the output will be:

C# C# Game C# Game Tic-Tac-Toe Game Tic-Tac-Toe

Sourabh Somani 18 4.9m 5 3

Sourabh Somani, the 3 times Microsoft MVP and 5-times C# Corner MVP, is a tech
lead, contributor, International Speaker, Author, and the founder of
www.PythonBabu.com. After possessing a B-Tech degree in Computer Science...
Read more
http://www.sourabhsomani.com https://www.pythonbabu.com

5 6

Type your comment here and press Enter Key (Minimum 10 characters)

thnks... It helped to improve my logic in program


Sadhana Gaud May 12, 2014
NA 1 0 1 1 Reply

Welcome Dear :)
Sourabh Somani Feb 28, 2015
18 41.5k 4.9m 0

Nice one
Shweta Lodha Apr 19, 2014
91 17.3k 1.1m 1 1 Reply

Thank you :)
Sourabh Somani Apr 19, 2014
18 41.5k 4.9m 0

nice artical sourabh


Shaili Dashora Apr 08, 2014
327 5k 1.1m 3 1 Reply

:)
Sourabh Somani Apr 14, 2014
18 41.5k 4.9m 1

Philadelphia Learn ASP.NET MVC Home


New York
Join C# Corner Learn ASP.NET Core Events
and millions of developer friends worldwide.
London Learn Python Consultants
Delhi Learn JavaScript Jobs
Enter your email address Sign Up
Learn Xamarin Career Advice
Learn Oracle Stories
More... Partners

About Us Contact Us Privacy Policy Terms Media Kit Sitemap Report a Bug FAQ
©2018 C# Corner. All contents are copyright of their authors.

You might also like