You are on page 1of 2

Name: Vipin Singh

Roll No: 187

Tic-Tac-Toe Game in Python

def print_board(board):

for row in board:

print(" | ".join(row))

print("-" * 9)

def check_win(board):

for row in board:

if len(set(row)) == 1 and row[0] != ' ':

return True

for col in range(3):

if board[0][col] == board[1][col] == board[2][col] != ' ':

return True

if board[0][0] == board[1][1] == board[2][2] != ' ' or board[0][2] == board[1][1] == board[2][0] != ' ':

return True

return False

def tic_tac_toe():

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

current_symbol = 'X'

moves_count = 0

while True:

print_board(board)
row = int(input(f"Enter the row number (1-3) for {current_symbol}: ")) - 1

col = int(input(f"Enter the column number (1-3) for {current_symbol}: ")) - 1

if 0 <= row <= 2 and 0 <= col <= 2 and board[row][col] == ' ':

board[row][col] = current_symbol

moves_count += 1

if check_win(board):

print_board(board)

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

break

if moves_count == 9:

print_board(board)

print("It's a draw!")

break

current_symbol = 'O' if current_symbol == 'X' else 'X'

else:

print("Invalid move, try again.")

if __name__ == "__main__":

tic_tac_toe()

You might also like