Skip to content

Instantly share code, notes, and snippets.

@ajnarayan
Created August 7, 2015 16:55
Show Gist options
  • Save ajnarayan/718d7fea9692f8442c20 to your computer and use it in GitHub Desktop.
Save ajnarayan/718d7fea9692f8442c20 to your computer and use it in GitHub Desktop.
A Simple tic-tac-toe C++ game
#include <iostream>
using namespace std;
char square[9] = {'0','1','2','3','4','5','6','7','8'};
int checkwin()
{
if (square[0] == square [1] && square[1] == square[2] )
{ if ( square [0] == 'X' )
return 1;
else
return 2;
}
else
if (square[3] == square [4] && square[4] == square[5] )
{ if ( square [3] == 'X' )
return 1;
else
return 2;
}
else
if (square[6] == square [7] && square[7] == square[8] )
{ if ( square [6] == 'X' )
return 1;
else
return 2;
}
else
if (square[0] == square [3] && square[3] == square[6] )
{ if ( square [0] == 'X' )
return 1;
else
return 2;
}
else
if (square[1] == square [4] && square[4] == square[7] )
{ if ( square [1] == 'X' )
return 1;
else
return 2;
}
else
if (square[2] == square [5] && square[5] == square[8] )
{ if ( square [2] == 'X' )
return 1;
else
return 2;
}
else
if (square[0] == square [4] && square[4] == square[8] )
{ if ( square [0] == 'X' )
return 1;
else
return 2;
}
else
if (square[2] == square [4] && square[4] == square[6] )
{ if ( square [2] == 'X' )
return 1;
else
return 2;
}
else
if (square[0] == square [3] && square[3] == square[6] )
{ if ( square [0] == 'X' )
return 1;
else
return 2;
}
else
return 0;
}
void mark(int player, int box)
{
if (player == 1 )
{
square[box] = 'X';
}
else
square[box] = 'Y';
}
void display()
{
for(int i=0;i<9;i++)
{
cout<< square[i] << "\t" ;
if (i == 2 || i== 5 || i==8)
cout<<"\n";
}
}
int main()
{
int player1 = 1, player2 =2 ;
int box, result = 0, flag = 0;
for(int i=1;i<5;i++)
{
cout<< "\n Player " << player1 << "Enter the Box";
cin>> box;
mark( player1, box);
display();
result =checkwin();
if (result == 1 )
{ cout<<"\n Congratualtions! player " << player1 << " has Won ";
flag = 1;
break;
}
else
if (result == 2 )
{ cout<<"\n Congratualtions! player " << player2 << " has Won ";
flag = 1;
break;
}
cout<< "\n Player " << player2 << "Enter the Box";
cin>> box;
mark ( player2, box);
display();
result =checkwin();
if (result == 1 )
{ cout<<"\n Congratualtions! player " << player1 << " has Won ";
flag = 1;
break;
}
else
if (result == 2 )
{ cout<<"\n Congratualtions! player " << player2 << " has Won ";
flag = 1;
break;
}
}
if (flag == 0 )
cout<<" \n Sorry, The game is a draw ";
return 0;
}
@poorgoat
Copy link

poorgoat commented Feb 9, 2018

Very cool mate potatie

@al3xionescu
Copy link

al3xionescu commented May 16, 2018

Hei, one issue would be that if X puts on 4 and then Y puts on 4, there will be a Y in the X's place.

@jrymk
Copy link

jrymk commented May 24, 2018

Try this code by me, it won't have the problem.

