The following Python program is a 2 player tic-tac-toe game. It is entirely a console game and can be played by 2 players with symbols O and X.

#board and empty positions 
board=['0','1','2','3','4','5','6','7','8']
empty = [0,1,2,3,4,5,6,7,8]

#function to display board
def display_board():
  print('  |   |   ')
  print(board[0]+' | '+board[1]+' | '+board[2])
  print('  |   |   ')
  print('---------')
  print('  |   |   ')
  print(board[3]+' | '+board[4]+' | '+board[5])
  print('  |   |   ')
  print('---------') 
  print('  |   |   ')
  print(board[6]+' | '+board[7]+' | '+board[8])
  print('  |   |   ')

#function to take inputs from player-I and II
def player_input(player):
  player_symbol = ['X','O']
  correct_input = True

  position = int(input('player {playerNo} chance! Choose field to fill {symbol} '.format(playerNo = player +1, symbol = player_symbol[player])))

  if board[position] == 'X' or board[position] == 'O':
    correct_input = False
  
  if not correct_input:
    print("Position already equipped")
    player_input(player)
  else:
    empty.remove(position)
    board[position] = player_symbol[player] 
    return 1

#function checks if any player won
def check_win():
  #define players symbols and winning positions
  player_symbol = ['X','O']
  winning_positions =[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]

  #check all winning positions for matching placements
  for check in winning_positions:
    first_symbol = board[check[0]]
    if first_symbol != ' ':
      won = True
      for point in check:
        if board[point] !=  first_symbol:
          won = False
          break
      if won:
        if first_symbol == player_symbol[0]:
          print('player 1 won')
        else:
          print('player 2 won')
        break
    else:
      won = False

  if won:
    return 0
  else:
    return 1

#function to invoke functions to play
def play():
  player = 0
  while empty and check_win():    
    display_board()
    player_input(player)
    player = int(not player)
  if not empty:
    print("NO WINNER!")

#driver code
if __name__ == '__main__':
  play()

The program has the following two global lists:

board=['0','1','2','3','4','5','6','7','8'] 
empty = [0,1,2,3,4,5,6,7,8]

The board list stores the positions which can be marked on the tic tac toe board (the board has a total of 9 positions).

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

Functions Explained

The program has the following 4 functions:

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

player_input(player)

We use this function to take input from the players. The players enter the empty positions to mark them with their symbol.

If in case the position is not empty (not in the empty list), we recursively call the same function, to again get the correct input from the player.

if board[position] == 'X' or board[position] == 'O': 
   correct_input = False 
if not correct_input: 
   print("Position already equipped") 
   player_input(player)

check_win()

In this function, we define the winning positions as follows:

winning_positions =[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]

To win the game, a player has to mark all entry of at least a single sub list.

If that happens, we print the winner of the game depending on the symbol of the player.

play()

In this function, we use a while loop to continuously run the game (get inputs from players) until we get a winner or all the positions are filled.

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

This Post Has 5 Comments

  1. leeladhar banothe

    plz advice me to further python data science.

    1. Adarsh Kumar

      Not an expert, but I think you should start initially from free youtube videos. See Whether it interest you? If it does then I recommend you to learn from good courses online or offline as you wish.

    1. Adarsh Kumar

      Change your last few lines of codes with the following:

      player = 0
      while space() and not (check_win()):
          print_board()
          player_input(player)
          player = int(not player)
      else:
          if space() is False:
              print("It's a Tie!!")
      
  2. vietnam

    if __name__ == ‘__main__’:
    what is this code mean?

Leave a Reply to Adarsh Kumar Cancel reply