Thursday 20 February 2014

How to create Tic Tack Game in Windows Application with C# .Net

How to create Tic Tack Game in Windows Application with C# .Net

Note: In this topic we will discuss about how to create Windows Games with cross and zero which is very popular and people generally play this game on paper with pen 

First we take a Windows Application with From1 and drag nine Buttons from Toolbox and create common click event for each Button as shown bellow picture…..



Code for Form1.cs ……………………..

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 TicTacToeWindowsFormsApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

int Count = 1;

// create click event for all  Button.................................

private void Click(object sender, EventArgs e)
{
Button b = (Button)sender;
b.Text = (Count % 2 == 0) ? "0" : "X";
b.Enabled = false;
Count++;
check();
}

private void Form1_Load(object sender, EventArgs e)
{

}

//condition for 8 logic...with row column diagonal...........................

void check()
{
if (button1.Text == button2.Text && button2.Text == button3.Text&&button1.Text!="")
{
result(button1.Text);
}
else if (button4.Text == button5.Text && button5.Text == button6.Text&&button4.Text!="")
{
result(button4.Text);
}
else if (button7.Text == button8.Text && button8.Text == button9.Text&&button7.Text!="")
{
result(button7.Text);
}
else if (button1.Text == button4.Text && button4.Text == button7.Text&&button1.Text!="")
{
result(button1.Text);
}
else if (button2.Text == button5.Text && button5.Text == button8.Text&&button2.Text!="")
{
result(button2.Text);
}
else if (button3.Text == button6.Text && button6.Text == button9.Text&&button3.Text!="")
{
result(button3.Text);
}
else if (button1.Text == button5.Text && button5.Text == button9.Text && button1.Text != "")
{
result(button1.Text);
}
else if (button3.Text == button5.Text && button5.Text == button7.Text && button3.Text != "")
{
result(button3.Text);
}
else if (Count == 10)
{
result("");
}
}

//code for  result.....................

void result(string text)
{
if (text == "0")
{
MessageBox.Show("Second Player has won the GAME!!!!!!!!");
}
else if (text == "X")
{
MessageBox.Show("First Player has won the GAME!!!!!!!!");
}
else
{
MessageBox.Show("Game Draw!!!!!");
}
if (MessageBox.Show("Are You Want To Play Again!", "Confirmation Message", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
reset();
}
else
{
this.Close();
}
}

//code for reset button.....................

void reset()
{
foreach (Button b in this.Controls)
{
b.Text = "";
b.Enabled = true;
}
Count = 1;
}
}
}
  
Result




1 comments: