def dijkstra(start_tile, end_tile): """ Dijkstra's algorithm :param start_tile: Tile object, start tile of board :param end_tile: Tile object, end tile of board :return: """ queue = PriorityQueue() queue.put(start_tile, 0) came_from = {start_tile: None} cost_so_far = {start_tile: 0} has_been_next_tile = [] while not queue.empty(): current_tile = queue.get() current_tile.visit() if current_tile == end_tile: break for next_tile in current_tile.neighbours: if next_tile not in has_been_next_tile: has_been_next_tile.append(next_tile) new_cost = cost_so_far[current_tile] + next_tile.weight if next_tile not in cost_so_far or new_cost < cost_so_far[ next_tile]: cost_so_far[next_tile] = new_cost priority = new_cost queue.put(next_tile, priority) came_from[next_tile] = current_tile return came_from, cost_so_far, has_been_next_tile
def timedGameScoreSearch(graph, playerKey, timeout): startPos = graph.getPosition(playerKey) counter = 0 frontier = PriorityQueue() graphKey = graph.getStateKey() foundKey = None frontier.put(graphKey, 0) cameFrom = {} costSoFar = {} startKey = graph.getStateKey() expandedNodes[startKey] = graph cameFrom[startKey] = None costSoFar[startKey] = 0 bestHeuristicSoFar = 99999 bestFoundSoFar = startKey targetScore = 50 while not frontier.empty(): counter += 1 if counter > 1999: break currentKey = frontier.get() current = expandedNodes[currentKey] if time.time() > timeout: foundKey = bestFoundSoFar logger.info("breaking because of timeout, counter: " + str(counter)) break #check for goal if current.getScore() > targetScore: foundKey = currentKey logger.info("breaking because found, counter: " + str(counter)) break nCounter = 0 for next in current.neighbors(playerKey): nCounter += 1 nextKey = next.getStateKey() expandedNodes[nextKey] = next newCost = costSoFar[currentKey] + 1 #graph.cost(current, next, playerKey) if nextKey not in costSoFar or newCost < costSoFar[nextKey]: costSoFar[nextKey] = newCost heuristic = next.cleverScoreHeuristic(targetScore) if heuristic < bestHeuristicSoFar and len(next.neighbors(playerKey)) > 0: bestFoundSoFar = nextKey bestHeuristicSoFar = heuristic priority = newCost + heuristic cameFrom[nextKey] = currentKey if len(next.neighbors(playerKey)) > 0: # add to frontier if I am alive in this NODE #Add large penalty for states where an opponent can blow me up so we only remove from frontier if absolutely nescecerry #get position nextPosition = next.getPosition(playerKey) inOpponentDangerZone = next.testIfInOpponentDanger(nextPosition) #logger.info("inOpponentDangerZone: %s" % inOpponentDangerZone) #check if in simulatedBombZone opponentDangerPenalty = 0 if inOpponentDangerZone: opponentDangerPenalty = 999 frontier.put(nextKey, priority + opponentDangerPenalty) #logger.info("returning from timedGameStarSearch, counter: " + str(counter)) return cameFrom, costSoFar, foundKey, startKey