Advertisement
MrThoe

Tic Tac Toe Python

Aug 16th, 2022
881
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. board = [  
  2.     ["-", "-", "-"],
  3.     ["-", "-", "-"],    
  4.     ["-", "-", "-"],
  5. ]
  6.  
  7. player = "X"
  8.  
  9. def check_win():
  10.     for i in range(3):
  11.         if board[i][0]==board[i][1]==board[i][2] and board[i][0] != "-":
  12.             return True
  13.         if board[0][i]==board[1][i]==board[2][i] and board[0][i] != "-":
  14.             return True
  15.     if board[0][0]==board[1][1]==board[2][2] or board[2][0]==board[1][1]==board[0][2]:
  16.         if board[1][1]!="-":
  17.             return True
  18.     return False
  19.  
  20. def check_tie():
  21.     for i in range(3):
  22.         for j in range(3):
  23.             if board[i][j] == "-":
  24.                 return False
  25.     return True
  26.  
  27. def place_player(player, row, col):
  28.     board[row][col] = player
  29.  
  30. def is_valid(row, col):
  31.     if row < 0 or row > 2 or col < 0 or col > 2:
  32.         print("Invalid dimensions for 'row' or 'column'.")
  33.         return False
  34.     if board[row][col] != '-':
  35.         print("That space is already taken.")
  36.         return False
  37.     return True
  38.    
  39. def get_choice(player):
  40.     print("It's " + player + "'s turn...")
  41.     r = int(input('Enter a valid row: '))
  42.     c = int(input('Enter a valid column: '))
  43.     if is_valid(r,c):
  44.         place_player(player, r, c)
  45.     else:
  46.         get_choice(player)
  47.        
  48. def print_board():
  49.     print("=========================")
  50.     print("\t0\t1\t2")
  51.     print("1\t" + board[0][0] + "\t" + board[0][1]  + "\t" + board[0][2])
  52.     print("1\t" + board[1][0] + "\t" + board[1][1]  + "\t" + board[1][2])
  53.     print("1\t" + board[2][0] + "\t" + board[2][1]  + "\t" + board[2][2])
  54.     print("=========================")
  55.  
  56.  
  57. gameExit = False
  58. while not gameExit:
  59.     get_choice(player)
  60.     print_board()
  61.     gameExit = check_win()
  62.     if player == "X" and not gameExit:
  63.         player = "O"
  64.     elif not gameExit:
  65.         player = "X"
  66. print(player + " wins!")
  67.  
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement