def q1_symmetric(state, W=11, H=9): # The first quadrant mod = (W + 2) // 2 + 1 q1 = [(W + 2) * (loc // mod) + loc % mod for loc in range(mod * (H // 2 + 1))] if state.locs[0] is None: return state if state.locs[0] in q1: return state # Horizontal if h_symmetry(state.locs[0]) in q1: return Isolation(board=state.board, ply_count=state.ply_count, locs=tuple(map(h_symmetry, state.locs))) # Vertical if v_symmetry(state.locs[0]) in q1: return Isolation(board=state.board, ply_count=state.ply_count, locs=tuple(map(v_symmetry, state.locs))) # Central if c_symmetry(state.locs[0]) in q1: return Isolation(board=state.board, ply_count=state.ply_count, locs=tuple(map(c_symmetry, state.locs)))
def load_latest_book(depth=4): filename = get_latest_book_name(get_book_list()) if filename is None: return get_empty_book(Isolation(), depth) with open(filename, 'rb') as file: latest_book = pickle.load(file) return latest_book
def build_table(num_rounds, depth): #builds a mapping [state -> most optimal move] #the move is based on the score from get_score() from collections import defaultdict, Counter book = defaultdict(Counter) state = Isolation() build_tree(state, book, depth) return ({k: max(v, key=v.get) for k, v in book.items()}, book)
def sym_sa(s_a, loc_sym, cardinal_sym): """ Symmetry for a (state, action) pair. Don't use if this state is from move 3 or more. loc_sym is a function that transforms a location. cardinal_sym is a dictionary that maps cardinal points in the symmetry. """ state = s_a[0] action = s_a[1] new_board = iso._BLANK_BOARD new_locs = tuple(map(loc_sym, state.locs)) if new_locs[0] is not None: new_board = new_board ^ (1 << (new_locs[0])) if new_locs[1] is not None: new_board = new_board ^ (1 << (new_locs[1])) new_state = Isolation(board=new_board, ply_count=state.ply_count, locs=new_locs) if isinstance(action, iso.Action): new_action = action_symmetric(action, cardinal_sym) else: new_action = loc_sym(action) return new_state, new_action
heatmap[k[0], k[1]] = score return heatmap def plot_heatmap(heatmap, min, max): ax = sns.heatmap(heatmap, cmap="Blues") ax.xaxis.tick_top() return ax if __name__ == "__main__": (book, ratios) = build_table(num_rounds=NUM_ROUNDS, depth=BOOK_DEPTH) #print best opening move game_start = Isolation() best_opening = book[game_start] print("Best opening move: {}".format(DebugState.ind2xy(best_opening))) #print best response to opening move resulting_state = game_start.result(best_opening) best_response = book[resulting_state] print("Best response: {}".format(DebugState.ind2xy(best_response))) #build heatmap of opening move wins.. opening_moves = ratios[game_start] xy = [DebugState.ind2xy(ind) for ind in opening_moves] (xs, ys) = zip(*xy) width = max(xs) + 1 height = max(ys) + 1
def build_table(num_rounds=NUM_ROUNDS): book = defaultdict(Counter) for _ in range(num_rounds): state = Isolation() build_tree(state, book) return {k: max(v, key=v.get) for k, v in book.items()}