Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Building a Tic Tac Toe AI in Python

Kiran
March 25, 2016

Building a Tic Tac Toe AI in Python

Kiran

March 25, 2016
Tweet

More Decks by Kiran

Other Decks in Technology

Transcript

  1. MINIMAX ➤ A decision rule used in game theory to

    minimise the worst case scenario (loss). ➤ It’s about minimising one’s maximum loss or maximising one’s minimum gain (hence the term Minimax) ➤ Originally designed for two player games where each player would alternate turns.
  2. ➤ If leaf node, return score from AI’s perspective ➤

    Otherwise, get all possible moves in board ➤ For each move ➤ Add minimax of that move to a scores list ➤ If it’s the AI’s turn, return max(scores) ➤ If it’s the player’s turn, return min(scores)
  3. MINIMAX def minimax(self, board, player): empty_cells = self.empty_cells(board) score =

    self.get_score(board) if score == 0: # Check for draw if len(empty_cells) == 0: return score else: return score scores = [] for cell in empty_cells: b = list(board) b[cell] = player scores.append(self.minimax(b, self.opponent(player))) if player == self.player: return max(scores) else: return min(scores)
  4. HEURISTIC FUNCTION def get_score(self, board): opp = self.opponent(self.player) win =

    self.has_won(board, self.player) has_two_in_line = self.has_two_in_line(board, self.player) opp_win = self.has_won(board, opp) opp_has_two_in_line = self.has_two_in_line(board, opp) score = 0 if win: score += 100 if has_two_in_line: score += 10 if opp_win: score -= 100 if opp_has_two_in_line: score -= 10 return score