Exemple #1
0
    def __init__(self):
        super().__init__()

        self.playerOne = Player()

        self.neighborhood = Neighborhood(3)
        self.generatehouses()
Exemple #2
0
    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 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
Exemple #4
0
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
Exemple #5
0
 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)
Exemple #6
0
 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)
Exemple #7
0
    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 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
Exemple #9
0
  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()
Exemple #10
0
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
Exemple #11
0
 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()
Exemple #12
0
    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
Exemple #13
0
 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"])
Exemple #14
0
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:
Exemple #15
0
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 ####
Exemple #16
0
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
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()