1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct LastMove
{
string symbol;
int row;
int col;
};
class TicTacTester
{
public:
TicTacTester(const vector<vector<string>>& board, int total_moves) :
side_(3),
board_(board),
total_moves_(total_moves),
game_over_(false),
winner_("No One")
{
}
void Reset(const vector<vector<string>>& board, int total_moves)
{
board_ = board;
total_moves_ = total_moves;
game_over_ = false;
winner_ = "No One";
}
// Conditions for game over:
// 1. Number of moves equal to SIDE*SIDE
// 2. Related rows/columns/diagonals filled with last symbol
bool IsGameOver(int row, int col)
{
// Can change game_over_
CheckTotalMoves();
last_.row = row;
last_.col = col;
last_.symbol = board_[row][col];
// All of these can change game_over_ and winner_
CheckRowWin() || CheckColWin() || CheckDiagWin();
return game_over_;
}
string Winner() { return winner_; }
private:
void CheckTotalMoves()
{
game_over_ = total_moves_==side_*side_;
}
bool CheckRowWin()
{
int down = last_.col-1;
while (down >= 0)
{
if (board_[last_.row][down] != last_.symbol)
return false;
down--;
}
int up = last_.col+1;
while (up < side_)
{
if (board_[last_.row][up] != last_.symbol)
return false;
up++;
}
game_over_ = true;
winner_ = last_.symbol;
return true;
}
//TODO: implement
bool CheckColWin()
{
return false;
}
//TODO: implement
bool CheckDiagWin()
{
return false;
}
const unsigned int side_;
vector<vector<string>> board_;
int total_moves_;
bool game_over_;
string winner_;
LastMove last_; // Last legal move played
};
int main()
{
vector<vector<vector<string>>> boards
{
{{ "X", "O", "X" },
{ "O", "O", "X" },
{ "X", "X", "O" }},
{{ "X", "X", "X" },
{ "˘", "˘", "˘" },
{ "O", "˘", "O" }},
{{ "X", "˘", "O" },
{ "X", "˘", "˘" },
{ "X", "˘", "O" }},
};
// 0. Test a Draw
TicTacTester t(boards[0], 9);
cout << "0. [Draw] ";
if (t.IsGameOver(2,0))
{
cout << "Winner is " << t.Winner() << endl;
}
else
{
cout << "Game is still going." << endl;
}
// 1. Test a Row win
t.Reset(boards[1], 5);
cout << "1. [Row] ";
if (t.IsGameOver(0,2))
{
cout << "Winner is " << t.Winner() << endl;
}
else
{
cout << "Game is still going." << endl;
}
// 2. Test a Column win
t.Reset(boards[2], 5);
cout << "2. [Col] ";
if (t.IsGameOver(2,0))
{
cout << "Winner is " << t.Winner() << endl;
}
else
{
cout << "Game is still going." << endl;
}
return 0;
}
|