def cmp0(mv0, mv1): move.make(mv0) s0 = static.eval() move.umake(mv0) move.make(mv1) s1 = static.eval() move.umake(mv1) if s0 < s1: return -1 elif s0 == s1: return 0 else: return +1
def forBlack(mvs): "random move best for black paired with static score" assert len(mvs) > 0 min_score = 99999 for mv in mvs: move.make(mv) score = static.eval() if score < min_score: best, min_score = [mv], score elif score == min_score: best.append(mv) move.umake(mv) return (random.choice(best), score)
def forWhite(mvs): "random move best for white paired with static score" assert len(mvs) > 0 max_score = -99999 for mv in mvs: move.make(mv) score = static.eval() if score > max_score: best, max_score = [mv], score elif score == max_score: best.append(mv) move.umake(mv) return (random.choice(best), score)
def AlphaBetaWithMemory(alpha, beta, d): if TT.has_key(board.hash): lowerbound, upperbound = TT[board.hash] if lowerbound >= beta: return lowerbound if upperbound <= alpha: return upperbound alpha = max(alpha, lowerbound) beta = min(beta, upperbound) if d == 0: g = static.eval() elif board.whiteToMove(): g, a = -inf, alpha # save original alpha value for mv in legal.moves(): if g >= beta: break move.make(mv) g = max(g, AlphaBetaWithMemory(a, beta, d - 1)) move.umake(mv) a = max(a, g) else: assert board.blackToMove() g, b = +inf, beta #save original beta value for mv in legal.moves(): if g <= alpha: break move.make(mv) g = min(g, AlphaBetaWithMemory(alpha, b, d - 1)) move.umake(mv) # transition table storing of bounds # fail low implies an upper bound if g <= alpha: if TT.has_key(board.hash): lower, upper = TT[board.hash] else: lower, upper = -inf, +inf TT[board.hash] = lower, g # found an accurate minimax value - will not occur if called with zero window if g > alpha and g < beta: TT[board.hash] = g, g # fail high result implies a lower bound if g > beta: if TT.has_key(board.hash): lower, upper = TT[board.hash] else: lower, upper = -inf, +inf TT[board.hash] = g, upper return g
def G2(alpha, beta, d, ln): global cnt # determine the successor positions mvlist = moves(d) if len(mvlist) == 0: return static.eval(), ln m = beta #mln = ln #? for mv in mvlist: make(mv) cnt = cnt + 1 mln = ln + [mv] t, tln = F2(alpha, m, d - 1, mln) umake(mv) if t < m: m, mln = t, tln if m <= alpha: break return m, mln
import sys,board,static inf = sys.maxint TT = { } def AlphaBetaWithMemory(mvlist,alpha,beta,d) if TT.has_key(board.hash): lowerbound,upperbound = TT[board.hash] if lowerbound >= beta: return lowerbound if upperbound <= alpha: return upperbound alpha = max(alpha,lowerbound) beta = min(beta,upperbound) if d==0: g = static.eval() elif board.whiteToMove(): g,a = -inf,alpha # save original alpha value for mv in mvlist: if g >= beta: break move.make(mv) g = max(g,AlphaBetaWithMemory(legal.moves(),a,beta,d-1)) move.umake(mv) a = max(a,g) else: assert board.blackToMove() g,b = +inf,beta #save original beta value for mv in mvlist: if g <= alpha: break