1#ifndef TicTacToe_H 2#define TicTacToe_H 3#include<array> 4class TicTacToe 5{ 6private: 7 static std::array<std::array<int, 3>, 3>T; 8 int num; 9public: 10 TicTacToe(int); 11 static bool win(); 12 void show(); 13 bool play(int,int); 14}; 15#endif
1#include"head.h" 2#include<iostream> 3using std::array; 4array<array<int, 3>, 3>TicTacToe::T{}; 5 6TicTacToe::TicTacToe(int n):num(n){} 7bool TicTacToe::win() 8{ 9 for (int i = 0; i < 3; i++) 10 { 11 if (T[i][1] == T[i][2] && T[i][0] == T[i][2] && T[i][1] != 0) 12 return true; 13 } 14 for (int i = 0; i < 3; i++) 15 { 16 if (T[0][i] == T[1][i] && T[1][i] == T[2][i] && T[0][i] != 0) 17 return true; 18 } 19 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]) 20 return true; 21 return false; 22} 23void TicTacToe::show() 24{ 25 for (int i = 0; i < 3; i++) 26 { 27 for (int j = 0; j < 3; j++) 28 { 29 std::cout << T[i][j] << " "; 30 } 31 std::cout << std::endl; 32 } 33} 34bool TicTacToe::play(int a, int b) 35{ 36 37 if ((a > 0 && a < 4 && b>0 && b < 4)&& T[a - 1][b - 1] == 0) 38 { 39 T[a - 1][b - 1] = this->num; 40 show(); 41 return true; 42 } 43 else 44 { 45 std::cout << "Please enter a valid position!" << std::endl; 46 return false; 47 } 48 49 if (win()) 50 { 51 std::cout << "Player" << this->num << " win!" << std::endl; 52 } 53}
1#include<iostream> 2#include"head.h" 3#include<array> 4using std::cin; 5using std::cout; 6using std::endl; 7int main() 8{ 9 TicTacToe player1(1); 10 TicTacToe player2(2); 11 int turn; 12 cout << "Please enter 1 or 2 to decide who to start." << endl; 13 cin >> turn; 14 if (turn != 1 && turn != 2) 15 { 16 cout << "You enter a wrong number!Enter again." << endl; 17 cin >> turn; 18 } 19 int final = turn; 20 while (TicTacToe::win() == false) 21 { 22 std::cout << "Please enter two integers between 1 and 3 to represent the position of tictactoe." << std::endl; 23 int a, b; 24 cin >> a >> b; 25 if (turn % 2 == 1) 26 { 27 if (player1.play(a, b) == false) 28 continue; 29 } 30 else if (turn % 2 == 0) 31 { 32 if (player2.play(a, b) == false) 33 continue; 34 } 35 turn++; 36 if ((turn - final == 9) && (TicTacToe::win() == false)) 37 { 38 cout << "No one win." << endl; 39 break; 40 } 41 } 42}
