-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmaster.py
More file actions
68 lines (57 loc) · 1.83 KB
/
master.py
File metadata and controls
68 lines (57 loc) · 1.83 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
# Edited
# Github: https://github.com/navdeeshahuja/Python-TicTacToe-Best-Move-Generator-Artificial-Intelligence-Minimax
def check_win(board, player):
for i in range(0, 7, 3):
if board[i] == player and board[i + 1] == player and board[i + 2] == player:
return True
for i in range(0, 3):
if board[i] == player and board[i + 3] == player and board[i + 6] == player:
return True
if board[0] == player and board[4] == player and board[8] == player:
return True
if board[2] == player and board[4] == player and board[6] == player:
return True
return False
def check_lose(board, player):
if player == "X":
opponent = "O"
else:
opponent = "X"
if check_win(board, opponent):
return True
return False
def check_tie(board):
for x in board:
if x == " ":
return False
return True
def get_ai_move(board, next_move, ai_player):
if check_win(board, ai_player):
return -1, 10
elif check_lose(board, ai_player):
return -1, -10
elif check_tie(board):
return -1, 0
moves = []
for i in range(len(board)):
if board[i] == " ":
board[i] = next_move
score = get_ai_move(board, ("X" if next_move == "O" else "O"), ai_player)[1]
moves.append((i, score))
board[i] = " "
if next_move == ai_player:
max_score = moves[0][1]
best_move = moves[0]
for move in moves:
if move[1] > max_score:
best_move = move
max_score = move[1]
return best_move
else:
min_score = moves[0][1]
worst_move = moves[0]
for move in moves:
if move[1] < min_score:
worst_move = move
min_score = move[1]
return worst_move