def run(self): place_data_server = PlaceDataServer() try: place_data_server.initialize_server("place_data.csv") except IOError as pds_io_exception: print("Exception thrown populating PDS data: %s" % pds_io_exception) image_server = ImageServer() try: image_server.initialize_server("image_data.csv") except IOError as is_io_exception: print("Exception thrown populating IS data: %s" % is_io_exception) neighborhood = Neighborhood(place_data_server, image_server) while True: print("~~~~~~~~~~~A new Server is running.!!") places_found = place_data_server.get_place_data_from_name( "Starbucks") for place in places_found: print("***: %s" % place) print("***: %s" % place_data_server.get_place_data( "Starbucks", LatLng(100, -200))) print("***: %s" % image_server.get_image_for_place( "Starbucks", LatLng(100, -200))) print("*** get_nearby_places: %s" % place_data_server.get_nearby_places(LatLng(100, -200), 2)) print("*** get_places: %s" % neighborhood.get_places(LatLng(100, -200), 1)) # Feel free to add more print statements here in order to test your code # and see how things are working. time.sleep(11)
def __init__(self, size=5): ''' A constructor for game. Creates the player and neighborhood and stores information regarding them. :param size: The size of the neighborhood. (Defaults to 5x5) ''' self.player = Player() self.player.add_observer(self) self.playerLoc = (0, 0) self.neighborhood = Neighborhood(size, size) self.isPlaying = True
def test_neighborhood(self): n_a = Neighborhood.get(self.a, self.edges) n_b = Neighborhood.get(self.b, self.edges) n_c = Neighborhood.get(self.c, self.edges) n_d = Neighborhood.get(self.d, self.edges) self.assertTrue(Edges({self.e1, self.e2}) == n_a) self.assertTrue(Edges({self.e3, self.e4}).isdisjoint(n_a)) self.assertTrue(Edges({self.e1, self.e4}) == n_b) self.assertTrue(Edges({self.e2, self.e3}).isdisjoint(n_b)) self.assertTrue(Edges({self.e3}) == n_c) self.assertTrue(Edges({self.e1, self.e2, self.e4}).isdisjoint(n_c)) self.assertTrue(Edges({self.e2, self.e3, self.e4}) == n_d) self.assertTrue(Edges({self.e1}).isdisjoint(n_d))
def loop(self): # modify, this is called with a timer? """ Main loop of the engine, moves things forward. Calculates the neighborhoods for each boid, then calculates the force to apply given by the rules and applies it. Lastly moves the boids forward on the screen. """ w = Engine.window_width h = Engine.window_height # n² for b1 in self.boids: # Initialize neighborhood hood = Neighborhood(b1, Engine.window_width, Engine.window_height, rules=self.rules) # Loop all boids, add to neighborhood if distance is short enough for b2 in self.boids: if b2 == b1: continue # skip adding the boid itself to its neighborhood dist_sqrd = b1.position.get_dist_sqrd_toroidal( b2.position, Engine.window_width, Engine.window_height ) # OK to compare squared distances if dist_sqrd <= Neighborhood.max_distance: # Check view angle condition # angle is now between -180 and 180 vect_ab = (- b1.position + b2.position) angle = b1.orientation.forward.get_angle_between(vect_ab) if angle >= -b1.view_angle and angle <= b1.view_angle: hood.add(b2) # Calculate weighted force force = Vec2d(0, 0) for rule in self.rules: w = Engine.window_width h = Engine.window_height # Normalize all vectors returned by rules and add them to total force += (type(rule).weight * rule.consult(b1, hood, w, h).normalized()) # Apply weighted force b1.move(force, w, h) # endloop b1 # Step all boids forward on the screen for b1 in self.boids: b1.step()
def __init__(self): super().__init__() self.playerOne = Player() self.neighborhood = Neighborhood(3) self.generatehouses()
def get_neighborhood(leaflet, mdsys): """ Get neighborhood object for the give leaflet """ dist = distances.distance_array(leaflet.positions, leaflet.positions, mdsys.dimensions[:3]) nbrs = Neighborhood(leaflet.positions, dist, mdsys.dimensions[:3]) return nbrs
def testNeighborhoodObject(self): n = Neighborhood(0, 1, 2, 3, 4, 5, 6, 7) self.assertEqual(n.areaNumber, 0) self.assertEqual(n.areaName, 1) self.assertEqual(n.percentHousingCrowded, 2) self.assertEqual(n.percentHousingBelowPovertyLine, 3) self.assertEqual(n.percentUnEmployed, 4) self.assertEqual(n.percentWithoutDiploma, 5) self.assertEqual(n.perCapitaIncome, 6) self.assertEqual(n.hardshipIndex, 7)
def get_neighborhood(self, neighborhood: Neighborhood, idx=0, total_length=0): save_path = f"{self.save_path_name}.txt" try: neighborhood = self.get_neighborhood_detail_info(neighborhood) logger.info(f"idx: {idx}:{total_length}, {neighborhood}") self.save_json(neighborhood.as_dict(), save_path) except Exception as err: logger.error(err) finally: time.sleep(4)
def __init__(self): self._player = Player(0, 0) self._neighborhood = Neighborhood(self, 5, 5) self._game_active = True temp_people = 0 for row in range(0, self._neighborhood.get_rows()): for col in range(0, self._neighborhood.get_cols()): temp_people += self._neighborhood.get_home(row, col).get_people() self._monsters = 250 - temp_people print("You wake up on Halloween and discover that the world") print("is not how you left it. Batches of bad candy have transformed") print("your friends and neighbors into all sorts of crazy monsters.") print("Somehow you missed the tainted candy; it is therefore up to") print( "you to save your neighborhood and turn everyone back to normal.") print() print("type \"help\" for instructions") print()
def get_neighborhood_list_from_file(self, filename): with open(filename, "rb") as f: for idx, line in enumerate(f): try: _dict = json.loads(line) if not isinstance(_dict, dict): continue except Exception as err: logger.error(err) continue neighborhood = Neighborhood(**_dict) self.neighborhood_list.append(neighborhood)
def makeNeighborhoodArray(): f = open( '../Data/Census_Data_-_Selected_socioeconomic_indicators_in_Chicago__2008___2012.csv' ) csvF = csv.reader(f) i = 0 for row in csvF: if (i > 0): #row 0 is the header n = Neighborhood(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7]) neighborhoods.append(n) else: i += 1 del neighborhoods[-1] #last row is stats for whole chicago -> not needed
def move_hero(self): block = Neighborhood() for x in range(5): for y in range(5): if block.grid[y][x] == "P": direction = input("Please enter a direction (n, s, e, w): ") while (direction != "n" and direction != "s" and direction != "e" and direction != "w"): direction = input("Invalid entry: Please enter a valid direction (n, s, e, w):") if direction == "n": if (y + 1) > 4: print("My parents say I can't go that far. I should try another direction") self.move_hero() else: block.grid[y][x] == "S" if block.grid[y + 1][x] == "H": block.grid[y + 1][x] == "P" self.fight_it_out() if direction == "s": if (y - 1) < 0: print("Never been there before, and I don't really wanna go") self.move_hero() else: block.grid[y][x] == "S" if block.grid[y - 1][x] == "H": block.grid[y - 1][x] == "P" self.fight_it_out() if direction == "e": if (x + 1) > 4: print("I got grounded last time I went there. I'll go another way") self.move_hero() else: block.grid[y][x] == "S" if block.grid[y][x + 1] == "H": block.grid[y][x + 1] == "P" self.fight_it_out() if direction == "w": if (x - 1) < 0: print("Mom said not to approach those buildings with the red lights") self.move_hero() else: block.grid[y][x] == "S" if block.grid[y][x - 1] == "H": block.grid[y][x - 1] == "P" self.fight_it_out()
def get_neighborhood_prices(city, state, workplace, client): ''' Given a city name and the state it's in, return a dict of neighborhood: rent_price values. ''' neighborhoods = [] with open('1_bedroom_rent.csv', newline='') as csvfile: n_reader = csv.reader(csvfile, delimiter=',') for row in n_reader: if row[1] == city and row[2] == state: nh = Neighborhood( f"{row[0]}, {row[1]}, {row[2]}", row[-1], workplace, client ) neighborhoods.append(nh) return neighborhoods
def neighbors(self, i=None, j=None): """ Construct and return Neighborhood of point if point is exists """ if not self.position_exists(i, j): raise ValueError( "Position ({}, {}) does not exist in a {} x {} matrix".format( i, j, self.m, self.n)) if (i is None) != (j is None): # Only one coordinate provided raise ValueError("Cannot get neighbors of a column or row") if i == j == None and self.position is None: # Both None raise ValueError( "Cannot retrieve neighbors. Either set start or provide coordinates to mark." ) i, j, _ = self.position nbhd = Neighborhood() # Keep things ordered clockwise for consistency in code # Top if i > 0: nbhd.top = Position(i - 1, j, self.M[i - 1][j]) # Right if j < self.n - 1: nbhd.right = Position(i, j + 1, self.M[i][j + 1]) # Bottom if i < self.m - 1: nbhd.bottom = Position(i + 1, j, self.M[i + 1][j]) # Left if j > 0: nbhd.left = Position(i, j - 1, self.M[i][j - 1]) return nbhd
def compute(self, edges): ns = set() for e in Neighborhood.get(self.v, edges): ns.add(e.adjacent(self.v)) self.neighbors = Vertices(ns)
def get_neighborhood_from_current_page(url): selector = etree.HTML(requests.get(url).text) for item in selector.xpath(Xpath.neighborhood): yield Neighborhood(name=item.text, url=item.attrib["href"])
person_developer = PersonDeveloper(setup, life_stages, statistics) city_couple_creator = CityCoupleCreator() couple_creator = CoupleCreator() couple_developer = CoupleDeveloper(statistics) foster_care_system = FosterCareSystem(statistics) # Initialize city, at last city = City(baby_generator, person_developer, city_couple_creator, life_stages, names, couple_developer, statistics, foster_care_system) # First time jumps to remove first older generation (the one without parents) for _ in range(20): city.time_jump_city() # Now populate neighborhood neighborhood = Neighborhood(names, baby_generator, person_developer, couple_creator, couple_developer, statistics, foster_care_system) neighborhood.populate_neighborhood(city.living_population, city.city_couples) # Display their stats (debugging purposes) neighborhood.display_households() print() for _ in range(30): city.time_jump_city() neighborhood.time_jump_neighborhood(city.romanceable_outsiders) for neighbor in neighborhood.neighbors: # Update city population with neighborhood newborns if neighbor not in city.population: city.population.append(neighbor) # Then remove dead neighbors from neighbors list and their assigned household if neighbor.is_alive is False:
from player import Player from neighborhood import Neighborhood import sys from random import randint import math #### Start of the game, gives a little background text #### ## Created by Austin Van Kempen and Lanndon Rose #### if __name__ == "__main__": print("Zork, A Text Based RPG") print("The goal is to go to every home in the neighborhood and remove") print("all of the monsters inside. Once this is done, choose the option check. \n") print("if all of the monsters are dead, you win. If they aren't. Too bad punk, you lose.") #### Setting neighborhood() to n #### n = Neighborhood() #### Setting n.get_neighborhood() to hood #### hood = n.get_neighborhood() #### Setting player() to hero #### hero = Player() #### Setting hero.get_inventory() to candyBucket #### candyBucket = hero.get_inventory() #### Spacing #### print() print() #### Spacing ####
def process_neighborhoods(west, south, rows, columns, ax, size, nodes, draw=False): hexes, centers, corners = tile_hex((west - 0.006, south + 0.002), rows, columns, ax, size, 'b', nodes, draw=draw) print(len(nodes), len(hexes)) # print(hex_dict.keys()) neighborhoods = [] for i in range(len(hexes)): current_center = centers[i] current_corners = corners[i] exits, distances = find_exits(hexes[i], current_corners, current_center, size) # print(exits) # print(len(hexes[i]),len(exits)) nh = Neighborhood() nh.setNodes(hexes[i]) nh.setCorners(current_corners) nh.setCenter(current_center) nh.setExits(exits) nh.setDistances(distances) if exits == None: nh = None neighborhoods.append(nh) if exits == None: continue # if draw: # for n in exits: # ax.scatter(n.x,n.y,s=50,c='b') hex_dict = find_neighbors(neighborhoods, columns) for i in range(len(neighborhoods)): if neighborhoods[i] != None: neighborhoods[i].setNeighbors(hex_dict[i]) neighborhoods[i].setID(i) return neighborhoods
class Game: hood = Neighborhood() hood.create_grid() hero = Player(random.randint(100, 125), random.uniform(10, 20)) hero.fill_inventory() hero.move_hero()
'neighborhood': 0, 'perceptron': 0, } # Test 9 versions of the dataset/algorithms for i in range(9): print(f'* * * Starting iteration {i+1} of 9 * * *') dataset = Dataset(data_file=DATA_IN_FILE, shuffle_data=True) dataset.partitionXTrain(0.8) print(f'Starting KNN') knn = KNN(dataset, k=K) knn.evalTest() logMetrics(knn, 'knn') bestDecision(knn, 'knn', KNN_DEC_BOUND, f'k-Nearest Neighbors Decision Boundary @ k={knn.k}') print(f'Starting Neighborhood') neighborhood = Neighborhood(dataset, R=R) neighborhood.evalTest() logMetrics(neighborhood, 'neighborhood') bestDecision(neighborhood, 'neighborhood', NEIGHBOR_DEC_BOUND, f'Neighborhood Decision Boundary @ R={neighborhood.R}') print(f'Starting Perceptron') perceptron = Perceptron(dataset, learning_rate=LEARNING_RATE) perceptron.train(epochs=EPOCHS) perceptron.evalTrain() logMetrics(perceptron, 'perc_train') perceptron.evalTest() logMetrics(perceptron, 'perc_test') train_err.append(np.subtract(1, perceptron.train_acc)) bestDecision(perceptron, 'perceptron', PERC_DEC_BOUND, f'Perceptron Decision Boundary') # Individual trial performance
class Game(Observer): ''' A game object that is used to play the game. The game has a player and a neighborhood, while storing the players location the player can attack that location. ''' def __init__(self, size=5): ''' A constructor for game. Creates the player and neighborhood and stores information regarding them. :param size: The size of the neighborhood. (Defaults to 5x5) ''' self.player = Player() self.player.add_observer(self) self.playerLoc = (0, 0) self.neighborhood = Neighborhood(size, size) self.isPlaying = True def receiveUpdate(self, info=None): ''' An abstract function that is impimented by game to get an update when the player still is playing. ''' self.isPlaying = False def getStatus(self): ''' A getter that returns the game status. ''' return self.isPlaying def getPlayer(self): ''' A getter that return the player ''' return self.player def getNeighborhood(self): ''' A getter that returns the neighborhood. ''' return self.neighborhood def getPlayerLoc(self): ''' A getter that returns the player location. ''' return self.playerLoc def move(self, direction): ''' A move function that moves the player location in four directions. Returns boolean values to determine if the move was possible or not. :param direction: a direction (north, south, east, west) ''' if not self.isPlaying: return False if direction == "north": newLoc = (self.playerLoc[0] - 1, self.playerLoc[1]) if self.neighborhood.inBounds(newLoc): self.playerLoc = newLoc return True elif direction == "south": newLoc = (self.playerLoc[0] + 1, self.playerLoc[1]) if self.neighborhood.inBounds(newLoc): self.playerLoc = newLoc return True elif direction == "east": newLoc = (self.playerLoc[0], self.playerLoc[1] + 1) if self.neighborhood.inBounds(newLoc): self.playerLoc = newLoc return True elif direction == "west": newLoc = (self.playerLoc[0], self.playerLoc[1] - 1) if self.neighborhood.inBounds(newLoc): self.playerLoc = newLoc return True return False def attackHouse(self, loc, weaponNum): ''' An attack function that attacks all monsters in a house. :param loc: The location being attacked. :param weaponNum: the weapon used to attack. ''' if not self.isPlaying: return self.player.attackAll(self.neighborhood.getHouse(loc), weaponNum) self.neighborhood.getHouse(loc).dealDamage(self.player) if self.getNeighborhood().isClear(): self.isPlaying = False
class Game(Observer): ####################################################### # constructor to initialize variables # # @param self current object ####################################################### def __init__(self): self._player = Player(0, 0) self._neighborhood = Neighborhood(self, 5, 5) self._game_active = True temp_people = 0 for row in range(0, self._neighborhood.get_rows()): for col in range(0, self._neighborhood.get_cols()): temp_people += self._neighborhood.get_home(row, col).get_people() self._monsters = 250 - temp_people print("You wake up on Halloween and discover that the world") print("is not how you left it. Batches of bad candy have transformed") print("your friends and neighbors into all sorts of crazy monsters.") print("Somehow you missed the tainted candy; it is therefore up to") print( "you to save your neighborhood and turn everyone back to normal.") print() print("type \"help\" for instructions") print() ####################################################### # loop that executes during entire life-cycle of game # # @param self current object ####################################################### def game_loop(self): while (self._game_active): print(">\t", end="") user_input = input().lower() move_pattern = re.compile("move ((north)|(south)|(east)|(west))") if move_pattern.fullmatch(user_input) != None: self.game_move(user_input) elif user_input == "attack": if self.game_attack(): self._game_active = False break elif user_input == "map": self.game_map() elif user_input == "stats": self.game_stats() elif user_input == "help": self.game_help() elif user_input == "exit": if self.game_exit(): self._game_active = False break else: self.game_unknown() if self._monsters <= 0: print( "You successfully all of the monsters back into people, congrats!" ) break ####################################################### # sub-function to handle user entering move command # # regex on call prevents any errors here # # @param self current object # @param user_input string the user entered ####################################################### def game_move(self, user_input): print("\n") if self._player.move(user_input, self._neighborhood.get_rows(), self._neighborhood.get_cols()): print("moved %s" % user_input[5:]) self.game_map() else: print("could not move %s" % user_input[5:]) print("\n") ####################################################### # sub-function to handle user entering attack command # # @param self current object # # @return boolean True if player has died ####################################################### def game_attack(self): print("\n") num_weapons = len(self._player.get_weapons()) weapons_regex = None if num_weapons >= 10: weapons_regex = re.compile("(10)|[1-9]") else: weapons_regex = re.compile("[1-%d]" % num_weapons) while True: print("choose weapon:") print() print("\tindex\tweapon\t\t\tatk_modifier\t\tuses") index = 1 for weapon in self._player.get_weapons(): print("\t%d.\t%s\t\t%f\t\t%d" % (index, weapon.get_name(), weapon.get_attack_modifier(), weapon.get_uses())) index += 1 print("\n") print(">\t", end="") user_input = input().lower() if weapons_regex.fullmatch(user_input) != None: break else: print() print("choose a valid number corresponding to desired weapon") print() weapon = self._player.get_weapons()[int(user_input) - 1] self._player.attack( self._neighborhood.get_home(self._player.get_row(), self._player.get_col()), weapon) weapon.use() return self._player.is_dead() ####################################################### # sub-function to handle user entering map command # # draws neighborhood to standard out # # @param self current object ####################################################### def game_map(self): print("\n") for row in range(0, self._neighborhood.get_rows()): for col in range(0, self._neighborhood.get_cols()): print(" ------ \t", end="") print() for col in range(0, self._neighborhood.get_cols()): if self._player.get_row() == row and self._player.get_col( ) == col: print("| \\/ |\t", end="") else: print("| |\t", end="") print() for col in range(0, self._neighborhood.get_cols()): if self._player.get_row() == row and self._player.get_col( ) == col: print("| /\\ |\t", end="") else: print("| |\t", end="") print() for col in range(0, self._neighborhood.get_cols()): print(" ------ \t", end="") print() for col in range(0, self._neighborhood.get_cols()): print("People: %d\t" % self._neighborhood.get_home(row, col).get_people(), end="") print() for col in range(0, self._neighborhood.get_cols()): print("Zombies: %d\t" % self._neighborhood.get_home(row, col).get_zombies(), end="") print() for col in range(0, self._neighborhood.get_cols()): print("Vampires: %d\t" % self._neighborhood.get_home(row, col).get_vampires(), end="") print() for col in range(0, self._neighborhood.get_cols()): print("Ghouls: %d\t" % self._neighborhood.get_home(row, col).get_ghouls(), end="") print() for col in range(0, self._neighborhood.get_cols()): print("Werewolves: %d\t" % self._neighborhood.get_home(row, col).get_werewolves(), end="") print("\n") print("\\/") print("/\\ ---> (player location)") print("\n") ####################################################### # sub-function to handle user entering stats command # # prints out current stats of character and surroundings # # @param self current object ####################################################### def game_stats(self): print("\n") print("monsters remaining:\t%d" % self._monsters) print() print("player:") print("\thp:\t\t\t\t" + str(self._player.get_hp())) print("\tattack:\t\t\t\t" + str(self._player.get_atk())) print("inventory:") print("\tweapon\t\t\t\tatk_modifier\t\t\tuses") print() for weapon in self._player.get_weapons(): if type(weapon) is HersheyKiss: print("\t" + weapon.get_name() + "\t\t\t" + str(weapon.get_attack_modifier()) + "\t\t\t\t" + str(weapon.get_uses())) else: print("\t" + weapon.get_name() + "\t\t\t" + str(weapon.get_attack_modifier()) + "\t\t" + str(weapon.get_uses())) print() print("monsters in current house:") print("\ttype\t\t\thealth") for monster in self._neighborhood.get_home( self._player.get_row(), self._player.get_col()).get_monsters(): if monster.get_type() == "werewolve": print("\t" + monster.get_type() + "\t\t" + str(monster.get_hp())) else: print("\t" + monster.get_type() + "\t\t\t" + str(monster.get_hp())) print("\n") ####################################################### # sub-function to handle user entering help command # # prints out help page # # @param self current object ####################################################### def game_help(self): print("\n") print("instructions:") print("\tmove [north|south|east|west] move houses in direction") print("\tattack attack current house") print("\tmap print out map with stats") print( "\tstats displays information about game and player" ) print("\thelp print help page") print("\texit exit game") print("\n") ####################################################### # sub-function to handle user entering exit command # # exits game # # @param self current object ####################################################### def game_exit(self): print("\n") print("exiting...") print("\n") return True ####################################################### # sub-function to handle user entering an unkown command # # @param self current object ####################################################### def game_unknown(self): print("\n") print("unknown command") print("\n") ####################################################### # process update from observable # # @param self current object # @param observable object calling update # @param msg message object is sending ####################################################### def update(self, observable, msg): self._monsters -= 1
def server(): rospy.Service('remove_blocked_edge', RemoveBlockedEdgeMsg, remove_blocked_edge) rospy.Service('check_is_edge', CheckEdge, check_is_edge) rospy.Service('reset_world', ResetWorldMsg, handle_reset_world) print("Ready!") rospy.spin() if __name__ == "__main__": args = parser.parse_args() print('houses: ' + str(args.houses * args.streets)) print('packages: ' + str(args.packages)) print('streets: ' + str(args.streets)) print('robots: ' + str(args.robots)) neighborhoodInfo = Neighborhood(12, 0.5) objects = neighborhoodInfo.generate_blocked_edges(args.houses, args.streets, args.packages, args.seed, root_path) objects = neighborhoodInfo.generate_launch(args.robots, objects, root_path) neighborhoodInfoCopy = copy.deepcopy(neighborhoodInfo) rospy.init_node('server') robot_action_server = RobotActionsServer(objects, args.robots, root_path, args.headless, args.seed) path = root_path + "/problem.pddl" with open(root_path + "/deliveries.json") as json_file: deliveries = json.load(json_file) problem_generator.write_pddl(path, deliveries) server()