-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask2.py
More file actions
87 lines (77 loc) · 2.68 KB
/
Copy pathtask2.py
File metadata and controls
87 lines (77 loc) · 2.68 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import math
def print_board(board):
for row in [board[i*3:(i+1)*3] for i in range(3)]:
print('| ' + ' | '.join(row) + ' |')
print()
def minimax(board, depth, is_maximizing, alpha, beta):
winner = check_winner(board)
if winner:
return {'X': -10, 'O': 10, 'Tie': 0}[winner]
if is_maximizing:
best_score = -math.inf
for i in range(9):
if board[i] == ' ':
board[i] = 'O'
score = minimax(board, depth + 1, False, alpha, beta)
board[i] = ' '
best_score = max(score, best_score)
alpha = max(alpha, best_score)
if beta <= alpha:
break
return best_score
else:
best_score = math.inf
for i in range(9):
if board[i] == ' ':
board[i] = 'X'
score = minimax(board, depth + 1, True, alpha, beta)
board[i] = ' '
best_score = min(score, best_score)
beta = min(beta, best_score)
if beta <= alpha:
break
return best_score
def best_move(board):
best_score = -math.inf
move = None
for i in range(9):
if board[i] == ' ':
board[i] = 'O'
score = minimax(board, 0, False, -math.inf, math.inf)
board[i] = ' '
if score > best_score:
best_score = score
move = i
return move
def check_winner(board):
win_combinations = [(0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6)]
for combo in win_combinations:
if board[combo[0]] == board[combo[1]] == board[combo[2]] and board[combo[0]] != ' ':
return board[combo[0]]
if ' ' not in board:
return 'Tie'
return None
def tic_tac_toe():
board = [' ' for _ in range(9)]
print("Welcome to Tic-Tac-Toe!")
print_board(board)
while True:
move = int(input("Enter your move (0-8): "))
if board[move] == ' ':
board[move] = 'X'
if check_winner(board):
print_board(board)
print("You win!")
break
ai_move = best_move(board)
if ai_move is not None:
board[ai_move] = 'O'
if check_winner(board):
print_board(board)
print("AI wins!")
break
print_board(board)
if check_winner(board) == 'Tie':
print("It's a tie!")
break
tic_tac_toe()