/* ex: set ts=2 et: */ /* A crappy game of Tic-Tac-Toe! Enjoy! */ #include #include /** * +------+------+------+ * | 0x100| 0x80 | 0x40 | * +------+------+------+ * | 0x20 | 0x10 | 0x08 | * +------+------+------+ * | 0x04 | 0x02 | 0x01 | * +------+------+------+ */ /* all winning bit sets */ static const unsigned Win[] = { 0x0184, 0x0038, 0x0007, 0x0124, 0x0092, 0x0049, 0x0111, 0x0054 }; static unsigned Player[2], Turn; static void print_board(void) { unsigned i, n; for (i = 0, n = 1 << 8; n; i++, n >>= 1) { if (0 == i % 3) printf("\n+---+---+---+\n|"); printf(" %c |", ((Player[0] & n) ? 'X' : (Player[1] & n) ? 'O' : ' ')); } printf("\n+---+---+---+"); } static unsigned check_win(unsigned state) { unsigned i = sizeof Win / sizeof Win[0] + 1, won = 0; while (i--) won = won | ((Win[i] & state) == Win[i]); return won; } static unsigned do_turn(void) { int cell = 0; print_board(); do { printf("\nPlayer %d: Which cell (1-9): ", (Turn & 1) + 1); fflush(stdout); cell = getc(stdin); if ('\n' != cell) getc(stdin); /* toss newline */ cell -= '0'; /* NOTE: assume ASCII */ cell--; cell = 8 - cell; } while (cell < 0 || cell > 8 || (Player[0] & (1 << cell)) || (Player[1] & (1 << cell))); Player[Turn & 1] |= 1 << cell; return Turn++ & 1; } main() { while (!check_win(Player[do_turn()])); print_board(); printf("\nPlayer %d is the winner!\n", !(Turn & 1)+1); return 0; }