|
| 1 | +from packages import common_module, config |
| 2 | +from time import sleep |
| 3 | + |
| 4 | + |
| 5 | +def modify_board_bot(letter, position, the_matrix): |
| 6 | + """Simultaneously updates the matrix and checks for a win or draw condition. |
| 7 | + This function is only specific to the bot-mode of the game |
| 8 | + """ |
| 9 | + |
| 10 | + the_matrix[position[0]][position[1]] = letter |
| 11 | + |
| 12 | + check_for_win = common_module.the_judge() |
| 13 | + if check_for_win == 'X': |
| 14 | + print('The player has won the game!\n') |
| 15 | + return -1 |
| 16 | + elif check_for_win == 'O': |
| 17 | + # print('The bot has won the game...\n') |
| 18 | + return 1 |
| 19 | + elif common_module.check_for_draw(): |
| 20 | + print('The game is a draw!\n') |
| 21 | + return 0 |
| 22 | + else: |
| 23 | + return None |
| 24 | + |
| 25 | + |
| 26 | +def the_algorithm(the_matrix, is_bot): |
| 27 | + """This function is the brain of the bot""" |
| 28 | + |
| 29 | + if common_module.finder('O'): |
| 30 | + return 1 |
| 31 | + elif common_module.finder('X'): |
| 32 | + return -1 |
| 33 | + elif common_module.check_for_draw(): |
| 34 | + return 0 |
| 35 | + |
| 36 | + if is_bot: |
| 37 | + best_score = -1000 |
| 38 | + for row in range(3): |
| 39 | + for column in range(3): |
| 40 | + if the_matrix[row][column] == '_': |
| 41 | + the_matrix[row][column] = 'O' |
| 42 | + score = the_algorithm(the_matrix, False) |
| 43 | + the_matrix[row][column] = '_' |
| 44 | + |
| 45 | + if score > best_score: |
| 46 | + best_score = score |
| 47 | + return best_score |
| 48 | + else: |
| 49 | + best_score = 1000 |
| 50 | + for row in range(3): |
| 51 | + for column in range(3): |
| 52 | + if the_matrix[row][column] == '_': |
| 53 | + the_matrix[row][column] = 'X' |
| 54 | + score = the_algorithm(the_matrix, True) |
| 55 | + the_matrix[row][column] = '_' |
| 56 | + if score < best_score: |
| 57 | + best_score = score |
| 58 | + return best_score |
| 59 | + |
| 60 | + |
| 61 | +def bot_turn(the_matrix): |
| 62 | + """Decides which move the bot has to do.""" |
| 63 | + |
| 64 | + print('The bot\'s turn: ') |
| 65 | + sleep(0.3) |
| 66 | + print('The bot is thinking..') |
| 67 | + sleep(0.8) |
| 68 | + best_score = -1000 |
| 69 | + best_move = [-1, -1] |
| 70 | + |
| 71 | + for row in range(3): |
| 72 | + for column in range(3): |
| 73 | + if the_matrix[row][column] == '_': |
| 74 | + the_matrix[row][column] = 'O' |
| 75 | + current_score = the_algorithm(the_matrix, False) |
| 76 | + the_matrix[row][column] = '_' |
| 77 | + if current_score > best_score: |
| 78 | + best_score = current_score |
| 79 | + best_move = row, column |
| 80 | + config.empty_cells -= 1 |
| 81 | + value = modify_board_bot('O', best_move, the_matrix=the_matrix) |
| 82 | + common_module.printer(the_matrix) |
| 83 | + return value |
0 commit comments