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
|
#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;
struct point
{
int r;
int c;
point(int rr, int cc) : r(rr), c(cc) {}
};
const string lft[3] {"T", "M", "B"};
const string top[3] {"L", "C", "R"};
const char sym[2] {'X', 'O'};
const unordered_map<string, point> msp {make_pair(lft[0] + top[0], point(0, 0)),
make_pair(lft[0] + top[1], point(0, 1)),
make_pair(lft[0] + top[2], point(0, 2)),
make_pair(lft[1] + top[0], point(1, 0)),
make_pair(lft[1] + top[1], point(1, 1)),
make_pair(lft[1] + top[2], point(1, 2)),
make_pair(lft[2] + top[0], point(2, 0)),
make_pair(lft[2] + top[1], point(2, 1)),
make_pair(lft[2] + top[2], point(2, 2))};
const point win[8][3] {{ { 0, 0 }, { 0, 1 }, { 0, 2 } },
{ { 1, 0 }, { 1, 1 }, { 1, 2 } },
{ { 2, 0 }, { 2, 1 }, { 2, 2 } },
{ { 0, 0 }, { 1, 0 }, { 2, 0 } },
{ { 0, 1 }, { 1, 1 }, { 2, 1 } },
{ { 0, 2 }, { 1, 2 }, { 2, 2 } },
{ { 0, 0 }, { 1, 1 }, { 2, 2 } },
{ { 0, 2 }, { 1, 1 }, { 2, 0 } }};
string toupper(const string& st)
{
string tu;
for (auto ch : st)
tu += toupper(ch);
return tu;
}
void draw(char board[3][3])
{
cout << endl;
for (int t = 0; t < 3; ++t)
cout << " " << top[t];
cout << endl << endl;
for (int rr = 0; rr < 3; ++rr) {
if (rr > 0)
cout << " -----------" << endl;
for (int cc = 0; cc < 3; ++cc) {
(cc > 0) ? cout << " |" : cout << lft[rr] << " ";
cout << " " << board[rr][cc];
}
cout << endl;
}
}
int main()
{
char again = 'n';
do {
char board[3][3] = {0};
string inp;
auto mit = msp.cbegin();
char gotwin = ' ';
draw(board);
for (int cnt = 0, play = 0; (cnt < 9) && (gotwin == ' ');) {
while ((cout << "\nEnter location for player " << play + 1 << " [" << sym[play] << "]: ") && (cin >> inp) && ((mit = msp.find(toupper(inp))) == msp.end()))
cout << "Invalid location";
char& pos = board[mit->second.r][mit->second.c];
if (pos > ' ')
cout << "Space taken!" << endl;
else {
pos = sym[play];
++cnt;
play = (play + 1) % 2;
draw(board);
for (int w = 0, b; (w < 8) && (gotwin == ' '); ++w)
if (((b = board[win[w][0].r][win[w][0].c]) > ' ') && (b == board[win[w][1].r][win[w][1].c]) && (b == board[win[w][2].r][win[w][2].c]))
gotwin = b;
if (gotwin != ' ')
cout << "\nPlayer " << (gotwin == 'X' ? "1" : "2") << " wins!" << endl;
}
}
if (gotwin == ' ')
cout << "\nDraw!" << endl;
while ((cout << "\nPlay again? [Y, N]: ") && (cin >> again) && ((again = toupper(again)) != 'N' && (again != 'Y')))
cout << "Please enter 'Y' or 'N': ";
} while (again == 'Y');
}
|