11f. Review: A Tic-Tac-Toe Game#

A review of Chapters 1 to 11 (with “11b. Additions: While Loops”): one project, a tic-tac-toe game that a person plays against the computer. The first part of the page gives the problem and an example of a person playing. The second part shows, one small step at a time, how a programmer can think while they write such a program. Try to write the program yourself first.

Run this page on Colab

Run the setup cell below first. It downloads thinkpython.py, the helper module the chapters use.

from os.path import basename, exists

def download(url):
    filename = basename(url)
    if not exists(filename):
        from urllib.request import urlretrieve

        local, _ = urlretrieve(url, filename)
        print("Downloaded " + str(local))
    return filename

download('https://github.com/AllenDowney/ThinkPython/raw/v3/thinkpython.py');

import thinkpython

The problem#

Question 1 (very hard): write a tic-tac-toe game#

The game. Tic-tac-toe is played on a board of 3 rows and 3 columns: 9 squares. One player is x and the other player is o; x goes first. The players take turns. In each turn, a player puts their letter in an empty square. The first player with 3 of their letters in a line wins: a row, a column or a diagonal. If all 9 squares are full and no one has 3 in a line, the game is a tie.

Write a program in which a person plays tic-tac-toe against the computer. The program must do these things:

  1. Show a menu with two choices, 1. play tic tac toe and 2. quit, and ask for the choice. After each game, show the menu again. Choice 2 ends the program.

  2. At the start of a game, ask the user if they want to be "x" or "o", until they type x or o. The computer gets the other letter. If the computer is x, it moves first.

  3. Show the board as 3 rows. A free square shows its number, 1 to 9; a used square shows its letter:

    ['1', '2', '3']
    ['4', '5', '6']
    ['7', '8', '9']
    
  4. Ask the user for the number of a square. If the number is not 1 to 9, or the square is not free, ask again.

  5. The computer picks a free square at random (the random module: random.randint(1, 9) gives a random whole number from 1 to 9).

  6. Show the board after each round. When a player wins, display x won. or o won.; when the board is full with no winner, display tie game.

An example. Here a user plays two games and then quits. The text after each prompt (choice: 1, choose position: 5, …) is what the user typed. In the first game, the user types y (not a letter of the game), 10 (not a square), and 1 (a square that the computer took): the program asks again each time.

1. play tic tac toe
2. quit
choice: 1

Would you like to be "x" or "o" ? y
I said "x" or "o", choose: x
['1', '2', '3']
['4', '5', '6']
['7', '8', '9']

choose position: 5

['o', '2', '3']
['4', 'x', '6']
['7', '8', '9']

choose position: 10
invalid, choose again: 1
invalid, choose again: 9

['o', 'o', '3']
['4', 'x', '6']
['7', '8', 'x']

choose position: 3

['o', 'o', 'x']
['4', 'x', 'o']
['7', '8', 'x']

choose position: 7

['o', 'o', 'x']
['4', 'x', 'o']
['x', '8', 'x']

x won.

1. play tic tac toe
2. quit
choice: 1

Would you like to be "x" or "o" ? o
['1', '2', 'x']
['4', '5', '6']
['7', '8', '9']

choose position: 2

['1', 'o', 'x']
['4', 'x', '6']
['7', '8', '9']

choose position: 7

['1', 'o', 'x']
['x', 'x', '6']
['o', '8', '9']

choose position: 6

['x', 'o', 'x']
['x', 'x', 'o']
['o', '8', '9']

choose position: 9

['x', 'o', 'x']
['x', 'x', 'o']
['o', 'x', 'o']

tie game

1. play tic tac toe
2. quit
choice: 2

What you need: lists, and lists of lists (Chapter 9); while loops (11b); input and int (11b); if statements (Chapter 5); functions that take arguments and return values (Chapters 3 and 6); break (Chapter 8); // and % (Chapter 2); the random module (11b).

Write the program in the cell below (or in Thonny: “Another Note From Prof. Rosenthal: Using Thonny”). Try it before you read the next part. If you get stuck, read the next part one step at a time, and stop after each step to continue on your own. The next part is also the answer.

Developing the program step by step#