#include <iostream>
#include <stdlib.h>
using namespace std;
void printBoard();
void playerInput();
void machineInput();
void refreshPage();
void resetGame();
int checkWinner();
int board[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int player = 1;
int main() {
	cout << "Tic Tac Toe\n\nTutorial:\n1.Type in the corresponding number given in the key map. \n2.If you lose, you will be first in the second round, otherwise, you will be second.\n";
	cout << "\nPress any key to play again...\n";
	char c;
	cin >> c;
start:
	refreshPage();
	printBoard();
	playerInput();
	refreshPage();
	printBoard();
	//**********************************************
	if (checkWinner() == 10) {
		cout << endl;
		cout << "***********************************\n";
		cout << "* Game over! It is a tie!         *\n";
		cout << "***********************************\n";
		cout << "\nPress any key to play again...\n";
		char c;
		cin >> c;
		player = 1;
		resetGame();
		goto start;
	}
	if (checkWinner() == player) {
		cout << endl;
		cout << "***********************************\n";
		cout << "* Game over! The winner is YOU!   *\n";
		cout << "***********************************\n";
		cout << "\nPress any key to play again...\n";
		char c;
		cin >> c;
		player = 2;
		resetGame();
		goto secround;
	}
	else if ((checkWinner() != 0) && (checkWinner() != player)) {
		cout << endl;
		cout << "***********************************\n";
		cout << "* Game over! The winner is ME!    *\n";
		cout << "***********************************\n";
		cout << "\nPress any key to play again...\n";
		char c;
		cin >> c;
		player = 1;
		resetGame();
		goto start;
	}
	//**********************************************
	refreshPage();
	printBoard();
secround:
	refreshPage();
	printBoard();
	machineInput();
	refreshPage();
	//printBoard();
	//**********************************************
	if (checkWinner() == 10) {
		cout << endl;
		cout << "***********************************\n";
		cout << "* Game over! It is a tie!         *\n";
		cout << "***********************************\n";
		cout << "\nPress any key to play again...\n";
		char c;
		cin >> c;
		player = 1;
		resetGame();
		goto start;
	}
	if (checkWinner() == player) {
		cout << endl;
		cout << "***********************************\n";
		cout << "* Game over! The winner is YOU!   *\n";
		cout << "***********************************\n";
		cout << "\nPress any key to play again...\n";
		char c;
		cin >> c;
		player = 2;
		resetGame();
		goto secround;
	}
	else if ((checkWinner() != 0) && (checkWinner() != player)) {
		cout << endl;
		cout << "***********************************\n";
		cout << "* Game over! The winner is ME!    *\n";
		cout << "***********************************\n";
		cout << "\nPress any key to play again...\n";
		char c;
		cin >> c;
		player = 1;
		resetGame();
		goto start;
	}
	//**********************************************
	refreshPage();
	printBoard();
	goto start;
	return 0;
}

void resetGame() {
	for (int i = 0; i < 9; i++) {
		board[i] = 0;
	}
}
void refreshPage() {
	for (int i = 0; i < 100; i++) {
		cout << "\n";
	}
}



int checkWinner() {
	if ((board[0] != 0) && (board[1] != 0) && (board[2] != 0) && (board[3] != 0) && (board[4] != 0) && (board[5] != 0) && (board[6] != 0) && (board[7] != 0) && (board[8] != 0)) {
		return 10;
	}
	if ((board[0] == board[1]) && (board[1] == board[2]) && (board[0] != 0)) {
		return board[0];
	}
	if ((board[3] == board[4]) && (board[4] == board[5]) && (board[3] != 0)) {
		return board[3];
	}
	if ((board[6] == board[7]) && (board[7] == board[8]) && (board[6] != 0)) {
		return board[6];
	}
	if ((board[0] == board[3]) && (board[3] == board[6]) && (board[0] != 0)) {
		return board[0];
	}
	if ((board[1] == board[4]) && (board[4] == board[7]) && (board[1] != 0)) {
		return board[1];
	}
	if ((board[2] == board[5]) && (board[5] == board[8]) && (board[2] != 0)) {
		return board[2];
	}
	if ((board[0] == board[4]) && (board[4] == board[8]) && (board[0] != 0)) {
		return board[0];
	}
	if ((board[2] == board[4]) && (board[4] == board[6]) && (board[2] != 0)) {
		return board[2];
	}
	return 0;
}

void machineInput() {
	int input = 9;
	cout << "My turn. Thinking...\n";
	if ((board[0] == board[1]) && (board[0] == player) && (board[2] == 0)) {
		input = 2;
	}
	if ((board[1] == board[2]) && (board[1] == player) && (board[0] == 0)) {
		input = 0;
	}
	if ((board[0] == board[2]) && (board[0] == player) && (board[1] == 0)) {
		input = 1;
	}
	if ((board[3] == board[4]) && (board[3] == player) && (board[5] == 0)) {
		input = 5;
	}
	if ((board[4] == board[5]) && (board[4] == player) && (board[3] == 0)) {
		input = 3;
	}
	if ((board[3] == board[5]) && (board[3] == player) && (board[4] == 0)) {
		input = 4;
	}
	if ((board[6] == board[7]) && (board[6] == player) && (board[8] == 0)) {
		input = 8;
	}
	if ((board[7] == board[8]) && (board[7] == player) && (board[6] == 0)) {
		input = 6;
	}
	if ((board[6] == board[8]) && (board[6] == player) && (board[7] == 0)) {
		input = 7;
	}
	if ((board[0] == board[3]) && (board[0] == player) && (board[6] == 0)) {
		input = 6;
	}
	if ((board[3] == board[6]) && (board[3] == player) && (board[0] == 0)) {
		input = 0;
	}
	if ((board[0] == board[6]) && (board[0] == player) && (board[3] == 0)) {
		input = 3;
	}
	if ((board[1] == board[4]) && (board[1] == player) && (board[7] == 0)) {
		input = 7;
	}
	if ((board[4] == board[7]) && (board[4] == player) && (board[1] == 0)) {
		input = 1;
	}
	if ((board[1] == board[7]) && (board[1] == player) && (board[4] == 0)) {
		input = 4;
	}
	if ((board[2] == board[5]) && (board[2] == player) && (board[8] == 0)) {
		input = 8;
	}
	if ((board[5] == board[8]) && (board[5] == player) && (board[2] == 0)) {
		input = 2;
	}
	if ((board[2] == board[8]) && (board[2] == player) && (board[5] == 0)) {
		input = 5;
	}
	if ((board[0] == board[4]) && (board[0] == player) && (board[8] == 0)) {
		input = 8;
	}
	if ((board[4] == board[8]) && (board[4] == player) && (board[0] == 0)) {
		input = 0;
	}
	if ((board[0] == board[8]) && (board[0] == player) && (board[4] == 0)) {
		input = 4;
	}
	if ((board[2] == board[4]) && (board[2] == player) && (board[6] == 0)) {
		input = 6;
	}
	if ((board[4] == board[6]) && (board[4] == player) && (board[2] == 0)) {
		input = 2;
	}
	if ((board[2] == board[6]) && (board[2] == player) && (board[4] == 0)) {
		input = 4;
	}
	if (input == 9) {
		cout << "No solution, randomly filling in...\n";
		int i;
		while (input != 9) {
			i = rand() % 9;
			if (board[i] == 0) {
				input = i;
			}
		}
	}
	if (player == 1) {
		board[input] = 2;
	}
	else {
		board[input] = 1;
	}
	cout << "Placed on address " << input << "\n";
	printBoard();
}

void playerInput() {
	int input;
ask:
	input = 0;
	cout << "Your turn. Enter a number.\n";
	cin >> input;
	if (input > 9) {
		cout << "The number you entered is too big.\n";
		goto ask;
	}
	else if (input < 1) {
		cout << "The number you entered is too small.\n";
		goto ask;
	}
	else if (board[input - 1] != 0) {
		cout << "The number you entered has already filled in.\n";
		goto ask;
	}
	else {
		board[input - 1] = player;
	}
}




void printBoard() {
	char displayBoard[9] = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
	for (int i = 0; i < 9; i++) {
		switch (board[i]) {
		case 0:
			displayBoard[i] = ' ';
			break;
		case 1:
			displayBoard[i] = 'O';
			break;
		case 2:
			displayBoard[i] = 'X';
			break;
		};
	}
	cout << "Game Board          Key Map\n";
	cout << "*************       *************\n";
	cout << "* " << displayBoard[0] << " * " << displayBoard[1] << " * " << displayBoard[2] << " *       * 1 * 2 * 3 *\n";
	cout << "*************       *************\n";
	cout << "* " << displayBoard[3] << " * " << displayBoard[4] << " * " << displayBoard[5] << " *       * 4 * 5 * 6 *\n";
	cout << "*************       *************\n";
	cout << "* " << displayBoard[6] << " * " << displayBoard[7] << " * " << displayBoard[8] << " *       * 7 * 8 * 9 *\n";
	cout << "*************       *************\n";
}

@mastrobirraio
Copy link

`#include
#include
using namespace std;

void board();
void player_choose(int player);
bool check_winner(int player);
void show_game(int player_winner);
char get_value(char mark);

char game_matrix[3][3] = {
'1', '2', '3',
'4', '5', '6',
'7', '8', '9'
};

int main() {
int player = 1;
int old_player;
int turns = 1;

do {
	board();
	player_choose(player);
	old_player = player;
	player = (player == 1)?2:1;
	turns++;
	if(turns == 10) {
		old_player = 0;
	}
} while(!check_winner(old_player) && turns < 10);

show_game(old_player);
return 0;

}

void board() {
system("clear");
cout << " | | " << endl;
for(size_t r=0; r<3; r++) {
cout << " " << game_matrix[r][0] << " | " << game_matrix[r][1] << " | " << game_matrix[r][2] << endl;
cout << "||_____" << endl;
cout << " | | " << endl;
}
}

void player_choose(int player) {
char choose;
char mark = (player == 1)?'X':'O';
cout << "Inserisci " << mark << ": ";
cin >> choose;

for(size_t r=0; r<3; r++) {
	for(size_t c=0; c<3; c++) {
		if(game_matrix[r][c] == choose) {
			game_matrix[r][c] = mark;
		}
	}
}

}

bool check_winner(int player) {
bool winner = false;
char mark = (player == 1)?'X':'O';

for(size_t r=0; r<3; r++) {
	int count = 0;
            for(size_t c=0; c<3; c++) {
		if(game_matrix[r][c] == mark) {
			count++;
		}
	}
	
	if(count == 3) {
		winner = true;
		break;
	}
}

if(!winner) {
	for(size_t r=0; r<3; r++) {
		int count = 0;
            	for(size_t c=0; c<3; c++) {
                    	if(game_matrix[c][r] == mark) {
				count++;
            	        }
    	        }

                if(count == 3) {
			winner = true;
                    	break;
            	}
    	}
}

if(!winner) {
	int count = 0;
	for(size_t i=0; i<3; i++) {
		if(game_matrix[i][i] == mark) {
                            count++;
	        }
		if(count == 3) {
			winner = true;
			break;
		}
	}
}	

if(!winner) {
            int count = 0;
            for(size_t c=2, r=0; c>0, r<3; c--, r++) {
                    if(game_matrix[r][c] == mark) {
                            count++;
                    }
                    if(count == 3) {
                            winner = true;
                            break;
                    }
            }
    }
return winner;			

}

void show_game(int winner) {
system("clear");

if(winner == 0) {
            cout << "TIE!!!!" << endl;
    } else {
            cout << "Winner player " << winner << endl;
    }

    cout << "     |     |     " << endl;
    for(size_t r=0; r<3; r++) {
	char cell1 = get_value(game_matrix[r][0]);
	char cell2 = get_value(game_matrix[r][1]);
	char cell3 = get_value(game_matrix[r][2]);

            cout << "  " << cell1 << "  |  " << cell2 << "  |  " << cell3 << endl;
            cout << "_____|_____|_____" << endl;
            cout << "     |     |     " << endl;
    }

}

char get_value(char mark) {
if(mark == 'X' || mark == 'O') {
return mark;
} else {
return ' ';
}
}

`

This is my version, let me know what do you think about

@mastrobirraio
Copy link

@muhammadimran-dev
Copy link

#include
using namespace std;
void ticTacToe();
void diplayGameBoard(char gameBoard[][3]);
void inputUserA(char gameBoard[][3]);
void inputUserB(char gameBoard[][3]);
bool isAWinner(char gameBoard[][3]);
bool isBWinner(char gameBoard[][3]);

void diplayGameBoard(char gameBoard[][3])
{
system("cls");
for (int i = 0; i < 3; i = i + 1)
{
for (int j = 0; j < 3; j = j + 1)
{
if (gameBoard[i][j] == 'A' || gameBoard[i][j] == 'B')
cout << gameBoard[i][j];
else
cout << (int)(gameBoard[i][j] - '0');
cout << "\t";
}
cout << "\n";
}

}
void inputUserA(char gameBoard[][3])
{
int location;
cin >> location;
while (gameBoard[location / 3][location % 3] == 'A' || gameBoard[location / 3][location % 3] == 'B')
{
cout << "\nEnter again, location is already occupied : ";
cin >> location;
}
gameBoard[location / 3][location % 3] = 'A';
}
void inputUserB(char gameBoard[][3])
{
int location;
cin >> location;
while (gameBoard[location / 3][location % 3] == 'A' || gameBoard[location / 3][location % 3] == 'B')
{
cout << "\nEnter again, location is already occupied : ";
cin >> location;
}
gameBoard[location / 3][location % 3] = 'B';
}
bool isAWinner(char gameBoard[][3])
{
bool flag1 = false, flag2 = false, flag3 = false;
int i = 0;
while (i < 3 && flag1 == false)
{
int j = 0;
flag1 = true;
while (j < 3 && flag1)
{
if (gameBoard[i][j] == 'A')
flag1 = true;
else
flag1 = false;
j = j + 1;
}
i = i + 1;
}
int k = 0;
while (k < 3 && flag1 == false)
{
int j = 0;
flag1 = true;
while (j < 3 && flag1)
{
if (gameBoard[j][k] == 'A')
flag1 = true;
else
flag1 = false;
j = j + 1;
}
k = k + 1;
}
if ((gameBoard[0][0] == 'A' && gameBoard[1][1] == 'A' && gameBoard[2][2] == 'A') || (gameBoard[0][2] == 'A' && gameBoard[1][1] == 'A' && gameBoard[2][0] == 'A'))
flag3 = true;
if (flag1 || flag2 || flag3)
return true;
else
return false;

}
bool isBWinner(char gameBoard[][3])
{
bool flag1 = false, flag2 = false, flag3 = false;
int i = 0;
while (i < 3 && flag1 == false)
{
int j = 0;
flag1 = true;
while (j < 3 && flag1)
{
if (gameBoard[i][j] == 'B')
flag1 = true;
else
flag1 = false;
j = j + 1;
}
i = i + 1;
}
int k = 0;
while (k < 3 && flag1 == false)
{
int j = 0;
flag1 = true;
while (j < 3 && flag1)
{
if (gameBoard[j][k] == 'B')
flag1 = true;
else
flag1 = false;
j = j + 1;
}
k = k + 1;
}
if ((gameBoard[0][0] == 'B' && gameBoard[1][1] == 'B' && gameBoard[2][2] == 'B') || (gameBoard[0][2] == 'B' && gameBoard[1][1] == 'B' && gameBoard[2][0] == 'B'))
flag3 = true;
if (flag1 || flag2 || flag3)
return true;
else
return false;

}
void ticTacToe()
{
char gameBoard[3][3] = { '0','1','2','3','4','5','6','7','8' };
int counter = 0;
while (counter < 5)
{
diplayGameBoard(gameBoard);
cout << "\nUser A, Enter location number : ";
inputUserA(gameBoard);
if (isAWinner(gameBoard))
{
diplayGameBoard(gameBoard);
cout << "\nUser A is Winner!\n";
exit(0);
}
if (counter != 4)
{
diplayGameBoard(gameBoard);
cout << "\nUser B, Enter location number : ";
inputUserB(gameBoard);
if (isBWinner(gameBoard))
{
diplayGameBoard(gameBoard);
cout << "\nUser B is Winner!\n";
exit(0);
}

	}
	counter = counter + 1;
}
if (counter == 5)
	cout << "Game Tie...";

}

int main()
{
ticTacToe();
cout << "\n";
return 0;
}

@muhammadimran-dev
Copy link

https://github.com/imrankhalid-tech/Tic-Tac-Toe
Link of whole project created in Visual Studio 2015

@b-hkm
Copy link

b-hkm commented Jan 10, 2021

in the display func you could add :: system("clear"); so it looks better

@b-hkm
Copy link

b-hkm commented Jan 10, 2021

or system("cls"); for windows i think

@liviugrigore
Copy link

Few more libraries to make it faster to play, use the numpad as it would be the board (^▽^)

#include <iostream>
#include <conio.h>
#include <stdlib.h>
bool gameOver = false, playerTurn, result ;
char gSpace[3][3];
void showResult(char res)
{
	gameOver = true;
	if (result == false)
	{
		if (res == 'D') std::cout << "Draw! \"\\_('o')_/\"";
		else std::cout << "Player " << res << " won!";
		result = true;
	}
}
void Logic()
{
	for (int i = 0; i < 3; i++)
	{
		int valrow = (gSpace[i][0] + gSpace[i][1] + gSpace[i][2]);
		if (valrow == 264) showResult('X');
		else if (valrow == 237) showResult('O');
	}
	for (int i = 0; i < 3; i++)
	{
		int valrow = (gSpace[0][i] + gSpace[1][i] + gSpace[2][i]);
		if (valrow == 264) showResult('X');
		else if (valrow == 237) showResult('O');
	}
	if ((gSpace[0][0] + gSpace[1][1] + gSpace[2][2]) == 264) showResult('X');
	if ((gSpace[0][0] + gSpace[1][1] + gSpace[2][2]) == 237) showResult('O');

	if ((gSpace[0][2] + gSpace[1][1] + gSpace[2][0]) == 264) showResult('X');
	if ((gSpace[0][2] + gSpace[1][1] + gSpace[2][0]) == 237) showResult('O');

	bool draw = true;
	for (int i = 0; i < 3; i++)
		for (int j = 0; j < 3; j++) if (gSpace[i][j] == '-') draw = false;
	if (draw) showResult('D');
}
void Draw()
{
	system("CLS");
	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			std::cout << gSpace[i][j] << '\t';
		}
		std::cout << std::endl << std::endl;
	}
	if (playerTurn) std::cout << "Turn player O " <<std::endl;
	else std::cout << "Turn player X " << std::endl;
}
int Input()
{
	if (_kbhit())
	{
		switch (_getch())
		{
		case '7': return 0;
		case '8': return 1;
		case '9': return 2;
		case '4': return 10;
		case '5': return 11;
		case '6': return 12;
		case '1': return 20;
		case '2': return 21;
		case '3': return 22;
		}
	}
	else return -1;
}
void Set()
{
	int input = -1;
	while (input == -1) input = Input();
	if (gSpace[input/10][input%10] == '-')
	{
		if (playerTurn == false)
		{
			gSpace[input/ 10][input % 10] = 'X';
			playerTurn = true;
		}
		else
		{
			gSpace[input / 10][input % 10] = 'O';
			playerTurn = false;
		}
	}
}
void Game()
{
	for (int i = 0; i < 3; i++)
		for (int j = 0; j < 3; j++)
			gSpace[i][j] = '-';
	Draw();
	result = false;
	while (!gameOver)
	{
		Set();
		Draw();
		Logic();
	}
}
int main()
{
	Draw();
	Game();
	while (_getch() != 'e')
	{
		if (_getch() == 'r')
		{
			gameOver = false;
			Game();
		}
	}
	return 0;
}

