-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolver.py
More file actions
103 lines (82 loc) · 2.87 KB
/
solver.py
File metadata and controls
103 lines (82 loc) · 2.87 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
88
89
90
91
92
93
94
95
96
97
98
99
100
from board import Board
from camera import CaptureBoard
def bestMove(board, depth, alpha=float('-inf'), beta=float('inf')):
def evaluate_board(board):
score = 0
center_col = 3
for col in range(board.nCol):
for row in range(board.nRow):
if board.board[col][row] == board.curPlayer:
score += 4 - abs(center_col - col)
return score
if board.nMoves == board.nRow * board.nCol:
return 0, -1
if depth == 0:
return evaluate_board(board), -1
for col in range(board.nCol):
if board.canPlay(col) and board.isWinningMove(col):
return (board.nCol * board.nRow + 1 - board.nMoves) // 2, col
bestScore = float('-inf')
bestCol = -1
playable_cols = [col for col in range(board.nCol) if board.canPlay(col)]
for col in playable_cols:
for row in range(board.nRow):
if board.board[col][row] == -1:
board.board[col][row] = board.curPlayer
board.curPlayer = (board.curPlayer + 1) % 2
board.nMoves += 1
break
score, _ = bestMove(board, depth - 1, -beta, -alpha)
score *= -1
for row in range(board.nRow - 1, -1, -1):
if board.board[col][row] != -1:
board.board[col][row] = -1
board.curPlayer = (board.curPlayer + 1) % 2
board.nMoves -= 1
break
if score > bestScore:
bestScore = score
bestCol = col
alpha = max(alpha, bestScore)
if alpha >= beta:
break
return bestScore, bestCol
def winCheck(board):
if(board.nMoves == 0):
empty = True
for i in range(board.nCol):
for j in range(board.nRow):
if(board.board[i][j] != -1):
empty = False
break
if(empty):
return 17, 3
for col in range(board.nCol):
if(board.canPlay(col) and board.isWinningMove(col)):
print("winning move detected at ", col)
return 22, col
orgPlayer = board.curPlayer
opponent = (board.curPlayer + 1) % 2
board.curPlayer = opponent
for col in range(board.nCol):
if(board.canPlay(col) and board.isWinningMove(col)):
return -21,col
board.curPlayer = orgPlayer
return bestMove(board,9)
def GetBestMoveFromPhoto(numMoves,cam):
board = Board(7,6)
grid = CaptureBoard(cam)
grid = grid -1
print(grid)
newBoard = [[-1] * 6 for _ in range(7)]
for i in range(len(grid)):
for j in range(len(grid[i])):
newBoard[j][i] = grid[i][j]
board.setBoard(newBoard)
for i in range(len(board.board)):
board.board[i].reverse()
print(board.board)
board.nMoves = numMoves
res = winCheck(board)
print("best move: ",res)
return res