def move_head(direction): global head, tail, head_x, head_y, facing, opposite, snake_head_img if direction == opposite: direction = head['facing'] if facing != direction: snake_head_img = orientate_snake(snake_head_img, head, direction.value) if direction == Directions.UP: head['rect'].top -= SEG_DIM head['facing'] = Directions.UP opposite = Directions.get_opposite(direction) elif direction == Directions.RIGHT: head['rect'].left += SEG_DIM head['facing'] = Directions.RIGHT opposite = Directions.get_opposite(direction) elif direction == Directions.DOWN: head['rect'].top += SEG_DIM head['facing'] = Directions.DOWN opposite = Directions.get_opposite(direction) elif direction == Directions.LEFT: head['rect'].left -= SEG_DIM head['facing'] = Directions.LEFT opposite = Directions.get_opposite(direction)
class DirectionResponseParser(object): @classmethod def parse(klass, response): parser = DirectionResponseParser(response) return parser._parse() def __init__(self, response): self.response = response self.json_dict = json.loads(response.read()) self.directions = Directions() def _parse(self): if self.response_valid(): self.set_timeline() self.build_steps() return self.directions else: return None def response_valid(self): return self.response.status == 200 def set_timeline(self): route = self.json_dict['routes'][0]['legs'][0] if 'arrival_time' in route.keys() and 'departure_time' in route.keys(): arrival = route['arrival_time']['text'] departure = route['departure_time']['text'] self.directions.set_timeline(arrival, departure) def build_steps(self): steps = self.json_dict['routes'][0]['legs'][0]['steps'] for step in steps: self.directions.add_step(DirectionStep(step))
def act(self, state): head_pos = state[0] apple_pos = state[1] step_size = state[2] facing = state[3] tail = state[4] shortest = None action = action_space[0] for i in range(0, len(action_space)): if Directions.get_opposite(facing) == directions[i]: continue direction = directions[i] opposite = Directions.get_opposite(direction) x, y = self.pred_position(head_pos.left, head_pos.top, direction, opposite, step_size) if not self.will_avoid_oneself(x, y, tail): continue distance = math.sqrt((apple_pos.top - y)**2 + (apple_pos.left - x)**2) if shortest == None or distance < shortest: shortest = distance action = action_space[i] return action
def __init__(self, unique_id, model, pos, exp, directions): self.unique_id = unique_id self.model = model self.pos = pos self.traversable = True self.trip_lengths = powerlaw.Power_Law( xmin=7, parameters=[exp]) #1.5-2.0 #xmin 17? self.direction_range = 3 self.directions = Directions(self.direction_range) self.current_direction = 0 self.remaining_steps = 0 self.start = None self.end_point = None
def selectProcess(command, authkeys): commandList = command.lower().split() command = command.lower() google_authkeys = authkeys["google"] yelp_authkeys = authkeys["yelp"] if (directionCommand(commandList)): return (Directions(command, google_authkeys)) elif (dictionaryCommand(commandList)): return (dictionary(command)) elif (yelpCommand(commandList)): return (Yelp(command, yelp_authkeys)) elif (wikiCommand(commandList)): return (SearchWiki(command)) elif (placesCommand(commandList)): return (GooglePlace(command, google_authkeys)) elif (helpCommand(commandList)): return (printHelp()) else: return ("We didn't understand your search, see if this helps:\n" + printHelp())
def __init__(self, N, height, width, exponent, steps): self.number_of_agents = N self.height = height self.width = width self.exponent = exponent #self.x_locs = np.zeros((N, steps)) #self.y_locs = np.zeros((N)) self.direction_range=3 self.directions = Directions(self.direction_range) self.current_step_contacts=[] self.adjacency_matrix = np.zeros((N, N)) self.grid = MultiGrid(self.width, self.height, torus=False) self.schedule = BaseScheduler(self) self.current_step = 0 # Add N pedestrians to model (schedule, grid) for i in range(self.number_of_agents): x = self.random.randrange(1, self.grid.width-1) y = self.random.randrange(1, self.grid.height-1) pos = (x, y) new_human = Pedestrian(i, self, pos, self.exponent, self.directions) self.schedule.add(new_human) self.grid.place_agent(new_human, pos) self.data_collector=DataCollector() self.running=True self.data_collector.collect(self)
def reset(settings, first_play=False): global head, tail, facing, opposite, direction, apple, snake_head_img, snake_body_img direction = settings['starting_direction'] opposite = Directions.get_opposite(facing) head['rect'] = get_segment() head['facing'] = settings['starting_direction'] apple = spawn_apple() snake_head_img = pygame.image.load("snake head.png") snake_head_img = pygame.transform.scale(snake_head_img, (settings['block_dim'], settings['block_dim'])) snake_body_img = pygame.image.load("snake body.png") snake_body_img = pygame.transform.scale(snake_body_img, (settings['block_dim'], settings['block_dim'])) if settings['autostart']: direction = facing if first_play: if settings['walls_on']: generate_walls() if settings['tunnels_on']: generate_tunnels() else: tail = [] for _ in range(settings['starting_tail']): move_head(head['facing']) tail.append(get_segment())
class Wonsz(): '''Wonsz class''' def __init__(self, board): '''object creation''' self.directions = Directions() self.direction = self.directions.get_random_direction() self.board = board self.body = [(self.board.rows // 2, self.board.cols // 2)]
def __init__(self, screen_size, earth, events): self.screen_size = screen_size self.earth_origin = earth.origin self.earth_radius = earth.earth_radius self.weapons = [] # Gun parts self.gun_cooldown = Cooldown(GameData.WEAPON_GUN_COOLDOWN) self.multigun_cooldown = Cooldown(GameData.WEAPON_MULTIGUN_COOLDOWN) self.gun_factory = GunFactory(Directions(1.0)) self.missile_cooldown = Cooldown(GameData.WEAPON_MISSILE_COOLDOWN) self.missile_factory = MissileFactory(Directions(1.0)) self.multimissile_cooldown = Cooldown( GameData.WEAPON_MULTIMISSILE_COOLDOWN) self.multimissile_factory = MultiMissileFactory(Directions(1.0)) #Events self.events = events self.watch_game_events()
def __init__(self, unique_id, model, pos, exp, x_min, seed=None): self.unique_id = unique_id self.model = model self.pos = pos self.area_traversed = np.zeros((model.width, model.height)) self.traversable = True self.trip_lengths = powerlaw.Power_Law( xmin=x_min, parameters=[exp]) #1.5-2.0 #xmin 17? self.direction_range = 3 self.directions = Directions(self.direction_range) self.trip_lengths_covered = [] self.steps_covered = [] self.area_traversed[self.pos[0], self.pos[1]] = 1 self.on_trip = False self.current_direction = 0 self.remaining_steps = 0
def ajax_quick_search(): origin = request.form.get('origin') destination = request.form.get('destination') max_travel_duration = int(request.form.get('max-travel-duration'))*3600 budget = int(request.form.get('budget')) max_hotel_price = settings.HOTEL_THRESHOLDS.get(budget) directions = Directions.generate_from_google(origin, destination) corridors = directions.get_corridors(max_travel_duration, settings.DEFAULT_CORRIDOR_DURATION) for corridor in corridors: corridor.generate_hotels(Hotel, max_hotel_price, settings.DEFAULT_EARLY_WEIGHT, settings.DEFAULT_DETOUR_WEIGHT) if len(corridor.hotels) >= settings.NUMBER_OF_HOTELS_RETURNED: corridor.hotels = corridor.hotels[:settings.NUMBER_OF_HOTELS_RETURNED] return render_template("quick_search_results.html", directions=directions, corridors=corridors)
def solve(self, seq_a, seq_b): score_mat = self._get_score_matrix((len(seq_a) + 1, len(seq_b) + 1)) directions = Directions(score_mat.shape) for i in range(1, score_mat.shape[0]): for j in range(1, score_mat.shape[1]): from_up = score_mat[i - 1][j] + self.gap_penalty from_left = score_mat[i][j - 1] + self.gap_penalty if seq_a[i - 1] == seq_b[j - 1]: from_diag = score_mat[i - 1][j - 1] + self.same else: from_diag = score_mat[i - 1][j - 1] + self.diff best_score = max(from_up, from_left, from_diag) score_mat[i][j] = best_score is_left = from_left == best_score is_up = from_up == best_score is_diag = from_diag == best_score directions.set_directions(i, j, is_left, is_up, is_diag) return score_mat, directions, self._get_final_score_from_score_mat( score_mat)
def generate_test(): origin = 'Boston' destination = 'Boulder' max_travel_duration = 10*3600 budget = 3 max_hotel_price = settings.HOTEL_THRESHOLDS.get(budget) directions = Directions.generate_from_google(origin, destination) corridors = directions.get_corridors(max_travel_duration, settings.DEFAULT_CORRIDOR_DURATION) for corridor in corridors: corridor.generate_hotels(Hotel, max_hotel_price, settings.DEFAULT_EARLY_WEIGHT, settings.DEFAULT_DETOUR_WEIGHT) if len(corridor.hotels) >= settings.NUMBER_OF_HOTELS_RETURNED: corridor.hotels = corridor.hotels[:settings.NUMBER_OF_HOTELS_RETURNED] with open('data/test.pk', 'wb') as output: pickle.dump(directions, output, pickle.HIGHEST_PROTOCOL) pickle.dump(corridors, output, pickle.HIGHEST_PROTOCOL) return "Success."
class Pedestrian(Agent): DIRECTION_DEGREES = 15 #NR_OF_DIRECTIONS = 24 def __init__(self, unique_id, model, pos, exp, seed=None): self.unique_id = unique_id self.model = model self.pos = pos self.traversable = False self.area_traversed = np.zeros((model.width, model.height)) self.traversable = True self.trip_lengths = powerlaw.Power_Law( xmin=7, parameters=[exp]) #1.5-2.0 #xmin 17? self.direction_range = 3 self.directions = Directions(self.direction_range) self.trip_lengths_covered = [] self.steps_covered = [] self.area_traversed[self.pos[0], self.pos[1]] = 1 self.on_trip = False self.current_direction = 0 self.remaining_steps = 0 def plan_trip(self): ''' Plan new tip: i. Determine trip length ii. Determine new direction based on current direction (correlated RW) ''' # Direction if self.current_direction == 0: # first trip direction = random.choice(self.directions.directions) self.current_direction = Direction(direction, self.direction_range) else: # correlated random walk radians = np.random.vonmises(0, kappa=4) degrees = math.degrees(radians) jumps = math.floor(degrees / Pedestrian.DIRECTION_DEGREES) self.current_direction = self.directions.correlated( self.current_direction, jumps) # Trip length length_of_trip = int(self.trip_lengths.generate_random(1) [0]) #generate_random ignores xmax self.remaining_steps = self.current_direction.calculate_steps( length_of_trip) self.trip_lengths_covered.append(length_of_trip) self.steps_covered.append(self.remaining_steps) def contact(self): ''' Find all other agents within range (radius = 5) and update contacts. ''' neighbors_in_contact = self.model.grid.get_neighbors(self.pos, moore=True, radius=5) if len(neighbors_in_contact) > 0: for neighbor in neighbors_in_contact: if neighbor.unique_id != self.unique_id: self.model.contact_update( (self.unique_id, neighbor.unique_id)) def check_if_traversable(self, coordinate): ''' Check if location is traversable. ''' traversable = True if (0 <= coordinate[0] < self.model.width) and (0 <= coordinate[1] < self.model.height): contents = self.model.grid.get_cell_list_contents(coordinate) for content in contents: if not content.traversable: traversable = False else: traversable = False return traversable def move(self): ''' Move pedestrian one step ''' # Plan new trip, if current trip length reached if self.remaining_steps == 0: self.plan_trip() # Determine move based on current direction shift = self.current_direction.move() move = (self.pos[0] + shift[0], self.pos[1] + shift[1]) # Check if move is possible (can't traverse walls) if self.check_if_traversable(move): new_position = move self.model.grid.move_agent(self, new_position) self.remaining_steps -= 1 else: ''' If not traversable, determine the two alternative moves (i. bounce of vertical wall, ii. bounce of horizontal wall). Determine which bouncing move works, then move and update direction accordingly ''' # Bouncing moves alternative_shifts = [[-shift[0], shift[1]], [shift[0], -shift[1]], [-shift[0], -shift[1]]] # If bouncing move possible --> move and update direction # TODO: Possible bias for objects??? Always checks vertical wall shift first for bounce_shift in alternative_shifts: move = (self.pos[0] + bounce_shift[0], self.pos[1] + bounce_shift[1]) if self.check_if_traversable(move): # Bounce: move + new direction new_position = move self.model.grid.move_agent(self, new_position) self.remaining_steps -= 1 self.current_direction.change(bounce_shift) break def step(self): self.move()
from directions import Directions if __name__ == '__main__': # Calculate values from input results = Directions('input.txt') at_least_one_present = str(results.houses_at_least_one_present) # Print out results print "The amount of houses that received at least one present: " + at_least_one_present
def __init__(self, response): self.response = response self.json_dict = json.loads(response.read()) self.directions = Directions()