Update app.py
Browse files
app.py
CHANGED
|
@@ -1,36 +1,46 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
if __name__ == "__main__":
|
| 36 |
-
|
|
|
|
| 1 |
+
def print_board(board):
|
| 2 |
+
for row in board:
|
| 3 |
+
print(" | ".join(row))
|
| 4 |
+
print("-" * 9)
|
| 5 |
+
|
| 6 |
+
def check_winner(board, player):
|
| 7 |
+
# Check rows, columns, and diagonals
|
| 8 |
+
for i in range(3):
|
| 9 |
+
if all(cell == player for cell in board[i]) or all(board[j][i] == player for j in range(3)):
|
| 10 |
+
return True
|
| 11 |
+
if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
|
| 12 |
+
return True
|
| 13 |
+
return False
|
| 14 |
+
|
| 15 |
+
def check_tie(board):
|
| 16 |
+
return all(cell != " " for row in board for cell in row)
|
| 17 |
+
|
| 18 |
+
def tic_tac_toe():
|
| 19 |
+
board = [[" " for _ in range(3)] for _ in range(3)]
|
| 20 |
+
current_player = "X"
|
| 21 |
+
|
| 22 |
+
print("Welcome to Tic-Tac-Toe!")
|
| 23 |
+
|
| 24 |
+
while True:
|
| 25 |
+
print_board(board)
|
| 26 |
+
|
| 27 |
+
row = int(input(f"Player {current_player}, enter row (0, 1, or 2): "))
|
| 28 |
+
col = int(input(f"Player {current_player}, enter column (0, 1, or 2): "))
|
| 29 |
+
|
| 30 |
+
if board[row][col] == " ":
|
| 31 |
+
board[row][col] = current_player
|
| 32 |
+
if check_winner(board, current_player):
|
| 33 |
+
print_board(board)
|
| 34 |
+
print(f"Player {current_player} wins! Congratulations!")
|
| 35 |
+
break
|
| 36 |
+
elif check_tie(board):
|
| 37 |
+
print_board(board)
|
| 38 |
+
print("It's a tie! Well played.")
|
| 39 |
+
break
|
| 40 |
+
else:
|
| 41 |
+
current_player = "O" if current_player == "X" else "X"
|
| 42 |
+
else:
|
| 43 |
+
print("Cell already occupied. Try again.")
|
| 44 |
|
| 45 |
if __name__ == "__main__":
|
| 46 |
+
tic_tac_toe()
|