Wed 17 December 2025

My First Tic-Tac-Toe Program

Posted by Al Sweigart in misc   

As an elaborate joke, I created a program to play tic-tac-toe (also called “noughts and crosses” or “Xs and Os”) against the computer made up of nothing but if statements. Every possible move the computer could make in response to the player is hard coded into the source code of the program. While a normal tic-tac-toe Python program can be under 100 lines of code, this program is over 5,100 lines long. I gave it the humorous name My First Tic-Tac-Toe Program because this is exactly how someone with limited experience (but a lot of spare time) would make it. Download the source code.

The output draws a tic-tac-toe board using text characters, like this:

X| |
-+-+-
 |X|
-+-+-
O| |O

Enter the number of your move:
  789
  456
  123

The source code is about 5,100 lines of if statements and print() calls, like this:

if move == '1':
    print('O moves on the top-left space.')
    print('O| | \n-+-+-\n | | \n-+-+-\nX| | \n')
    print('Enter the number of your move:')
    print('  789\n  456\n  123')
    move = input()

    if move == '2':
        print('O moves on the bottom-right space.')
        print('O| | \n-+-+-\n | | \n-+-+-\nX|X|O\n')
        print('Enter the number of your move:')
        print('  789\n  456\n  123')
        move = input()

        if move == '4':
            print('O moves on the center space.')
            print('O| | \n-+-+-\nX|O| \n-+-+-\nX|X|O\n')
            print('The computer wins!')
            sys.exit()
        if move == '5':
            print('O moves on the top-center space.')
            print('O|O| \n-+-+-\n |X| \n-+-+-\nX|X|O\n')
            print('Enter the number of your move:')
            print('  789\n  456\n  123')
            move = input()

Of course, I didn't write this code myself. I created generate_code_for_tictactoe.py to produce this source code. However, as a joke-within-a-joke, I created a fake program that generates tictactoe.py as well.

I'm a fan of tic-tac-Toe as a programming exercise. It's simple enough for beginners to make, but large enough that you can't just hard-code everything. I used this concept in a zine of a Choose Your Own Adventure tic-tac-toe game where you play against the zine, which has hundreds of possible tic-tac-toe boards. You can read the PDF online or download printable versions to create your own physical zine. My blog post, Procedurally Generating a Tic-Tac-Toe Zine with Python goes into more detail.


Check out other books by Al Sweigart, free online or available for purchase:

...and other books as well! Or register for the online video course. You can also donate to or support the author directly.