Advertisement
ZEdKasat

TicTacToe.py

Jul 19th, 2021
1,641
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. def switch_turn(turn):
  3.     if turn == "X":
  4.         return "O"
  5.     else:
  6.         return "X"
  7.  
  8. def printboard(board):
  9.     print()
  10.     print(board[1] + " | " + board[2] + " | " +board[3])
  11.     print("- + - + -")
  12.     print(board[4] + " | " + board[5] + " | " +board[6])
  13.     print("- + - + -")
  14.     print(board[7] + " | " + board[8] + " | " +board[9])
  15.     print()
  16.  
  17. def get_input(turn, board):
  18.     while True:
  19.         print(turn + "'s turn")
  20.         position = input("Enter the position you want to play: ")
  21.  
  22.         if not position.isdigit(): # what if user enters something that is not a number?
  23.             print("Please enter a number. ")
  24.         elif not 1 <= int(position) <= 9:
  25.             print("Enter a number in the valid range.")
  26.         elif not board[int(position)].isdigit():
  27.             print("Position already taken, please try another position.")
  28.         else:
  29.            
  30.             return int(position)
  31.  
  32. def checkwin(board):
  33.     if board[1] == board[2] == board[3]:
  34.         return True, board[3]
  35.     elif board[4] == board[5] == board[6]:
  36.         return True, board[6]
  37.     elif board[7] == board[8] == board[9]:
  38.         return True, board[9]
  39.     elif board[1] == board[4] == board[7]:
  40.         return True, board[7]
  41.     elif board[2] == board[5] == board[8]:
  42.         return True, board[5]
  43.     elif board[3] == board[6] == board[9]:
  44.         return True, board[9]
  45.     elif board[1] == board[5] == board[9]:
  46.         return True, board[9]
  47.     elif board[3] == board[5] == board[7]:
  48.         return True, board[7]
  49.     else:
  50.         return False, None
  51.        
  52.    
  53.  
  54. def main():
  55.     turn = "X"
  56.     board = ["0", "1","2", "3","4", "5","6", "7","8", "9"]
  57.     printboard(board)
  58.     game_over = False
  59.     count = 0
  60.     while not game_over and count < 9:
  61.         position = get_input(turn, board)
  62.         count += 1
  63.         board[position] = turn
  64.         printboard(board)
  65.         game_over, winner = checkwin(board)
  66.         turn = switch_turn(turn)
  67.    
  68.     print(winner, "won the game")
  69.  
  70. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement