-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpro tic.py
More file actions
53 lines (43 loc) · 1.55 KB
/
pro tic.py
File metadata and controls
53 lines (43 loc) · 1.55 KB
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
def print_board(board):
print("\n")
print(" | ".join(board[0:3]))
print("-" * 9)
print(" | ".join(board[3:6]))
print("-" * 9)
print(" | ".join(board[6:9]))
print("\n")
def check_winner(board, player):
win_conditions = [(0, 1, 2), (3, 4, 5), (6, 7, 8), # Rows
(0, 3, 6), (1, 4, 7), (2, 5, 8), # Columns
(0, 4, 8), (2, 4, 6)] # Diagonals
for condition in win_conditions:
if board[condition[0]] == board[condition[1]] == board[condition[2]] == player:
return True
return False
def check_draw(board):
return all([spot in ['X', 'O'] for spot in board])
def tic_tac_toe():
board = [str(i+1) for i in range(9)]
current_player = "X"
while True:
print_board(board)
try:
move = int(input(f"Player {current_player}, enter your move (1-9): ")) - 1
if board[move] in ['X', 'O']:
print("This spot is already taken. Choose another one.")
continue
except (IndexError, ValueError):
print("Invalid move. Please choose a spot between 1 and 9.")
continue
board[move] = current_player
if check_winner(board, current_player):
print_board(board)
print(f"Player {current_player} wins!")
break
if check_draw(board):
print_board(board)
print("It's a draw!")
break
current_player = "O" if current_player == "X" else "X"
# Run the Tic-Tac-Toe game
tic_tac_toe()