acclivity

pyTicTacToe

Jan 13th, 2021 (edited)
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. # Tic Tac Toe
  2. # By Mike Kerry, December 2020 - Email: acclivity2@gmail.com
  3. # For Python Programmers (Beginners) Facebook Group
  4.  
  5. def play_turn(letter):          # letter is X or O
  6.     global board
  7.     # Define the 8 possible winning combinations
  8.     wins = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 4, 7), (2, 5, 8), (3, 6, 9), (1, 5, 9), (3, 5, 7)]
  9.  
  10.     # Keep looping until player selects a valid empty cell, 1 to 9
  11.     while True:
  12.         print(letter + " your turn: ")
  13.         user = input("Select a square 1 to 9: ")
  14.         if user in board:
  15.             x = board.index(user)
  16.             break
  17.         print("Invalid cell, or cell already occupied, try again")
  18.  
  19.     board[x] = letter
  20.  
  21.     # Print the updated board
  22.     for row in range(3):
  23.         print(board[row * 3], "|", board[row * 3 + 1], "|", board[row * 3 + 2])
  24.  
  25.     # Look to see if this last player has won, by getting three in a row
  26.     for tup in wins:
  27.         work = [" "] + board
  28.         if work[tup[0]] == letter and work[tup[1]] == letter and work[tup[2]] == letter:
  29.             return letter       # Return a "WIN" indication
  30.     return None                 # Return "No Winner" indication
  31.  
  32.  
  33. alt = False     # this is a 1/0 flip flop which determimes who goes first, X or O
  34. while True:
  35.     # Start a new round.  Create 9 empty (numbered) cells
  36.     # Cells are numbered 1 (top left) to 9 (bottom right)
  37.     board = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
  38.     for row in range(3):    # Print the empty board
  39.         print(board[row * 3], "|", board[row * 3 + 1], "|", board[row * 3 + 2])
  40.     alt = not alt       # Alternate between O and X going first
  41.  
  42.     # Loop around, allowing X and O to play in turns
  43.     for ch in "XOXOXOXOXO"[alt:]:
  44.         if play_turn(ch) == ch:
  45.             print(ch, "wins!\n=================")
  46.             break
  47.         for cell in board:
  48.             if cell.isdigit():
  49.                 break
  50.         else:
  51.             # All cells are occupied, but no one won
  52.             print("It's a draw!\n=================")
  53.             break
  54.  
  55.     if input("Play again? (Y/N): ").upper() != "Y":
  56.         break
  57.  
Add Comment
Please, Sign In to add comment