rendered paste body#include <iostream>
#include <string>
using std::cout;
using std::cin;
#include "tictactoe.h"
// constructor
ticTacToe::ticTacToe()
{
int i;
turn = 1;
for(i = 0; i < 9; i++)
{
board[i] = 0;
}
};
// Put the game on
int ticTacToe::startGame()
{
play();
return 0;
};
// Do the real play
int ticTacToe::play()
{
// Check at the start to avoid futile plays
if(checkDraw() == true)
return 0;
drawBoard();
cout << (turn == 1?"X ":"O ") << "turn." << endl;
cout << "Set the position you want to play: ";
cin >> position;
while(checkValid(position) != true)
{
play();
}
// Check at the end to prize the winner
if(checkWin() == true)
return 0;
}
// Check if it's a real and valid position
int ticTacToe::checkValid(int value)
{
if(value < 1 || value > 9)
{
cout << "Invalid value, put a number between 1 and 9." << endl;
return false;
}
if(board[value -1] != 0)
{
cout << "Position already played, choose another one." << endl;
return false;
}
else
{
board[value - 1] = turn;
cout << "\n" << endl;
return true;
}
};
// Check for the win
int ticTacToe::checkWin()
{
if(board[0] == turn && board[1] == turn && board[2] == turn ||
board[0] == turn && board[3] == turn && board[6] == turn ||
board[0] == turn && board[4] == turn && board[8] == turn ||
board[1] == turn && board[4] == turn && board[7] == turn ||
board[2] == turn && board[5] == turn && board[8] == turn ||
board[2] == turn && board[4] == turn && board[6] == turn ||
board[3] == turn && board[4] == turn && board[5] == turn ||
board[6] == turn && board[7] == turn && board[8] == turn)
{
displayWinMessage();
return true;
}
else
{
if(turn == 1)
{
turn = 2;
}
else
{
turn = 1;
}
play();
}
};
// Check for a draw game
int ticTacToe::checkDraw()
{
int i;
int counter;
counter = 0;
for(i = 0; i < 9; i++)
{
if(board[i] == 0)
{
counter++;
}
}
if(counter == 0)
{
displayDrawMessage();
return true;
}
else
{
return false;
}
};
// Draw the most beatifull Tic Tac Toe board on the world
void ticTacToe::drawBoard()
{
int i;
int sum;
sum = 1;
for(i = 0; i < 9; i++)
{
if(i == 3 || i == 6)
{
cout << "\n-----|-----|-----\n";
}
if(board[i] == 1)
{
if(i == 0 || i == 3 || i == 6)
{
cout << " X |";
}
else if(i == 2 || i == 5 || i ==8)
{
cout << "| X ";
}
else
{
cout << " X ";
}
}
else if(board[i] == 2)
{
if(i == 0 || i == 3 || i == 6)
{
cout << " O |";
}
else if(i == 2 || i == 5 || i ==8)
{
cout << "| O ";
}
else
{
cout << " O ";
}
}
else
{
if(i == 0 || i == 3 || i == 6)
{
cout << " " << (sum = i + 1) <<" |";
}
else if(i == 2 || i == 5 || i ==8)
{
cout << "| " << (sum = i + 1) << " ";
}
else
{
cout << " " << (sum = i + 1) << " ";
}
}
}
cout << "\n" << endl;
};
// Two fucking loser players draw the game
void ticTacToe::displayDrawMessage()
{
drawBoard();
cout << "Draw Game!" << endl;
};
// Shows that someone won the game
void ticTacToe::displayWinMessage()
{
drawBoard();
cout << "Congratulations, you win!" << endl;
};