tictactoe.c (1519B)
1 #include <stdint.h> 2 #include <stdio.h> 3 4 #include "tictactoe.h" 5 6 #define SIDE_BY_SIDE 1 7 8 typedef char (*Get_move_fn)(char*, char); 9 10 static void print_board_offset(char *board, int offx, int offy, _Bool clear) { 11 #ifndef DEBUG 12 if(clear) tb_clear(); 13 print_box_offset(7, 7, offx, offy); 14 for(int i=0; i < 9; i++) { 15 print_bw(((i%3) * 2) + 2 + offx, (i/3*2) + 2 + offy, board[i]); 16 } 17 tb_present(); 18 #endif 19 } 20 static void print_board(char *board) { 21 print_board_offset(board, 0, 0, 1); 22 } 23 24 char play(Get_move_fn get_x_move, Get_move_fn get_o_move) { 25 struct tb_event ev; 26 char board[10] = " "; 27 char winner = 0; 28 char player = 'O'; 29 if(get_o_move == NULL) 30 get_o_move = get_x_move; 31 if(!SIDE_BY_SIDE) 32 print_board(board); 33 for(int turns=0; !winner && turns < 9; turns++) { 34 winner = (turns & 1) ? get_x_move(board, player) : get_o_move(board, player); 35 player = OPPONENT; 36 if(SIDE_BY_SIDE) 37 print_board_offset(board, turns * 10, 0, 0); 38 else 39 print_board(board); 40 tb_peek_event(&ev, 300); 41 } 42 return winner; 43 } 44 45 #ifndef UNIT_TEST 46 int main(void) { 47 struct tb_event ev; 48 tb_init(); 49 char winner = play(get_move_minimax, get_move_minimax); 50 if(winner) 51 print_msg("%c wins.", winner); 52 else 53 print_msg("SCRATCH"); 54 tb_present(); 55 while(tb_poll_event(&ev) == TB_OK) 56 if (ev.type == TB_EVENT_KEY && ev.key == TB_KEY_CTRL_C) 57 tb_shutdown(); 58 } 59 #endif