Python Program for Tic Tac Toe
Intermediate · Games and random numbers
Tic tac toe is played on a 3 x 3 grid: two players, X and O, take turns marking a square, and the first to get three in a row, column or diagonal wins. If all nine squares fill up with no winner, the game is a draw. This program plays a whole game from a list of moves and prints the board after every turn.
Program
X takes square 4: | | ---+---+--- | X | ---+---+--- | | O takes square 0: O | | ---+---+--- | X | ---+---+--- | | X takes square 2: O | | X ---+---+--- | X | ---+---+--- | | Square 4 is taken, O must pick again O takes square 6: O | | X ---+---+--- | X | ---+---+--- O | | X takes square 3: O | | X ---+---+--- X | X | ---+---+--- O | | O takes square 8: O | | X ---+---+--- X | X | ---+---+--- O | | O X takes square 5: O | | X ---+---+--- X | X | X ---+---+--- O | | O X wins!
How it works
- The board is a list of 9 strings, one per square, numbered 0 to 8 from the top left, and
" "marks an empty square. WIN_LINESlists the 8 ways to win, 3 rows, 3 columns and 2 diagonals, andhas_won()checks whether one player holds all three squares of any of them.- Each move is checked first: square 4 is picked a second time, so the program refuses it and the same player picks again.
- After every move the board is printed, and the game stops when a player wins or when no empty square is left, which is a draw.
player = "O" if player == "X" else "X"swaps turns, and themoveslist stands in for theinput()line in the comment.
Another way to write it
Two computer players picking at random
X | X | O X | X | O O | O | X X wins!
Both players pick a random empty square until someone wins or the board fills, so the game and its result change on every run. any() checks all eight winning lines in one expression.
Try it yourself
Change the moves to [0, 4, 8, 2, 6, 3, 5, 7, 1] and check that the game ends in a draw.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises