Skip to content

Instantly share code, notes, and snippets.

@H2CO3
Created March 31, 2016 12:35
Show Gist options
  • Save H2CO3/237b6db28a47da4a2bc923c6b1f30316 to your computer and use it in GitHub Desktop.
Save H2CO3/237b6db28a47da4a2bc923c6b1f30316 to your computer and use it in GitHub Desktop.
#include <vector>
#include <array>
#include <cstdio>
#include <iostream>
#include <random>
enum State: unsigned char {
Empty,
X,
O
};
#define TABLE_SIZE 3
typedef std::array<std::array<State, TABLE_SIZE>, TABLE_SIZE> Table;
static bool wins(const Table &table, State player)
{
// three in a row?
for (auto &row : table) {
if (row == std::array<State, TABLE_SIZE> {{ player, player, player }}) {
return true;
}
}
// Three in a column?
for (int i = 0; i < TABLE_SIZE; i++) {
if (table[0][i] == player && table[1][i] == player && table[2][i] == player) {
return true;
}
}
// Three in a diagonal?
return table[0][0] == player && table[1][1] == player && table[2][2] == player
|| table[0][2] == player && table[1][1] == player && table[2][0] == player;
}
static void print_table(const Table &table) {
const char chars[] = { ' ', 'X', 'O' };
for (auto &row : table) {
for (auto cell : row) {
std::printf(" %c |", chars[cell]);
}
std::printf("\n-----+-----+-----+\n");
}
std::printf("\n");
}
struct Coord {
int r, c;
};
Coord get_input() {
Coord coord;
std::cin >> coord.r >> coord.c;
return coord;
}
bool place_ai(Table &table) {
for (auto &row : table) {
for (auto &cell : row) {
if (cell != Empty) {
continue;
}
auto tmp_cell = cell;
cell = X;
if (wins(table, X)) {
return true;
} else if (place_ai(table)) {
cell = tmp_cell;
return true;
}
cell = tmp_cell;
}
}
return false;
}
int main()
{
Table table
{{
{{ Empty, Empty, Empty }},
{{ Empty, Empty, Empty }},
{{ Empty, Empty, Empty }},
}};
std::uniform_int_distribution<int> dist(0, 2);
std::random_device rd;
int r = dist(rd), c = dist(rd);
table[r][c] = X;
while (!wins(table, X) && !wins(table, O)) {
print_table(table);
while (true) {
auto player_coord = get_input();
if (table[player_coord.r][player_coord.c] == Empty) {
table[player_coord.r][player_coord.c] = O;
break;
} else {
printf("You can't place an 'O' there. Retry.\n");
}
}
place_ai(table);
}
print_table(table);
std::printf("'%c' wins!\n", wins(table, X) ? 'X' : 'O');
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment