How to Program 2 Player Tic Tac Toe Python

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 a main function, which call above function for gameplay.

2 Player Tic Tac Toe Python Code

To run the program/game execute play().

Note: We have use used two global list.

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 empty list as 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 inititalized player = 0. So obviously player = 1  is the second player we have used.

Basically in this function we are taking input from 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 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 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 element 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 non of the board position are 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.

Also check:

C++ Programs.

C Programs.

admin

I am a B.tech IT Student from India. Technology and programming is the most enthusiastic thing for me in this world. I like learning new techniques and use them for real-world application because I feel tech is future. Let's learn and grow TOGETHER.