0% found this document useful (0 votes)
10 views3 pages

Tic Tac Toe Game

This document outlines a simple Tic Tac Toe game implemented in Python. It includes functions to display the board, check for a winner, and determine if the game is a draw. The main game loop allows two players to take turns until one wins or the game ends in a draw.

Uploaded by

bidhangautam127
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views3 pages

Tic Tac Toe Game

This document outlines a simple Tic Tac Toe game implemented in Python. It includes functions to display the board, check for a winner, and determine if the game is a draw. The main game loop allows two players to take turns until one wins or the game ends in a draw.

Uploaded by

bidhangautam127
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

# Tic Tac Toe Game

# Function to display the Tic Tac Toe board

def display_board(board):

print("-----------")

for row in board:

print("|".join(row))

print("-----------")

# Function to check if there's a winner

def check_winner(board, player):

# Check rows, columns, and diagonals

for i in range(3):

if all([cell == player for cell in board[i]]): # Row check

return True

if all([board[j][i] == player for j in range(3)]): # Column check

return True

if all([board[i][i] == player for i in range(3)]) or all([board[i][2 - i] == player for i in range(3)]): #


Diagonals

return True

return False

# Function to check if the board is full (draw)

def is_draw(board):

return all([cell != " " for row in board for cell in row])
# Main game loop

def play_game():

board = [[" " for _ in range(3)] for _ in range(3)] # 3x3 Tic Tac Toe board

current_player = "X" # Player X always starts

while True:

display_board(board)

print(f"Player {current_player}, make your move (row and column from 1 to 3):")

try:

row, col = map(int, input("Enter row and column (e.g., '1 3'): ").split())

if row < 1 or row > 3 or col < 1 or col > 3 or board[row - 1][col - 1] != " ":

print("Invalid move! Try again.")

continue

board[row - 1][col - 1] = current_player

except ValueError:

print("Invalid input! Please enter two numbers separated by a space.")

continue

if check_winner(board, current_player):

display_board(board)

print(f"Player {current_player} wins!")

break

elif is_draw(board):

display_board(board)
print("It's a draw!")

break

# Switch player

current_player = "O" if current_player == "X" else "X"

# Run the game

play_game()

You might also like