本文整理汇总了Python中PriorityQueue.PriorityQueue.put方法的典型用法代码示例。如果您正苦于以下问题:Python PriorityQueue.put方法的具体用法?Python PriorityQueue.put怎么用?Python PriorityQueue.put使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PriorityQueue.PriorityQueue
的用法示例。
在下文中一共展示了PriorityQueue.put方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: search
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import put [as 别名]
def search(self, startHex, goalHex):
startNode = HexNode(startHex, None)
goalNode = HexNode(goalHex, None)
frontier = PriorityQueue()
frontier.put(startNode, 0)
cameFrom = {}
currCost = {}
cameFrom[startNode] = None
currCost[startNode] = 0
while not frontier.empty():
currNode = frontier.get()
if currNode.h == goalNode.h:
break
for nextNode in self.getNeighborNodes(currNode.h):
newCost = currCost[currNode] + self.cost(currNode, nextNode)
if nextNode not in currCost or newCost < currCost[nextNode]:
currCost[nextNode] = newCost
priority = newCost + HexMap.heuristic(goalNode, nextNode)
frontier.put(nextNode, priority)
cameFrom[nextNode] = currNode
return cameFrom, currCost
示例2: a_star_search
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import put [as 别名]
def a_star_search(self, start, goal):
frontier = PriorityQueue()
frontier.put(start, 0)
came_from = {}
cost_so_far = {}
came_from[start] = start
cost_so_far[start] = 0
while not frontier.empty():
current = frontier.get()
if current.position_x == goal.position_x and current.position_y == goal.position_y:
break
for next in self.neighbors(current):
next_cell = Cell(next[0], next[1])
if next_cell.position_x == goal.position_x and next_cell.position_y == goal.position_y:
next_cell = goal
new_cost = cost_so_far[current] + self.heuristic(current, next_cell)
if next_cell not in cost_so_far or new_cost < cost_so_far[next_cell]:
cost_so_far[next_cell] = new_cost
priority = new_cost + self.heuristic(goal, next_cell)
frontier.put(next_cell, priority)
came_from[next_cell] = current
return came_from # , cost_so_far
示例3: astar
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import put [as 别名]
def astar(start, successors, goal, g, h):
path = []
states = PriorityQueue()
firststate = (start,None)
states.put((-g(firststate) - h(firststate), firststate))
i = 0
while True:
i += 1
if i % 2500 == 0:
print '%8d: # states: %5d, h of best state: %5d' % \
(i, len(states), min(h(state[1]) for state in states))
try:
if goal(states.top()[1]):
return g(states.top()[1]), getpath(states.top()[1])
except IndexError:
return None
best = states.top()[1]
states.pop()
for s in successors(best):
prev = [x for x in states if x[1][0] == s]
s = (s, best)
#if len(prev)>0:print prev[0][1]
#print s
if len(prev) > 0 and g(s) < g(prev[0][1]):
states.remove(prev[0])
if len(prev) > 0:
continue
states.put((-g(s) - h(s), s))
示例4: astar
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import put [as 别名]
def astar(start, successors, goal, g, h):
path = []
states = PriorityQueue()
firststate = start
states.put((-g(firststate) - h(firststate), firststate))
i = 0
nexti = 1
while True:
i += 1
# if i == 40000:
# return (0, None)
if i == nexti:
nexti += 1 # 3*len(states)
curbest = states.top()[1]
print "%8d: # states: %5d, h of best state: %5d" % (i, len(states), h(curbest))
print "\tcurrent top: score = %6d; %r" % (g(curbest) + h(curbest), curbest)
try:
if goal(states.top()[1]):
print i
return (states.top()[1], g(states.top()[1]))
except IndexError:
return (0, None)
best = states.top()[1]
states.pop()
for s in successors(best):
prev = [x for x in states if x[1] == s]
# if len(prev)>0:print prev[0][1]
# print s
if len(prev) > 0 and g(s) < g(prev[0][1]):
states.remove(prev[0])
if len(prev) > 0:
continue
states.put((-g(s) - h(s), s))
示例5: __init__
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import put [as 别名]
class Game:
""" Defines a running instance of a Murder Mystery.
Handles the initialization of the various game states.
"""
def __init__(self, abilities, players):
self.gm = players[0]
self.errorAbility = ErrorAbility()
self.eventQueue = PriorityQueue()
self.parser = Parser()
self.inbox = Inbox()
self.outbox = Outbox()
self.players = {}
for player in players[1:]:
self.players[player.getName().lower()] = player
self.abilities = {}
for ability in abilities:
self.abilities[ability.getName().lower()] = ability
def getGameMaster(self):
return self.gm
def addEvent(self, event):
""" Schedules an event to be run.
"""
self.eventQueue.put(event)
def addEvents(self, events):
""" Schedules a list of events to be run.
"""
if(events):
for event in events:
self.eventQueue.put(event)
def removeEvent(self, event):
""" Removes a specific event from the priority queue
"""
self.eventQueue.remove(event)
def getOutbox(self):
return self.outbox
def isValidAbility(self, name):
return name.lower() in self.abilities
def getAbility(self, name):
return self.abilities[name.lower()]
def getAbilityNames(self):
return self.abilities.keys()
def isValidPlayer(self, name):
return name.lower() in self.players
def getPlayer(self, name):
return self.players[name.lower()]
def getPlayerNames(self):
return self.players.keys()
def removePlayer(self, name):
if( self.isValidPlayer(name) ):
del self.players[name.lower()]
def run(self):
""" Run the game, and Don't stop.
Ever.
"""
print "Starting the main loop!"
while( True ):
self.step()
time.sleep(5)
def step(self):
""" Perform one step of the game logic.
You need to call this repeatedly to make the game run.
"""
#process incoming messages
newMessages = self.inbox.poll()
commands = self.parser.parse(self.abilities.values(), newMessages, self.errorAbility)
for (sender,ability,args) in commands:
print "Handling '"+ability.getName()+"' for '"+sender+"'"
for player in self.players.values():
if( player.getContact() == sender ):
print "\tRunning the ability!"
self.addEvents(ability.getEventsFor(self, player, args))
break
#Process the queue of events
while( not self.eventQueue.empty() ):
event = self.eventQueue.get()
if( event.when() < datetime.now() ):
print "Performing an event"
self.addEvents(event.perform(self))
else:
#Doesn't support peeking, so shove it back in the queue if it
#shouldn't happen yet
self.eventQueue.put(event)
break
示例6: PathFinder
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import put [as 别名]
#.........这里部分代码省略.........
except:
print >> sys.stderr, 'Vertex not found in points'
return
# find the neighbors of this point
row = self.visibility_graph[index]
for i in range(0, len(row)):
neighbor = self.points[i]
if row[i] == 1 and neighbor not in self.visited:
if self.is_goal(neighbor):
# If this child is the goal node, we're done!
last_node = BFSNode(neighbor, current_node)
self.frontier.append(last_node)
self.search_snapshots.append(Snapshot(list(self.visited), list(self.frontier), uses_bfs_nodes=True))
self.reconstruct_path_from_last_node(last_node)
return
else:
# Add this child to the end of the queue
self.frontier.append(BFSNode(neighbor, current_node))
# If we get to this point, then the frontier became empty before we found the goal
print "BFS failed to find the goal"
def reconstruct_path_from_last_node(self, last_node):
self.path = []
node = last_node
while node:
self.path.insert(0, node.my_point)
node = node.parent
############################
### A-STAR ALGORITHM ###
############################
def get_a_star_path(self):
print "Running A* to Get Path"
self.a_star_search()
return self.path
def a_star_search(self):
self.clear_history()
self.frontier = PriorityQueue()
self.frontier.put(AStarNode(self.points[0], None, 0), 0)
last_node = None
# iterate until the frontier is empty
while not self.frontier.empty():
snapshot = Snapshot(list(self.visited), self.frontier.getNodes(), uses_a_star_nodes=True)
self.search_snapshots.append(snapshot)
current = self.frontier.get()
if current.my_point in self.visited:
# Never mind, we didn't want that snapshot :)
self.search_snapshots.remove(snapshot)
continue
self.visited.append(current.my_point)
# end immediately if the goal is found
if self.is_goal(current.my_point):
last_node = current
break
# find out which point we're dealing with
try:
index = self.points.index(current.my_point)
except:
print >> sys.stderr, 'Vertex not found in points'
return False
# prepare qualified new neighbors to be added to frontier
row = self.visibility_graph[index]
index = 0
for item in row:
neighbor = self.points[index]
if item == 1 and neighbor not in self.visited:
distance = current.cost
distance += self.distance(neighbor, current.my_point) # distance so far
est_distance_remaining = distance + self.distance(neighbor, self.points[1]) # est. distance to go
self.frontier.put(AStarNode(neighbor, current, distance), est_distance_remaining)
index += 1
# unwind path back to start
while not last_node == None:
self.path.insert(0, last_node.my_point)
last_node = last_node.parent
################################
### SEARCH ALGORITHM HELPERS ###
################################
def clear_history(self):
self.visited = []
self.frontier = []
self.path = []
self.search_snapshots = []
def is_goal(self, point):
return point == self.points[1] # the goal point is always the second one in our list of points
def distance(self, point1, point2):
return math.sqrt((point1[0]-point2[0])**2 + (point1[1] - point2[1]) ** 2)