Design and implement a Tic Tack Toe game (Two Player).
Design:-
Code:-
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 tic_tac_toe
{
public partial class frmtictactoe : Form
{
bool turn = true;
int turn_count = 0;
public frmtictactoe()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Arsh Prajapati", "Tic Tac Toe help");
}
private void Button_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
if (turn == true)
{
b.Text = "X";
}
else
{
b.Text = "O";
}
turn =! turn;
turn_count++;
b.Enabled = false;
check_winner();
}
private void check_winner()
{
bool check_for_winner=false;
//Horizontal Checks
if((btna1.Text==btna2.Text)&&(btna2.Text==btna3.Text)&&(btna1.Enabled==false))
{
check_for_winner=true;
}
else if((btnb1.Text==btnb2.Text)&&(btnb2.Text==btnb3.Text)&&(btnb1.Enabled==false))
{
check_for_winner=true;
}
else if((btnc1.Text==btnc2.Text)&&(btnc2.Text==btnc3.Text)&&(btnc1.Enabled==false))
{
check_for_winner=true;
}
//Vertical Checks
else if ((btna1.Text == btnb1.Text) && (btnb1.Text == btnc1.Text) && (btna1.Enabled == false))
{
check_for_winner = true;
}
else if ((btna2.Text == btnb2.Text) && (btnb2.Text == btnc2.Text) && (btna2.Enabled == false))
{
check_for_winner = true;
}
else if ((btna3.Text == btnb3.Text) && (btnb3.Text == btnc3.Text) && (btna3.Enabled == false))
{
check_for_winner = true;
}
//Diagonal Check
else if ((btna1.Text == btnb2.Text) && (btnb2.Text == btnc3.Text) && (btna1.Enabled == false))
{
check_for_winner = true;
}
else if ((btna3.Text == btnb2.Text) && (btnb2.Text == btnc1.Text) && (btna3.Enabled == false))
{
check_for_winner = true;
}
if (check_for_winner == true)
{
disablebutton();
if (turn == true)
{
MessageBox.Show("O is a Winner", "Winner");
}
else
{
MessageBox.Show("X is a Winner", "Winner");
}
}
else
{
if (turn_count == 9)
{
MessageBox.Show("Game is Tie", "Tic Tac Toe");
}
}
}
private void disablebutton()
{
try
{
foreach (Control c in Controls)
{
Button b = (Button)c;
b.Enabled = false;
}
}
catch { }
}
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
turn = true;
turn_count = 0;
try
{
foreach (Control c in Controls)
{
Button b = (Button)c;
b.Enabled = true;
b.Text = "";
}
}
catch { }
}
}
}
No comments:
Post a Comment