- 14th Dec 2023
- 19:41 pm
This code defines a basic Tic-Tac-Toe game where two players take turns inputting their moves. It checks for a winner after each move and displays the game board until there is a winner or a tie. To play, simply run the script, and it will prompt players to enter their moves by specifying row and column numbers.
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
def check_winner(board, player):
for row in board:
if all(cell == player for cell in row):
return True
for col in range(3):
if all(board[row][col] == player for row in range(3)):
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)):
return True
return False
def play_game():
board = [[" " for _ in range(3)] for _ in range(3)]
players = ['X', 'O']
player_index = 0
game_over = False
while not game_over:
print_board(board)
player = players[player_index]
print(f"Player {player}'s turn.")
row = int(input("Enter the row (0, 1, 2): "))
col = int(input("Enter the column (0, 1, 2): "))
if board[row][col] == " ":
board[row][col] = player
if check_winner(board, player):
print_board(board)
print(f"Player {player} wins!")
game_over = True
elif all(cell != " " for row in board for cell in row):
print_board(board)
print("It's a tie!")
game_over = True
else:
player_index = (player_index + 1) % 2
else:
print("That position is already taken. Try again.")
if __name__ == "__main__":
play_game()