@fahadcprogramming
Copy link

Your code looks clean. Thanks a lot for taking the time and writing this clean code.

Simple TicTacToe C++ example with a complete explanation

Game is developed in C++ code blocks IDE. It has the defined board size of 5X5 with two modes

  1. Player vs Player. 2. Player vs Computer

C++ Concept used in this code are

  • Variables
  • Two dimensional Arrays (2D arrays)
  • Nested for loop
  • if else statement
  • functions

Functions
void menu();
void printBoard();
void input(int);
void player1();
void player2();
void p2p();
bool check();
bool defend(int, int, int);
bool attack();
void computerMoves(int);
void p2c();

Complete code here: C++ tic tac toe simple example with logic explanation

@deeepikamg
Copy link

deeepikamg commented Mar 6, 2021

/Here is my implementation/

#include < iostream >
using namespace std;
int isAnyoneWinner(int arr[]);
int findBestNextMove(int arr[]);
void DisplayBoard(int arr[]);

int main()
{
int array[9] = { 0 };
int player = 1;
int nextMove = 0;
cout << endl << "Who is first player to start? ( pls enter 1 for Computer[X], 2 for Human-Being[O]) = ";
cin >> player;

if (player != 1 && player != 2)
{
    player = 1;
    cout << endl << "You entered wrong number to select player so computer will be a first player";
}
while (true)
{
    int currentMark = (player == 1) ? 'x' : 'o';

    if (player == 2) // Human Being
    {
        cout << "\n Enter Next move = ";
        cin >> nextMove;
    }
    else // Computer
    {
        nextMove = findBestNextMove(array);
        cout << endl << " Computer chosen position = " << nextMove;
    }
    if (nextMove > 0 && nextMove < 10 && array[nextMove - 1] == 0)
    {
        array[nextMove - 1] = currentMark;
        int winner = isAnyoneWinner(array);
        if (winner > 0)
        {
            if (winner < 3)
            {
                cout << endl << " Winner is = " << winner;
            }
            else
            {
                cout << endl << endl << "*********** Match is drawn, It is a tie ******************";
            }
            //cin>> winner;
            break;
        }
        player = (player == 2) ? 1 : 2;
        DisplayBoard(array);
    }
    else
    {
        cout << endl << "You entered wrong move, please renter the value";
    }
}
DisplayBoard(array);

cout << endl << endl << "================== THANK YOU ============================ " << endl;
return 0;

}

