def interpret_data(self, args): if 'error' in args: debug('Error: ' + args['error']) return if 'number' in args: self.my_number = args['number'] if 'board' in args: self.dimension = args['board']['dimension'] self.turn = args['turn'] self.grid = args['board']['grid'] self.all_blocks = args['blocks'][:] self.bonus_squares = {tuple(coords) for coords in args['board']['bonus_squares']} for x in xrange(len(self.all_blocks)): for y in xrange(len(self.all_blocks[x])): self.all_blocks[x][y] = [Point(offset) for offset in self.all_blocks[x][y]] self.all_blocks[x][y][0].x * 9000 self.all_blocks[x][y][0].y * 9001 if (('move' in args) and (args['move'] == 1)): send_command(" ".join(str(x) for x in util.run_search_function(self, util.memoize(self.find_move))))
def best_first_graph_search(problem, f): """ Search the nodes with the lowest f scores first. You specify the function f(node) that you want to minimize; for example, if f is a heuristic estimate to the goal, then we have greedy best first search; if f is node.depth then we have breadth-first search. There is a subtlety: the line "f = memoize(f, 'f')" means that the f values will be cached on the nodes as they are computed. So after doing a best first search you can examine the f values of the path returned. """ f = memoize(f, 'f') node = Node(problem.getStartState()) if problem.isGoalState(node.state): return node frontier = PriorityQueue(min, f) frontier.push(node) explored = set() while frontier: node = frontier.pop() if problem.isGoalState(node.state): return node explored.add(node.state) for child in node.expand(problem): if child.state not in explored and not frontier.contains(child): frontier.push(child) elif frontier.contains(child): incumbent = frontier.__getitem__(child) if f(child) < f(incumbent): del frontier[incumbent] frontier.push(child) return None
val = -1 * alphabeta_find_board_value( alpha, beta, False, new_board, current_moves, repetitive_moves, depth - 1, eval_fn, get_next_moves_fn, is_terminal_fn) #print("This is val: ", val, "move ", move) if best_val is None or val > best_val[0]: best_val = (val, move, new_board) #test = list(filter(lambda x: len(x) > 1, board.chain_cells(2))) #print(test) print("MINIMAX_alphabeta: Decided on column {} with rating {}".format( best_val[1], best_val[0])) return best_val[1] # Now you should be able to search twice as deep in the same amount of time. # (Of course, this alpha-beta-player won't work until you've defined alpha_beta_search.) focused_evaluate = memoize(focused_evaluate) def alpha_beta_player(board): return alpha_beta_search(board, depth=8, eval_fn=focused_evaluate) # This player uses progressive deepening, so it can kick your ass while # making efficient use of time: def ab_iterative_player(board): return run_search_function(board, search_fn=alpha_beta_search, eval_fn=focused_evaluate, timeout=5)
sec_info.append((1, None)) sec_info.sort() def get_section(self, addr): key = (-addr, ) idx = bisect.bisect(self._sec_info, key) _, sec = self._sec_info[idx] if not sec: return if addr - sec.header.sh_addr >= sec.header.sh_size: return return sec get_address_space = memoize(WeakKeyDictionary)(AddressSpace) class MemoryStream(object): def __init__(self, elf): self.elf = elf self._address_space = get_address_space(elf) def seek(self, addr): self._addr = addr def tell(self): return self._addr def _read(self, size): assert size >= 0
for point in chain: score -= 5 * abs( 3 - point[1] ) # scale to 5, place in center ones have more chance to win for chain in board.chain_cells(board.get_other_player_id()): score -= len(chain) * len(chain) * len( chain) # because defense is more important for point in chain: score += 7 * abs( 3 - point[1] ) # scale to 5, place in center ones have more chance to win return score #raise NotImplementedError # Comment this line after you've fully implemented better_evaluate #better_evaluate = memoize(basic_evaluate) # Uncomment this line to make your better_evaluate run faster. better_evaluate = memoize(better_evaluate) # A player that uses alpha-beta and better_evaluate: #def my_player(board): # return run_search_function(board, search_fn=alpha_beta_search, eval_fn=better_evaluate, timeout=5) # NOTE: # set the depth to be 6, at the beginning of each game, it might be slow, take about 5-6s, but will be much # faster as the process of the game. my_player = lambda board: alpha_beta_search( board, depth=6, eval_fn=better_evaluate)
from logging import getLogger from itertools import chain from flask import Blueprint, render_template, abort, request, Response, \ current_app, url_for from werkzeug.routing import BuildError import opensearch from util import memoize, requestedFormat log = getLogger('agherant') agherant = Blueprint('agherant', __name__) Client = memoize(opensearch.Client) @agherant.route('/search') def search(): query = request.args.get('q', None) if query is None: abort(400, "No query given") books = aggregate(current_app.config['AGHERANT_DESCRIPTIONS'], query) format = requestedFormat(request, ['text/html', 'text/xml', 'application/rss+xml', 'opensearch']) if (not format) or (format is 'text/html'): return render_template('os_search.html', books=books, query=query) if format in ['opensearch', 'text/xml', 'application/rss+xml']: return Response(render_template('os_opens.xml', books=books, query=query),
if board.get_cell(r, c_i) == other_player]), # 2. Vertical chains (r, c), (r+1, c), ... #sum([1 for r_i in xrange(r, r+3) sum([1 for r_i in xrange(r, r+k-1) if board.get_cell(r_i, c) == other_player]), # 3. Diagonal chains (r, c), (r+1, c+1), ... #sum([1 for d_i in xrange(3) sum([1 for d_i in xrange(k-1) if board.get_cell(r+d_i, c+d_i) == other_player]) ) ** 2 return score new_evaluate = memoize(new_evaluate) def get_all_next_moves(board): """ Return a generator of all moves that the current player could take from this position """ from connectfour import InvalidMoveException for i in xrange(board.board_width): try: yield (i, board.do_move(i)) except InvalidMoveException: pass def is_terminal(depth, board): """ Generic terminal state check, true when maximum depth is reached or the game has ended.
def _iter_cu_dios(self, cu): for die, parent_pos in _iter_DIEs(cu): yield DebugInfoObject(self, die, parent_pos) def iter_dios(self): # Skip sentinel (1, None) at position zero for cu_pos, cu in itertools.islice(reversed(self._cu_pos), 1, None): for dio in self._iter_cu_dios(cu): yield dio def lookup(self, cu_name): cu = self._cu_names.get(cu_name) return DebugInfoObject(self, cu.get_top_DIE(), DI_ROOT) if cu else None get_debug_info = memoize(WeakKeyDictionary)(DebugInfo) class Struct(object): def __init__(self, **kwargs): for name, value in kwargs.iteritems(): setattr(self, name, value) def __repr__(self): data = [ "%s = %r" % (name, value) for name, value in self.__dict__.iteritems() if not name.startswith("__") ] data.sort() return "Struct(%s)" % ", ".join(data)
from logging import getLogger from itertools import chain from flask import Blueprint, render_template, abort, request, Response, \ current_app, url_for from werkzeug.routing import BuildError import opensearch from util import memoize, requestedFormat log = getLogger('agherant') agherant = Blueprint('agherant', __name__) Client = memoize(opensearch.Client) @agherant.route('/search') def search(): query = request.args.get('q', None) if query is None: abort(400, "No query given") books = aggregate(current_app.config['AGHERANT_DESCRIPTIONS'], query) format = requestedFormat( request, ['text/html', 'text/xml', 'application/rss+xml', 'opensearch']) if (not format) or (format is 'text/html'): return render_template('os_search.html', books=books, query=query) if format in ['opensearch', 'text/xml', 'application/rss+xml']: return Response(render_template('os_opens.xml', books=books, query=query), mimetype='text/xml')