A beginner often tries to write the whole program at once, and then gets many errors at the same time. Programmers do not work like that. They write a small piece, run it, check that it works, and only then write the next piece. This part shows that way of working.

  • The Thoughts … boxes show what a programmer thinks while they write the code: the questions they ask themselves, and why they choose one way and not another.

  • The Stop and check paragraphs are places where you stop: run the code, look at what it displays, and make sure that you understand it before you go on.

  • The Thinking … refactor boxes show a step in which the code does not get new features, but gets clearer.

Run the cells of this part in order: a later cell uses the functions of the cells before it. In Colab, the cells that play a game wait for you to type the replies. On the website, each of these cells shows a game with replies that a pretend user typed.

Step 1: the board#

Thoughts …

What does the program need to remember? The 9 squares. The board has 3 rows of 3 squares, so I can store it as a list of 3 lists: one list for each row. board[1] is the second row, and board[1][2] is the third square in the second row.

What is in a square? At the start, I put the number of each square in it, as a string: '1' to '9'. Then the user sees the numbers to type. When a player takes a square, the number changes to their letter, 'x' or 'o'. Every item is a string, so the board is easy to display.

board = [ ['1','2','3'],
          ['4','5','6'],
          ['7','8','9']  ]
print(board)
print(board[1])
print(board[1][2])
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
['4', '5', '6']
6

Stop and check. board[1] is the second row, ['4', '5', '6'], because indexes start at 0. board[1][2] is '6'.

Thoughts …

print(board) shows the whole board on one line. That is hard to read. I want one row on each line, and an empty line after the board. I will need to show the board many times, so I write a function for it. I call its parameter b (for “board”).

def print_board(b):
    for row in b:
        print(row)
    print()
board = [ ['1','2','3'],
          ['4','5','6'],
          ['7','8','9']  ]
print_board(board)
['1', '2', '3']
['4', '5', '6']
['7', '8', '9']

Stop and check. The board shows 3 rows, and an empty line after them.

Step 2: from the number of a square to a row and a column#

Thoughts …

The user types a number from 1 to 9. To change the board, I need the row and the column of that square, as indexes from 0 to 2. Let me write them down:

Square

1

2

3

4

5

6

7

8

9

Row

0

0

0

1

1

1

2

2

2

Column

0

1

2

0

1

2

0

1

2

If I subtract 1 from the square, I get 0 to 8. Then the row is that number // 3 (every 3 squares, the row goes up by 1), and the column is that number % 3 (the remainder: 0, 1, 2, 0, 1, 2, …). I do not trust myself: I check the formulas with a loop before I use them.

for position in range(1, 10):
    row_number = (position-1) // 3
    col_number = (position-1) % 3
    print(position, row_number, col_number)
1 0 0
2 0 1
3 0 2
4 1 0
5 1 1
6 1 2
7 2 0
8 2 1
9 2 2

Stop and check. Compare each line with the table. Then put an 'x' in square 6:

board = [ ['1','2','3'],
          ['4','5','6'],
          ['7','8','9']  ]
position = 6
row_number = (position-1) // 3
col_number = (position-1) % 3
board[row_number][col_number] = 'x'
print_board(board)
['1', '2', '3']
['4', '5', 'x']
['7', '8', '9']

Step 3: a first game function: the user makes moves#

Thoughts …

Now I start the function for one game. I call it ttt (for “tic-tac-toe”). I do not write the whole game. I start with a small part that I can test: the user types a square 3 times, and the program puts an x there and shows the board. No computer, no winner yet. The for loop with range(3) is only for this test.

def ttt():
    board = [ ['1','2','3'],
              ['4','5','6'],
              ['7','8','9']  ]

    for turn in range(3):
        users_position = int(input('choose position: '))
        row_number = (users_position-1) // 3
        col_number = (users_position-1) % 3
        board[row_number][col_number] = 'x'
        print_board(board)
ttt()
choose position: 5
['1', '2', '3']
['4', 'x', '6']
['7', '8', '9']

choose position: 1
['x', '2', '3']
['4', 'x', '6']
['7', '8', '9']

choose position: 9
['x', '2', '3']
['4', 'x', '6']
['7', '8', 'x']

Stop and check. Run ttt() and type 3 squares. Then try a square that already has an x. What happens? And 10?

Thoughts …