int findBestNextMove(int arr[])
{
int possibleWinningMoves[8][3] = { {0,4,8},{2,4,6},{0,3,6},{1,4,7},{2,5,8},{0,1,2},{3,4,5},{6,7,8} };
int Winner = 0;
int potentialWinningPos = -1;

for (int counter = 0; counter < 2 && potentialWinningPos == -1; counter++)
{
    for (int outer = 0; outer < 8 && potentialWinningPos == -1; outer++)
    {
        int sum = 0;
        for (int inner = 0; inner < 3; inner++)
        {
            sum += arr[possibleWinningMoves[outer][inner]];
        }

        if (sum == ((2 - counter) * 'x') || sum == ((2 - counter) * 'o')) //find if the computer is winning OR opponent is winning
        {
            for (int inner = 0; inner < 3; inner++)
            {
                if (arr[possibleWinningMoves[outer][inner]] == 0)
                {
                    potentialWinningPos = possibleWinningMoves[outer][inner] + 1;
                    break;
                }
            }
        }
    }
}

if (potentialWinningPos == -1)//failed get position
{
    if (arr[4] == 0)
    {
        potentialWinningPos = 5;
    }
    else
    {
        cout << endl << "Your logic is failed, please relook";
    }
}
return potentialWinningPos;

}

