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. BUILDING A
    TIC TAC TOE
    BOT IN
    PYTHON
    Kiran Gangadharan

    View full-size slide

  2. WHAT THIS TALK IS NOT
    ABOUT

    View full-size slide

  3. BUILDING A SIMPLE,
    EFFECTIVE AI FOR
    TIC TAC TOE
    (that almost always beats you)

    View full-size slide

  4. 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.

    View full-size slide

  5. WHY USE MINIMAX?

    View full-size slide

  6. https://xkcd.com/832/

    View full-size slide

  7. HOW DOES IT WORK?

    View full-size slide

  8. Image from http://neverstopbuilding.com/minimax

    View full-size slide

  9. ➤ 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)

    View full-size slide

  10. LET’S LOOK AT SOME CODE!

    View full-size slide

  11. 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)

    View full-size slide

  12. 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

    View full-size slide

  13. ALPHA-BETA PRUNING

    View full-size slide

  14. http://yuliana.lecturer.pens.ac.id/Kecerdasan%20Buatan/ppt/Game%20Playing/contoh%20prunning/

    View full-size slide

  15. RESOURCES
    https://youtu.be/STjW3eH0Cik

    View full-size slide

  16. https://github.com/kirang89/tictac

    View full-size slide

  17. kirang89 @kirang89
    http://kirang.in

    View full-size slide