CoursesAIMathCodePhysicsAbout and FAQ

TwiddleLab / Code / Build with Python

Tic-Tac-Toe with a Bot

Lesson 12 of 12 · 7 min · Free, no account needed

What you will learn

  • Program design: plan the parts first (show, move, check), then write each as a function.
  • A game loop repeats: move, check for a winner, switch players, until the game ends.
  • free_cells loops over the grid; random.choice picks one of them, so the bot never cheats.
  • Rules in order (win, block, then anything) make a bot much stronger. Looking at every future move makes it unbeatable.

Start the lesson

How the lesson goes

  1. Your final build: a game a friend can play, against a bot you wrote.

    First, play the finished game. You are X.

  2. Plan the game loop.

    Put the stations in the order the game runs them.

  3. Which cells will free_cells(board) return?

    Tap every cell you think it lists. Cells are numbered 0 to 8, row by row.

  4. Run free_cells.

    Two loops visit every cell; empty ones go into the list as r * 3 + c.

  5. Program design and the game loop.

    Program design: decide the parts before writing code. Each part becomes a function with a clear name.

    The game loop runs while nobody has won and the board isn't full: a player move, a check, a bot move.

    Small functions can be tested one by one: free_cells, winner, bot_move.

  6. Classic: write bot_move.

    The bot picks a random free cell and puts an O there. Cell m is row m // 3, column m % 3.

  7. A friend's bot cheats: it sometimes plays on a taken cell.

    Run it. Then make it pick from the free cells.

  8. Challenge: give your bot a brain.

    Drag rules into its three slots. The first rule that finds a move decides. Then test it on 100 games.

  9. Random bot against your bot, 100 games each.

    Run them, then tap the better bot.

  10. Your bot is O, and it's its turn. Where will it play?

    Follow your bot's rules in order.

  11. Win, block, or anything? The bot is O.

    Drop each position into what a win-block bot does.

  12. Pass it to a friend.

    Your friend is X. Your bot, with your rules, is O.

Previous lesson: Grids: Lists of Lists · Part of the course: Build with Python

Lessons are interactive and need JavaScript. Turn it on to play them.

Loading TwiddleLab