From 267d5adae8b426650960ff5b5f818dd6cc2647d8 Mon Sep 17 00:00:00 2001 From: Mihir008 <91221854+Mihir008@users.noreply.github.com> Date: Tue, 8 Oct 2024 23:45:55 +0530 Subject: [PATCH] tic_tac_toe.py made an easy tic-tac-toe game using python and its libraries --- Game-Galore/tic-tac-toe.py | 56 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Game-Galore/tic-tac-toe.py diff --git a/Game-Galore/tic-tac-toe.py b/Game-Galore/tic-tac-toe.py new file mode 100644 index 0000000..cbdf339 --- /dev/null +++ b/Game-Galore/tic-tac-toe.py @@ -0,0 +1,56 @@ +def print_board(board): + for row in board: + print(" | ".join(row)) + print("-" * 9) + +def check_winner(board): + # Check rows, columns, and diagonals + for i in range(3): + if board[i][0] == board[i][1] == board[i][2] != " ": + return board[i][0] + if board[0][i] == board[1][i] == board[2][i] != " ": + return board[0][i] + + if board[0][0] == board[1][1] == board[2][2] != " ": + return board[0][0] + if board[0][2] == board[1][1] == board[2][0] != " ": + return board[0][2] + + return None + +def is_full(board): + return all(cell != " " for row in board for cell in row) + +def tic_tac_toe(): + board = [[" " for _ in range(3)] for _ in range(3)] + current_player = "X" + + while True: + print_board(board) + try: + row = int(input(f"Player {current_player}, enter the row (0, 1, or 2): ")) + col = int(input(f"Player {current_player}, enter the column (0, 1, or 2): ")) + except ValueError: + print("Invalid input. Please enter numbers 0, 1, or 2.") + continue + + 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 + winner = check_winner(board) + + if winner: + print_board(board) + print(f"Player {winner} wins!") + break + if is_full(board): + print_board(board) + print("It's a tie!") + break + + current_player = "O" if current_player == "X" else "X" + +if __name__ == "__main__": + tic_tac_toe() \ No newline at end of file