From 9ca7ea035a95cb4c11cb9ee9dd103dc27e0e65cb Mon Sep 17 00:00:00 2001 From: AlberLC Date: Thu, 17 Nov 2022 02:26:37 +0100 Subject: [PATCH] Improve connect 4 ai --- flanabot/bots/connect_4_bot.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/flanabot/bots/connect_4_bot.py b/flanabot/bots/connect_4_bot.py index 1449f2a..64e399d 100644 --- a/flanabot/bots/connect_4_bot.py +++ b/flanabot/bots/connect_4_bot.py @@ -55,13 +55,6 @@ class Connect4Bot(MultiBot, ABC): if player_1.number in self._check_winners(i, j, board): return self.insert_piece(j, player_2.number, message) - # check if after the ai plays, it will have 2 positions to win - for i, j in available_positions_: - board_copy = copy.deepcopy(board) - board_copy[i][j] = player_2.number - if self._winning_positions(board_copy)[player_2.number] >= 2: - return self.insert_piece(j, player_2.number, message) - # check if after the human plays, he will have 2 positions to win for i, j in available_positions_: board_copy = copy.deepcopy(board) @@ -75,7 +68,6 @@ class Connect4Bot(MultiBot, ABC): for i, j in available_positions_: if i < 1: continue - board_copy = copy.deepcopy(board) board_copy[i][j] = player_2.number winners = self._check_winners(i - 1, j, board_copy) @@ -84,6 +76,15 @@ class Connect4Bot(MultiBot, ABC): elif player_2.number in winners: ai_win_positions.append((i, j)) + # check if after the ai plays, it will have 2 positions to win + for i, j in available_positions_: + if (i, j) in human_win_positions: + continue + board_copy = copy.deepcopy(board) + board_copy[i][j] = player_2.number + if self._winning_positions(board_copy)[player_2.number] >= 2: + return self.insert_piece(j, player_2.number, message) + good_positions = [pos for pos in available_positions_ if pos not in human_win_positions and pos not in ai_win_positions] if good_positions: j = random.choice(self._best_plays(good_positions, player_2.number, board))[1]