Skip to content

Instantly share code, notes, and snippets.

@keyurshah
Created January 1, 2024 21:25
Show Gist options
  • Save keyurshah/8d99f9b4a7a01ed55c8892a68353ca8a to your computer and use it in GitHub Desktop.
Save keyurshah/8d99f9b4a7a01ed55c8892a68353ca8a to your computer and use it in GitHub Desktop.
Tic tac toe
# Function to print the current state of the board
def print_board(board):
# Iterate over the board in steps of 3 to print each row
for i in range(1, 10, 3):
# Print the current row of the board with corresponding values
print(f"{i}: {board[i]} {i+1}: {board[i+1]} {i+2}: {board[i+2]}\n")
# Function to check if there's a winner
def check_win(board):
# Define all possible winning combinations
winning_combinations = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 4, 7), (2, 5, 8), (3, 6, 9), (1, 5, 9), (3, 5, 7)]
# Iterate through each winning combination
for combo in winning_combinations:
# Check if the current combination is a winning one
if board[combo[0]] == board[combo[1]] == board[combo[2]] and board[combo[0]] != ' ':
# Return True if a winning combination is found
return True
# Return False if no winning combination is present
return False
# Main function to play Tic Tac Toe
def tic_tac_toe():
# Initialize the board with numbers 1 to 9 as keys and blank spaces as values
board = {i: ' ' for i in range(1, 10)}
# Print the initial empty board
print_board(board)
current_player = 'x' # Start with player 'x'
# Loop for each turn in the game (maximum of 9 turns)
for _ in range(9):
try:
# Prompt the current player to pick a number between 1 and 9
move = int(input(f"Player {current_player}, pick a number between 1 and 9: "))
# Check if the chosen number is outside the valid range
if move < 1 or move > 9:
# Inform the player about the invalid number and continue the loop
print("Invalid number. Please choose a number between 1 and 9.")
continue
# Check if the chosen spot is available
if board[move] == ' ':
# Assign the current player's symbol ('x' or 'o') to the chosen spot
board[move] = current_player
# Print the updated board
print_board(board)
# Check for a winning condition after the move
if check_win(board):
# Announce the winner and exit the game
print(f"Player {current_player} wins!")
return
# Switch to the other player for the next turn
current_player = 'o' if current_player == 'x' else 'x'
else:
# If the chosen spot is already taken, ask for a different number
print("That spot is already taken. Please choose another.")
except ValueError:
# Handle the case where the input is not a number
print("Please enter a valid number.")
# If the loop completes without a winner, declare a tie
print("It's a tie!")
# Start the game by calling the main function
tic_tac_toe()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment