-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTOM.py
100 lines (78 loc) · 2.61 KB
/
TOM.py
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 Move import Move
import numpy
import math
inf = 100000000000000000000000000
def TOM(depth):
b = Board(1)
turn=0
while not b.isGameOver:
turn=turn+1
if b.whoseTurn == 1:
move = getMinimaxMove(b, depth)
b.makeMove(move)
print("your value:"+str(b.rateBoardOverall(2)))
print("my value: "+str(b.rateBoardOverall(1)))
print("turn "+str(turn))
b.printBoard()
else:
move = promptMove(b)
#move = getMinimaxMove(b, depth)
b.makeMove(move)
return 0
def getMinimaxMove(board, depth):
if board.whoseTurn == 1:
bestVal = -1*inf
else:
bestVal = inf
bestMove = None
for move in board.getAllMoves():
if board.whoseTurn==1:
moveVal=minimax(move, board, depth, True, -inf, inf)
# print("entry: "+str(move.entry)+" value: "+str(moveVal))
if moveVal > bestVal:
bestMove = move
bestVal = moveVal
else:
moveVal=minimax(move, board, depth, False, -inf, inf)
#print("entry: "+str(move.entry)+" value: "+str(moveVal))
if moveVal < bestVal:
bestMove=move
bestVal=moveVal
if math.fabs(bestVal)>1000:
print("gg")
return bestMove
def promptMove(board):
if board.mainBoardMatrix[board.lastBoard%3, math.floor(board.lastBoard/3)]==0:
subboard=board.lastBoard;
print("Your move is in board"+str(board.lastBoard))
else:
subboard=input("What board?")
entry = input("what square? ")
return Move(2, int(subboard), int(entry))
def minimax(node, board, depth, maximizingPlayer, alpha, beta):
newBoard = board.__copy__()
newBoard.makeMove(node)
if depth == 0 or newBoard.isGameOver:
bestValue = newBoard.rateBoardOverall(1) - newBoard.rateBoardOverall(2)
return bestValue
if maximizingPlayer:
bestValue = -1*inf
for child in newBoard.getAllMoves():
val = minimax(child, newBoard, depth - 1, False, alpha, beta);
bestValue = max(bestValue, val)
alpha=max(alpha, bestValue)
if alpha>=beta:
break
return bestValue
else:
bestValue = inf
for child in newBoard.getAllMoves():
val = minimax(child, newBoard, depth - 1, True, alpha, beta)
bestValue = min(bestValue, val)
beta=min(beta, bestValue)
if alpha>=beta:
break
return bestValue
if __name__ == '__main__':
TOM(4)