Two problems. If I type a square that is already taken, the program writes over it. If I type 10, the row is 9 // 3, which is 3, and board[3] raises an IndexError. The program must check the number, and ask again while the number is wrong. “While the number is wrong” sounds like a while loop.

How do I know that a square is taken? I could look at the board: a taken square has a letter, not a number. I choose another way: I keep a list of the squares that were chosen, chosen_positions, and append each new square to it. Then users_position in chosen_positions tells me if a square is taken.

Step 4: check the user’s square#

def ttt():
    board = [ ['1','2','3'],
              ['4','5','6'],
              ['7','8','9']  ]
    chosen_positions = []

    for turn in range(3):
        users_position = int(input('choose position: '))
        while users_position < 1 or users_position > 9 or users_position in chosen_positions:
            users_position = int(input('invalid, choose again: '))
        row_number = (users_position-1) // 3
        col_number = (users_position-1) % 3
        board[row_number][col_number] = 'x'
        chosen_positions.append(users_position)
        print_board(board)
ttt()
choose position: 5
['1', '2', '3']
['4', 'x', '6']
['7', '8', '9']

choose position: 10
invalid, choose again: 5
invalid, choose again: 1
['x', '2', '3']
['4', 'x', '6']
['7', '8', '9']

choose position: 9
['x', '2', '3']
['4', 'x', '6']
['7', '8', 'x']

Stop and check. Type 10, and a square that you took before: the program asks again. The condition of the while loop is true when the number is too small, too big, or already chosen.

Step 5: the computer’s move#

Thoughts …

The computer picks a random square: random.randint(1,9). But the square may be taken. That is the same problem as in Step 4: while the square is taken, pick again. Then I put an o in it, and append it to chosen_positions. I add this to ttt after the user’s move.

import random

def ttt():
    board = [ ['1','2','3'],
              ['4','5','6'],
              ['7','8','9']  ]
    chosen_positions = []

    for turn in range(3):
        # the user's move
        users_position = int(input('choose position: '))
        while users_position < 1 or users_position > 9 or users_position in chosen_positions:
            users_position = int(input('invalid, choose again: '))
        row_number = (users_position-1) // 3
        col_number = (users_position-1) % 3
        board[row_number][col_number] = 'x'
        chosen_positions.append(users_position)

        # the computer's move
        computers_position = random.randint(1,9)
        while computers_position in chosen_positions:
            computers_position = random.randint(1,9)
        row_number = (computers_position-1) // 3
        col_number = (computers_position-1) % 3
        board[row_number][col_number] = 'o'
        chosen_positions.append(computers_position)

        print_board(board)
ttt()
choose position: 5
['1', '2', '3']
['4', 'x', 'o']
['7', '8', '9']

choose position: 1
['x', '2', '3']
['4', 'x', 'o']
['7', '8', 'o']

choose position: 3
['x', '2', 'x']
['4', 'x', 'o']
['7', 'o', 'o']

Stop and check. Play a few times. The computer never takes a square that is already taken.

Thinking … refactor

It works, but ttt is getting long, and two parts of it are almost the same: the 4 lines that put a letter on the board (the row, the column, the assignment, and append). The only differences are the letter and the square. If I find a mistake in these lines later, I must correct it in two places, and I can forget one.

This is the time to refactor. To refactor code means to change how the code is written, without changing what it does: the same input gives the same output. The goal is code that is easier to read, to test and to change. Here, I move the 4 lines into a function, assign_position, with parameters for what is different: the board, the letter, the square, and the list of chosen squares.

The function changes the board and the list that it gets. That works because lists are mutable: the parameter b and the variable board refer to the same list, so a change through b is a change of board (“9b. Additions: Iterables, and Changing a List in a Loop”, “Lists are mutable”).

def assign_position(b, letter, position, chosen):
        row_number = (position-1) // 3
        col_number = (position-1) % 3
        b[row_number][col_number] = letter
        chosen.append(position)
def ttt():
    board = [ ['1','2','3'],
              ['4','5','6'],
              ['7','8','9']  ]
    chosen_positions = []

    for turn in range(3):
        # the user's move
        users_position = int(input('choose position: '))
        while users_position < 1 or users_position > 9 or users_position in chosen_positions:
            users_position = int(input('invalid, choose again: '))
        assign_position(board, 'x', users_position, chosen_positions)

        # the computer's move
        computers_position = random.randint(1,9)
        while computers_position in chosen_positions:
            computers_position = random.randint(1,9)
        assign_position(board, 'o', computers_position, chosen_positions)

        print_board(board)
