1
2 """MTD(f)
3
4 from http://www.cs.vu.nl/~aske/mtdf.html
5
6 The name of the algorithm is short for MTD(n, f), which stands for
7 something like Memory-enhanced Test Driver with node n and value f.
8 """
9
10 import boardRep
11
12
13
14 POSINFINITY=99999
15 NEGINFINITY=-99999
16
17 AIPLAYER=1
18
21 self.lowerBound = NEGINFINITY
22 self.upperBound = POSINFINITY
23 self.bestMove = None
24 self.furthestDepthSearched = -1
25 self.isTerminal = False
26
30
31 - def lookup(self, node, depth):
32 ttn=self.cache.get(node,None)
33 if ttn is None:
34 return ttn
35 if depth<=ttn.furthestDepthSearched:
36 return ttn
37 if ttn.isTerminal:
38 return ttn
39 del self.cache[node]
40 return None
41
46
51
56
61
66
67
68
69
70
71 transTable=TranspositionTable()
72
73
74 -def mtdf(node, f, depth):
75
76 g=f
77 upperBound=POSINFINITY
78 lowerBound=NEGINFINITY
79 while lowerBound<upperBound:
80 if g==lowerBound:
81 beta = g+1
82 else:
83 beta = g
84 g = alphaBetaWithMemory(node, beta-1, beta, depth, depth)
85 if g< beta:
86 upperBound=g
87 else:
88 lowerBound=g
89 return g
90
91
93 indent=printDepth-depth
94 indentString=" "*indent
95
96 transTableInfo=transTable.lookup(node, depth)
97
98 if transTableInfo:
99
100
101
102 if transTableInfo.lowerBound >= beta:
103 return transTableInfo.lowerBound
104 if transTableInfo.upperBound <= alpha:
105 return transTableInfo.upperBound
106 alpha = max(alpha, transTableInfo.lowerBound)
107 beta = min(beta, transTableInfo.upperBound)
108
109 terminal=isTerminal(node)
110 if depth==0 or terminal:
111 g=evaluate(node, AIPLAYER)
112
113 elif isMaximizing(node):
114 g = NEGINFINITY
115 a = alpha
116 for c in getChildren(node):
117 if g >= beta:
118 break
119 g=max(g,alphaBetaWithMemory(c, a, beta, depth-1, printDepth))
120 a=max(a,g)
121 else:
122 g = POSINFINITY
123 b = beta
124 for c in getChildren(node):
125 if g <= alpha:
126 break
127 g = min(g,alphaBetaWithMemory(c, alpha, b, depth-1, printDepth))
128 b = min(b,g)
129
130 if g <= alpha:
131 transTable.storeUpperBound(node,g)
132 elif g > alpha and g < beta:
133 transTable.storeLowerBound(node,g)
134 transTable.storeUpperBound(node,g)
135 raise "never happens"
136 else:
137 transTable.storeLowerBound(node,g)
138 transTable.storeDepth(node, depth)
139 transTable.setTerminal(node, terminal)
140 return g
141
142
144
145 firstGuess=0
146 for d in range(1,12):
147 firstGuess=mtdf(node, firstGuess,d)
148
149
150 return firstGuess
151
155
159
164
168
182
183 if __name__=="__main__":
184 f=file("boardDescs.txt")
185 fLines=f.readlines()
186 f.close()
187
188 for boardIndex in range(len(fLines)):
189 splitLine=fLines[boardIndex].split(',')
190 boardHash=int(splitLine[0])
191
192 v=iterativeDeepening(boardHash)
193
194 print boardHash,v,getBestMoves(boardHash, 10, v)
195