-
Notifications
You must be signed in to change notification settings - Fork 48
/
Tic-Tac-Toe Game
39 lines (33 loc) · 1.21 KB
/
Tic-Tac-Toe Game
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
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_winner(board):
for row in board:
if row.count(row[0]) == 3 and row[0] != " ":
return True
for col in range(3):
if all(board[row][col] == board[0][col] != " " for row in range(3)):
return True
if board[0][0] == board[1][1] == board[2][2] != " " or board[0][2] == board[1][1] == board[2][0] != " ":
return True
return False
def tic_tac_toe():
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"
for turn in range(9):
print_board(board)
row = int(input(f"Player {current_player}, enter row (0-2): "))
col = int(input(f"Player {current_player}, enter col (0-2): "))
if board[row][col] == " ":
board[row][col] = current_player
if check_winner(board):
print_board(board)
print(f"Player {current_player} wins!")
return
current_player = "O" if current_player == "X" else "X"
else:
print("Invalid move! Try again.")
print_board(board)
print("It's a draw!")
tic_tac_toe()