// A function to show the current board status
void DisplayBoard(int arr[])
{
cout << endl << endl;
cout << "| " << (char)arr[0] << " | " << (char)arr[1] << " | " << (char)arr[2] << " |" << endl;
cout << "||" << endl;
cout << "| " << (char)arr[3] << " | " << (char)arr[4] << " | " << (char)arr[5] << " |" << endl;
cout << "|
|" << endl;
cout << "| " << (char)arr[6] << " | " << (char)arr[7] << " | " << (char)arr[8] << " |" << endl;
return;
}

int isAnyoneWinner(int arr[])
{
int WinningRowColumn[8];
int Winner = 0;
WinningRowColumn[0] = arr[0] + arr[3] + arr[6];
WinningRowColumn[1] = arr[1] + arr[4] + arr[7];
WinningRowColumn[2] = arr[2] + arr[5] + arr[8];

WinningRowColumn[3] = arr[0] + arr[1] + arr[2];
WinningRowColumn[4] = arr[3] + arr[4] + arr[5];
WinningRowColumn[5] = arr[6] + arr[7] + arr[8];

WinningRowColumn[6] = arr[0] + arr[4] + arr[8];
WinningRowColumn[7] = arr[2] + arr[4] + arr[6];

int i = 0;
for (; i <= 8; i++)
{
    if (WinningRowColumn[i] == (3 * 'x'))
    {
        Winner = 1;
        break;
    }
    else if (WinningRowColumn[i] == (3 * 'o'))
    {
        Winner = 2;
        break;
    }
}
if (i > 8 && Winner == 0)
{
    bool isPosAvailable = false;
    for (i = 0; i <= 9; i++)
    {
        if (arr[i] == 0)
        {
            isPosAvailable = true;
            break;
        }
    }
    if (!isPosAvailable)
    {
        Winner = 3;// Draw
    }
}
return Winner;

}

