{{tag>projects cloud club computing virtualization machines VMs AWS Azure GCP}} [[python_club|About the Club]]\\ ==== Python Club Topics - Exercise: Guess my number game ==== ==== Exercise: Tic Tac Toe ==== - Output: Create the game of Tic Tac Toe for 2 players - What you learn from the example: - Use loops, conditionals, and functions - Get input from user - Use lists ==== Solution ==== def print_board(board): for row in board: print(" | ".join(row)) print("-" * 9) def check_win(board, player): for i in range(3): if all([board[i][j] == player for j in range(3)]) or \ all([board[j][i] == player for j 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 tic_tac_toe(): board = [[" " for _ in range(3)] for _ in range(3)] current_player = "X" moves = 0 while moves < 9: print_board(board) row = int(input(f"Player {current_player}, enter row (0-2): ")) col = int(input(f"Player {current_player}, enter column (0-2): ")) if row < 0 or row > 2 or col < 0 or col > 2 or board[row][col] != " ": print("Invalid move. Try again.") continue board[row][col] = current_player moves += 1 if check_win(board, current_player): print_board(board) print(f"Player {current_player} wins!") break current_player = "O" if current_player == "X" else "X" else: print_board(board) print("It's a tie!") if __name__ == "__main__": tic_tac_toe()