Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Online C++ Compiler and Editor */
- #include <bits/stdc++.h>
- using namespace std;
- class Player{
- public:
- string name;
- char sign;
- Player(string name, char sign){
- this->name=name;
- this->sign=sign;
- }
- };
- class TikTacToe{
- int size,count=0;
- vector<vector<char>>board;
- deque<Player>players;
- public:
- TikTacToe(int size){
- this->size = size;
- board = vector<vector<char>>(size,vector<char>(size, '.'));
- Player p1 = Player("player1",'X');
- Player p2 = Player("player2",'O');
- players.push_back(p1);
- players.push_back(p2);
- }
- void StartGame();
- bool EnterValue(Player p);
- void PrintBoard();
- bool IsGameCompleted(int row, int col, Player p);
- };
- void TikTacToe::StartGame(){
- while(count<size*size){
- Player current = players.front();
- if(EnterValue(current)==false){
- break;
- }
- players.pop_front();
- players.push_back(current);
- }
- }
- bool TikTacToe::EnterValue(Player p){
- int row, col;
- cout<<p.name<<" please enter row and col\n";
- cin>>row>>col;
- if(row<0 || col<0 || row>=size || col>=size){
- cout<<"invalid index write again\n";
- return EnterValue(p);
- }
- if(board[row][col]!='.'){
- cout<<"value is already filled in index write again\n";
- return EnterValue(p);
- }
- board[row][col]=p.sign;
- PrintBoard();
- count++;
- if (IsGameCompleted(row,col,p)){
- cout<<p.name<<" won game";
- return false;
- }
- if(count==size*size){
- cout<<"withddraw game";
- return false;
- }
- cout<<endl;
- return true;
- }
- void TikTacToe::PrintBoard(){
- for(int i=0;i<size;i++){
- cout<<"|";
- for(int j=0;j<size;j++){
- cout<<board[i][j]<<"|";
- }
- cout<<"\n--------\n";
- }
- }
- bool TikTacToe::IsGameCompleted(int row, int col, Player p){
- bool valid=true;
- for(int i=0;i<size;i++){
- if(board[row][i]!=p.sign){
- valid=false;
- break;
- }
- }
- if(valid)return true;
- valid=true;
- for(int i=0;i<size;i++){
- if(board[i][col]!=p.sign){
- valid=false;
- break;
- }
- }
- if(valid)return true;
- valid=true;
- for(int i=0;i<size;i++){
- if(board[i][i]!=p.sign){
- valid=false;
- break;
- }
- }
- if(valid)return true;
- valid=true;
- for(int i=0;i<size;i++){
- if(board[i][size-i-1]!=p.sign){
- valid=false;
- break;
- }
- }
- if(valid)return true;
- return false;
- }
- int main()
- {
- TikTacToe obj = TikTacToe(3);
- obj.StartGame();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement