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

Document Python

This document contains a Python implementation of a Tic Tac Toe game. It includes functions to print the board, check for a win, determine if the board is full, get player moves, and manage the game flow. The game alternates between two players, 'X' and 'O', until one wins or the game ends in a draw.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Document Python

This document contains a Python implementation of a Tic Tac Toe game. It includes functions to print the board, check for a win, determine if the board is full, get player moves, and manage the game flow. The game alternates between two players, 'X' and 'O', until one wins or the game ends in a draw.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

def print_board(board):

"""Prints the Tic Tac Toe board."""

for row in board:


print(" | ".join(row))

def check_win(board, player):

"""Checks if the given player has won the game."""


# Check rows

for row in board:


if all(cell == player for cell in row):

return True
# Check columns
for col in range(3):

if all(board[row][col] == player for row in range(3)):


return True

# Check diagonals
if (board[0][0] == player and board[1][1] == player and board[2][2] == player) or \

(board[0][2] == player and board[1][1] == player and board[2][0] == player):


return True

return False

def is_board_full(board):
"""Checks if the board is full."""
for row in board:

for cell in row:


if cell == " ":

return False
return True

def get_player_move(board):
"""Gets the player's move."""

while True:
try:

move = int(input("Enter your move (1-9): ")) - 1


row, col = move // 3, move % 3

if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == " ":
return row, col

else:
print("Invalid move. Please try again.")
except ValueError:

print("Invalid input. Please enter a number.")

def play_tic_tac_toe():
"""Plays the Tic Tac Toe game."""

board = [[" " for _ in range(3)] for _ in range(3)]


current_player = "X"

while True:

print_board(board)
row, col = get_player_move(board)
board[row][col] = current_player

if check_win(board, current_player):

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


break
elif is_board_full(board):

print("It's a draw!")
break

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

if __name__ == "__main__":

play_tic_tac_toe()

You might also like