ttt()
choose position: 5
['1', '2', '3']
['4', 'x', 'o']
['7', '8', '9']

choose position: 1
['x', '2', '3']
['4', 'x', 'o']
['7', '8', 'o']

choose position: 3
['x', '2', 'x']
['4', 'x', 'o']
['7', 'o', 'o']

Stop and check. A refactoring must not change what the program does. On the website, this game has the same replies and the same random numbers as the game before it, and the output is the same. Compare them.

Thinking … refactor

ttt is still about two jobs at a time. The comments # the user's move and # the computer's move tell me where the functions are: each comment names a part that can be a function. I move each part into its own function, user_pick_move and computer_pick_move. Each takes the board, the list of chosen squares, and the letter of the player, so that the user can also play o later.

computer_pick_move also returns the square that it chose. This program does not use the value, but a later version could display it (“The computer took square 7”).

def user_pick_move(b, chosen, letter):
    users_position = int(input('choose position: '))
    while users_position < 1 or users_position > 9 or users_position in chosen:
        users_position = int(input('invalid, choose again: '))
    assign_position(b, letter, users_position, chosen)

def computer_pick_move(b, chosen, letter):
    computers_position = random.randint(1,9)
    while computers_position in chosen:
         computers_position = random.randint(1,9)

    assign_position(b, letter, computers_position, chosen)
    return computers_position
def ttt():
    board = [ ['1','2','3'],
              ['4','5','6'],
              ['7','8','9']  ]
    chosen_positions = []

    for turn in range(3):
        user_pick_move(board, chosen_positions, 'x')
        computer_pick_move(board, chosen_positions, 'o')
        print_board(board)
ttt()
choose position: 5
['1', '2', '3']
['4', 'x', 'o']
['7', '8', '9']

choose position: 1
['x', '2', '3']
['4', 'x', 'o']
['7', '8', 'o']

choose position: 3
['x', '2', 'x']
['4', 'x', 'o']
['7', 'o', 'o']

Stop and check. The same game again, with the same output. Read ttt now: it reads almost like a description of a round of the game. That is what refactoring is for.

Step 6: who won?#

Thoughts …

The loop of ttt runs 3 times only because I needed a test. A real game goes on until someone wins or the board is full. So I need a function that looks at the board and tells me the state of the game. What should it return? Four answers are possible: 'x' (x won), 'o' (o won), 'tie', or 'no winner yet'. I call it winner. It takes the board and the list of chosen squares.

This function has many parts: rows, columns, two diagonals, and a tie. I will not write it all at once. I start with the rows only, and I test it with boards that I make by hand. I do not need to play a game to test it.

def winner(b, chosen):
    for letter in ['x','o']:
        # check rows
        for row in b:
            if row == [letter,letter,letter]:
                return letter

    return 'no winner yet'
row_win = [ ['x','x','x'],
            ['4','o','6'],
            ['o','8','9']  ]
column_win = [ ['o','x','3'],
               ['o','x','6'],
               ['7','x','9']  ]
print(winner(row_win, [1, 2, 3, 5, 7]))
print(winner(column_win, [1, 2, 4, 5, 8]))
x
no winner yet

Stop and check. The first board has x in the top row: winner returns 'x'. The second board has x in the middle column, but winner does not check the columns yet, so it returns 'no winner yet'. That is what I expect now.

Thoughts …

A row is easy: it is a list, and I compare it with [letter,letter,letter]. A column is not a list in the board. Column column has the squares b[0][column], b[1][column] and b[2][column]. I go down the rows with a loop. As soon as one square is not the letter, the column is not a win, and I can stop looking at this column: break ends the inner loop (Chapter 8). If the loop gets to the last row (row == len(b) - 1) without a break, every square of the column had the letter.

Why len(b) and not 3? It is the number of rows; 3 would also work. The diagonals work in the same way: one diagonal has the squares b[0][0], b[1][1], b[2][2]; the other has b[0][2], b[1][1], b[2][0], so its column is len(b) - 1 - row.

