Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tic Tac Toe
- # By Mike Kerry, December 2020 - Email: acclivity2@gmail.com
- # For Python Programmers (Beginners) Facebook Group
- def play_turn(letter): # letter is X or O
- global board
- # Define the 8 possible winning combinations
- 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)]
- # Keep looping until player selects a valid empty cell, 1 to 9
- while True:
- print(letter + " your turn: ")
- user = input("Select a square 1 to 9: ")
- if user in board:
- x = board.index(user)
- break
- print("Invalid cell, or cell already occupied, try again")
- board[x] = letter
- # Print the updated board
- for row in range(3):
- print(board[row * 3], "|", board[row * 3 + 1], "|", board[row * 3 + 2])
- # Look to see if this last player has won, by getting three in a row
- for tup in wins:
- work = [" "] + board
- if work[tup[0]] == letter and work[tup[1]] == letter and work[tup[2]] == letter:
- return letter # Return a "WIN" indication
- return None # Return "No Winner" indication
- alt = False # this is a 1/0 flip flop which determimes who goes first, X or O
- while True:
- # Start a new round. Create 9 empty (numbered) cells
- # Cells are numbered 1 (top left) to 9 (bottom right)
- board = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
- for row in range(3): # Print the empty board
- print(board[row * 3], "|", board[row * 3 + 1], "|", board[row * 3 + 2])
- alt = not alt # Alternate between O and X going first
- # Loop around, allowing X and O to play in turns
- for ch in "XOXOXOXOXO"[alt:]:
- if play_turn(ch) == ch:
- print(ch, "wins!\n=================")
- break
- for cell in board:
- if cell.isdigit():
- break
- else:
- # All cells are occupied, but no one won
- print("It's a draw!\n=================")
- break
- if input("Play again? (Y/N): ").upper() != "Y":
- break
Add Comment
Please, Sign In to add comment