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
|
#include <iostream>
using namespace std;
void display(char* board) {
const char* h_sep = "---+---+---";
const char* v_sep = " |";
for (unsigned row = 0; row < 3; ++row)
{
for (unsigned col = 0; col < 3; ++col)
{
cout << ' ' << board[row * 3 + col];
if (col < 2) cout << v_sep;
}
cout << '\n';
if (row < 2) cout << h_sep << '\n';
}
cout<< '\n';
}
char check_winner(char* board, unsigned* t)
{
if (board[t[0]] == board[t[1]] && board[t[1]] == board[t[2]])
return board[t[0]];
return '\0';
}
int check_winner(char* board) {
const std::size_t n_triplets = 8;
static unsigned triplets[n_triplets][3] =
{
{ 0,1,2 },{ 3,4,5 },{ 6,7,8 },{ 0,3,6 },
{ 1,4,7 },{ 2,5,8 },{ 0,4,8 },{ 2,4,6 }
};
for (std::size_t i = 0; i < n_triplets; ++i)
if (char winner = check_winner(board, triplets[i]))
return winner;
return '\0';
}
int main() {
char board[9] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
cout << "\nTic Tac toe\n\n";
display(board);
unsigned turn = 0;
while ( turn < 9 && !check_winner(board))
{
char mark = "XO"[turn % 2];
unsigned cell;
cout << mark << " it's your turn, where will you play?\n> ";
cin >> cell;
if (!cin || cell < 1 || cell > 9)
{
cin.clear();
cin.ignore(1000, '\n');
cout << "Invalid input.\n";
}
else if (board[cell - 1] == 'X' || board[cell - 1] == 'Y')
cout << "Cell is occupied.\n";
else
{
board[cell - 1] = mark;
++turn;
display(board);
}
}
if (char winner = check_winner(board))
cout << winner << " wins!\n";
else
cout << "It's a tie!\n";
}
|