└── Tic tac Toe /Tic tac Toe: -------------------------------------------------------------------------------- 1 | def initialize_board(): 2 | return [[' ' for _ in range(3)] for _ in range(3)] 3 | 4 | def print_board(board): 5 | for row in board: 6 | print('|'.join(row)) 7 | print('-' * 5) 8 | 9 | def check_win(board, player): 10 | # Check rows 11 | for row in board: 12 | if all([cell == player for cell in row]): 13 | return True 14 | 15 | # Check columns 16 | for col in range(3): 17 | if all([board[row][col] == player for row in range(3)]): 18 | return True 19 | 20 | # Check diagonals 21 | if all([board[i][i] == player for i in range(3)]) or all([board[i][2 - i] == player for i in range(3)]): 22 | return True 23 | 24 | return False 25 | 26 | def check_draw(board): 27 | for row in board: 28 | if ' ' in row: 29 | return False 30 | return True 31 | 32 | def player_move(board, player): 33 | while True: 34 | try: 35 | move = input(f"Player {player}, enter your move (row and column): ") 36 | row, col = map(int, move.split()) 37 | if board[row][col] == ' ': 38 | board[row][col] = player 39 | break 40 | else: 41 | print("This cell is already taken. Try again.") 42 | except (ValueError, IndexError): 43 | print("Invalid input. Please enter row and column as two numbers between 0 and 2, separated by a space.") 44 | 45 | def tic_tac_toe(): 46 | board = initialize_board() 47 | current_player = 'X' 48 | 49 | while True: 50 | print_board(board) 51 | player_move(board, current_player) 52 | 53 | if check_win(board, current_player): 54 | print_board(board) 55 | print(f"Player {current_player} wins!") 56 | break 57 | 58 | if check_draw(board): 59 | print_board(board) 60 | print("The game is a draw!") 61 | break 62 | 63 | current_player = 'O' if current_player == 'X' else 'X' 64 | 65 | if __name__ == "__main__": 66 | tic_tac_toe() 67 | --------------------------------------------------------------------------------