@wilganm1
Copy link

wilganm1 commented Sep 3, 2022

Late to the party but here's my version. It's the best one in this thread.

The game is you (X) vs the computer (O) and is randomly decided who goes first. 50/50 chance.
It displays the game board with each position whether it's filled or not, and even tells you which positions are available.

There's unlimited retries and the board resets after every turn so there's no clutter.

You'll need to link a header file called random.hpp.

#include <iostream>
#include <vector>  //to create vectors
#include <algorithm> // for .begin() and .end() for vectors
#include <cstdlib> //rand() and srand().
#include "random.hpp"   //better at guessing random numbers

using Random = effolkronium::random_static; //from "random.hpp" file

bool checksSpaces(std::vector<int>ops, int choice){ //checks if the player enters a space that is not available.
    if (std::find(ops.begin(), ops.end(), choice) != ops.end()) {
        return true;}
    else {
        return false;}
}

void print(std::vector<int> const &ops){  //prints out available positions. found online.
    for (auto const &i: ops) {
        std::cout << i << " ";}
}

void board(std::vector<char>& vec){ //displays the game.
    system("CLS");
    std::cout << "\t\t   Tic Tac Toe\n\n";
    std::cout << "\t\t   7    8    9" <<std::endl;
    std::cout << "\t\t      |   |     " << std::endl;
    std::cout << "\t\t   " << vec[6]<<"  | " << vec[7] <<" |  " << vec[8] << std::endl;
    std::cout << "\t\t _____|___|_____" << std::endl;
    std::cout << "\t\t      |   |     " << std::endl;
    std::cout << "\t\t4  " << vec[3]<<"  | " << vec[4] <<" |  " << vec[5] << "  6 " << std::endl;
    std::cout << "\t\t _____|___|_____" << std::endl;
    std::cout << "\t\t      |   |     " << std::endl;
    std::cout << "\t\t   " << vec[0]<<"  | " << vec[1] <<" |  " << vec[2] << std::endl;
    std::cout << "\t\t      |   |     " << std::endl;
    std::cout << "\t\t   1    2    3";
}

