-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tic-Tac-Toe.py
71 lines (56 loc) · 1.87 KB
/
Tic-Tac-Toe.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_win(board, player):
# Check rows, columns, and diagonals
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 is_board_full(board):
for row in board:
if " " in row:
return False
return True
def main():
board = [[" " for _ in range(3)] for _ in range(3)]
players = ['X', 'O']
player_index = 0
print("Welcome to Tic-Tac-Toe Text Adventure!")
print_board(board)
while True:
player = players[player_index]
print(f"Player {player}'s turn.")
while True:
try:
row = int(input("Enter row (0, 1, or 2): "))
if row not in [0, 1, 2]:
raise ValueError
break
except ValueError:
print("Invalid input. Row must be 0, 1, or 2.")
while True:
try:
col = int(input("Enter column (0, 1, or 2): "))
if col not in [0, 1, 2]:
raise ValueError
break
except ValueError:
print("Invalid input. Column must be 0, 1, or 2.")
if board[row][col] != " ":
print("That position is already taken. Try again.")
continue
board[row][col] = player
print_board(board)
if check_win(board, player):
print(f"Player {player} wins!")
break
if is_board_full(board):
print("It's a tie!")
break
player_index = (player_index + 1) % 2
if __name__ == "__main__":
main()