tictactoe

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

commit 6129d4dee09b1b24b41630d2068b56082010368c
parent ade02b2af7cc2149d34666c560ef839f9b804b09
Author: Wilson Gheen <wilson@wilsonrgheen.com>
Date:   Fri, 23 Dec 2022 13:09:23 -0600

Make minimax AI choose a random move if it's not a sure win or loss

Diffstat:
Mtictactoe.h | 21+++++++++++++--------
Munit_test.c | 2+-
2 files changed, 14 insertions(+), 9 deletions(-)

diff --git a/tictactoe.h b/tictactoe.h @@ -225,15 +225,20 @@ static struct move minimax_best_move(char *board, char player, int *legal_moves, } } /* No wins -- try for a draw */ - while(lm_cnt-->0) { - if(moves[lm_cnt].winner == 0) { - struct move ret = moves[lm_cnt]; - free(moves); - ret.move_ind = legal_moves[lm_cnt]; - return ret; - } + int scratch_moves[9]; + int sm_cnt = 0; + while(lm_cnt-->0) + if(moves[lm_cnt].winner == 0) + scratch_moves[sm_cnt++] = legal_moves[lm_cnt]; + struct move ret; + if(sm_cnt) { + ret.winner = 0; + ret.move_ind = scratch_moves[get_rand(sm_cnt)]; + } + else { + ret.winner = OPPONENT; + ret.move_ind = legal_moves[0]; //whatever } - struct move ret = moves[0]; //whatever free(moves); return ret; } diff --git a/unit_test.c b/unit_test.c @@ -68,7 +68,7 @@ int main() { printf("Result was: %s\n", actual_result); failures += print_test_results(i, !strcmp(actual_result, b->expected_result)); } - failures += test_ai_against(get_move_minimax, 50, ++i, "itself", "a draw for all executions", false); + failures += test_ai_against(get_move_minimax, 500, ++i, "itself", "a draw for all executions", false); failures += test_ai_against(get_random_move, 500, ++i, "a random move generator", "the AI wins or draws for all executions", true); failures += test_ai_against(get_winning_move_else_random, 500, ++i, "a slightly dumber AI", "the AI wins or draws for all executions", true); failures += test_ai_against(get_winning_move_else_block_else_random, 500, ++i, "a slightly smarter, dumber AI", "the AI wins or draws for all executions", true);