Hi there! :)
Today I'll be sharing the code of Tic Tac Toe. It is a two players game. Enjoy! :P
Points to remember :
- The board is a 2D array[3x3] that is either filled or empty.
- To make a move, you need to give the coordinates i.e. to place in centre, you have to enter 11 that is the centre of a 2D array of the size 3x3.
- To enter 11, enter separately i.e. 1 >> enter >> 1.
Source:
// http://progrithms.blogspot.com/
#include <iostream>
#include <conio.h>
using namespace std;
void printArray(int arr[][3], int rows, int cols)
{
for (int i = 0; i<rows; i++)
{
for (int j = 0; j<cols; j++)
{
if (arr[i][j] == 0)
cout << "_" << " ";
else if (arr[i][j] == 1)
cout << "O" << " ";
else
cout << "X" << " ";
}
cout << endl;
}
}
bool checkWinner(int board[][3], int row, int &who)
{
for (int i = 0; i<3; i++)
{
if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != 0)
{
who = board[i][0];
return true;
}
}
for (int j = 0; j<3; j++)
{
if (board[0][j] == board[1][j] && board[1][j] == board[2][j] && board[0][j] != 0)
{
who = board[0][j];
return true;
}
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != 0)
{
who = board[0][0];
return true;
}
if (board[2][0] == board[1][1] && board[1][1] == board[2][0] && board[2][0] != 0)
{
who = board[2][0];
return true;
}
return false;
}
void main()
{
bool winner = false;
int board[3][3] = { 0 };
int nought = 1, cross = 2, row, col;
printArray(board, 3, 3);
int player = nought;
int who = 0;
for (int i = 0; i<9; i++)
{
if (player == 1)
{
cout << "Player 1's turn....." << endl;
cin >> row >> col;
while (board[row][col] != 0)
{
cout << "Already filled. Re-enter:" << endl;
cin >> row >> col;
}
board[row][col] = 1;
player = 2;
}
else
{
cout << "Player 2's turn....." << endl;
cin >> row >> col;
while (board[row][col] != 0)
{
cout << "Already filled. Re-enter:" << endl;
cin >> row >> col;
}
board[row][col] = 2;
player = 1;
}
printArray(board, 3, 3);
winner = checkWinner(board, 3, who);
if (winner)
break;
}
if (winner)
cout << "Player" << who << " is winner." << endl;
else
cout << "Draw." << endl;
_getch();
return;
}
___________________________________________________________________________________
___________________________________________________________________________________
In case of any questions, just comment below. :)
0 comments:
Post a Comment