-
-
Save ajnarayan/718d7fea9692f8442c20 to your computer and use it in GitHub Desktop.
#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; | |
} |
in the display func you could add :: system("clear"); so it looks better
or system("cls"); for windows i think
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;
}
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
- 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
/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;
}
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;
}
#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;
}
https://github.com/imrankhalid-tech/Tic-Tac-Toe
Link of whole project created in Visual Studio 2015