Click here to Skip to main content
Licence CPOL
First Posted 2 Sep 2011
Views 7,787
Downloads 740
Bookmarked 14 times

Tic Tac Toe implemented in C#

By | 2 Sep 2011 | Article
A simple game in C# that runs on Windows, Mac (Mono), and Linux (Mono).

Capture.JPG

Screenshot.png

Under .NetFW
Under Mono

Introduction

This is a simple two player Tic-Tac-Toe or Tic-Tack-Toe game which basically demonstrates the following:

  1. The similarities and differences between the two industry leading languages C#, Java, and also their outcomes. The Java implementation is available here.
  2. Array-less implementation of game logic just to demonstrate there is always another way of doing something when programming is involved, used here to make the comparison easy.

Background

I wondered if Mono could do what JRE does on different platforms with equal prospects. Though not functional, but the visual outcome differs as seen above which was not at all present in the case of Java. (I really miss something like Nimbus here.)

Using the code

To start with, let us take an overview of the variables used:

  • int a, b, c, d, e, f, g, h, i - To represent each box, used instead of an array of 9 elements.
  • char let='X' - The character to be placed when the first move is made, stored in the let() variable.
  • int val=1, cnt=0; val corresponds to 'let' 1 for X and 2 for O, used to check win.

Now let us take a look at the methods used:

  • reset(): To restart the game at any point, clears everything.
  • chekwin(int): This method is used to check the win condition and display the appropriate message.
  • flip(): To change the character between moves, changes 'val' accordingly.
// Method to reset the game to beginning.
void reset()
{
    a=b=c=d=e=f=g=h=i=8;
    let='X';
    val=1;
    cnt=0;
    button1.Text="";
    button2.Text="";
    button3.Text="";
    button4.Text="";
    button5.Text="";
    button6.Text="";
    button7.Text="";
    button8.Text="";
    button9.Text="";
}

// Method to check the win.
void chekwin(int no)
{
    if(cnt>4)
    {
        if(no==1)
        {
            if((a+b+c)==3||(a+d+g)==3||(i+h+g)==3||(c+f+i)==3||
               (a+e+i)==3||(c+e+g)==3||(b+e+h)==3||(d+e+f)==3)
            {
                MessageBox.Show("Player 1(Playing X) Wins!");
                reset();
            }
            else
            {
                    if(cnt==9)
                {
                    MessageBox.Show("The game is a Draw!");
                    reset();
                }
            }
        }
        else
        {
            if((a+b+c)==6||(a+d+g)==6||(i+h+g)==6||(c+f+i)==6||
               (a+e+i)==6||(c+e+g)==6||(b+e+h)==6||(d+e+f)==6)
            {
                MessageBox.Show("Player 2(Playing O) Wins!");
                    reset();
            }
            else
            {
                 if(cnt==9)
                {
                    MessageBox.Show("The game is a Draw!");
                        reset();
                }
            }
        }
    }
}

//Method to swich between Characters(X&O) after a move.
void flip()
{
    if(let=='X')
    {
        let = 'O';
        val=2;
        cnt++;
    }
    else
    {
        let = 'X';
        val=1;
        cnt++;
    }
}

private void jButton1MouseClicked(java.awt.event.MouseEvent evt)
//this is the code that executes when 1st button is clicked.
{                                          
    if(a==8)//a==8 is checked so that move is not overplayed.
    {
        jButton1.setText(String.valueOf(let));
        a = val;
        flip();
        chekwin(a);
    }
}

Now the core:

The logic is simple: A variable is associated with each block set to value 8. Why 8? Read ahead. When a player makes a move, say 'X', its corresponding value, that is 1, is assigned to the corresponding variable, say 'a'. Next, say 2 will be assigned to say 'd', and so on. After four moves, since there is a possibility that any of the players may have won, we check for a win using the method chekwin(). In this crust lies the real fun - how a win is calculated. First, we make trios of variables which if they contain the same values determine a win - in all 8 of them. For example, the first row trio would be: 'abc'. How do we know if their values are the same? We need not check for each of them, instead we simply check if their sum is 3 or 6! Got why we used 8 initially? Because even if one vacant box stays in between the trio, the answer will be more than 3 or 6. To maximize efficiency, we use 'cnt' and 'no', i.e., by checking win only after 4 moves and only for the last played character. The other use of 'cnt' is to determine a draw! If the total of the trio is 3 then player 1 wins, else if it is 6 then player 2 - that simple.

The logic of flip() and reset() are self explanatory...

The code that is executed with every button click is the final segment in the code above which shows the flow of execution.

Note: Using source under #develop would be a breeze (File->Open Solution->Extracted Folder->.sln or .csproj file) but manually compiling MainForm.cs and MainForm.Designer.cs under the source directory would do the same. .NET or Mono is required to run as well as compile the project.

Points of interest

Comparing both C# and Java implementations will allow you to learn a lot of things. Moreover, a C# developer can learn Java this way and vice versa!

History

A Java implementation of the program was done for comparison. It was 95% copy-paste and took 10 mins to be ready.

License

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

About the Author

Tejas_Pathak

Engineer
Contrivance technologies India
India India

Member

Follow on Twitter Follow on Twitter


Collaborative Group
2 members

I was a C# developer initially...
But the urge to write True Platform Independent applications drove me to code in Java Lately.
The IDEs I use are #develop and NetBeans.
 
BE(Computers)Mumbai University.
ME(ETC-Microelectronics)In Progress.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionVote of 4; Also About Event Handling PinmemberMatt U.10:16 2 Apr '12  
QuestionInteresting way of determining a win PinmemberShane Story9:04 20 Sep '11  
SuggestionI have a proposed code for revision... PinmemberBlubbo3:55 6 Sep '11  
GeneralMy vote of 4 PinmemberBlubbo3:44 6 Sep '11  

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.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 2 Sep 2011
Article Copyright 2011 by Tejas_Pathak
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid