To write 2 Player Tic Tac Toe Python program you only need basic knowledge of python functions and list.

In this program we have used 4 major functions required to make 2 Player tic tac toe using python:

  • display_board() – To display Tic Tac Toe board (GUI).
  • player_input(player) – To get input position from the player.
  • check_win() – To check winner of the game.
  • play() – More like the main function, which calls above function for gameplay.

2 Player Tic Tac Toe Python Code

To run the program/game execute play().

Note: We have used two global lists.

Board list stores the positions which can be marked on the tic tac toe board (Since the board has total 9 positions).

Empty list stores the empty positions of the board. We are using the empty list as a parameter in play() function to check whether the game is over or not.

Also, we already assigned X symbol to player 1 and O symbol to player 2 using one line Code.

Functions Explained

display_board()

At the very starting of this function, we have used clear_output() function, which we have imported from IPython.display python library. Basically, this function clears the previous output from the terminal or screen, So that fresh and updated Tic Tac board can be displayed.

player_input(player)

Before calling this function in play(). We have initialized player = 0. So obviously player = 1  is the second player we have used.

Basically, in this function, we are taking input from the player (which position they want to mark on the board).

Also after taking input, we are checking if the position is empty or not using an empty list. If the position on the board is not empty then we are again calling the same function recursively, to again get the input from the player for the correct position.

check_win()

In player_input function, we have already stored all possible winning position as a list into

Now using for loop we are looping each list and checking whether any list contains all three elements same symbol. If that happens, we are printing the winner of the game depending on the player Symbol (X or O).

play()

In this function using while loop we are continuously taking the input from the 2 players and displaying the updated board each time until none of the board position is empty or there is some winner.

That’s all for building 2 players tic tac toe game using python 3. If you have any doubts regarding this comment below.

Leave a Reply

Close Menu