def winner(b, chosen):
    for letter in ['x','o']:
        # check rows
        for row in b:
            if row == [letter,letter,letter]:
                return letter

        # check columns
        for column in range(0,3):
            for row in range(len(b)):
                if b[row][column] != letter:
                    break
                if row == len(b) - 1:
                    return letter

    return 'no winner yet'
column_win = [ ['o','x','3'],
               ['o','x','6'],
               ['7','x','9']  ]
diagonal_win = [ ['o','x','x'],
                 ['4','o','6'],
                 ['x','8','o']  ]
print(winner(column_win, [1, 2, 4, 5, 8]))
print(winner(diagonal_win, [1, 2, 3, 5, 7, 9]))
x
no winner yet

Stop and check. The column board now gives 'x'. The diagonal board gives 'no winner yet', because the diagonals come next.

def winner(b, chosen):
    for letter in ['x','o']:
        # check rows
        for row in b:
            if row == [letter,letter,letter]:
                return letter

        # check columns
        for column in range(0,3):
            for row in range(len(b)):
                if b[row][column] != letter:
                    break
                if row == len(b) - 1:
                    return letter

        # check upper left to lower right diagonal
        for column in range(len(b[0])):
            if b[column][column] != letter:
                break
            if column == len(b[0]) - 1:
                return letter

        # check upper right to lower left diagonal
        for row in range(len(b)):
            if b[row][len(b) - 1 - row] != letter:
                break
            if row == len(b) - 1:
                return letter

    if len(chosen) == len(b) * len(b[0]):
        return 'tie'

    return 'no winner yet'
diagonal_win = [ ['o','x','x'],
                 ['4','o','6'],
                 ['x','8','o']  ]
other_diagonal = [ ['o','o','x'],
                   ['4','x','6'],
                   ['x','8','9']  ]
full_board = [ ['x','o','x'],
               ['x','o','o'],
               ['o','x','x']  ]
not_finished = [ ['x','2','3'],
                 ['4','o','6'],
                 ['7','8','9']  ]