void playerSelection(std::vector<int>& op, std::vector<char>& vec){ //The player choosing a spot
    p_select:
        std::cout << "\nPlease select an open space: ";
        print(op);
        std::cout << std::endl;
        int player_selection{};
        std::cin >> player_selection;
        if (checksSpaces(op, player_selection)) {
            vec[player_selection - 1] = 'X'; // -1 so the indices work out between 2 vectors
            std::vector<int>::iterator itr = std::find(op.begin(), op.end(), player_selection);
            int index = std::distance(op.begin(), itr);
            op.erase(op.begin() + index);}
        else if (!checksSpaces(op, player_selection)){
            std::cout << "Invalid. Try again." << std::endl;
            std::cin.clear();  //will erase the cin input
            std::cin.ignore(10000, '\n');
            goto p_select;}
}

void computerSelection(std::vector<int>& op, std::vector<char>& vec){ //computer randomly selecting a spot
    srand(time(0));  // NEED THIS for random every time
    int comp_select = std::rand() % (op.size());
    int sel_elem = op[comp_select];
    vec[sel_elem - 1] = 'O'; // -1 so the indices work out between 2 vectors
    std::vector<int>::iterator itr = std::find(op.begin(), op.end(), sel_elem);
    int index = std::distance(op.begin(), itr);
    op.erase(op.begin() + index);
}

bool whoGoesFirst(){  // coin flip for who goes first
    return (Random::get<bool>()); // true with 50% probability by default
}

