def build_maze(): """Creates the maze.""" maze = Graph() # add the player's starting positions and the end p1_start = maze.add_node(name="p1_start") p2_start = maze.add_node(name="p2_start") end = maze.add_node(name="END") # create a list of connected components nodes = [[p1_start], [p2_start], [end]] # add all the rooms, making each its own component for i in range(NUM_ROOMS): nodes.append([maze.add_node(name=i)]) # while some components are unconnected while len(nodes) > 1: # choose two components at random component_1, component_2 = random.sample(list(nodes), 2) # and one node from each component node_1 = random.choice(component_1) node_2 = random.choice(component_2) # and if they don't have too many doors... if len(node_1.outgoing) < NUM_DOORS and len(node_2.outgoing) < NUM_DOORS: # connect them maze.add_edge(node_1, node_2, is_directed=False) # then merge the components component_1.extend(component_2) nodes.remove(component_2) # finally, make sure that the start and end points have doors. choices = random.sample(list(maze.nodes), 3) if len(p1_start.outgoing) < NUM_DOORS: maze.add_edge(p1_start, choices[0], is_directed=False) if len(p2_start.outgoing) < NUM_DOORS: maze.add_edge(p2_start, choices[1], is_directed=False) if len(end.outgoing) < NUM_DOORS: maze.add_edge(end, choices[2], is_directed=False) return p1_start, p2_start, maze
def cycle(n, is_directed=True): """Generates a cycle of size n. The verticies are numbered [0, n). The edges are named after the verticies they connect such that an edge connecting verticies 1 and 2 is named (1,2). """ G = Graph() for i in range(n): G.add_node(i) for i in range(n): j = (i + 1) % n G.add_edge(i, j, (i,j), is_directed=is_directed) return G
def K(n): """Generates a completely connected undirected graph of size n. The verticies are numbered [0, n). The edges are named after the verticies they connect such that an edge connected verticies 1 and 2 is named (1,2). """ # create the graph k = Graph() # generate all the nodes for i in range(n): k.add_node(i) # generate all the edges for i in range(n): for j in range(i+1, n): k.add_edge(i, j, (i,j), is_directed=False) # return the graph return k
def handle_graph_start(self, attrs): """Creates a new node and puts it on the stack.""" # create the new graph self.current_graph = Graph() # associate it with its id self.ids[attrs["id"]] = self.current_graph # set the default edge direction self.defaults["edgedefault"] = attrs["edgedefault"] # add it to the graphs stack self.elements.append(self.current_graph)
def walk_fsm(data): fsm = Graph() fsm.add_edge("consume_one", "loop_on_zero", consumes="1", accept=False) fsm.add_edge("loop_on_zero", "loop_on_zero", consumes="0", accept=False) fsm.add_edge("loop_on_zero", "end_with_one", consumes="1", accept=True) accept = False w = fsm.walk_path("consume_one") for edges in w: try: next = {e.consumes: e for e in edges}[data.pop(0)] accept = next.accept w.send(next) except: return False return accept and not data
#GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with pyFish. If not, see <http://www.gnu.org/licenses/>. from pyFish import Core from pyFish.Moves import * from graph.base import Graph from ContinentBot import ContinentBot #The id of the game the bot is to play. GAME_ID = '73888572' #The name of the player in the game the bot will be playing for. PLAYER_NAME = 'The Curmudgeon' #The cookie the bot will use to authenticate as PLAYER_NAME COOKIE = 'SESSID=21548ed928da03bb61bade292db94948; LAST=829925F678A3F7AB3A03F11EC9BCBB6800340380D4A4' bot = ContinentBot(GAME_ID, PLAYER_NAME, COOKIE) territory = bot.game.map.territories['1'] g = Graph() g.add_node(territory) for neighbor in territory.attackable_neighbors.values(): g.add_node(neighbor) g.add_edge(territory, neighbor) print for edge in g.search_edges(start=territory): print(edge.end.name.name)
class Reader(ContentHandler): """Generates a Graph from GraphML data.""" def startDocument(self): """Handles the beginning of a given document.""" self.current_graph = None self.elements = [] self.ids = {} self.defaults = {} def startElement(self, name, attrs): """Dispatches opening tags to the appropriate handler.""" try: handler = getattr(self, "handle_%s_start" % name) except AttributeError as error: print(error) print("Warning: ignoring unsupported tag %s" % name) handler(attrs) def endElement(self, name): """Dispatches closing tags to the appropriate handler.""" try: handler = getattr(self, "handle_%s_end" % name) except AttributeError as error: print(error) print("Warning: ignoring unsupported tag %s" % name) handler() def handle_graphml_start(self, attrs): pass def handle_graphml_end(self): pass def handle_graph_start(self, attrs): """Creates a new node and puts it on the stack.""" # create the new graph self.current_graph = Graph() # associate it with its id self.ids[attrs["id"]] = self.current_graph # set the default edge direction self.defaults["edgedefault"] = attrs["edgedefault"] # add it to the graphs stack self.elements.append(self.current_graph) def handle_graph_end(self): """Pops the graph off the graph stack.""" if isinstance(self.elements[-1], Graph): self.elements.pop() else: raise ParseError("Invalid closing tag.") def handle_node_start(self, attrs): """Creates a new Node and puts it on the stack.""" # get the id id = attrs["id"] # create the node node = self.current_graph.add_node(id) # associate it with its id self.ids[id] = node # put it on the stack self.elements.append(node) def handle_node_end(self): """Ties off the node and removes it from the stack.""" if isinstance(self.elements[-1], Graph.Node): self.elements.pop() else: raise ParseError("Invalid closing tag.") def handle_edge_start(self, attrs): """Creates a new edge and puts it on the stack.""" # get the edge's id id = attrs["id"] # get the edge's start and end start = self.ids[attrs["source"]] end = self.ids[attrs["target"]] # verify them if not isinstance(start, Graph.Node) or not isinstance(end, Graph.Node): raise ParseError("Encountered invalid node ids while parsing edge %s" % id) # get the edge's directed state is_directed = attrs.get("directed", self.defaults["edgedefault"]) # build the edge edge = self.current_graph.add_edge(start, end, id, is_directed=is_directed) # associate its id with it self.ids[id] = edge # and push it onto the stack self.elements.append(edge) def handle_edge_end(self): """Ties off the edge and removes it from the stack.""" if isinstance(self.elements[-1], Graph.Edge): self.elements.pop() else: raise ParseError("Invalid closing tag.") def handle_key_start(self, attrs): """Creates a new key and puts it on the stack.""" # keys are represented as dictionaries key = {"_data_type": "key"} # now, so are attrs attrs = dict(attrs.items()) # with two attributes: id and for key["id"] = attrs.pop("id") key["for"] = attrs.pop("for") # now figure out the other ones for k, v in attrs.items(): if k.startswith("attr."): key[k[5:]] = v # and put the miserable concoction on the stack self.elements.append(key) # and into the ids dict self.ids[key["id"]] = key def handle_key_end(self): """Ties off the key and removes it from the stack.""" if self.elements[-1]["_data_type"] == "key": self.elements.pop() else: raise ParseError("Invalid closing tag.") def handle_data_start(self, attrs): """Creates a new data structure and puts it onto the stack.""" data = {} key_id = attrs["key"] data["key"] = self.ids[key_id] self.elements.append(data) def handle_data_end(self): """Ties off the data structure and removes it from the stack.""" data = self.elements.pop() key = data["key"] data_name = key["name"] data_type = key["type"] default_value = key.get("default", False) data_value = data.get("default", default_value) types = { "obj": loads, "string": str, "boolean": bool, "int": int, "float": float, "double": float, "long": float, } setattr(self.elements[-1], data_name, types[data_type](data_value)) def handle_default_start(self, attrs): """Creates a new default and attaches it to the parent key.""" self.elements[-1]["default"] = None def handle_default_end(self): """Ties off the default value.""" pass def handle_desc_start(self): """Creates a new key and puts it on the stack.""" print("Warning: ignoring description") def handle_desc_end(self): """Ties off the key and removes it from the stack.""" print("Warning: ignoring description") def characters(self, data): """If valid, associates the characters with the last element on the stack.""" try: data = data.strip() if data: self.elements[-1]["default"] = data.strip() except: pass
#! /usr/bin/env python3 import sys import os.path from html.parser import HTMLParser from graph.base import Graph G = Graph() class UrlGetter(HTMLParser): """Extracts all the links from the given html""" links = None def handle_starttag(self, tag, attrs): attrs = dict(attrs) if tag == "a": href = attrs.get("href", False) if href: if not self.links: self.links = [] self.links.append(href) def get_urls(filename): """Extracts all the links from the given file.""" parser = UrlGetter() txt = str(open(filename).read()) parser.feed(txt) parser.close() return parser.links