#ifndef TicTacToe_H
#define TicTacToe_H
#include<array>
class TicTacToe
{
private:
static std::array<std::array<int, 3>, 3>T;
int num;
public:
TicTacToe(int);
static bool win();
void show();
bool play(int,int);
};
#endif
#include"head.h"
#include<iostream>
using std::array;
array<array<int, 3>, 3>TicTacToe::T{};
TicTacToe::TicTacToe(int n):num(n){}
bool TicTacToe::win()
{
for (int i = 0; i < 3; i++)
{
if (T[i][1] == T[i][2] && T[i][0] == T[i][2] && T[i][1] != 0)
return true;
}
for (int i = 0; i < 3; i++)
{
if (T[0][i] == T[1][i] && T[1][i] == T[2][i] && T[0][i] != 0)
return true;
}
if(((T[0][0] == T[1][1] && T[1][1] == T[2][2])|| (T[2][0] == T[1][1] && T[1][1] == T[0][2]))&& T[1][1])
return true;
return false;
}
void TicTacToe::show()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
std::cout << T[i][j] << " ";
}
std::cout << std::endl;
}
}
bool TicTacToe::play(int a, int b)
{
if ((a > 0 && a < 4 && b>0 && b < 4)&& T[a - 1][b - 1] == 0)
{
T[a - 1][b - 1] = this->num;
show();
return true;
}
else
{
std::cout << "Please enter a valid position!" << std::endl;
return false;
}
if (win())
{
std::cout << "Player" << this->num << " win!" << std::endl;
}
}
#include<iostream>
#include"head.h"
#include<array>
using std::cin;
using std::cout;
using std::endl;
int main()
{
TicTacToe player1(1);
TicTacToe player2(2);
int turn;
cout << "Please enter 1 or 2 to decide who to start." << endl;
cin >> turn;
if (turn != 1 && turn != 2)
{
cout << "You enter a wrong number!Enter again." << endl;
cin >> turn;
}
int final = turn;
while (TicTacToe::win() == false)
{
std::cout << "Please enter two integers between 1 and 3 to represent the position of tictactoe." << std::endl;
int a, b;
cin >> a >> b;
if (turn % 2 == 1)
{
if (player1.play(a, b) == false)
continue;
}
else if (turn % 2 == 0)
{
if (player2.play(a, b) == false)
continue;
}
turn++;
if ((turn - final == 9) && (TicTacToe::win() == false))
{
cout << "No one win." << endl;
break;
}
}
}