-
Notifications
You must be signed in to change notification settings - Fork 0
/
tic_tac_toe
44 lines (39 loc) · 1.48 KB
/
tic_tac_toe
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
def print_board(board):
for row in board:
print(" " + " | ".join(row))
print("---+---+---+---+---")
def check_winner(board, player):
for row in board:
if row.count(player) == 5:
return True
for col in range(5):
if [board[row][col] for row in range(5)].count(player) == 5:
return True
if [board[i][i] for i in range(5)].count(player) == 5 or [board[i][4-i] for i in range(5)].count(player) == 5:
return True
return False
def tic_tac_toe():
board = [[" " for _ in range(5)] for _ in range(5)]
current_player = "X"
while True:
print_board(board)
try:
row, col = map(int, input(f"Player {current_player}, enter row and column to place {current_player} (0, 1, 2, 3, 4): ").split())
if board[row][col] != " ":
print("This spot is already taken!")
continue
except (ValueError, IndexError):
print("Invalid input. Please enter row and column numbers between 0 and 4.")
continue
board[row][col] = current_player
if check_winner(board, current_player):
print_board(board)
print(f"Player {current_player} wins!")
break
if all(cell != " " for row in board for cell in row):
print_board(board)
print("It's a tie!")
break
current_player = "O" if current_player == "X" else "X"
if __name__ == "__main__":
tic_tac_toe()