print(winner(diagonal_win, [1, 2, 3, 5, 7, 9]))
print(winner(other_diagonal, [1, 2, 3, 5, 7]))
print(winner(full_board, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(winner(not_finished, [1, 5]))
o
x
tie
no winner yet

Stop and check. The four boards give 'o', 'x', 'tie' and 'no winner yet'. This is the final winner: it also checks the two diagonals, and it returns 'tie' when all 9 squares are chosen.

Thoughts …

Why does the check for a tie come after the checks for a win? The last move of a game can fill the board and make 3 in a line. Then the game is a win, not a tie. If I checked for a full board first, I would report a tie by mistake. The order of the checks matters.

winner is long, but each part has a comment, and I tested each part on its own. I could refactor it into smaller functions (one for the rows, one for the columns, one for the diagonals). I keep it as one function with comments, because each part is short and the parts are tested.

Step 7: the game loop#

Thoughts …

Now ttt can repeat the rounds while winner returns 'no winner yet'. One detail: after the user’s move, the game can be over (the user won, or filled the last square). Then the computer must not move. So I check winner again before the computer’s move. After the loop, I ask winner one more time, to display the result.

def ttt():
    board = [ ['1','2','3'],
              ['4','5','6'],
              ['7','8','9']  ]
    chosen_positions = []

    print_board(board)

    while winner(board, chosen_positions) == 'no winner yet':
        # get the user's move
        user_pick_move(board, chosen_positions, 'x')

        print()

        if winner(board, chosen_positions) == 'no winner yet':
            # computer picks a move
            computer_pick_move(board, chosen_positions, 'o')

        print_board(board)

    who_won = winner(board, chosen_positions)
    if who_won == 'tie':
        print('tie game')
    else:
        print(who_won, "won.")
    print()
ttt()
['1', '2', '3']
['4', '5', '6']
['7', '8', '9']

choose position: 5

['1', '2', '3']
['4', 'x', 'o']
['7', '8', '9']

choose position: 1

['x', '2', 'o']
['4', 'x', 'o']
['7', '8', '9']

choose position: 9

['x', '2', 'o']
['4', 'x', 'o']
['7', '8', 'x']

x won.

Stop and check. Play until the end several times: win, lose, and try to get a tie.

Step 8: the user chooses x or o#

Thoughts …

The user should choose the letter. I ask with input, and ask again while the reply is not 'x' or 'o' (the same pattern as Step 4: while user_letter not in ['x','o']). The computer gets the other letter. And x goes first: if the computer is x, the computer moves once before the loop. After that, the rounds are the same as before: user, then computer. Now I pass the variables user_letter and computer_letter to the functions, not 'x' and 'o': this is why the functions got a letter parameter in Step 5.

def ttt():
    board = [ ['1','2','3'],
              ['4','5','6'],
              ['7','8','9']  ]

    chosen_positions = []

    # ask user to choose letter
    user_letter = input('Would you like to be "x" or "o" ? ')
    while user_letter not in ['x','o']:
        user_letter = input('I said "x" or "o", choose: ')

    # computer is assigned the other letter
    if user_letter == 'x' :
        computer_letter = 'o'
    else:
        computer_letter = 'x'

    # If the computer is 'x' then the computer picks the first move
    if computer_letter == 'x':
        computer_pick_move(board, chosen_positions, computer_letter)

    print_board(board)

    while winner(board, chosen_positions) == 'no winner yet':
        # get the user's move
        user_pick_move(board, chosen_positions, user_letter)

        print()

        if winner(board, chosen_positions) == 'no winner yet':
            # computer picks a move
            computer_pick_move(board, chosen_positions, computer_letter)

        print_board(board)

    who_won = winner(board, chosen_positions)
    if who_won == 'tie':
        print('tie game')
    else:
        print(who_won, "won.")
    print()
ttt()
Would you like to be "x" or "o" ? o
['1', '2', '3']
['4', '5', '6']
['7', 'x', '9']

choose position: 5

['1', '2', '3']
['4', 'o', '6']
['7', 'x', 'x']

choose position: 7

['1', '2', '3']
['x', 'o', '6']
['o', 'x', 'x']

choose position: 3

['1', '2', 'o']
['x', 'o', '6']
['o', 'x', 'x']

o won.

Stop and check. Play once as x and once as o. As o, the computer’s x is on the board before your first move.

Step 9: the menu#

Thoughts …

The last part is the menu: play or quit. One function shows the menu and returns the choice: displayInitialMenu. (Python programmers usually write names with underscores, as display_initial_menu; this name is in the style of other languages. Both work.)

main repeats the games while the choice is not 2. It is the same pattern as add_numbers in 11b: ask once before the loop, and again at the end of the body.

def displayInitialMenu():
    print('1. play tic tac toe')
    print('2. quit')
    users_choice = int(input('choice: '))
    print()
    return users_choice

def main():
    choice = displayInitialMenu()

    # main loop to choose if the user wants to play or quit
    while(choice != 2):
        ttt()
        choice = displayInitialMenu()
main()
1. play tic tac toe
2. quit
choice: 1

Would you like to be "x" or "o" ? x
['1', '2', '3']
['4', '5', '6']
['7', '8', '9']

choose position: 5

['1', '2', 'o']
['4', 'x', '6']
['7', '8', '9']

choose position: 1

['x', '2', 'o']
['o', 'x', '6']
['7', '8', '9']

choose position: 9

['x', '2', 'o']
['o', 'x', '6']
['7', '8', 'x']

x won.

1. play tic tac toe
2. quit
choice: 2

Stop and check. Choose 1 to play a game, then 2 to quit.

Step 10: the whole program#

Thoughts …

The program is complete. This cell has the whole program, in the order of the file tttGame.py: the import, then each function. The last line, main(), starts the program: a file of functions does nothing until a line calls one of them. To run it in Thonny, copy the cell into a new file, save it as ttt.py, and press F5.

On the website, this cell shows the game of “The problem” above: the same replies and the same random choices give the same output.

import random

def displayInitialMenu():
    print('1. play tic tac toe')
    print('2. quit')
    users_choice = int(input('choice: '))
    print()
    return users_choice

def print_board(b):
    for row in b:
        print(row)
    print()

def computer_pick_move(b, chosen, letter):
    computers_position = random.randint(1,9)
    while computers_position in chosen:
         computers_position = random.randint(1,9)

    assign_position(b, letter, computers_position, chosen)
    return computers_position

def user_pick_move(b, chosen, letter):
    users_position = int(input('choose position: '))
    while users_position < 1 or users_position > 9 or users_position in chosen:
        users_position = int(input('invalid, choose again: '))
    assign_position(b, letter, users_position, chosen)

def assign_position(b, letter, position, chosen):
        row_number = (position-1) // 3
        col_number = (position-1) % 3
        b[row_number][col_number] = letter
        chosen.append(position)

def winner(b, chosen):
    for letter in ['x','o']:
        # check rows
        for row in b:
            if row == [letter,letter,letter]:
                return letter

        # check columns
        for column in range(0,3):
            for row in range(len(b)):
                if b[row][column] != letter:
                    break
                if row == len(b) - 1:
                    return letter

        # check upper left to lower right diagonal
        for column in range(len(b[0])):
            if b[column][column] != letter:
                break
            if column == len(b[0]) - 1:
                return letter

        # check upper right to lower left diagonal
        for row in range(len(b)):
            if b[row][len(b) - 1 - row] != letter:
                break
            if row == len(b) - 1:
                return letter

    if len(chosen) == len(b) * len(b[0]):
        return 'tie'

    return 'no winner yet'

def ttt():
    board = [ ['1','2','3'],
              ['4','5','6'],
              ['7','8','9']  ]

    chosen_positions = []

    # ask user to choose letter
    user_letter = input('Would you like to be "x" or "o" ? ')
    while user_letter not in ['x','o']:
        user_letter = input('I said "x" or "o", choose: ')

    # computer is assigned the other letter
    if user_letter == 'x' :
        computer_letter = 'o'
    else:
        computer_letter = 'x'

    # If the computer is 'x' then the computer picks the first move
    if computer_letter == 'x':
        computer_pick_move(board, chosen_positions, computer_letter)

    print_board(board)

    while winner(board, chosen_positions) == 'no winner yet':
        # get the user's move
        user_pick_move(board, chosen_positions, user_letter)

        print()

        if winner(board, chosen_positions) == 'no winner yet':
            # computer picks a move
            computer_pick_move(board, chosen_positions, computer_letter)

        print_board(board)

    who_won = winner(board, chosen_positions)
    if who_won == 'tie':
        print('tie game')
    else:
        print(who_won, "won.")
    print()

def main():
    choice = displayInitialMenu()

    # main loop to choose if the user wants to play or quit
    while(choice != 2):
        ttt()
        choice = displayInitialMenu()

main()
1. play tic tac toe
2. quit
choice: 1

Would you like to be "x" or "o" ? y
I said "x" or "o", choose: x
['1', '2', '3']
['4', '5', '6']
['7', '8', '9']

choose position: 5

['o', '2', '3']
['4', 'x', '6']
['7', '8', '9']

choose position: 10
invalid, choose again: 1
invalid, choose again: 9

['o', 'o', '3']
['4', 'x', '6']
['7', '8', 'x']

choose position: 3

['o', 'o', 'x']
['4', 'x', 'o']
['7', '8', 'x']

choose position: 7

['o', 'o', 'x']
['4', 'x', 'o']
['x', '8', 'x']

x won.

1. play tic tac toe
2. quit
choice: 1

Would you like to be "x" or "o" ? o
['1', '2', 'x']
['4', '5', '6']
['7', '8', '9']

choose position: 2

['1', 'o', 'x']
['4', 'x', '6']
['7', '8', '9']

choose position: 7

['1', 'o', 'x']
['x', 'x', '6']
['o', '8', '9']

choose position: 6

['x', 'o', 'x']
['x', 'x', 'o']
['o', '8', '9']

choose position: 9

['x', 'o', 'x']
['x', 'x', 'o']
['o', 'x', 'o']

tie game

1. play tic tac toe
2. quit
choice: 2

Thoughts … what next?

The program works, but a programmer always sees more to do. Some ideas, to try on your own:

  • If the user types something that is not a number (five), int raises a ValueError, and the program stops. Check the reply with isdigit (“8b. Additions: String Methods”) before you call int.

  • In the menu, any choice that is not 2 (for example 3) starts a game. Ask again until the choice is 1 or 2.

  • The computer plays at random. Make it smarter: first take a square that wins, then block a square where the user would win.

Credits#

Additions by Prof. Y. Rosenthal, for Think Python: 3rd Edition by Allen B. Downey. Text license: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International