bool aWinner(std::vector<char>vec) { //determines a winner
    if (vec[0] == 'X' && vec[1] == 'X' && vec[2] == 'X' || vec[3] == 'X' && vec[4] == 'X' && vec[5] == 'X' || vec[6] == 'X' && vec[7] == 'X' && vec[8] == 'X') {
        std::cout << "\nYou win! Horizontal." << std::endl;
        return false;}
    else if (vec[0] == 'X' && vec[3] == 'X' && vec[6] == 'X' || vec[1] == 'X' && vec[4] == 'X' && vec[7] == 'X' || vec[2] == 'X' && vec[5] == 'X' && vec[8] == 'X') {
        std::cout << "\nYou win! Vertical." << std::endl;
        return false;}
    else if (vec[0] == 'X' && vec[4] == 'X' && vec[8] == 'X' || vec[2] == 'X' && vec[4] == 'X' && vec[6] == 'X') {
        std::cout << "\nYou win! Diagonal." << std::endl;
        return false;}
    else if (vec[0] == 'O' && vec[1] == 'O' && vec[2] == 'O' || vec[3] == 'O' && vec[4] == 'O' && vec[5] == 'O' || vec[6] == 'O' && vec[7] == 'O' && vec[8] == 'O') {
        std::cout << "\nComputer wins! Horizontal." << std::endl;
        return false;}
    else if (vec[0] == 'O' && vec[3] == 'O' && vec[6] == 'O' || vec[1] == 'O' && vec[4] == 'O' && vec[7] == 'O' || vec[2] == 'O' && vec[5] == 'O' && vec[8] == 'O') {
        std::cout << "\nComputer wins! Vertical." << std::endl;
        return false;}
    else if (vec[0] == 'O' && vec[4] == 'O' && vec[8] == 'O' || vec[2] == 'O' && vec[4] == 'O' && vec[6] == 'O') {
        std::cout << "\nComputer wins! Diagonal." << std::endl;
        return false;}
    else {
        return true;}
}

int main(){
    while(true){
        std::vector<int> open_positions = {1,2,3,4,5,6,7,8,9};   //these two variables are passed by reference in functions to change them dynamically.
        std::vector<char> pst = {' ',' ',' ',' ',' ',' ',' ',' ',' '};
        board(pst);
        switch (whoGoesFirst()){
            case 0: //false. Player goes first
                while (aWinner(pst) && open_positions.size() != 0){ //keeps the game going unless someone wins or no more spaces.
                    board(pst);
                    std::cout << "\nYou go first." << std::endl;
                    playerSelection(open_positions, pst);
                    if (aWinner(pst) && open_positions.size() != 0){ //Need this so the game stops at the moment someone wins
                        computerSelection(open_positions, pst);}
                    else {
                        break;}}
                break;
            case 1: //true. Computer goes first
                while (aWinner(pst) && open_positions.size() != 0){
                    computerSelection(open_positions, pst);
                    board(pst);
                    std::cout << "\nComputer goes first." << std::endl;
                    if (aWinner(pst) && open_positions.size() != 0){
                        playerSelection(open_positions, pst);}
                    else {
                        break;}}
                break;}
        board(pst);
        aWinner(pst);
        if (open_positions.size() == 0){
            std::cout << "\nNo one wins.";
        }
        std::cout << "\nPlay again? (y/n): ";
        char retry{};
        std::cin >> retry;
        if (retry == 'y'){}
        else {
            break;}}
    std::cout << "Thanks for playing!" << std::endl;
    return 0;
}

@konan625
Copy link

#include <bits/stdc++.h>
using namespace std;

void Print(vector<vector<char>> &board)
{
    for (int i = 0; i < 3; i++)
    {
        cout << "-------" << endl;
        cout << "|" << board[i][0] << "|" << board[i][1] << "|" << board[i][2] << "|" << endl;
    }
    cout << "-------" << endl;
    return;
}
bool win(vector<vector<char>> &board, int row, int col)
{
    char chk = board[row - 1][col - 1];
    // Check the diagonals
    if (board[0][0] == chk && board[1][1] == chk && board[2][2] == chk)
        return true;
    if (board[0][2] == chk && board[1][1] == chk && board[2][0] == chk)
        return true;

    // Checking Rows and columns
    for (int i = 0; i < 3; i++)
    {
        if (board[i][0] == chk && board[i][1] == chk && board[i][2] == chk)
            return true;
        if (board[0][i] == chk && board[1][i] == chk && board[2][i] == chk)
            return true;
    }
    return false;
}
int main()
{
    int count = 0;
    vector<vector<char>> board(3, vector<char>(3, ' '));
    bool gameon = true;
    bool first = true, second = false;
    while (gameon)
    {
        if (count == 9)
        {
            cout << "That's a Draw! Game Over!" << endl;
            break;
        }
        if (first)
        {
            cout << "First Player Choose the Row and Column numbers" << endl;
        }
        else
        {
            cout << "Second Player Choose the Row and Column numbers" << endl;
        }
        int row, col;
        cout << "Row Number (1,2,3) - ";
        cin >> row;
        cout << endl
             << "Column Number (1,2,3) - ";
        cin >> col;
        if (board[row - 1][col - 1] != ' ')
        {
            cout << "\n This cell is occupied, choose another" << endl;
            continue;
        }
        if (first)
            board[row - 1][col - 1] = 'X';
        else
            board[row - 1][col - 1] = 'O';
        count++;
        Print(board);
        bool won = win(board, row, col);
        if (won)
        {
            if (first)
                cout << "First Player Won! Congratulations!";
            else
                cout << "Second Player Won! Congratulations!";
            return 0;
            gameon = false;
        }
        first = !first;
        second = !second;
    }
    cout << "\n Game Over";
    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment